Merge branch 'test' into prod
# Conflicts: # backend/.env
This commit is contained in:
commit
729ec2908d
105 files changed
+21090
-1150
No files matched your search
@@ -7,20 +7,26 @@ DATABASE_URL=postgresql://postgres:123456@8.152.207.171/hxops_db
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=development
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=password
|
||||
|
||||
AUTH_JWT_ISSUER=http://192.168.100.192:8870
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
|
||||
# 共用 IdP(可与生产 Casdoor 同机)
|
||||
CASDOOR_BASE_URL=http://192.168.100.230:8870
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
CASDOOR_CLIENT_ID=<hxops-dev-client-id>
|
||||
CASDOOR_CLIENT_SECRET=<hxops-dev-client-secret>
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 本地开发常用;若用其它入口访问前端,请在 Casdoor 该应用的 Redirect URLs 中一并登记
|
||||
CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=<hxops-dev-client-id>
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_JWT_REQUIRED=true
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
# Shared variables are maintained in .env.shared
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
|
||||
# hxops environment variables template
|
||||
# Copy as needed:
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# - .env.local for local-only overrides (do not commit)
|
||||
|
||||
# Runtime selector
|
||||
ENV_NAME=dev
|
||||
|
||||
# Core
|
||||
SECRET_KEY=replace-with-strong-random-secret
|
||||
DATABASE_URL=postgresql://<db_user>:<db_password>@<db_host>:5432/<db_name>
|
||||
REDIS_URL=redis://:<redis_password>@<redis_host>:6379/0
|
||||
|
||||
# Knowledge base runtime
|
||||
KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=sync
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
|
||||
# Dify
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=
|
||||
|
||||
# Feature switch
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# HR workflow
|
||||
HR_WORKFLOW_IFRAME_URL=
|
||||
HR_WORKFLOW_API_BASE=
|
||||
HR_WORKFLOW_API_KEY=
|
||||
|
||||
# Integration API
|
||||
INTEGRATION_API_MODE=local
|
||||
INTEGRATION_API_BASE=
|
||||
INTEGRATION_API_KEY=
|
||||
|
||||
# WeCom
|
||||
WECOM_ENABLED=false
|
||||
WECOM_CORP_ID=
|
||||
WECOM_AGENT_ID=
|
||||
WECOM_SECRET=
|
||||
WECOM_REDIRECT_URI=
|
||||
WECOM_AUTO_CREATE_USER=true
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
WECOM_FIRST_LOGIN_BIND_MODE=match_rules
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=
|
||||
WECOM_HOMEPAGE_URL=
|
||||
WECOM_TRUSTED_DOMAIN=
|
||||
WECOM_PUBLIC_BASE_URL=
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed
|
||||
|
||||
# Auth and Casdoor
|
||||
AUTH_LEGACY_HEADER_ENABLED=true
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_JWT_ISSUER=
|
||||
AUTH_JWT_AUDIENCE=
|
||||
AUTH_JWT_JWKS_URL=
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
CASDOOR_BASE_URL=
|
||||
CASDOOR_CLIENT_ID=
|
||||
CASDOOR_CLIENT_SECRET=
|
||||
CASDOOR_REDIRECT_URI=
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_WECOM_PROVIDER_HINT=
|
||||
CASDOOR_WECOM_SILENT_SIGNIN=false
|
||||
|
||||
# Optional data source
|
||||
HR_SQLSERVER_DRIVER=
|
||||
HR_SQLSERVER_HOST=
|
||||
HR_SQLSERVER_PORT=1433
|
||||
HR_SQLSERVER_DATABASE=
|
||||
HR_SQLSERVER_USERNAME=
|
||||
HR_SQLSERVER_PASSWORD=
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
|
||||
ORACLE_CLIENT_LIB_DIR=
|
||||
ERP_JDBC_JAR=
|
||||
ERP_JDBC_JAR_URL=
|
||||
ERP_DB_DSN=
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
GJL_API_KEY=
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
|
||||
# MinIO
|
||||
MINIO_ENDPOINT=127.0.0.1:9000
|
||||
MINIO_BUCKET=image-hosting-service
|
||||
MINIO_ACCESS_KEY=
|
||||
MINIO_SECRET_KEY=
|
||||
MINIO_PUBLIC_BASE_URL=
|
||||
@@ -7,6 +7,18 @@ DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=production
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
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=http://192.168.100.230:8870
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
@@ -19,9 +31,3 @@ CASDOOR_SCOPE=openid profile email
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
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
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_JWT_REQUIRED=true
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# Shared environment variables for all environments (dev/test/prod)
|
||||
# Keep only values that are truly identical across all environments.
|
||||
|
||||
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
|
||||
ENV_NAME=dev
|
||||
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
# Common runtime defaults
|
||||
FLASK_APP=run.py
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
|
||||
# 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
|
||||
|
||||
# Common WeCom behavior defaults
|
||||
WECOM_AUTO_CREATE_USER=true
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
WECOM_FIRST_LOGIN_BIND_MODE=match_rules
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS=employee_id,mobile,email
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
|
||||
# MINIO
|
||||
MINIO_ENDPOINT=127.0.0.1:9000
|
||||
MINIO_BUCKET=image-hosting-service
|
||||
|
||||
# 硅基流动相关
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
|
||||
# HR SQL Server Configuration
|
||||
HR_SQLSERVER_HOST=192.168.100.191
|
||||
HR_SQLSERVER_PORT=1433
|
||||
HR_SQLSERVER_DATABASE=NH_N8_HEXIN
|
||||
HR_SQLSERVER_USERNAME=AI_Knowledge_Base_Hr
|
||||
HR_SQLSERVER_PASSWORD=hoo-thai@123_AI_HR
|
||||
HR_SQLSERVER_DRIVER=SQL Server
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
@@ -2,22 +2,31 @@
|
||||
# Test — docker compose / deploy_compose.sh test
|
||||
# Casdoor 做法 A:共用 CASDOOR_BASE_URL,独立 Application「hxops-test」
|
||||
# =============================================================================
|
||||
DATABASE_URL=postgresql://postgres:change_me@127.0.0.1:5432/hxops_db
|
||||
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
|
||||
FLASK_APP=run.py
|
||||
FLASK_ENV=test
|
||||
|
||||
CASDOOR_BASE_URL=http://192.168.100.230:8870
|
||||
CASDOOR_CLIENT_ID=<hxops-test-client-id>
|
||||
CASDOOR_CLIENT_SECRET=<hxops-test-client-secret>
|
||||
# 测试环境前端访问根地址(按实际修改主机与端口)
|
||||
CASDOOR_REDIRECT_URI=http://<TEST_FRONTEND_HOST>:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
# Casdoor Providers → wecom(Name=wecom)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=<hxops-test-client-id>
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
AUTH_JWT_REQUIRED=true
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_JWT_ISSUER=http://192.168.100.192:8870
|
||||
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
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# 兜底 redirect_uri;实际 OAuth 以浏览器地址为准,Casdoor「hxops-prod」应用须登记例如:
|
||||
# http://192.168.100.192:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.192:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
+4
-1
@@ -33,7 +33,7 @@ __pycache__/
|
||||
|
||||
# Frontend
|
||||
frontend/node_modules/
|
||||
# frontend/dist/ <-- Commented out to allow committing dist
|
||||
frontend/dist/
|
||||
frontend/.DS_Store
|
||||
frontend/.env.local
|
||||
frontend/.env.*.local
|
||||
@@ -67,3 +67,6 @@ Thumbs.db
|
||||
|
||||
# 忽略Oracle Instant Client本地目录
|
||||
oracle_client/
|
||||
|
||||
# local env override
|
||||
.env.local
|
||||
Vendored
+5
-5
@@ -27,18 +27,18 @@ pipeline {
|
||||
environment {
|
||||
// 环境服务器地址 / Environment hosts
|
||||
DEV_DEPLOY_HOST = '8.152.207.171'
|
||||
TEST_DEPLOY_HOST = 'YOUR_TEST_SERVER_IP'
|
||||
TEST_DEPLOY_HOST = '192.168.100.192'
|
||||
PROD_DEPLOY_HOST = '192.168.100.230'
|
||||
|
||||
// SSH 连接参数 / SSH connection settings
|
||||
DEV_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'root'
|
||||
TEST_SSH_USER = 'lisq'
|
||||
PROD_SSH_USER = 'inspur'
|
||||
SSH_PORT = '22'
|
||||
|
||||
// 各环境统一部署目录 / Unified deploy root
|
||||
DEV_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/opt/hxops'
|
||||
TEST_DEPLOY_ROOT = '/home/lisq/ai/platform/hxops'
|
||||
PROD_DEPLOY_ROOT = '/data/ai-platform/hxops/'
|
||||
}
|
||||
|
||||
@@ -216,7 +216,7 @@ pipeline {
|
||||
when {
|
||||
expression {
|
||||
// test 分支部署到 test 环境 / test branch deploys to test environment
|
||||
env.BRANCH_NAME == 'test' &&
|
||||
(env.BRANCH_NAME == 'test') &&
|
||||
(env.FRONTEND_CHANGED == 'true' || env.BACKEND_CHANGED == 'true' || env.DEPLOY_CONFIG_CHANGED == 'true')
|
||||
}
|
||||
}
|
||||
@@ -245,7 +245,7 @@ pipeline {
|
||||
}
|
||||
|
||||
stage('Deploy Prod') {
|
||||
// 默认允许分支:prod、sophie、sophie-wecom。其它分支在 Job 环境变量设 EXTRA_PROD_BRANCHES=分支a,分支b
|
||||
// 默认允许分支:prod、sophie。其它分支在 Job 环境变量设 EXTRA_PROD_BRANCHES=分支a,分支b
|
||||
// 临时免确认试跑:SKIP_PROD_DEPLOY_INPUT=true
|
||||
when {
|
||||
expression {
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
# Casdoor JWT 验签三件套
|
||||
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 OAuth
|
||||
CASDOOR_BASE_URL=http://192.168.100.230:8870
|
||||
CASDOOR_CLIENT_ID=758be5fcba2df784fdb4
|
||||
CASDOOR_CLIENT_SECRET=522161bea5bb4f90b63f77c41dc26d223f1244ab
|
||||
# CASDOOR_REDIRECT_URI=http://localhost:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
|
||||
# 是否保留本地密码登录/本地JWT兼容(按你当前需求建议保留)
|
||||
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
|
||||
|
||||
DATABASE_URL=postgresql://postgres:@localhost:5432/hxops_db
|
||||
|
||||
# SiliconFlow API Configuration
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
@@ -1,94 +0,0 @@
|
||||
# hxops backend — template for secrets / local Flask (optional).
|
||||
#
|
||||
# Jenkins / docker-compose 部署时,真正被加载的是「仓库根目录」的 .env.prod / .env.dev
|
||||
#(见 scripts/deploy_compose.sh 与 docker-compose.yml 里 hxops-backend.env_file)。
|
||||
# 本文件仅作字段说明;可复制关键项到根目录 .env.prod,或复制到服务器上的 backend/.env(挂载进容器,供 dotenv 与后台持久化配置)。
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Core
|
||||
# -----------------------------------------------------------------------------
|
||||
SECRET_KEY=replace-with-strong-random-secret
|
||||
DATABASE_URL=postgresql://<db_user>:<db_password>@<db_host>:5432/<db_name>
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Dify
|
||||
# -----------------------------------------------------------------------------
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
DIFY_API_KEY=replace-with-default-dify-api-key
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Redis
|
||||
# -----------------------------------------------------------------------------
|
||||
REDIS_URL=redis://:<redis_password>@<redis_host>:6379/0
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Feature switches
|
||||
# -----------------------------------------------------------------------------
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Optional integrations
|
||||
# -----------------------------------------------------------------------------
|
||||
HR_WORKFLOW_IFRAME_URL=https://<your-hr-workflow-url>
|
||||
HR_WORKFLOW_API_BASE=https://<your-hr-workflow-api-base>
|
||||
HR_WORKFLOW_API_KEY=
|
||||
|
||||
INTEGRATION_API_BASE=https://<your-integration-api-base>
|
||||
INTEGRATION_API_KEY=
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# WeCom OAuth
|
||||
# -----------------------------------------------------------------------------
|
||||
WECOM_ENABLED=true
|
||||
WECOM_CORP_ID=wwxxxxxxxxxxxxxxxx
|
||||
WECOM_AGENT_ID=1000001
|
||||
WECOM_SECRET=replace-with-wecom-app-secret
|
||||
WECOM_REDIRECT_URI=https://<your-domain>/workspace
|
||||
# Optional: public HTTPS origin for WeCom console URLs (admin copy helper). Overrides notify base and request host when set.
|
||||
WECOM_PUBLIC_BASE_URL=https://<your-domain>
|
||||
|
||||
# Login strategy:
|
||||
# - Match existing local account first.
|
||||
# - If no match, block login and require admin provision/binding.
|
||||
WECOM_AUTO_CREATE_USER=false
|
||||
WECOM_MATCH_RULES=employee_id,mobile
|
||||
WECOM_MATCH_OPERATOR=AND
|
||||
|
||||
# Employee id source options:
|
||||
# - userid (default)
|
||||
# - extattr:<name> (from WeCom custom attributes)
|
||||
# - any direct field name returned by user/get
|
||||
WECOM_EMPLOYEE_ID_SOURCE=userid
|
||||
WECOM_MOBILE_NORMALIZE=true
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_ENCODING_AES_KEY=
|
||||
WECOM_CALLBACK_URL=https://<your-domain>/api/user/wecom/callback
|
||||
WECOM_HOMEPAGE_URL=https://<your-domain>/workspace
|
||||
WECOM_TRUSTED_DOMAIN=<your-domain>
|
||||
|
||||
# WeCom notify/deeplink
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
WECOM_NOTIFY_BASE_URL=https://<your-domain>
|
||||
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Casdoor (password + OAuth). When frontend auth.wecom.loginViaCasdoor=true, WeCom login uses Casdoor only.
|
||||
# -----------------------------------------------------------------------------
|
||||
# Casdoor 控制台地址
|
||||
CASDOOR_BASE_URL=http://192.168.100.230:8870
|
||||
CASDOOR_CLIENT_ID=<application-client-id>
|
||||
CASDOOR_CLIENT_SECRET=<application-secret>
|
||||
# 兜底 redirect_uri;实际登录会以浏览器地址为准,以下两条都要在 Casdoor Application → Redirect URLs 里添加:
|
||||
# http://192.168.100.230:8881/casdoor-callback
|
||||
# http://ai.well-trust.com:8881/casdoor-callback
|
||||
CASDOOR_REDIRECT_URI=http://192.168.100.230:8881/casdoor-callback
|
||||
CASDOOR_SCOPE=openid profile email
|
||||
|
||||
# Provider「Name」与 Casdoor 控制台一致(示例:Name=wecom,Display name=企业微信,Organization=organization_HX)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
# Optional: append silentSignin=1 on authorize URL (Casdoor version dependent).
|
||||
CASDOOR_WECOM_SILENT_SIGNIN=false
|
||||
|
||||
AUTH_JWT_ISSUER=http://192.168.100.230:8870
|
||||
AUTH_JWT_AUDIENCE=<same-as-client-id-or-as-configured>
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
+35
-7
@@ -1,17 +1,45 @@
|
||||
FROM python:3.12-slim-bookworm
|
||||
ARG PYTHON_BASE_IMAGE=python:3.12-slim
|
||||
FROM ${PYTHON_BASE_IMAGE}
|
||||
|
||||
ARG APT_MIRROR=https://mirrors.aliyun.com
|
||||
ARG PIP_INDEX_URL=https://mirrors.aliyun.com/pypi/simple
|
||||
ARG PIP_EXTRA_INDEX_URL
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Oracle Instant Client runtime dependencies for thick mode.
|
||||
# `libaio1` is available on Debian bookworm, while newer variants may expose `libaio1t64`.
|
||||
RUN apt-get update \
|
||||
&& (apt-get install -y --no-install-recommends libaio1 libnsl2 \
|
||||
|| apt-get install -y --no-install-recommends libaio1t64 libnsl2) \
|
||||
RUN set -eux; \
|
||||
if [ -f /etc/apt/sources.list.d/debian.sources ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list.d/debian.sources; \
|
||||
fi; \
|
||||
if [ -f /etc/apt/sources.list ]; then \
|
||||
sed -i "s|http://deb.debian.org/debian|${APT_MIRROR}/debian|g" /etc/apt/sources.list; \
|
||||
sed -i "s|http://deb.debian.org/debian-security|${APT_MIRROR}/debian-security|g" /etc/apt/sources.list; \
|
||||
fi; \
|
||||
apt-get update && apt-get install -y \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libxcb1 \
|
||||
libx11-6 \
|
||||
libxext6 \
|
||||
libreoffice \
|
||||
fonts-noto-cjk \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install Python dependencies
|
||||
COPY backend/requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
RUN set -eux; \
|
||||
PIP_ARGS="--no-cache-dir --retries 10 --timeout 60"; \
|
||||
if [ -n "${PIP_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --index-url ${PIP_INDEX_URL}"; \
|
||||
fi; \
|
||||
if [ -n "${PIP_EXTRA_INDEX_URL:-}" ]; then \
|
||||
PIP_ARGS="$PIP_ARGS --extra-index-url ${PIP_EXTRA_INDEX_URL}"; \
|
||||
fi; \
|
||||
pip install $PIP_ARGS -r requirements.txt && \
|
||||
pip uninstall -y opencv-python && \
|
||||
pip install $PIP_ARGS opencv-python-headless && \
|
||||
python -c "import networkx, openpyxl"
|
||||
|
||||
# Copy backend code and the Text2SQL schema required at runtime
|
||||
COPY backend/ .
|
||||
|
||||
@@ -49,6 +49,8 @@ def create_app(config_name='default'):
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.knowledge_base import knowledge_base_bp
|
||||
from app.api.integration import integration_bp
|
||||
|
||||
# 聊天相关接口
|
||||
app.register_blueprint(chat_bp, url_prefix='/api/chat')
|
||||
@@ -58,6 +60,10 @@ def create_app(config_name='default'):
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库/数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
|
||||
@@ -446,7 +446,7 @@ def test_agent(id):
|
||||
'tested_at': tested_at
|
||||
}), 400
|
||||
|
||||
request_url = DifyService.build_chat_messages_url(base_url)
|
||||
request_url = DifyService._build_chat_messages_url(base_url)
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
|
||||
+37
-16
@@ -4,14 +4,25 @@ backend/app/api/agents.py
|
||||
引用文件:flask, models, decorators
|
||||
逻辑关系:根据当前用户的权限返回其可访问的 Agent 集合
|
||||
"""
|
||||
from flask import Blueprint, jsonify, g
|
||||
from app.models import Agent, User
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
from app import db
|
||||
from app.decorators import _get_current_user # 内部工具函数
|
||||
from app.models import Agent, User
|
||||
|
||||
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
|
||||
agents_bp = Blueprint('agents', __name__)
|
||||
|
||||
|
||||
def _serialize_agent_row(row) -> dict:
|
||||
return {
|
||||
'id': row.id,
|
||||
'name': row.name,
|
||||
'description': row.description,
|
||||
'icon_url': row.icon_url,
|
||||
}
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
def list_user_agents():
|
||||
"""
|
||||
@@ -23,12 +34,27 @@ def list_user_agents():
|
||||
|
||||
# 管理员:返回所有激活的 Agent
|
||||
if user.role == 'admin':
|
||||
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# 普通用户:仅返回多对多关系中已授权的 Agent
|
||||
agents = [a for a in user.agents if a.is_active]
|
||||
agent_rows = [
|
||||
type('AgentRow', (), {
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
})()
|
||||
for a in user.agents
|
||||
if a.is_active
|
||||
]
|
||||
|
||||
# 序列化为前端所需字段
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
|
||||
@agents_bp.route('/public', methods=['GET'])
|
||||
def list_public_agents():
|
||||
@@ -37,17 +63,12 @@ def list_public_agents():
|
||||
用途:登录页面展示
|
||||
"""
|
||||
# 返回所有激活的 Agent,包含基本信息
|
||||
agents = Agent.query.filter_by(is_active=True).order_by(Agent.id.asc()).all()
|
||||
|
||||
data = [
|
||||
{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url,
|
||||
}
|
||||
for a in agents
|
||||
]
|
||||
return jsonify(data)
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([_serialize_agent_row(row) for row in agent_rows])
|
||||
|
||||
|
||||
+186
-27
@@ -43,7 +43,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
return False
|
||||
|
||||
# 显式放行配置中的集成服务主机。
|
||||
integration_base = (current_app.config.get("INTEGRATION_API_BASE") or "").strip()
|
||||
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:
|
||||
@@ -76,8 +76,8 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
headers = {}
|
||||
base_url = current_app.config.get('INTEGRATION_API_BASE', '')
|
||||
api_key = current_app.config.get('INTEGRATION_API_KEY', '')
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
|
||||
def _resolve_latest_integration_url(raw_url: str):
|
||||
dataset_id = ''
|
||||
@@ -280,6 +280,81 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
raise Exception("PDF output not found after conversion")
|
||||
|
||||
|
||||
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',
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'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}'}")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
|
||||
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
if normalized_ext == 'xls':
|
||||
content = _convert_excel_to_xlsx(content, normalized_ext)
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
|
||||
|
||||
@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}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
@@ -292,13 +367,8 @@ def get_chat_sessions():
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
# 聚合查询:按 conversation_id 分组,获取最新时间
|
||||
# 注意:这里简化处理,直接取最新一条记录的 query 作为标题(或者第一条,取决于需求)
|
||||
# 为了性能,这里我们取 max(created_at) 和 max(query) - 这只是一个近似值
|
||||
# 更严谨的做法是先查出 conversation_ids,再查详情。
|
||||
# 这里为了简单,我们假设 query 不为空
|
||||
|
||||
# 修正逻辑:先查出最近的 20 个 conversation_id
|
||||
# 先查出最近活跃的会话,再为每个会话回溯最近一条非空 query 作为标题。
|
||||
# 这样本地表单/确认等“无 query 的助手消息”不会把原始用户问题覆盖成 New Chat。
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
@@ -307,25 +377,27 @@ def get_chat_sessions():
|
||||
agent_id=agent.id
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
# 联表查询获取详细信息,按时间倒序
|
||||
results = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
ChatLog.query
|
||||
).join(
|
||||
ChatLog,
|
||||
(ChatLog.conversation_id == subquery.c.conversation_id) &
|
||||
(ChatLog.created_at == subquery.c.last_active)
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
sessions = []
|
||||
for row in results:
|
||||
if not row.conversation_id:
|
||||
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, # 前端需要 id key
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': row.query[:30] + ('...' if len(row.query) > 30 else '') if row.query else 'New Chat',
|
||||
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
||||
'created_at': row.last_active.isoformat()
|
||||
})
|
||||
|
||||
@@ -401,18 +473,94 @@ def get_chat_messages():
|
||||
|
||||
messages = []
|
||||
for log in logs:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
})
|
||||
}
|
||||
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 = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
data = request.get_json() or {}
|
||||
conversation_id = data.get('conversation_id')
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not conversation_id:
|
||||
import uuid
|
||||
conversation_id = str(uuid.uuid4())
|
||||
|
||||
if not message_type:
|
||||
return jsonify({'error': 'type is required'}), 400
|
||||
|
||||
# 如果 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,
|
||||
conversation_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=conversation_id,
|
||||
query=user_query,
|
||||
answer=content,
|
||||
message_type=message_type,
|
||||
payload=payload
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
@@ -458,10 +606,20 @@ def chat_completions():
|
||||
from app.services.dify import DifyService
|
||||
|
||||
if kb_type == 'ERP知识库':
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.text2sql import Text2SQLService
|
||||
generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id)
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
|
||||
else:
|
||||
generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id)
|
||||
else:
|
||||
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id)
|
||||
else:
|
||||
generator = DifyService.stream_chat(query, user.id, agent, conversation_id)
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
@@ -578,8 +736,8 @@ def preview_excel():
|
||||
"""
|
||||
内网 Excel 预览接口(简版可上线)。
|
||||
说明:
|
||||
- 当前仅支持 xlsx;
|
||||
- xls 返回 415,由前端走下载兜底。
|
||||
- xlsx 直接解析;
|
||||
- xls 先转为 xlsx 后再解析。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
@@ -602,13 +760,13 @@ def preview_excel():
|
||||
limit = 100
|
||||
limit = max(1, min(limit, 300))
|
||||
|
||||
content, _, err = _fetch_preview_source_bytes(file_url)
|
||||
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
|
||||
try:
|
||||
wb = load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
wb = _load_excel_workbook(content, ext)
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[excel-preview] parse workbook failed: %s", e)
|
||||
return jsonify({'error': 'failed to parse excel file'}), 422
|
||||
@@ -673,7 +831,8 @@ def preview_text():
|
||||
if ext and ext not in allowed:
|
||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url)
|
||||
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
|
||||
return jsonify({'error': msg}), code
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
"""
|
||||
backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
def _require_integration_key():
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
if not configured:
|
||||
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
|
||||
if configured != incoming:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
return None
|
||||
|
||||
|
||||
def _integration_base_url() -> str:
|
||||
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||
if explicit:
|
||||
return explicit
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
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,
|
||||
):
|
||||
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)
|
||||
)
|
||||
|
||||
base_url = _integration_base_url()
|
||||
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
||||
markdown_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
|
||||
def _list_files_payload(
|
||||
*,
|
||||
knowledge_base_id: int | None = None,
|
||||
department_id: int | None = None,
|
||||
file_name: str | None = None,
|
||||
) -> list[dict]:
|
||||
normalized_file_name = str(file_name or '').strip().lower()
|
||||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||
|
||||
documents = query.all()
|
||||
payload = []
|
||||
for document in documents:
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
continue
|
||||
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||||
if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower():
|
||||
continue
|
||||
payload.append(_serialize_integration_document(document, version=version))
|
||||
return payload
|
||||
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
if kind == 'source':
|
||||
path = Path(version.source_file_path)
|
||||
filename = version.source_file_name or f'document-{version.document_id}'
|
||||
return path, filename
|
||||
|
||||
preferred = version.cleaned_file_path or version.cleaned_preview_path
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
path = Path(preferred)
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return path, filename
|
||||
|
||||
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
result = _require_integration_key()
|
||||
if result is not None:
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||
def get_file_detail(file_id: int):
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return jsonify({'error': 'Document not found.'}), 404
|
||||
return jsonify(_serialize_integration_document(document))
|
||||
|
||||
|
||||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||
def list_knowledge_bases():
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
q = str(request.args.get('q') or '').strip()
|
||||
|
||||
document_counts = (
|
||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
.group_by(KbDocument.group_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
query = (
|
||||
db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
||||
.filter(KbGroup.is_active.is_(True))
|
||||
.order_by(KbGroup.name.asc())
|
||||
)
|
||||
if department_id is not None:
|
||||
query = query.filter(KbGroup.department_id == department_id)
|
||||
if q:
|
||||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||
|
||||
rows = query.all()
|
||||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||
|
||||
|
||||
@integration_bp.route('/files', methods=['GET'])
|
||||
def list_files():
|
||||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
file_name = request.args.get('file_name')
|
||||
return jsonify({'data': _list_files_payload(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
department_id=department_id,
|
||||
file_name=file_name,
|
||||
)})
|
||||
|
||||
|
||||
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
return jsonify({'data': _list_files_payload(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_name=request.args.get('file_name'),
|
||||
)})
|
||||
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_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:
|
||||
return jsonify({'error': 'remote_document_id is required'}), 400
|
||||
|
||||
record_query = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(KbDifySyncRecord.document_version)
|
||||
.joinedload(KbDocumentVersion.document)
|
||||
.joinedload(KbDocument.group),
|
||||
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
)
|
||||
if dataset_id:
|
||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
if not document:
|
||||
return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404
|
||||
|
||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
def resolve_files_by_dify():
|
||||
data = request.get_json(silent=True) or {}
|
||||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||
if not items:
|
||||
return jsonify({'data': []})
|
||||
|
||||
remote_ids = sorted({
|
||||
str(item.get('remote_document_id') or '').strip()
|
||||
for item in items
|
||||
if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()
|
||||
})
|
||||
dataset_ids = sorted({
|
||||
str(item.get('dataset_id') or '').strip()
|
||||
for item in items
|
||||
if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()
|
||||
})
|
||||
if not remote_ids:
|
||||
return jsonify({'data': []})
|
||||
|
||||
query = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
|
||||
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
|
||||
.options(
|
||||
joinedload(KbDifySyncRecord.document_version)
|
||||
.joinedload(KbDocumentVersion.document)
|
||||
.joinedload(KbDocument.group),
|
||||
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
|
||||
)
|
||||
.filter(
|
||||
KbDocument.is_deleted.is_(False),
|
||||
KbDifySyncRecord.remote_document_id.in_(remote_ids),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
)
|
||||
if dataset_ids:
|
||||
query = query.filter(
|
||||
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
|
||||
)
|
||||
|
||||
records = query.all()
|
||||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||
for record in records:
|
||||
key = (record.dataset_id, record.remote_document_id)
|
||||
records_by_key.setdefault(key, record)
|
||||
records_by_remote.setdefault(record.remote_document_id, record)
|
||||
|
||||
payload = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
requested_dataset_id = str(item.get('dataset_id') or '').strip() or None
|
||||
requested_remote_document_id = str(item.get('remote_document_id') or '').strip()
|
||||
if not requested_remote_document_id:
|
||||
continue
|
||||
record = records_by_key.get((requested_dataset_id, requested_remote_document_id))
|
||||
if record is None and requested_dataset_id is None:
|
||||
record = records_by_remote.get(requested_remote_document_id)
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
payload.append({
|
||||
'request': {
|
||||
'dataset_id': requested_dataset_id,
|
||||
'remote_document_id': requested_remote_document_id,
|
||||
},
|
||||
'found': bool(document),
|
||||
'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None,
|
||||
})
|
||||
return jsonify({'data': payload})
|
||||
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||
def download_file(file_id: int):
|
||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return jsonify({'error': 'Document not found.'}), 404
|
||||
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
return jsonify({'error': 'No version found.'}), 404
|
||||
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
if not path.exists():
|
||||
return jsonify({'error': 'File not found on disk.'}), 404
|
||||
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
File diff suppressed because it is too large.
Load diff
+225
-98
@@ -5,7 +5,7 @@ from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_even
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.auth_jwt import get_current_user as _auth_current_user
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
@@ -147,6 +147,20 @@ def _get_current_user():
|
||||
"""
|
||||
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 _is_wecom_configured():
|
||||
return all([
|
||||
current_app.config.get('WECOM_ENABLED'),
|
||||
@@ -507,6 +521,15 @@ def _clean_str(value):
|
||||
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:
|
||||
@@ -891,7 +914,7 @@ def login():
|
||||
'error_code': 'PASSWORD_LOGIN_DISABLED',
|
||||
}), 403
|
||||
|
||||
try:
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
@@ -919,12 +942,28 @@ def login():
|
||||
_write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_build_login_payload(user, 'password'))
|
||||
|
||||
try:
|
||||
return _attempt_login()
|
||||
except OperationalError as e:
|
||||
print(f"Database connection error: {e}")
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
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)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except DatabaseError as e:
|
||||
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)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
print(f"Login error: {e}")
|
||||
current_app.logger.exception('Login error: %s', e)
|
||||
return jsonify({'error': 'Internal server error'}), 500
|
||||
|
||||
|
||||
@@ -1527,6 +1566,65 @@ def wecom_task_complete():
|
||||
return jsonify(result), 200 if result.get('ok') else 202
|
||||
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
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)),
|
||||
'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')),
|
||||
'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):
|
||||
return jsonify({'error': f'{label}不能为空。'}), 400
|
||||
|
||||
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)
|
||||
return jsonify({'error': str(exc)}), 400
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||||
return jsonify({'error': f'OA 请假提交失败:{exc}'}), 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('/wecom/callback', methods=['GET', 'POST'])
|
||||
def wecom_callback():
|
||||
"""
|
||||
@@ -1720,64 +1818,76 @@ def home():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# Get all agents available to user (including public ones)
|
||||
if user.role == 'admin':
|
||||
agents = db.session.query(Agent).filter_by(is_active=True).all()
|
||||
else:
|
||||
# User permissions
|
||||
agents = user.agents
|
||||
|
||||
# Favorites
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
# Quick Questions (Global + User specific)
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||
).all()
|
||||
|
||||
# Layout
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
|
||||
# Embedded agents
|
||||
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:
|
||||
embedded_agents.append({
|
||||
|
||||
def _load_home_payload():
|
||||
# Get all agents available to user (including public ones)
|
||||
if user.role == 'admin':
|
||||
agent_rows = (
|
||||
db.session.query(Agent.id, Agent.name, Agent.description, Agent.icon_url)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.all()
|
||||
)
|
||||
else:
|
||||
# User permissions
|
||||
agent_rows = [{
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||
})
|
||||
'description': agent.description,
|
||||
'icon_url': agent.icon_url,
|
||||
} for agent in user.agents]
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'language': user.language,
|
||||
'theme_preference': user.theme_preference or 'system',
|
||||
},
|
||||
'agents': [{
|
||||
'id': a.id,
|
||||
'name': a.name,
|
||||
'description': a.description,
|
||||
'icon_url': a.icon_url
|
||||
} for a in agents],
|
||||
'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
|
||||
})
|
||||
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(
|
||||
(QuickQuestion.user_id == user.id) | (QuickQuestion.user_id == None)
|
||||
).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:
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': agent.extra_config.get('iframe_url') if agent.extra_config else None
|
||||
})
|
||||
|
||||
return jsonify({
|
||||
'user': {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'language': user.language,
|
||||
'theme_preference': user.theme_preference or 'system',
|
||||
},
|
||||
'agents': [{
|
||||
'id': a.id if hasattr(a, 'id') else a['id'],
|
||||
'name': a.name if hasattr(a, 'name') else a['name'],
|
||||
'description': a.description if hasattr(a, 'description') else a['description'],
|
||||
'icon_url': a.icon_url if hasattr(a, 'icon_url') else a['icon_url']
|
||||
} 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)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
@@ -1888,41 +1998,45 @@ def user_profile():
|
||||
|
||||
# PUT
|
||||
data = request.get_json() or {}
|
||||
|
||||
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']:
|
||||
return jsonify({'error': 'Invalid theme preference'}), 400
|
||||
user.theme_preference = data['theme_preference']
|
||||
|
||||
# Allow editing email, employee_id, department
|
||||
if 'email' in data:
|
||||
# Check uniqueness
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
user.email = data['email']
|
||||
|
||||
if 'employee_id' in data:
|
||||
# Check uniqueness
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
user.employee_id = data['employee_id']
|
||||
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
|
||||
try:
|
||||
|
||||
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']:
|
||||
return jsonify({'error': 'Invalid theme preference'}), 400
|
||||
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:
|
||||
return jsonify({'error': 'Email already exists'}), 400
|
||||
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:
|
||||
return jsonify({'error': 'Employee ID already exists'}), 400
|
||||
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)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
return jsonify({'error': str(e)}), 500
|
||||
@@ -2055,17 +2169,30 @@ def get_announcements():
|
||||
"""
|
||||
Get active announcements (Public)
|
||||
"""
|
||||
try:
|
||||
anns = db.session.query(Announcement).filter_by(is_active=True).order_by(Announcement.created_at.desc()).all()
|
||||
def _load_announcements():
|
||||
anns = (
|
||||
db.session.query(
|
||||
Announcement.id,
|
||||
Announcement.title,
|
||||
Announcement.content,
|
||||
Announcement.created_at,
|
||||
)
|
||||
.filter(Announcement.is_active.is_(True))
|
||||
.order_by(Announcement.created_at.desc())
|
||||
.all()
|
||||
)
|
||||
return jsonify([{
|
||||
'id': a.id,
|
||||
'title': a.title,
|
||||
'content': a.content,
|
||||
'created_at': a.created_at.isoformat()
|
||||
} for a in anns])
|
||||
except Exception as e:
|
||||
import traceback
|
||||
return jsonify({'error': str(e), 'traceback': traceback.format_exc()}), 500
|
||||
|
||||
try:
|
||||
return _run_db_with_retry(_load_announcements, label='user.announcements')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.announcements retry failed: %s', exc)
|
||||
return jsonify({'error': 'Database connection failed'}), 503
|
||||
|
||||
@user_bp.route('/announcements', methods=['POST'])
|
||||
def create_announcement():
|
||||
|
||||
+56
-29
@@ -6,6 +6,7 @@ from typing import Any, Optional
|
||||
import jwt
|
||||
import requests
|
||||
from flask import current_app, g, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
@@ -156,43 +157,69 @@ def _extract_unverified_claims(token: str) -> dict:
|
||||
|
||||
def _resolve_user_from_claims(claims: dict) -> Optional[User]:
|
||||
# Resolution order keeps compatibility with different token claim conventions.
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = claims.get('user_id') or claims.get('id')
|
||||
if user_id is not None:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = claims.get('preferred_username') or claims.get('username') or claims.get('name')
|
||||
if username:
|
||||
user = db.session.query(User).filter_by(username=str(username)).first()
|
||||
if user:
|
||||
return user
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
|
||||
email = claims.get('email')
|
||||
if email:
|
||||
user = db.session.query(User).filter_by(email=str(email)).first()
|
||||
if user:
|
||||
return user
|
||||
return None
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def _legacy_header_user() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
def _lookup() -> Optional[User]:
|
||||
user_id = request.headers.get('X-User-Id')
|
||||
if user_id:
|
||||
try:
|
||||
user = db.session.get(User, int(user_id))
|
||||
if user:
|
||||
return user
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
username = request.headers.get('X-Username')
|
||||
if username:
|
||||
return db.session.query(User).filter_by(username=username).first()
|
||||
return None
|
||||
|
||||
try:
|
||||
return _lookup()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('[auth_jwt] transient db error when resolving legacy header user, retry with reconnect path=%s err=%s', request.path, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception:
|
||||
current_app.logger.warning('[auth_jwt] failed to dispose engine during legacy user reconnect recovery', exc_info=True)
|
||||
return _lookup()
|
||||
|
||||
|
||||
def get_current_user() -> Optional[User]:
|
||||
|
||||
+84
-54
@@ -1,4 +1,4 @@
|
||||
"""
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
@@ -8,14 +8,55 @@ from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
# Auto-load backend/.env so new shell windows also pick up local settings.
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
load_dotenv(_BACKEND_DIR / '.env')
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _load_environment_files() -> str:
|
||||
"""Load env files from project root with stable priority.
|
||||
|
||||
Priority (low -> high):
|
||||
1. .env.shared
|
||||
2. .env.<ENV_NAME>
|
||||
3. .env.local (only for dev)
|
||||
4. system environment variables (always highest because override=False)
|
||||
"""
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
shared_file = _ROOT_DIR / '.env.shared'
|
||||
if shared_file.exists():
|
||||
load_dotenv(shared_file, override=False)
|
||||
|
||||
env_file = _ROOT_DIR / f'.env.{env_name}'
|
||||
if env_file.exists():
|
||||
load_dotenv(env_file, override=False)
|
||||
|
||||
if env_name == 'dev':
|
||||
local_file = _ROOT_DIR / '.env.local'
|
||||
if local_file.exists():
|
||||
load_dotenv(local_file, override=False)
|
||||
return env_name
|
||||
|
||||
|
||||
ACTIVE_ENV_NAME = _load_environment_files()
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY', 'dev-secret-key')
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
|
||||
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower()
|
||||
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
|
||||
# 数据库连接池配置
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {
|
||||
'pool_size': 20,
|
||||
@@ -24,20 +65,23 @@ class Config:
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL', 'redis://:difyai123456@localhost:6379/0')
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv(
|
||||
'HR_WORKFLOW_IFRAME_URL',
|
||||
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg',
|
||||
)
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv('HR_WORKFLOW_IFRAME_URL')
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
OA_WORKFLOW_WSDL_URL = os.getenv(
|
||||
'OA_WORKFLOW_WSDL_URL',
|
||||
'http://oa.well-trust.com:8888/services/WorkflowService?wsdl',
|
||||
)
|
||||
OA_LEAVE_WORKFLOW_CODE = os.getenv('OA_LEAVE_WORKFLOW_CODE', '879')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE', 'http://192.168.100.230:8891')
|
||||
INTEGRATION_API_MODE = os.getenv('INTEGRATION_API_MODE', 'local').strip().lower()
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
@@ -47,25 +91,22 @@ class Config:
|
||||
WECOM_SECRET = os.getenv('WECOM_SECRET')
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES', 'employee_id,mobile')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR', 'AND').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE', 'match_rules')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE', 'userid')
|
||||
WECOM_MATCH_RULES = os.getenv('WECOM_MATCH_RULES')
|
||||
WECOM_MATCH_OPERATOR = os.getenv('WECOM_MATCH_OPERATOR').upper()
|
||||
WECOM_FIRST_LOGIN_BIND_MODE = os.getenv('WECOM_FIRST_LOGIN_BIND_MODE')
|
||||
WECOM_FIRST_LOGIN_INPUT_FIELDS = os.getenv('WECOM_FIRST_LOGIN_INPUT_FIELDS')
|
||||
WECOM_EMPLOYEE_ID_SOURCE = os.getenv('WECOM_EMPLOYEE_ID_SOURCE')
|
||||
WECOM_MOBILE_NORMALIZE = os.getenv('WECOM_MOBILE_NORMALIZE', 'true').lower() == 'true'
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN', '')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY', '')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL', '')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL', '')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN', '')
|
||||
WECOM_CALLBACK_TOKEN = os.getenv('WECOM_CALLBACK_TOKEN')
|
||||
WECOM_ENCODING_AES_KEY = os.getenv('WECOM_ENCODING_AES_KEY')
|
||||
WECOM_CALLBACK_URL = os.getenv('WECOM_CALLBACK_URL')
|
||||
WECOM_HOMEPAGE_URL = os.getenv('WECOM_HOMEPAGE_URL')
|
||||
WECOM_TRUSTED_DOMAIN = os.getenv('WECOM_TRUSTED_DOMAIN')
|
||||
# Public HTTPS origin for WeCom console URLs (takes priority over notify base + request host).
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL', '')
|
||||
WECOM_PUBLIC_BASE_URL = os.getenv('WECOM_PUBLIC_BASE_URL')
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL', '')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv(
|
||||
'WECOM_NOTIFY_EVENTS',
|
||||
'permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed',
|
||||
)
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS')
|
||||
|
||||
# JWT/Casdoor auth configuration (phase-1 compatible rollout)
|
||||
AUTH_LEGACY_HEADER_ENABLED = os.getenv('AUTH_LEGACY_HEADER_ENABLED', 'true').lower() == 'true'
|
||||
@@ -74,48 +115,37 @@ 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', 'casdoor').strip().lower()
|
||||
AUTH_LOGIN_MODE = os.getenv('AUTH_LOGIN_MODE').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', 'http://192.168.100.230:8870')
|
||||
AUTH_JWT_ISSUER = os.getenv('AUTH_JWT_ISSUER')
|
||||
# JWT 的受众(aud)校验值,后端用它确认“这个 token 是发给哪个应用的”
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE', '758be5fcba2df784fdb4')
|
||||
AUTH_JWT_AUDIENCE = os.getenv('AUTH_JWT_AUDIENCE')
|
||||
# 公钥集合地址(JWKS),后端从这里拉公钥来验签 JWT
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL', 'http://192.168.100.230:8870/.well-known/jwks')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL', 'http://192.168.100.230:8870')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID', '758be5fcba2df784fdb4')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET', '')
|
||||
AUTH_JWT_JWKS_URL = os.getenv('AUTH_JWT_JWKS_URL')
|
||||
CASDOOR_BASE_URL = os.getenv('CASDOOR_BASE_URL')
|
||||
CASDOOR_CLIENT_ID = os.getenv('CASDOOR_CLIENT_ID')
|
||||
CASDOOR_CLIENT_SECRET = os.getenv('CASDOOR_CLIENT_SECRET')
|
||||
# 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',
|
||||
'http://192.168.100.230:8881/casdoor-callback',
|
||||
)
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE', 'openid profile email')
|
||||
CASDOOR_REDIRECT_URI = os.getenv('CASDOOR_REDIRECT_URI')
|
||||
CASDOOR_SCOPE = os.getenv('CASDOOR_SCOPE')
|
||||
# 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_PROVIDER_HINT = os.getenv('CASDOOR_WECOM_PROVIDER_HINT').strip()
|
||||
CASDOOR_WECOM_SILENT_SIGNIN = os.getenv('CASDOOR_WECOM_SILENT_SIGNIN', 'false').lower() == 'true'
|
||||
AUTH_LOCAL_JWT_ISSUER = os.getenv('AUTH_LOCAL_JWT_ISSUER', 'hxops-backend')
|
||||
AUTH_LOCAL_JWT_AUDIENCE = os.getenv('AUTH_LOCAL_JWT_AUDIENCE', 'hxops-frontend')
|
||||
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'))
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||
#'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
|
||||
#'postgresql://postgres:123456@localhost:5432/hxops_db',
|
||||
)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_prod',
|
||||
)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
@@ -127,7 +157,7 @@ class TestingConfig(Config):
|
||||
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'testing': TestingConfig,
|
||||
'test': TestingConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
@@ -8,12 +8,12 @@ container's writable layer is discarded on every ``docker compose up --build``.
|
||||
Storage strategy:
|
||||
|
||||
1. Database (``app_settings`` table) - canonical, always authoritative.
|
||||
2. ``backend/.env`` - best-effort secondary write so local/dev workflows that
|
||||
read the env file directly (or restart without DB access) still see updates.
|
||||
2. ``.env.local`` (dev only) - best-effort secondary write so local/dev
|
||||
workflows that restart without DB access still see updates.
|
||||
3. ``os.environ`` - mirrored on write so legacy ``os.getenv`` consumers stay
|
||||
in sync within the running process.
|
||||
|
||||
On read we merge .env (lowest priority) over DB (highest priority); the DB
|
||||
On read we merge env files (lowest priority) over DB (highest priority); the DB
|
||||
value wins whenever it exists.
|
||||
"""
|
||||
|
||||
@@ -30,7 +30,10 @@ from dotenv import dotenv_values, set_key
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
BACKEND_ENV_PATH = Path(__file__).resolve().parents[1] / '.env'
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
_ROOT_DIR = _BACKEND_DIR.parent
|
||||
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
|
||||
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
|
||||
WECOM_BOOL_KEYS = {
|
||||
'WECOM_ENABLED',
|
||||
'WECOM_AUTO_CREATE_USER',
|
||||
@@ -46,15 +49,26 @@ WECOM_BOOL_KEYS = {
|
||||
|
||||
def _ensure_env_file_exists() -> bool:
|
||||
try:
|
||||
BACKEND_ENV_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
BACKEND_ENV_PATH.write_text('', encoding='utf-8')
|
||||
ROOT_ENV_LOCAL_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not ROOT_ENV_LOCAL_PATH.exists():
|
||||
ROOT_ENV_LOCAL_PATH.write_text('', encoding='utf-8')
|
||||
return True
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot create %s: %s', BACKEND_ENV_PATH, exc)
|
||||
logger.warning('Cannot create %s: %s', ROOT_ENV_LOCAL_PATH, exc)
|
||||
return False
|
||||
|
||||
|
||||
def _normalize_env_name(raw: str | None) -> str:
|
||||
value = (raw or '').strip().lower()
|
||||
if value in ('dev', 'development', ''):
|
||||
return 'dev'
|
||||
if value in ('test', 'testing'):
|
||||
return 'test'
|
||||
if value in ('prod', 'production'):
|
||||
return 'prod'
|
||||
return 'dev'
|
||||
|
||||
|
||||
def _to_env_string(value: object) -> str:
|
||||
if isinstance(value, bool):
|
||||
return 'true' if value else 'false'
|
||||
@@ -147,6 +161,9 @@ def _load_from_db(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
|
||||
|
||||
def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
env_name = _normalize_env_name(os.getenv('ENV_NAME') or os.getenv('FLASK_ENV'))
|
||||
if env_name != 'dev':
|
||||
return True
|
||||
if not values:
|
||||
return True
|
||||
if not _ensure_env_file_exists():
|
||||
@@ -154,26 +171,27 @@ def _persist_to_env_file(values: dict[str, str]) -> bool:
|
||||
ok = True
|
||||
for key, value in values.items():
|
||||
try:
|
||||
set_key(str(BACKEND_ENV_PATH), key, value, quote_mode='auto')
|
||||
set_key(str(ROOT_ENV_LOCAL_PATH), key, value, quote_mode='auto')
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot write %s to %s: %s', key, BACKEND_ENV_PATH, exc)
|
||||
logger.warning('Cannot write %s to %s: %s', key, ROOT_ENV_LOCAL_PATH, exc)
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
|
||||
if not BACKEND_ENV_PATH.exists():
|
||||
return {}
|
||||
try:
|
||||
loaded = dotenv_values(BACKEND_ENV_PATH)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', BACKEND_ENV_PATH, exc)
|
||||
return {}
|
||||
return {
|
||||
key: (value if value is not None else '')
|
||||
for key, value in loaded.items()
|
||||
if key and _matches_prefixes(key, prefixes)
|
||||
}
|
||||
merged: dict[str, str] = {}
|
||||
for env_path in (LEGACY_BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
|
||||
if not env_path.exists():
|
||||
continue
|
||||
try:
|
||||
loaded = dotenv_values(env_path)
|
||||
except OSError as exc:
|
||||
logger.warning('Cannot read %s: %s', env_path, exc)
|
||||
continue
|
||||
for key, value in loaded.items():
|
||||
if key and _matches_prefixes(key, prefixes):
|
||||
merged[key] = value if value is not None else ''
|
||||
return merged
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -188,8 +206,8 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
1. Mirror to ``os.environ`` so the current process picks them up
|
||||
immediately.
|
||||
2. Persist to the database (canonical, survives container rebuilds).
|
||||
3. Best-effort write to ``backend/.env`` so dev workflows that grep the
|
||||
file or restart without DB access keep working.
|
||||
3. In dev only, best-effort write to ``.env.local`` so local restarts
|
||||
without DB access keep working.
|
||||
"""
|
||||
if not values:
|
||||
return {}
|
||||
@@ -205,7 +223,7 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
|
||||
if not db_ok and not file_ok:
|
||||
logger.error(
|
||||
'Failed to persist settings %s to BOTH database and .env file. '
|
||||
'Failed to persist settings %s to BOTH database and .env.local mirror. '
|
||||
'Settings will be lost when the process restarts.',
|
||||
list(persisted.keys()),
|
||||
)
|
||||
@@ -216,8 +234,8 @@ def persist_env_settings(values: dict[str, object]) -> dict[str, str]:
|
||||
def apply_env_settings(prefixes: tuple[str, ...] = ('WECOM_',)) -> dict[str, object]:
|
||||
"""Load settings from the canonical store and apply to ``os.environ``.
|
||||
|
||||
DB values take priority over ``backend/.env`` values; both are merged so
|
||||
keys that only live in the env file (e.g. fresh deploy before any admin
|
||||
DB values take priority over env-file values; both are merged so
|
||||
keys that only live in env files (e.g. fresh deploy before any admin
|
||||
edit) are still honored.
|
||||
"""
|
||||
file_values = _load_from_env_file(prefixes)
|
||||
|
||||
+188
-1
@@ -1,6 +1,6 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index
|
||||
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from app import db
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
@@ -192,6 +192,8 @@ class ChatLog(Base):
|
||||
answer: Mapped[str] = mapped_column(Text)
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
@@ -338,6 +340,191 @@ class AppSetting(Base):
|
||||
)
|
||||
|
||||
|
||||
class KbGroup(Base):
|
||||
"""
|
||||
知识库分组
|
||||
用途:承载数据清洗/知识库管理模块中的分组/知识库
|
||||
"""
|
||||
__tablename__ = 'kb_groups'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
Index('ix_kb_groups_department_active', 'department_id', 'is_active'),
|
||||
Index('ix_kb_groups_dify_dataset_id', 'dify_dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(128), index=True)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
department_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True, index=True)
|
||||
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
dify_dataset_id: Mapped[Optional[str]] = mapped_column(String(128))
|
||||
dify_dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
documents: Mapped[List["KbDocument"]] = relationship(
|
||||
"KbDocument",
|
||||
back_populates="group",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
|
||||
|
||||
class KbDocument(Base):
|
||||
"""
|
||||
知识库逻辑文档
|
||||
用途:表示一个文档条目,不直接等同于某一次上传文件
|
||||
"""
|
||||
__tablename__ = 'kb_documents'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
Index('ix_kb_documents_group_status', 'group_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[int] = mapped_column(ForeignKey('kb_groups.id'), index=True)
|
||||
title: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
status: Mapped[str] = mapped_column(String(32), default='draft', index=True)
|
||||
source_type: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
is_deleted: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
group: Mapped["KbGroup"] = relationship("KbGroup", back_populates="documents")
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
updated_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[updated_by_id])
|
||||
versions: Mapped[List["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="document",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDocumentVersion.version_no)",
|
||||
)
|
||||
|
||||
|
||||
class KbDocumentVersion(Base):
|
||||
"""
|
||||
知识库文档版本
|
||||
用途:记录每次上传、清洗、同步产生的版本信息
|
||||
"""
|
||||
__tablename__ = 'kb_document_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
Index('ix_kb_document_versions_doc_status', 'document_id', 'status'),
|
||||
Index('ix_kb_document_versions_sha256', 'sha256'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
document_id: Mapped[int] = mapped_column(ForeignKey('kb_documents.id'), index=True)
|
||||
version_no: Mapped[int] = mapped_column(Integer)
|
||||
status: Mapped[str] = mapped_column(String(32), default='uploaded', index=True)
|
||||
is_current: Mapped[bool] = mapped_column(Boolean, default=True, index=True)
|
||||
source_file_name: Mapped[str] = mapped_column(String(255))
|
||||
source_file_path: Mapped[str] = mapped_column(Text)
|
||||
source_file_ext: Mapped[Optional[str]] = mapped_column(String(32))
|
||||
source_file_size: Mapped[Optional[int]] = mapped_column(Integer)
|
||||
cleaned_file_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
cleaned_preview_path: Mapped[Optional[str]] = mapped_column(Text)
|
||||
sha256: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
word_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
warnings_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
uploaded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
converted_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
document: Mapped["KbDocument"] = relationship("KbDocument", back_populates="versions")
|
||||
uploaded_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[uploaded_by_id])
|
||||
jobs: Mapped[List["KbJob"]] = relationship(
|
||||
"KbJob",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
)
|
||||
sync_records: Mapped[List["KbDifySyncRecord"]] = relationship(
|
||||
"KbDifySyncRecord",
|
||||
back_populates="document_version",
|
||||
cascade="all, delete-orphan",
|
||||
order_by="desc(KbDifySyncRecord.updated_at)",
|
||||
)
|
||||
|
||||
|
||||
class KbJob(Base):
|
||||
"""
|
||||
知识库后台任务
|
||||
用途:记录上传、清洗、同步等后台任务执行情况
|
||||
"""
|
||||
__tablename__ = 'kb_jobs'
|
||||
__table_args__ = (
|
||||
Index('ix_kb_jobs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
job_type: Mapped[str] = mapped_column(String(32), index=True)
|
||||
status: Mapped[str] = mapped_column(String(32), default='queued', index=True)
|
||||
queue_job_id: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
progress: Mapped[int] = mapped_column(Integer, default=0)
|
||||
message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
payload_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
result_json: Mapped[Optional[dict]] = mapped_column(JSON)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
|
||||
created_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[created_by_id])
|
||||
document_version: Mapped[Optional["KbDocumentVersion"]] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="jobs",
|
||||
)
|
||||
|
||||
|
||||
class KbDifySyncRecord(Base):
|
||||
"""
|
||||
知识库 Dify 同步记录
|
||||
用途:记录本地文档版本与 Dify 远端文档之间的同步映射
|
||||
"""
|
||||
__tablename__ = 'kb_dify_sync_records'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote'
|
||||
),
|
||||
Index('ix_kb_dify_sync_records_dataset_id', 'dataset_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'))
|
||||
document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_documents.id'))
|
||||
document_version_id: Mapped[int] = mapped_column(ForeignKey('kb_document_versions.id'), index=True)
|
||||
dataset_id: Mapped[str] = mapped_column(String(128))
|
||||
dataset_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
remote_document_id: Mapped[str] = mapped_column(String(128))
|
||||
remote_document_name: Mapped[Optional[str]] = mapped_column(String(255))
|
||||
status: Mapped[str] = mapped_column(String(32), default='pending', index=True)
|
||||
sync_hash: Mapped[Optional[str]] = mapped_column(String(64))
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text)
|
||||
synced_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'))
|
||||
synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
document_version: Mapped["KbDocumentVersion"] = relationship(
|
||||
"KbDocumentVersion",
|
||||
back_populates="sync_records",
|
||||
)
|
||||
synced_by: Mapped[Optional["User"]] = relationship("User", foreign_keys=[synced_by_id])
|
||||
|
||||
|
||||
class WecomCallbackAudit(Base):
|
||||
"""
|
||||
企业微信回调审计表
|
||||
|
||||
@@ -24,6 +24,7 @@ chat.py (/api/chat/completions)
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
@@ -38,22 +39,53 @@ class DifyService:
|
||||
"""Dify service wrapper."""
|
||||
|
||||
@staticmethod
|
||||
def build_chat_messages_url(raw_base_url: str) -> str:
|
||||
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
|
||||
"""
|
||||
统一构建 Dify chat-messages URL,兼容以下输入:
|
||||
- http(s)://host
|
||||
- http(s)://host/v1
|
||||
- http(s)://host/chat-messages
|
||||
- http(s)://host/v1/chat-messages
|
||||
Dify 只接受标准 UUID 会话 ID。
|
||||
本项目里 ERP Text2SQL 会生成 `erp_xxx` 形式的本地会话号,
|
||||
这类值不能继续透传给 Dify,否则会触发 400 invalid_param。
|
||||
"""
|
||||
base_url = (raw_base_url or '').strip().rstrip('/')
|
||||
if not base_url:
|
||||
return ''
|
||||
if base_url.endswith('/v1/chat-messages') or base_url.endswith('/chat-messages'):
|
||||
return base_url
|
||||
if base_url.endswith('/v1'):
|
||||
return f'{base_url}/chat-messages'
|
||||
return f'{base_url}/v1/chat-messages'
|
||||
value = str(conversation_id or "").strip()
|
||||
if not value:
|
||||
return ""
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] ignore non-uuid conversation_id for dify: %s",
|
||||
value,
|
||||
)
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _build_chat_messages_url(base_url: str) -> str:
|
||||
"""
|
||||
Build the Dify chat-messages endpoint URL from a base URL.
|
||||
|
||||
Our config/agent base_url may be:
|
||||
- https://api.dify.ai/v1
|
||||
- http://host:port
|
||||
- http://host:port/v1
|
||||
- (user mistake) http://host:port/v1/chat-messages
|
||||
|
||||
This helper normalizes common mistakes and prevents duplicate `/v1/v1/...`.
|
||||
"""
|
||||
base = str(base_url or "").strip().rstrip("/")
|
||||
if not base:
|
||||
# Keep old behavior: downstream will fail with a request error.
|
||||
return "/v1/chat-messages"
|
||||
|
||||
# User mistake hardening: strip endpoint suffix if someone stored it as base_url.
|
||||
if base.endswith("/v1/chat-messages"):
|
||||
base = base[: -len("/v1/chat-messages")].rstrip("/")
|
||||
elif base.endswith("/chat-messages"):
|
||||
base = base[: -len("/chat-messages")].rstrip("/")
|
||||
|
||||
# Config.DIFY_API_BASE defaults to ".../v1". Avoid double "/v1".
|
||||
if base.endswith("/v1"):
|
||||
return f"{base}/chat-messages"
|
||||
return f"{base}/v1/chat-messages"
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||
@@ -78,7 +110,8 @@ class DifyService:
|
||||
"""
|
||||
# Prefer agent-specific base URL; fallback to global config.
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
url = DifyService.build_chat_messages_url(base_url)
|
||||
url = DifyService._build_chat_messages_url(base_url)
|
||||
normalized_conversation_id = DifyService._normalize_dify_conversation_id(conversation_id)
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
@@ -88,7 +121,7 @@ class DifyService:
|
||||
'inputs': {},
|
||||
'query': query,
|
||||
'response_mode': 'streaming',
|
||||
'conversation_id': conversation_id or '',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'user': str(user_id),
|
||||
}
|
||||
|
||||
@@ -99,7 +132,7 @@ class DifyService:
|
||||
getattr(agent, 'id', None),
|
||||
base_url,
|
||||
len(query or ''),
|
||||
conversation_id,
|
||||
normalized_conversation_id or conversation_id,
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
@@ -150,7 +183,7 @@ class DifyService:
|
||||
event,
|
||||
len(data.get('answer', '') or ''),
|
||||
bool(data.get('metadata')),
|
||||
data.get('conversation_id') or conversation_id,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
@@ -185,7 +218,7 @@ class DifyService:
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=''.join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
@@ -198,7 +231,7 @@ class DifyService:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
||||
data.get('conversation_id') or conversation_id,
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
len(''.join(full_answer)),
|
||||
len(retriever_resources),
|
||||
len(attribution_parts),
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from flask import current_app
|
||||
|
||||
|
||||
class HRLeaveSQLServerService:
|
||||
_LEAVE_KEYWORDS = ("年假", "育儿假", "假期", "休假", "请假")
|
||||
_PROCESS_KEYWORDS = (
|
||||
"流程",
|
||||
"如何",
|
||||
"怎么办",
|
||||
"怎么",
|
||||
"申请",
|
||||
"审批",
|
||||
"制度",
|
||||
"规则",
|
||||
"办法",
|
||||
"政策",
|
||||
"指引",
|
||||
"规范",
|
||||
"是什么",
|
||||
)
|
||||
_SELF_KEYWORDS = ("我", "我的", "本人", "自己")
|
||||
_BALANCE_KEYWORDS = (
|
||||
"还剩",
|
||||
"还有",
|
||||
"剩余",
|
||||
"多少",
|
||||
"余额",
|
||||
"可休",
|
||||
"未休",
|
||||
"已休",
|
||||
"总时数",
|
||||
"情况",
|
||||
"记录",
|
||||
"明细",
|
||||
"查询",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def supports(query: str) -> bool:
|
||||
text = (query or "").strip()
|
||||
if not text:
|
||||
return False
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._LEAVE_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS):
|
||||
return False
|
||||
if not any(keyword in text for keyword in HRLeaveSQLServerService._SELF_KEYWORDS):
|
||||
return False
|
||||
if any(keyword in text for keyword in HRLeaveSQLServerService._BALANCE_KEYWORDS):
|
||||
return True
|
||||
return bool(re.search(r"(20\d{2}|今年|去年|本年)", text))
|
||||
|
||||
@staticmethod
|
||||
def _detect_leave_type(query: str) -> str:
|
||||
text = (query or "").strip()
|
||||
if "育儿假" in text:
|
||||
return "childcare"
|
||||
if "年假" in text:
|
||||
return "annual"
|
||||
return "all"
|
||||
|
||||
@staticmethod
|
||||
def _extract_year(query: str) -> int | None:
|
||||
text = (query or "").strip()
|
||||
now_year = datetime.now().year
|
||||
explicit = re.search(r"(20\d{2})", text)
|
||||
if explicit:
|
||||
return int(explicit.group(1))
|
||||
if "今年" in text or "本年" in text:
|
||||
return now_year
|
||||
if "去年" in text:
|
||||
return now_year - 1
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _get_employee_code(user) -> str:
|
||||
employee_code = str(
|
||||
getattr(user, "employee_id", None)
|
||||
or getattr(user, "username", None)
|
||||
or ""
|
||||
).strip()
|
||||
if not employee_code:
|
||||
raise RuntimeError("当前登录用户缺少工号,无法查询 HR 假期数据")
|
||||
return employee_code
|
||||
|
||||
@staticmethod
|
||||
def _pick_driver(pyodbc) -> str:
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
try:
|
||||
import pyodbc
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("pyodbc 未安装,无法连接 HR SQL Server") from exc
|
||||
|
||||
driver = os.getenv("HR_SQLSERVER_DRIVER", "").strip() or cls._pick_driver(pyodbc)
|
||||
server = os.getenv("HR_SQLSERVER_HOST", "192.168.100.191").strip()
|
||||
port = os.getenv("HR_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("HR_SQLSERVER_DATABASE", "NH_N8_HEXIN").strip()
|
||||
username = os.getenv("HR_SQLSERVER_USERNAME", "AI_Knowledge_Base_Hr").strip()
|
||||
password = os.getenv("HR_SQLSERVER_PASSWORD", "hoo-thai@123_AI_HR").strip()
|
||||
encrypt = os.getenv("HR_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("HR_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("HR_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@staticmethod
|
||||
def _build_query(view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, year: int | None):
|
||||
base_sql = f"""
|
||||
SELECT TOP 1
|
||||
c001001 AS department_code,
|
||||
c001002 AS department_name,
|
||||
a008003 AS parent_department_name,
|
||||
c002001 AS employee_id,
|
||||
c002002 AS employee_name,
|
||||
{year_column} AS leave_year,
|
||||
{total_column} AS total_hours,
|
||||
{used_column} AS used_hours,
|
||||
{remaining_column} AS remaining_hours
|
||||
FROM {view_name}
|
||||
WHERE c002001 = ?
|
||||
"""
|
||||
params = []
|
||||
if year is not None:
|
||||
base_sql += f" AND {year_column} = ?\n"
|
||||
params.append(year)
|
||||
base_sql += f"ORDER BY {year_column} DESC"
|
||||
return base_sql.strip(), params
|
||||
|
||||
@classmethod
|
||||
def _query_one(cls, view_name: str, year_column: str, total_column: str, used_column: str, remaining_column: str, employee_code: str, year: int | None):
|
||||
sql, extra_params = cls._build_query(view_name, year_column, total_column, used_column, remaining_column, year)
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
params = [employee_code] + extra_params
|
||||
cursor.execute(sql, params)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return sql, None
|
||||
return sql, {columns[idx]: row[idx] for idx in range(len(columns))}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@staticmethod
|
||||
def _format_number(value):
|
||||
if value is None:
|
||||
return "暂无数据"
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value)
|
||||
|
||||
@classmethod
|
||||
def _format_quota(cls, value) -> str:
|
||||
formatted = cls._format_number(value)
|
||||
if formatted == "暂无数据":
|
||||
return formatted
|
||||
return f"{formatted}天"
|
||||
|
||||
@staticmethod
|
||||
def _resolve_response_year(record: dict | None, requested_year: int | None) -> str:
|
||||
if record and record.get("leave_year") is not None:
|
||||
return str(record["leave_year"])
|
||||
if requested_year is not None:
|
||||
return str(requested_year)
|
||||
return str(datetime.now().year)
|
||||
|
||||
@classmethod
|
||||
def _render_section(cls, title: str, record: dict | None, requested_year: int | None) -> str:
|
||||
response_year = cls._resolve_response_year(record, requested_year)
|
||||
if not record:
|
||||
return (
|
||||
f"### {title}\n\n"
|
||||
f"暂未查询到您 {response_year} 年度的{title}记录。"
|
||||
)
|
||||
remaining = cls._format_quota(record.get("remaining_hours"))
|
||||
return (
|
||||
f"### {title}\n\n"
|
||||
f"您当前{title}剩余额度为 {remaining}。\n"
|
||||
f"- 年度:{response_year}\n"
|
||||
f"- 年度可休:{cls._format_quota(record.get('total_hours'))}\n"
|
||||
f"- 已休:{cls._format_quota(record.get('used_hours'))}\n"
|
||||
f"- 当前剩余:{remaining}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _build_result_text(cls, leave_type: str, requested_year: int | None, annual_result, childcare_result):
|
||||
_, annual_record = annual_result
|
||||
_, childcare_record = childcare_result
|
||||
displayed_records = []
|
||||
if leave_type in ("annual", "all"):
|
||||
displayed_records.append(annual_record)
|
||||
if leave_type in ("childcare", "all"):
|
||||
displayed_records.append(childcare_record)
|
||||
|
||||
intro_year = next(
|
||||
(
|
||||
cls._resolve_response_year(record, requested_year)
|
||||
for record in displayed_records
|
||||
if record
|
||||
),
|
||||
str(requested_year or datetime.now().year),
|
||||
)
|
||||
sections = [
|
||||
f"您好,已为您查询到 {intro_year} 年度假期情况:",
|
||||
]
|
||||
if leave_type in ("annual", "all"):
|
||||
sections.extend(["", cls._render_section("年假", annual_record, requested_year)])
|
||||
if leave_type in ("childcare", "all"):
|
||||
sections.extend(["", cls._render_section("育儿假", childcare_record, requested_year)])
|
||||
sections.extend(
|
||||
[
|
||||
"",
|
||||
"如需继续查询其他假期明细或历史休假记录,请告诉我,我继续帮您核对。",
|
||||
"",
|
||||
'如需发起请假,可点击 <a href="#" class="leave-action-trigger" data-leave-action="start-leave-flow">【点我请假】</a> 或输入 <span class="leave-intent-highlight">“我要请假”</span>。',
|
||||
]
|
||||
)
|
||||
return "\n".join(sections)
|
||||
|
||||
@classmethod
|
||||
def stream_chat(cls, query: str, user, agent, conversation_id: str = None):
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
|
||||
try:
|
||||
employee_code = cls._get_employee_code(user)
|
||||
leave_type = cls._detect_leave_type(query)
|
||||
year = cls._extract_year(query)
|
||||
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已识别为假期查询,正在为您核对假期明细,请稍候...\n'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
annual_result = ("-- 未执行年假查询", None)
|
||||
childcare_result = ("-- 未执行育儿假查询", None)
|
||||
|
||||
if leave_type in ("annual", "all"):
|
||||
annual_result = cls._query_one(
|
||||
view_name="VIEW_D044",
|
||||
year_column="D044001",
|
||||
total_column="D044005",
|
||||
used_column="D044006",
|
||||
remaining_column="D044007",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
if leave_type in ("childcare", "all"):
|
||||
childcare_result = cls._query_one(
|
||||
view_name="VIEW_D072",
|
||||
year_column="d072001",
|
||||
total_column="d072002",
|
||||
used_column="d072003",
|
||||
remaining_column="d072004",
|
||||
employee_code=employee_code,
|
||||
year=year,
|
||||
)
|
||||
|
||||
result_text = cls._build_result_text(leave_type, year, annual_result, childcare_result)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[hr-leave] query done user_id=%s employee_code=%s leave_type=%s year=%s latency_ms=%s",
|
||||
getattr(user, "id", None),
|
||||
employee_code,
|
||||
leave_type,
|
||||
year,
|
||||
latency,
|
||||
)
|
||||
|
||||
from app.models import ChatLog, db
|
||||
|
||||
chat_log_id = None
|
||||
try:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=final_conversation_id,
|
||||
query=query,
|
||||
answer=result_text,
|
||||
tokens_used=0,
|
||||
latency=latency,
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
chat_log_id = chat_log.id
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.error("Failed to log hr leave chat: %s", exc)
|
||||
db.session.rollback()
|
||||
|
||||
end_data = {
|
||||
"event": "message_end",
|
||||
"answer": result_text,
|
||||
"replace_answer": True,
|
||||
"chat_log_id": chat_log_id,
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception("[hr-leave] stream_chat failed query=%s", query)
|
||||
error_data = {
|
||||
"event": "error",
|
||||
"message": str(exc) or "HR 假期查询失败",
|
||||
"conversation_id": final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
@@ -3,9 +3,10 @@ Integration API client for resolving original source-file download links.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
from flask import current_app, has_app_context, has_request_context, request
|
||||
|
||||
from app.config import Config
|
||||
|
||||
@@ -13,6 +14,44 @@ from app.config import Config
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _is_loopback_url(url: str) -> bool:
|
||||
host = (urlparse(str(url or "").strip()).hostname or "").strip().lower()
|
||||
return host in {"127.0.0.1", "localhost", "::1"}
|
||||
|
||||
@staticmethod
|
||||
def get_api_key() -> str:
|
||||
if has_app_context():
|
||||
return str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
|
||||
return str(Config.INTEGRATION_API_KEY or "").strip()
|
||||
|
||||
@staticmethod
|
||||
def get_base_url() -> str:
|
||||
mode = "local"
|
||||
if has_app_context():
|
||||
mode = str(current_app.config.get("INTEGRATION_API_MODE") or "local").strip().lower()
|
||||
configured = str(current_app.config.get("INTEGRATION_API_BASE") or "").strip().rstrip("/")
|
||||
public_base = str(current_app.config.get("WECOM_PUBLIC_BASE_URL") or "").strip().rstrip("/")
|
||||
else:
|
||||
mode = str(getattr(Config, "INTEGRATION_API_MODE", "local") or "local").strip().lower()
|
||||
configured = str(Config.INTEGRATION_API_BASE or "").strip().rstrip("/")
|
||||
public_base = ""
|
||||
|
||||
if mode != "external":
|
||||
# For server-side lookups inside containers/workers, an explicit integration
|
||||
# endpoint is more reliable than a public loopback URL like 127.0.0.1:5002.
|
||||
if configured and (
|
||||
not has_request_context()
|
||||
or IntegrationApiService._is_loopback_url(public_base)
|
||||
):
|
||||
return configured
|
||||
if public_base:
|
||||
return public_base
|
||||
if has_request_context():
|
||||
return request.host_url.rstrip("/")
|
||||
|
||||
return configured
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
@@ -60,8 +99,8 @@ class IntegrationApiService:
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return None
|
||||
|
||||
@@ -82,7 +121,7 @@ class IntegrationApiService:
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
return None
|
||||
|
||||
@@ -121,8 +160,8 @@ class IntegrationApiService:
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
@@ -136,7 +175,7 @@ class IntegrationApiService:
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if current_app:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
@@ -187,7 +226,7 @@ class IntegrationApiService:
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
if has_app_context():
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
# Fallback to single lookup when batch call errors.
|
||||
for item in unresolved:
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
"""
|
||||
知识库清洗服务包
|
||||
"""
|
||||
@@ -0,0 +1,305 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
def get_document(self, *, dataset_id: str, document_id: str) -> dict:
|
||||
return self._request('GET', f'/datasets/{dataset_id}/documents/{document_id}')
|
||||
|
||||
def delete_document(self, *, dataset_id: str, document_id: str) -> None:
|
||||
self._request(
|
||||
'DELETE',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}',
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def _is_remote_document_missing(error_text: str) -> bool:
|
||||
return (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
|
||||
try:
|
||||
payload = service.get_document(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
)
|
||||
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 document.title
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
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 document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
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,
|
||||
)
|
||||
.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='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
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
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
|
||||
|
||||
def delete_document_from_dify(document_id: int) -> dict:
|
||||
records = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document_id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
KbDifySyncRecord.dataset_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.all()
|
||||
)
|
||||
if not records:
|
||||
return {'deleted': True, 'remote_document_count': 0}
|
||||
|
||||
service = KbDifySyncService()
|
||||
deleted_count = 0
|
||||
visited: set[tuple[str, str]] = set()
|
||||
|
||||
for record in records:
|
||||
key = (str(record.dataset_id), str(record.remote_document_id))
|
||||
if key in visited:
|
||||
continue
|
||||
visited.add(key)
|
||||
try:
|
||||
service.delete_document(dataset_id=key[0], document_id=key[1])
|
||||
except KbDifySyncError as exc:
|
||||
if not _is_remote_document_missing(str(exc)):
|
||||
raise
|
||||
record.status = 'deleted'
|
||||
record.error_message = None
|
||||
record.synced_at = datetime.utcnow()
|
||||
deleted_count += 1
|
||||
|
||||
db.session.commit()
|
||||
return {'deleted': True, 'remote_document_count': deleted_count}
|
||||
@@ -0,0 +1,242 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/dify_sync_service.py
|
||||
文件用途:知识库文档版本到 Dify 的最小同步服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocumentVersion, KbGroup
|
||||
from app.services.knowledge_cleaning.settings_service import get_kb_dify_settings
|
||||
|
||||
|
||||
class KbDifySyncError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class KbDifySyncService:
|
||||
def __init__(self) -> None:
|
||||
settings = get_kb_dify_settings()
|
||||
self.base_url = str(settings.get('DIFY_API_BASE') or '').rstrip('/')
|
||||
self.api_key = str(settings.get('DIFY_API_KEY') or '').strip()
|
||||
self.permission = str(settings.get('KB_DIFY_PERMISSION') or 'only_me')
|
||||
self.indexing_technique = str(settings.get('KB_DIFY_INDEXING_TECHNIQUE') or 'high_quality')
|
||||
self.search_method = str(settings.get('KB_DIFY_SEARCH_METHOD') or 'semantic_search')
|
||||
self.doc_form = str(settings.get('KB_DIFY_DOC_FORM') or 'text_model')
|
||||
self.timeout = 60
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
if not self.base_url:
|
||||
raise KbDifySyncError('DIFY_API_BASE 未配置')
|
||||
if not self.api_key:
|
||||
raise KbDifySyncError('DIFY_API_KEY 未配置')
|
||||
return {
|
||||
'Authorization': f'Bearer {self.api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
def _request(self, method: str, path: str, **kwargs):
|
||||
url = f'{self.base_url}{path}'
|
||||
try:
|
||||
response = requests.request(
|
||||
method,
|
||||
url,
|
||||
headers=self._headers(),
|
||||
timeout=self.timeout,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise KbDifySyncError(f'Dify API {method} {path} 请求失败: {exc}') from exc
|
||||
if response.status_code >= 400:
|
||||
raise KbDifySyncError(
|
||||
f'Dify API {method} {path} failed: {response.status_code} {response.text}'
|
||||
)
|
||||
if response.status_code == 204:
|
||||
return None
|
||||
return response.json()
|
||||
|
||||
def list_datasets(self) -> list[dict]:
|
||||
payload = self._request('GET', '/datasets')
|
||||
return payload.get('data', []) if isinstance(payload, dict) else []
|
||||
|
||||
def create_dataset(self, *, name: str, description: str | None) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'description': description or '',
|
||||
'permission': self.permission,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'retrieval_model': {
|
||||
'search_method': self.search_method,
|
||||
'reranking_enable': False,
|
||||
'top_k': 3,
|
||||
'score_threshold_enabled': False,
|
||||
'score_threshold': None,
|
||||
},
|
||||
}
|
||||
return self._request('POST', '/datasets', json=payload)
|
||||
|
||||
def ensure_dataset(self, group: KbGroup) -> tuple[str, str]:
|
||||
if group.dify_dataset_id:
|
||||
return group.dify_dataset_id, group.dify_dataset_name or group.name
|
||||
|
||||
dataset_name = group.dify_dataset_name or group.name
|
||||
existing = next((item for item in self.list_datasets() if item.get('name') == dataset_name), None)
|
||||
if existing:
|
||||
group.dify_dataset_id = existing.get('id')
|
||||
group.dify_dataset_name = existing.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
created = self.create_dataset(name=dataset_name, description=group.description)
|
||||
group.dify_dataset_id = created.get('id')
|
||||
group.dify_dataset_name = created.get('name') or dataset_name
|
||||
db.session.commit()
|
||||
return group.dify_dataset_id, group.dify_dataset_name
|
||||
|
||||
def create_document_by_text(self, *, dataset_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'indexing_technique': self.indexing_technique,
|
||||
'doc_form': self.doc_form,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request('POST', f'/datasets/{dataset_id}/document/create-by-text', json=payload)
|
||||
|
||||
def update_document_by_text(self, *, dataset_id: str, document_id: str, name: str, text: str) -> dict:
|
||||
payload = {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'process_rule': {'mode': 'automatic'},
|
||||
}
|
||||
return self._request(
|
||||
'POST',
|
||||
f'/datasets/{dataset_id}/documents/{document_id}/update-by-text',
|
||||
json=payload,
|
||||
)
|
||||
|
||||
|
||||
def _load_sync_text(version: KbDocumentVersion) -> tuple[str, str]:
|
||||
candidate_paths = [version.cleaned_file_path, version.cleaned_preview_path, version.source_file_path]
|
||||
for value in candidate_paths:
|
||||
if not value:
|
||||
continue
|
||||
path = Path(value)
|
||||
if not path.exists():
|
||||
continue
|
||||
text = path.read_text(encoding='utf-8', errors='ignore').strip()
|
||||
if text:
|
||||
return text, str(path)
|
||||
raise KbDifySyncError('没有可用于同步的文本结果')
|
||||
|
||||
|
||||
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
|
||||
version = db.session.get(KbDocumentVersion, document_version_id)
|
||||
if not version or not version.document or not version.document.group:
|
||||
raise KbDifySyncError('文档版本或关联分组不存在')
|
||||
|
||||
group = version.document.group
|
||||
document = version.document
|
||||
text, source_path = _load_sync_text(version)
|
||||
sync_hash = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
service = KbDifySyncService()
|
||||
dataset_id, dataset_name = service.ensure_dataset(group)
|
||||
|
||||
existing_record = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter(
|
||||
KbDifySyncRecord.document_id == document.id,
|
||||
KbDifySyncRecord.remote_document_id.isnot(None),
|
||||
)
|
||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
remote_document_id = None
|
||||
remote_document_name = None
|
||||
if existing_record and existing_record.sync_hash == sync_hash:
|
||||
remote_document_id = existing_record.remote_document_id
|
||||
remote_document_name = existing_record.remote_document_name
|
||||
elif existing_record and existing_record.dataset_id == dataset_id:
|
||||
try:
|
||||
payload = service.update_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
document_id=existing_record.remote_document_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
except KbDifySyncError as exc:
|
||||
error_text = str(exc)
|
||||
remote_missing = (
|
||||
'404' in error_text
|
||||
and ('Document not found' in error_text or '"code":"not_found"' in error_text)
|
||||
)
|
||||
if not remote_missing:
|
||||
raise
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
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 document.title
|
||||
else:
|
||||
payload = service.create_document_by_text(
|
||||
dataset_id=dataset_id,
|
||||
name=document.title,
|
||||
text=text,
|
||||
)
|
||||
remote_document_id = payload.get('document', {}).get('id') or payload.get('id')
|
||||
remote_document_name = payload.get('document', {}).get('name') or document.title
|
||||
|
||||
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,
|
||||
)
|
||||
.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='synced',
|
||||
sync_hash=sync_hash,
|
||||
synced_by_id=synced_by_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
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
|
||||
|
||||
record.synced_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return {
|
||||
'dataset_id': dataset_id,
|
||||
'dataset_name': dataset_name,
|
||||
'remote_document_id': remote_document_id,
|
||||
'remote_document_name': remote_document_name,
|
||||
'sync_hash': sync_hash,
|
||||
'source_path': source_path,
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/edkb_adapter.py
|
||||
文件用途:edkb_system 轻量适配层
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
TEXT_EXTS = {'.txt', '.md'}
|
||||
|
||||
|
||||
def _find_generated_markdown(output_root: Path) -> Path:
|
||||
# Look for md files directly inside output_root or inside any of its subdirectories
|
||||
# Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir
|
||||
candidates = [path for path in output_root.rglob('*.md') if not path.name.startswith('_')]
|
||||
if not candidates:
|
||||
raise RuntimeError('No markdown output produced by edkb_system.')
|
||||
candidates.sort(key=lambda item: len(item.parts))
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
content = source_path.read_text(encoding='utf-8', errors='ignore')
|
||||
cleaned_path.write_text(content, encoding='utf-8')
|
||||
return {
|
||||
'mode': 'plain_text',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(cleaned_path),
|
||||
'word_count': len(content.split()),
|
||||
}
|
||||
|
||||
|
||||
def build_clean_result(source_path: Path, target_dir: Path) -> dict:
|
||||
"""
|
||||
优先产出真实文本结果:
|
||||
- txt/md:直接抽取文本;
|
||||
- 其它格式:尝试走 edkb_system;
|
||||
- 失败时由调用方决定是否回退。
|
||||
"""
|
||||
suffix = source_path.suffix.lower()
|
||||
if suffix in TEXT_EXTS:
|
||||
return _write_text_result(source_path, target_dir)
|
||||
|
||||
from edkb_system.config import SystemConfig
|
||||
from edkb_system.controller import build_knowledge
|
||||
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='edkb_', dir=str(target_dir.parent)) as tmp_dir:
|
||||
tmp_root = Path(tmp_dir)
|
||||
output_dir = tmp_root / 'output'
|
||||
cache_dir = tmp_root / 'cache'
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# IMPORTANT: copy the source file into tmp_root so that its parent directory is predictable
|
||||
# edkb_system seems to output to output_dir / <parent_dir_name> / <filename>.md
|
||||
# ALSO IMPORTANT: ensure the file has its original suffix, otherwise edkb_system might fail or output nothing
|
||||
original_name = getattr(source_path, "original_filename", None)
|
||||
if not original_name:
|
||||
original_name = source_path.name
|
||||
if "." not in original_name and hasattr(source_path, "suffix_hint"):
|
||||
original_name += source_path.suffix_hint
|
||||
|
||||
tmp_source_path = tmp_root / original_name
|
||||
shutil.copy2(source_path, tmp_source_path)
|
||||
|
||||
config = SystemConfig.load(None)
|
||||
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
|
||||
failures = [item for item in result if item.get('status') == 'failed']
|
||||
if failures:
|
||||
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
|
||||
|
||||
markdown_source = _find_generated_markdown(output_dir)
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
shutil.copy2(markdown_source, cleaned_path)
|
||||
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
|
||||
|
||||
return {
|
||||
'mode': 'edkb_system',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(cleaned_path),
|
||||
'word_count': len(content.split()),
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/queue_service.py
|
||||
文件用途:知识库任务调度最小实现
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import KbJob
|
||||
|
||||
|
||||
def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
最小任务调度器:
|
||||
- sync: 上传后立即在请求内执行;
|
||||
- worker: 仅保留 queued,等待独立 worker 轮询;
|
||||
- manual: 保留 queued,等待管理台手动执行。
|
||||
"""
|
||||
mode = str(current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')).strip().lower()
|
||||
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, 'job_not_found'
|
||||
|
||||
if mode == 'sync':
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if job.job_type == 'clean':
|
||||
return run_clean_job(job_id)
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job_id)
|
||||
return False, f'unsupported_sync_job:{job.job_type}'
|
||||
|
||||
if mode == 'worker':
|
||||
return True, 'queued_for_worker'
|
||||
|
||||
return True, 'queued_manual'
|
||||
|
||||
|
||||
def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
return enqueue_kb_job(job_id)
|
||||
|
||||
|
||||
def process_next_kb_job() -> tuple[bool, str]:
|
||||
job = (
|
||||
db.session.query(KbJob)
|
||||
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
|
||||
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
|
||||
.first()
|
||||
)
|
||||
if not job:
|
||||
return False, 'no_job'
|
||||
|
||||
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
|
||||
|
||||
if job.job_type == 'path_upload':
|
||||
return run_path_upload_job(job.id)
|
||||
return run_clean_job(job.id)
|
||||
|
||||
|
||||
def process_next_clean_job() -> tuple[bool, str]:
|
||||
return process_next_kb_job()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/settings_service.py
|
||||
文件用途:知识库 Dify 设置读写服务
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.env_persistence import persist_env_settings
|
||||
from app.models import AppSetting, KbDifySyncRecord, KbGroup, KbJob, KbDocumentVersion
|
||||
|
||||
|
||||
SETTING_DEFAULTS = {
|
||||
'DIFY_API_BASE': '',
|
||||
'DIFY_API_KEY': '',
|
||||
'KB_DIFY_PERMISSION': 'only_me',
|
||||
'KB_DIFY_INDEXING_TECHNIQUE': 'high_quality',
|
||||
'KB_DIFY_SEARCH_METHOD': 'semantic_search',
|
||||
'KB_DIFY_DOC_FORM': 'text_model',
|
||||
}
|
||||
|
||||
|
||||
def _get_setting_value(key: str) -> str:
|
||||
row = db.session.get(AppSetting, key)
|
||||
if row and row.value is not None:
|
||||
return row.value
|
||||
config_value = current_app.config.get(key)
|
||||
if config_value is not None:
|
||||
return str(config_value)
|
||||
return str(os.getenv(key, SETTING_DEFAULTS.get(key, '')))
|
||||
|
||||
|
||||
def get_kb_dify_settings() -> dict:
|
||||
payload = {key: _get_setting_value(key) for key in SETTING_DEFAULTS}
|
||||
payload['dify_api_configured'] = bool(payload.get('DIFY_API_KEY'))
|
||||
return payload
|
||||
|
||||
|
||||
def save_kb_dify_settings(values: dict[str, object]) -> dict:
|
||||
allowed = {key: values[key] for key in SETTING_DEFAULTS if key in values}
|
||||
persisted = persist_env_settings(allowed)
|
||||
return {
|
||||
**get_kb_dify_settings(),
|
||||
**persisted,
|
||||
'dify_api_configured': bool((persisted.get('DIFY_API_KEY') or _get_setting_value('DIFY_API_KEY')).strip()),
|
||||
}
|
||||
|
||||
|
||||
def get_kb_dify_health_payload() -> dict:
|
||||
settings = get_kb_dify_settings()
|
||||
base_url = settings.get('DIFY_API_BASE') or ''
|
||||
api_key = settings.get('DIFY_API_KEY') or ''
|
||||
|
||||
payload = {
|
||||
'dify_base_url': base_url,
|
||||
'dify_api_configured': bool(api_key),
|
||||
'api': {
|
||||
'configured': bool(api_key),
|
||||
'reachable': False,
|
||||
'dataset_count': None,
|
||||
'error': None,
|
||||
},
|
||||
'local_sync_health': {
|
||||
'dataset_bound_groups': db.session.query(KbGroup).filter(KbGroup.dify_dataset_id.isnot(None)).count(),
|
||||
'sync_records': db.session.query(KbDifySyncRecord).count(),
|
||||
'syncing_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'syncing').count(),
|
||||
'synced_versions': db.session.query(KbDocumentVersion).filter(KbDocumentVersion.status == 'synced').count(),
|
||||
'failed_sync_records': db.session.query(KbDifySyncRecord).filter(KbDifySyncRecord.status == 'failed').count(),
|
||||
'pending_sync_jobs': db.session.query(KbJob).filter(KbJob.job_type == 'sync_dify', KbJob.status == 'queued').count(),
|
||||
},
|
||||
}
|
||||
return payload
|
||||
@@ -0,0 +1,471 @@
|
||||
"""
|
||||
backend/app/services/knowledge_cleaning/tasks.py
|
||||
文件用途:知识库任务执行第一版
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
from flask import current_app
|
||||
from app import db
|
||||
from app.models import KbDocument, KbDocumentVersion, KbJob
|
||||
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
|
||||
from app.services.knowledge_cleaning.dify_sync_service import (
|
||||
KbDifySyncError,
|
||||
sync_document_version_to_dify,
|
||||
)
|
||||
from werkzeug.utils import secure_filename
|
||||
|
||||
|
||||
def _utc_now() -> datetime:
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def _infer_missing_extension(source_path: Path) -> str:
|
||||
if zipfile.is_zipfile(source_path):
|
||||
try:
|
||||
with zipfile.ZipFile(source_path) as archive:
|
||||
names = archive.namelist()
|
||||
except Exception:
|
||||
names = []
|
||||
if any(name.startswith('xl/') for name in names):
|
||||
return '.xlsx'
|
||||
if any(name.startswith('word/') for name in names):
|
||||
return '.docx'
|
||||
if any(name.startswith('ppt/') for name in names):
|
||||
return '.pptx'
|
||||
return '.zip'
|
||||
|
||||
try:
|
||||
header = source_path.read_bytes()[:8]
|
||||
except Exception:
|
||||
return ''
|
||||
if header.startswith(b'\xd0\xcf\x11\xe0'):
|
||||
return '.xls'
|
||||
return ''
|
||||
|
||||
|
||||
def _normalized_source_filename(version: KbDocumentVersion, source_path: Path) -> str:
|
||||
raw_name = Path(version.source_file_name or source_path.name).name
|
||||
if Path(raw_name).suffix:
|
||||
return raw_name
|
||||
|
||||
ext = version.source_file_ext
|
||||
if ext:
|
||||
normalized_ext = ext if str(ext).startswith('.') else f'.{ext}'
|
||||
else:
|
||||
normalized_ext = _infer_missing_extension(source_path)
|
||||
|
||||
return f'{raw_name}{normalized_ext}' if normalized_ext else raw_name
|
||||
|
||||
|
||||
def _hash_file(source_path: Path) -> tuple[str, int]:
|
||||
sha = hashlib.sha256()
|
||||
size = 0
|
||||
with source_path.open('rb') as handle:
|
||||
while True:
|
||||
chunk = handle.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
sha.update(chunk)
|
||||
size += len(chunk)
|
||||
return sha.hexdigest(), size
|
||||
|
||||
|
||||
def _safe_storage_filename(filename: str) -> str:
|
||||
candidate = Path(filename or '').name.strip()
|
||||
if not candidate:
|
||||
return 'uploaded_file'
|
||||
safe_stem = secure_filename(Path(candidate).stem) or 'uploaded_file'
|
||||
suffix = Path(candidate).suffix.lower()
|
||||
return f'{safe_stem}{suffix}'
|
||||
|
||||
|
||||
def _kb_storage_root() -> Path:
|
||||
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return root
|
||||
|
||||
|
||||
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
|
||||
document = (
|
||||
db.session.query(KbDocument)
|
||||
.filter(KbDocument.group_id == group_id, KbDocument.title == title)
|
||||
.first()
|
||||
)
|
||||
if document and document.is_deleted:
|
||||
document.is_deleted = False
|
||||
if document:
|
||||
document.description = description
|
||||
document.updated_by_id = user_id
|
||||
return document
|
||||
|
||||
document = KbDocument(
|
||||
group_id=group_id,
|
||||
title=title,
|
||||
description=description,
|
||||
status='draft',
|
||||
source_type='upload',
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
return document
|
||||
|
||||
|
||||
def _find_existing_active_document(*, group_id: int, title: str) -> KbDocument | None:
|
||||
return (
|
||||
db.session.query(KbDocument)
|
||||
.filter(
|
||||
KbDocument.group_id == group_id,
|
||||
KbDocument.title == title,
|
||||
KbDocument.is_deleted.is_(False),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _next_version_no(document: KbDocument) -> int:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return 1
|
||||
return max(item.version_no for item in versions) + 1
|
||||
|
||||
|
||||
def _register_document_version_from_staged_file(
|
||||
*,
|
||||
group_id: int,
|
||||
relative_path: str,
|
||||
staged_path: Path,
|
||||
original_name: str,
|
||||
user_id: int | None,
|
||||
) -> tuple[KbDocument, KbDocumentVersion, KbJob]:
|
||||
display_name = Path(original_name or relative_path).name or Path(relative_path).name or 'uploaded_file'
|
||||
if _find_existing_active_document(group_id=group_id, title=display_name):
|
||||
raise FileExistsError('上传失败,文件已存在')
|
||||
document = _get_or_create_document(
|
||||
group_id=group_id,
|
||||
title=display_name,
|
||||
description=display_name,
|
||||
user_id=user_id,
|
||||
)
|
||||
version_no = _next_version_no(document)
|
||||
source_file_name = _safe_storage_filename(original_name)
|
||||
ext = Path(source_file_name).suffix.lower().lstrip('.') or None
|
||||
version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}'
|
||||
version_dir.mkdir(parents=True, exist_ok=True)
|
||||
target_path = version_dir / source_file_name
|
||||
shutil.copy2(staged_path, target_path)
|
||||
sha256, file_size = _hash_file(target_path)
|
||||
|
||||
for existing in document.versions:
|
||||
if existing.is_current:
|
||||
existing.is_current = False
|
||||
|
||||
version = KbDocumentVersion(
|
||||
document_id=document.id,
|
||||
version_no=version_no,
|
||||
status='uploaded',
|
||||
is_current=True,
|
||||
source_file_name=source_file_name,
|
||||
source_file_path=str(target_path),
|
||||
source_file_ext=ext,
|
||||
source_file_size=file_size,
|
||||
sha256=sha256,
|
||||
uploaded_by_id=user_id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
|
||||
document.source_type = 'upload'
|
||||
document.status = 'uploaded'
|
||||
document.updated_by_id = user_id
|
||||
|
||||
upload_job = KbJob(
|
||||
job_type='upload',
|
||||
status='success',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=100,
|
||||
message=f'已通过上传路径导入文件:{relative_path}',
|
||||
payload_json={
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
'source_file_size': file_size,
|
||||
},
|
||||
result_json={
|
||||
'sha256': sha256,
|
||||
'stored_path': str(target_path),
|
||||
},
|
||||
created_by_id=user_id,
|
||||
started_at=version.created_at,
|
||||
finished_at=version.created_at,
|
||||
)
|
||||
clean_job = KbJob(
|
||||
job_type='clean',
|
||||
status='queued',
|
||||
group_id=group_id,
|
||||
document_id=document.id,
|
||||
document_version_id=version.id,
|
||||
progress=0,
|
||||
message='等待清洗任务执行',
|
||||
payload_json={
|
||||
'document_version_id': version.id,
|
||||
'source_file_name': source_file_name,
|
||||
'relative_path': relative_path,
|
||||
},
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.session.add(upload_job)
|
||||
db.session.add(clean_job)
|
||||
db.session.commit()
|
||||
|
||||
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job
|
||||
|
||||
enqueue_clean_job(clean_job.id)
|
||||
return document, version, clean_job
|
||||
|
||||
|
||||
def run_path_upload_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'path_upload':
|
||||
return False, '当前任务不是 path_upload 类型'
|
||||
|
||||
payload = dict(job.payload_json or {})
|
||||
items = list(payload.get('files') or [])
|
||||
total = max(int(payload.get('total_files') or len(items) or 0), 1)
|
||||
result = dict(job.result_json or {})
|
||||
result.setdefault('total', total)
|
||||
result.setdefault('success', 0)
|
||||
result.setdefault('failed', 0)
|
||||
result.setdefault('staged', len(items))
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = min(job.progress or 0, 5)
|
||||
job.message = '后台开始批量导入上传路径文件'
|
||||
job.started_at = job.started_at or _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
success_count = 0
|
||||
fail_count = 0
|
||||
processed = 0
|
||||
|
||||
for item in items:
|
||||
if item.get('status') in ('success', 'failed'):
|
||||
processed += 1
|
||||
if item.get('status') == 'success':
|
||||
success_count += 1
|
||||
else:
|
||||
fail_count += 1
|
||||
continue
|
||||
|
||||
staged_path = Path(str(item.get('staged_path') or ''))
|
||||
item['status'] = 'uploading'
|
||||
item['error'] = None
|
||||
payload['current_file'] = item.get('relative_path') or item.get('original_name')
|
||||
job.payload_json = payload
|
||||
job.message = f'正在导入:{payload["current_file"]}'
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
if not staged_path.exists():
|
||||
raise FileNotFoundError('暂存文件不存在')
|
||||
|
||||
document, version, _clean_job = _register_document_version_from_staged_file(
|
||||
group_id=job.group_id,
|
||||
relative_path=str(item.get('relative_path') or item.get('original_name') or staged_path.name),
|
||||
staged_path=staged_path,
|
||||
original_name=str(item.get('original_name') or staged_path.name),
|
||||
user_id=job.created_by_id,
|
||||
)
|
||||
item['status'] = 'success'
|
||||
item['document_id'] = document.id
|
||||
item['version_id'] = version.id
|
||||
item['error'] = None
|
||||
success_count += 1
|
||||
except Exception as exc:
|
||||
item['status'] = 'failed'
|
||||
item['error'] = str(exc)
|
||||
fail_count += 1
|
||||
|
||||
processed += 1
|
||||
result['success'] = success_count
|
||||
result['failed'] = fail_count
|
||||
result['processed'] = processed
|
||||
result['items'] = items
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = min(int(processed * 100 / total), 100)
|
||||
db.session.commit()
|
||||
|
||||
payload['current_file'] = ''
|
||||
job.payload_json = payload
|
||||
job.result_json = result
|
||||
job.progress = 100
|
||||
job.finished_at = _utc_now()
|
||||
if fail_count > 0:
|
||||
job.status = 'failed'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条,失败 {fail_count} 条'
|
||||
job.error_message = f'部分文件上传失败:{fail_count} 条'
|
||||
db.session.commit()
|
||||
return False, 'partial_failed'
|
||||
|
||||
job.status = 'success'
|
||||
job.message = f'路径上传完成,成功 {success_count} 条'
|
||||
job.error_message = None
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def run_clean_job(job_id: int) -> tuple[bool, str]:
|
||||
"""
|
||||
第一版最小清洗任务执行器。
|
||||
当前先不接 edkb_system,只做以下动作:
|
||||
1. 把 queued 的 clean 任务改为 running/success;
|
||||
2. 为版本生成 cleaned_preview_path;
|
||||
3. 更新版本状态为 cleaned;
|
||||
4. 为下一步接真实清洗链路预留结构。
|
||||
"""
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'clean':
|
||||
return False, '当前任务不是 clean 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
source_path = Path(version.source_file_path)
|
||||
if not source_path.exists():
|
||||
job.status = 'failed'
|
||||
job.error_message = '原始文件不存在,无法执行 clean'
|
||||
version.status = 'failed'
|
||||
version.error_message = '原始文件不存在,无法执行 clean'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '原始文件不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始执行最小清洗任务'
|
||||
job.started_at = _utc_now()
|
||||
version.status = 'processing'
|
||||
db.session.commit()
|
||||
|
||||
target_dir = source_path.parent
|
||||
warnings = []
|
||||
|
||||
try:
|
||||
normalized_name = _normalized_source_filename(version, source_path)
|
||||
staged_source = target_dir / normalized_name
|
||||
if staged_source != source_path:
|
||||
shutil.copy2(source_path, staged_source)
|
||||
source_path = staged_source
|
||||
|
||||
result = build_clean_result(source_path, target_dir)
|
||||
job_message = '真实清洗结果已生成'
|
||||
except Exception as exc:
|
||||
preview_path = target_dir / f'{_normalized_source_filename(version, source_path)}.preview.txt'
|
||||
preview_path.write_text(
|
||||
'\n'.join([
|
||||
f'source_file={source_path.name}',
|
||||
f'source_size={version.source_file_size or 0}',
|
||||
'clean_status=placeholder_success',
|
||||
f'fallback_reason={str(exc)}',
|
||||
]),
|
||||
encoding='utf-8',
|
||||
)
|
||||
result = {
|
||||
'mode': 'placeholder_clean',
|
||||
'cleaned_file_path': None,
|
||||
'cleaned_preview_path': str(preview_path),
|
||||
'word_count': 0,
|
||||
}
|
||||
warnings.append({'message': f'edkb_fallback={str(exc)}'})
|
||||
job_message = 'edkb_system 未就绪,已回退到占位清洗结果'
|
||||
|
||||
version.cleaned_file_path = result.get('cleaned_file_path')
|
||||
version.cleaned_preview_path = result.get('cleaned_preview_path')
|
||||
version.word_count = int(result.get('word_count') or 0)
|
||||
version.status = 'cleaned'
|
||||
version.converted_at = _utc_now()
|
||||
version.error_message = None
|
||||
version.warnings_json = warnings or None
|
||||
if version.document:
|
||||
version.document.status = 'ready'
|
||||
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = job_message
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def run_sync_job(job_id: int) -> tuple[bool, str]:
|
||||
job = db.session.get(KbJob, job_id)
|
||||
if not job:
|
||||
return False, '任务不存在'
|
||||
if job.job_type != 'sync_dify':
|
||||
return False, '当前任务不是 sync_dify 类型'
|
||||
|
||||
version = db.session.get(KbDocumentVersion, job.document_version_id)
|
||||
if not version:
|
||||
job.status = 'failed'
|
||||
job.error_message = '关联文档版本不存在'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, '关联文档版本不存在'
|
||||
|
||||
job.status = 'running'
|
||||
job.progress = 20
|
||||
job.message = '开始同步到 Dify'
|
||||
job.started_at = _utc_now()
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
result = sync_document_version_to_dify(version.id, synced_by_id=job.created_by_id)
|
||||
except KbDifySyncError as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = str(exc)
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
except Exception as exc:
|
||||
version.status = 'ready'
|
||||
job.status = 'failed'
|
||||
job.progress = 100
|
||||
job.error_message = f'同步到 Dify 时发生未预期错误:{exc}'
|
||||
job.message = '同步到 Dify 失败'
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return False, str(exc)
|
||||
|
||||
version.status = 'synced'
|
||||
job.status = 'success'
|
||||
job.progress = 100
|
||||
job.message = '已同步到 Dify'
|
||||
job.error_message = None
|
||||
job.result_json = result
|
||||
job.finished_at = _utc_now()
|
||||
db.session.commit()
|
||||
return True, 'ok'
|
||||
@@ -0,0 +1,354 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
|
||||
SOAP_ENV_NS = 'http://schemas.xmlsoap.org/soap/envelope/'
|
||||
SERVICE_NS = 'webservices.services.weaver.com.cn'
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
XSI_NS = 'http://www.w3.org/2001/XMLSchema-instance'
|
||||
|
||||
NS = {
|
||||
'soapenv': SOAP_ENV_NS,
|
||||
'svc': SERVICE_NS,
|
||||
'wf': WORKFLOW_NS,
|
||||
'xsi': XSI_NS,
|
||||
}
|
||||
|
||||
ET.register_namespace('soapenv', SOAP_ENV_NS)
|
||||
ET.register_namespace('svc', SERVICE_NS)
|
||||
ET.register_namespace('wf', WORKFLOW_NS)
|
||||
ET.register_namespace('xsi', XSI_NS)
|
||||
|
||||
|
||||
class OALeaveWorkflowError(RuntimeError):
|
||||
"""Raised when OA leave workflow submission fails."""
|
||||
|
||||
|
||||
class OALeaveWorkflowService:
|
||||
WORKFLOW_ID = '879'
|
||||
OA_USER_MAP = {
|
||||
'26030025': {'user_id': '21784', 'name': '梁春艳'},
|
||||
'26040006': {'user_id': '21823', 'name': '刘义亮'},
|
||||
}
|
||||
# Keep backend leave labels aligned with the chat form options so OA browser
|
||||
# fields always receive the expected showValue instead of a raw code.
|
||||
LEAVE_TYPE_LABELS = {
|
||||
'005': '事假(小时)',
|
||||
'006': '病假(小时)',
|
||||
'007': '丧假(天)',
|
||||
'010': '年假(天)',
|
||||
'021': '因公出差(小时)',
|
||||
'025': '调休假(小时)',
|
||||
'035': '其他假(小时)',
|
||||
'401': '产假(天)',
|
||||
'402': '陪产假(天)',
|
||||
'403': '婚假(天)',
|
||||
'405': '住院病假(小时)',
|
||||
'406': '工伤假(天)',
|
||||
'408': '育儿假(小时)',
|
||||
'ZZ01': '返乡假(小时)',
|
||||
'ZZ04': '事假(经理专用小时)',
|
||||
'ZZ05': '病假(经理专用小时)',
|
||||
'ZZ07': '丧假(经理专用天)',
|
||||
'ZZ08': '产假(经理专用天)',
|
||||
'ZZ09': '陪产假(经理专用天)',
|
||||
'ZZ10': '婚假(经理专用天)',
|
||||
}
|
||||
ERROR_MESSAGES = {
|
||||
'-1': '创建流程失败',
|
||||
'-2': '用户没有流程创建权限',
|
||||
'-3': '创建流程基本信息失败',
|
||||
'-4': '保存表单主表信息失败',
|
||||
'-5': '更新紧急程度失败',
|
||||
'-6': '流程操作者失败',
|
||||
'-7': '流转至下一节点失败',
|
||||
'-8': '节点附加操作失败',
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _get_wsdl_url(cls) -> str:
|
||||
return (
|
||||
current_app.config.get('OA_WORKFLOW_WSDL_URL')
|
||||
or os.getenv('OA_WORKFLOW_WSDL_URL')
|
||||
or 'http://oa.well-trust.com:8888/services/WorkflowService?wsdl'
|
||||
).strip()
|
||||
|
||||
@classmethod
|
||||
def _get_service_url(cls) -> str:
|
||||
wsdl_url = cls._get_wsdl_url()
|
||||
return wsdl_url[:-5] if wsdl_url.lower().endswith('?wsdl') else wsdl_url
|
||||
|
||||
@classmethod
|
||||
def _request_timeout(cls) -> tuple[int, int]:
|
||||
return (5, 25)
|
||||
|
||||
@classmethod
|
||||
def _post_soap(cls, action: str, body_el: ET.Element) -> ET.Element:
|
||||
envelope = ET.Element(f'{{{SOAP_ENV_NS}}}Envelope')
|
||||
ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Header')
|
||||
body = ET.SubElement(envelope, f'{{{SOAP_ENV_NS}}}Body')
|
||||
body.append(body_el)
|
||||
payload = ET.tostring(envelope, encoding='utf-8', xml_declaration=True)
|
||||
headers = {
|
||||
'Content-Type': 'text/xml; charset=utf-8',
|
||||
'SOAPAction': action,
|
||||
}
|
||||
try:
|
||||
response = requests.post(
|
||||
cls._get_service_url(),
|
||||
data=payload,
|
||||
headers=headers,
|
||||
timeout=cls._request_timeout(),
|
||||
)
|
||||
response.raise_for_status()
|
||||
except requests.RequestException as exc:
|
||||
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
|
||||
try:
|
||||
return ET.fromstring(response.text)
|
||||
except ET.ParseError as exc:
|
||||
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
|
||||
|
||||
@classmethod
|
||||
def resolve_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError('缺少员工工号,无法匹配 OA 用户。')
|
||||
matched = cls.OA_USER_MAP.get(employee_id)
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'工号 {employee_id} 暂未配置 OA userid 映射。')
|
||||
return {
|
||||
'employee_id': employee_id,
|
||||
'user_id': matched['user_id'],
|
||||
'name': (real_name or matched.get('name') or '').strip() or matched['name'],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def resolve_creator_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='请假人')
|
||||
|
||||
@classmethod
|
||||
def resolve_agent_oa_user(cls, employee_id: str | None, real_name: str | None = None) -> dict[str, str]:
|
||||
return cls._resolve_runtime_oa_user(employee_id, real_name, role_label='代理人')
|
||||
|
||||
@classmethod
|
||||
def _resolve_runtime_oa_user(
|
||||
cls,
|
||||
employee_id: str | None,
|
||||
real_name: str | None = None,
|
||||
*,
|
||||
role_label: str,
|
||||
) -> dict[str, str]:
|
||||
employee_id = (employee_id or '').strip()
|
||||
real_name = (real_name or '').strip()
|
||||
if not employee_id:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}工号,无法匹配 OA 用户。')
|
||||
if not real_name:
|
||||
raise OALeaveWorkflowError(f'缺少{role_label}姓名,无法匹配 OA 用户。')
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
matched = OASQLServerService.get_employee_by_name_and_workcode(real_name, employee_id)
|
||||
except Exception as exc:
|
||||
raise OALeaveWorkflowError(f'查询{role_label} OA 用户失败:{exc}') from exc
|
||||
|
||||
if not matched:
|
||||
raise OALeaveWorkflowError(f'未找到{role_label} OA 用户:{real_name}({employee_id})。')
|
||||
|
||||
return {
|
||||
'employee_id': matched['employeeId'],
|
||||
'user_id': matched['uid'],
|
||||
'name': matched['name'],
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def _build_get_template_body(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}getCreateWorkflowRequestInfo')
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in0').text = str(workflow_id)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _get_template_request_info(cls, workflow_id: str, oa_user_id: str) -> ET.Element:
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.getCreateWorkflowRequestInfo'
|
||||
root = cls._post_soap(action, cls._build_get_template_body(workflow_id, oa_user_id))
|
||||
out = root.find('.//svc:out', NS)
|
||||
if out is None or out.attrib.get(f'{{{XSI_NS}}}nil') == 'true' or len(list(out)) == 0:
|
||||
raise OALeaveWorkflowError('OA 未返回建单模板,请确认 workflowId 与 OA userid 是否正确。')
|
||||
return deepcopy(out)
|
||||
|
||||
@classmethod
|
||||
def _find_field(cls, request_info: ET.Element, field_name: str) -> ET.Element | None:
|
||||
for field in request_info.findall('.//wf:WorkflowRequestTableField', NS):
|
||||
if (field.findtext('wf:fieldName', default='', namespaces=NS) or '').strip() == field_name:
|
||||
return field
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def _set_field(
|
||||
cls,
|
||||
request_info: ET.Element,
|
||||
field_name: str,
|
||||
*,
|
||||
value: str | None,
|
||||
show_value: str | None = None,
|
||||
) -> None:
|
||||
field = cls._find_field(request_info, field_name)
|
||||
if field is None:
|
||||
current_app.logger.warning('[oa-leave] field not found in template: %s', field_name)
|
||||
return
|
||||
value_node = field.find('wf:fieldValue', NS)
|
||||
if value_node is None:
|
||||
value_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue')
|
||||
value_node.text = '' if value is None else str(value)
|
||||
|
||||
if show_value is not None:
|
||||
show_node = field.find('wf:fieldShowValue', NS)
|
||||
if show_node is None:
|
||||
show_node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue')
|
||||
show_node.text = str(show_value)
|
||||
|
||||
@classmethod
|
||||
def _set_text(cls, parent: ET.Element, xpath: str, value: str) -> None:
|
||||
node = parent.find(xpath, NS)
|
||||
if node is not None:
|
||||
node.text = value
|
||||
|
||||
@classmethod
|
||||
def _parse_frontend_datetime(cls, raw: str, field_name: str) -> datetime:
|
||||
text = (raw or '').strip().replace('T', ' ')
|
||||
try:
|
||||
return datetime.strptime(text, '%Y-%m-%d %H:%M')
|
||||
except ValueError as exc:
|
||||
raise OALeaveWorkflowError(f'{field_name} 格式不正确,应为 YYYY-MM-DD HH:MM。') from exc
|
||||
|
||||
@classmethod
|
||||
def _build_request_name(cls, creator_name: str, start_dt: datetime) -> str:
|
||||
return f'请假申请单-{creator_name}-{start_dt.strftime("%Y-%m-%d")}'
|
||||
|
||||
@classmethod
|
||||
def _normalize_duration(cls, value: Any) -> str:
|
||||
try:
|
||||
hours = float(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise OALeaveWorkflowError('请假时长格式不正确。') from exc
|
||||
if hours <= 0:
|
||||
raise OALeaveWorkflowError('请假时长必须大于 0。')
|
||||
return f'{hours:.2f}'.rstrip('0').rstrip('.')
|
||||
|
||||
@classmethod
|
||||
def build_request_info(cls, form_data: dict[str, Any], current_user: Any) -> tuple[ET.Element, dict[str, str], dict[str, str], dict[str, str]]:
|
||||
filler_name = (
|
||||
form_data.get('fillerName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
filler = cls._resolve_runtime_oa_user(
|
||||
getattr(current_user, 'employee_id', None),
|
||||
filler_name,
|
||||
role_label='填单人'
|
||||
)
|
||||
|
||||
applicant_name = (
|
||||
form_data.get('applicantName')
|
||||
or getattr(current_user, 'real_name', None)
|
||||
or getattr(current_user, 'username', None)
|
||||
or '当前用户'
|
||||
)
|
||||
applicant = cls.resolve_creator_oa_user(
|
||||
form_data.get('employeeId') or getattr(current_user, 'employee_id', None),
|
||||
applicant_name,
|
||||
)
|
||||
agent = cls.resolve_agent_oa_user(form_data.get('agentEmployeeId'), form_data.get('agentName'))
|
||||
|
||||
workflow_id = str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID)
|
||||
request_info = cls._get_template_request_info(workflow_id, filler['user_id'])
|
||||
|
||||
start_dt = cls._parse_frontend_datetime(form_data.get('startTime'), '开始时间')
|
||||
end_dt = cls._parse_frontend_datetime(form_data.get('endTime'), '结束时间')
|
||||
if end_dt <= start_dt:
|
||||
raise OALeaveWorkflowError('结束时间必须晚于开始时间。')
|
||||
|
||||
leave_type_code = (form_data.get('leaveType') or '').strip()
|
||||
if not leave_type_code:
|
||||
raise OALeaveWorkflowError('缺少假别编码。')
|
||||
leave_type_label = cls.LEAVE_TYPE_LABELS.get(leave_type_code, leave_type_code)
|
||||
request_name = cls._build_request_name(applicant['name'], start_dt)
|
||||
|
||||
cls._set_text(request_info, 'wf:creatorId', filler['user_id'])
|
||||
cls._set_text(request_info, 'wf:creatorName', filler['name'])
|
||||
cls._set_text(request_info, 'wf:requestLevel', '0')
|
||||
cls._set_text(request_info, 'wf:requestName', request_name)
|
||||
cls._set_text(request_info, './/wf:workflowBaseInfo/wf:workflowId', workflow_id)
|
||||
|
||||
cls._set_field(request_info, 'requestname', value=request_name, show_value=request_name)
|
||||
cls._set_field(request_info, 'tdrgh', value=filler['employee_id'], show_value=filler['employee_id'])
|
||||
cls._set_field(request_info, 'sqrgh', value=applicant['employee_id'], show_value=applicant['employee_id'])
|
||||
cls._set_field(request_info, 'tdrxm', value=filler['user_id'], show_value=filler['name'])
|
||||
cls._set_field(request_info, 'sqrxm', value=applicant['user_id'], show_value=applicant['name'])
|
||||
cls._set_field(request_info, 'dlrgh', value=agent['employee_id'], show_value=agent['employee_id'])
|
||||
cls._set_field(request_info, 'dlrxm', value=agent['user_id'], show_value=agent['name'])
|
||||
cls._set_field(request_info, 'dlrlogid', value=agent['user_id'], show_value=agent['user_id'])
|
||||
cls._set_field(request_info, 'jb', value=leave_type_code, show_value=leave_type_label)
|
||||
cls._set_field(request_info, 'jbbh', value=leave_type_code, show_value=leave_type_code)
|
||||
cls._set_field(request_info, 'kssj', value=start_dt.strftime('%Y-%m-%d'), show_value=start_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'kssk', value=start_dt.strftime('%H:%M'), show_value=start_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'jssj', value=end_dt.strftime('%Y-%m-%d'), show_value=end_dt.strftime('%Y-%m-%d'))
|
||||
cls._set_field(request_info, 'jssk', value=end_dt.strftime('%H:%M'), show_value=end_dt.strftime('%H:%M'))
|
||||
cls._set_field(request_info, 'qjsc', value=cls._normalize_duration(form_data.get('durationHours')), show_value=cls._normalize_duration(form_data.get('durationHours')))
|
||||
cls._set_field(request_info, 'sfwgs', value=str(form_data.get('isWorkInjury')), show_value='是' if str(form_data.get('isWorkInjury')) == '0' else '否')
|
||||
cls._set_field(request_info, 'sfwc', value=str(form_data.get('isOutOfOffice')), show_value='是' if str(form_data.get('isOutOfOffice')) == '0' else '否')
|
||||
cls._set_field(request_info, 'bz', value=(form_data.get('remark') or '').strip(), show_value=(form_data.get('remark') or '').strip())
|
||||
|
||||
return request_info, filler, applicant, agent
|
||||
|
||||
@classmethod
|
||||
def _build_create_body(cls, request_info: ET.Element, oa_user_id: str) -> ET.Element:
|
||||
root = ET.Element(f'{{{SERVICE_NS}}}doCreateWorkflowRequest')
|
||||
in0 = deepcopy(request_info)
|
||||
in0.tag = f'{{{SERVICE_NS}}}in0'
|
||||
root.append(in0)
|
||||
ET.SubElement(root, f'{{{SERVICE_NS}}}in1').text = str(oa_user_id)
|
||||
return root
|
||||
|
||||
@classmethod
|
||||
def _parse_create_response(cls, root: ET.Element) -> str:
|
||||
out = root.findtext('.//svc:out', default='', namespaces=NS)
|
||||
out = (out or '').strip()
|
||||
if not out:
|
||||
raise OALeaveWorkflowError('OA 未返回单据编号。')
|
||||
if out in cls.ERROR_MESSAGES:
|
||||
raise OALeaveWorkflowError(cls.ERROR_MESSAGES[out])
|
||||
if out.startswith('-'):
|
||||
raise OALeaveWorkflowError(f'OA 创建流程失败,返回码:{out}')
|
||||
return out
|
||||
|
||||
@classmethod
|
||||
def serialize_request_xml(cls, request_info: ET.Element) -> str:
|
||||
return ET.tostring(request_info, encoding='unicode')
|
||||
|
||||
@classmethod
|
||||
def submit_leave_request(cls, form_data: dict[str, Any], current_user: Any) -> dict[str, Any]:
|
||||
request_info, filler, applicant, agent = cls.build_request_info(form_data, current_user)
|
||||
action = 'urn:weaver.workflow.webservices.WorkflowService.doCreateWorkflowRequest'
|
||||
root = cls._post_soap(action, cls._build_create_body(request_info, filler['user_id']))
|
||||
request_id = cls._parse_create_response(root)
|
||||
return {
|
||||
'ok': True,
|
||||
'request_id': request_id,
|
||||
'request_name': request_info.findtext('wf:requestName', default='', namespaces=NS),
|
||||
'submitted_at': datetime.now().strftime('%Y-%m-%d %H:%M'),
|
||||
'creator': applicant,
|
||||
'filler': filler,
|
||||
'agent': agent,
|
||||
'workflow_id': str(current_app.config.get('OA_LEAVE_WORKFLOW_CODE') or cls.WORKFLOW_ID),
|
||||
'request_xml': cls.serialize_request_xml(request_info),
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import os
|
||||
import pyodbc
|
||||
from flask import current_app
|
||||
|
||||
class OASQLServerService:
|
||||
@staticmethod
|
||||
def _pick_driver():
|
||||
drivers = pyodbc.drivers()
|
||||
preferred = [
|
||||
"ODBC Driver 18 for SQL Server",
|
||||
"ODBC Driver 17 for SQL Server",
|
||||
"SQL Server",
|
||||
]
|
||||
for name in preferred:
|
||||
if name in drivers:
|
||||
return name
|
||||
if not drivers:
|
||||
raise RuntimeError("未找到可用的 SQL Server ODBC 驱动")
|
||||
return drivers[-1]
|
||||
|
||||
@classmethod
|
||||
def _connect(cls):
|
||||
driver = os.getenv("OA_SQLSERVER_DRIVER", "").strip() or cls._pick_driver()
|
||||
server = os.getenv("OA_SQLSERVER_HOST", "192.168.100.225").strip()
|
||||
port = os.getenv("OA_SQLSERVER_PORT", "1433").strip()
|
||||
database = os.getenv("OA_SQLSERVER_DATABASE", "ecology").strip()
|
||||
username = os.getenv("OA_SQLSERVER_USERNAME", "AI_Knowledge_Base_OA").strip()
|
||||
password = os.getenv("OA_SQLSERVER_PASSWORD", "hoo-thai@123_AI_OA").strip()
|
||||
encrypt = os.getenv("OA_SQLSERVER_ENCRYPT", "no").strip().lower()
|
||||
trust_cert = os.getenv("OA_SQLSERVER_TRUST_CERT", "yes").strip().lower()
|
||||
timeout = int(os.getenv("OA_SQLSERVER_TIMEOUT", "10"))
|
||||
|
||||
conn_str = (
|
||||
f"DRIVER={{{driver}}};"
|
||||
f"SERVER={server},{port};"
|
||||
f"DATABASE={database};"
|
||||
f"UID={username};"
|
||||
f"PWD={password};"
|
||||
f"Encrypt={encrypt};"
|
||||
f"TrustServerCertificate={trust_cert};"
|
||||
)
|
||||
return pyodbc.connect(conn_str, timeout=timeout)
|
||||
|
||||
@classmethod
|
||||
def search_employees(cls, keyword: str, page: int, page_size: int):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
offset = (page - 1) * page_size
|
||||
params = []
|
||||
|
||||
# Count total
|
||||
count_sql = "SELECT COUNT(1) FROM userInfo_view WHERE 1=1"
|
||||
if keyword:
|
||||
count_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
like_kw = f"%{keyword}%"
|
||||
params.extend([like_kw, like_kw])
|
||||
|
||||
cursor.execute(count_sql, params)
|
||||
total = cursor.fetchone()[0]
|
||||
|
||||
# Fetch page
|
||||
# Compatible with older SQL Server versions (2008/2012)
|
||||
query_sql = """
|
||||
SELECT id, workcode, lastname
|
||||
FROM (
|
||||
SELECT id, workcode, lastname, ROW_NUMBER() OVER(ORDER BY id) as rn
|
||||
FROM userInfo_view
|
||||
WHERE 1=1
|
||||
"""
|
||||
if keyword:
|
||||
query_sql += " AND (workcode LIKE ? OR lastname LIKE ?)"
|
||||
|
||||
query_sql += """
|
||||
) as T
|
||||
WHERE rn > ? AND rn <= ?
|
||||
"""
|
||||
|
||||
page_params = params + [offset, offset + page_size]
|
||||
cursor.execute(query_sql, page_params)
|
||||
|
||||
items = []
|
||||
for row in cursor.fetchall():
|
||||
items.append({
|
||||
"uid": str(row.id),
|
||||
"employeeId": str(row.workcode),
|
||||
"name": str(row.lastname)
|
||||
})
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_employee_by_name_and_workcode(cls, real_name: str, employee_id: str):
|
||||
connection = cls._connect()
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
normalized_name = (real_name or "").strip()
|
||||
normalized_employee_id = (employee_id or "").strip()
|
||||
if not normalized_name or not normalized_employee_id:
|
||||
raise RuntimeError("缺少姓名或工号,无法查询 OA 用户")
|
||||
|
||||
query_sql = """
|
||||
SELECT TOP 1 id, workcode, lastname
|
||||
FROM userInfo_view
|
||||
WHERE workcode = ? AND lastname = ?
|
||||
ORDER BY id
|
||||
"""
|
||||
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
|
||||
row = cursor.fetchone()
|
||||
if not row:
|
||||
return None
|
||||
|
||||
return {
|
||||
"uid": str(row.id),
|
||||
"employeeId": str(row.workcode),
|
||||
"name": str(row.lastname),
|
||||
}
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
@@ -2,13 +2,13 @@ import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from pathlib import Path
|
||||
from flask import current_app, has_app_context
|
||||
|
||||
class Text2SQLService:
|
||||
_schema_text = None
|
||||
_oracle_client_init_attempted = False
|
||||
_oracle_client_init_error = None
|
||||
_oracle_client_mode = "unknown"
|
||||
_oracle_client_initialized = False
|
||||
_jdbc_driver_url = "https://repo1.maven.org/maven2/com/oracle/database/jdbc/ojdbc8/19.25.0.0/ojdbc8-19.25.0.0.jar"
|
||||
|
||||
@staticmethod
|
||||
def _backend_dir() -> str:
|
||||
@@ -151,6 +151,122 @@ class Text2SQLService:
|
||||
text = (error_message or "").upper()
|
||||
return any(code in text for code in ("ORA-00904", "ORA-00942", "INVALID IDENTIFIER", "TABLE OR VIEW DOES NOT EXIST"))
|
||||
|
||||
@classmethod
|
||||
def _get_oracle_client_dir(cls) -> str | None:
|
||||
env_dir = (os.getenv("ORACLE_CLIENT_LIB_DIR") or "").strip()
|
||||
if env_dir and os.path.exists(env_dir):
|
||||
return env_dir
|
||||
|
||||
linux_candidates = [
|
||||
"/opt/oracle/instantclient",
|
||||
"/opt/oracle/instantclient_19_28",
|
||||
"/opt/oracle/instantclient_19_27",
|
||||
]
|
||||
for path in linux_candidates:
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
|
||||
return cls._find_oracle_client_dir()
|
||||
|
||||
@classmethod
|
||||
def _init_oracle_client(cls, oracledb) -> None:
|
||||
if cls._oracle_client_initialized or not getattr(oracledb, "is_thin_mode", lambda: True)():
|
||||
return
|
||||
|
||||
import platform
|
||||
import shutil
|
||||
import tempfile
|
||||
|
||||
target_lib_dir = cls._get_oracle_client_dir()
|
||||
|
||||
if platform.system() == 'Windows' and target_lib_dir:
|
||||
# OCI C-library fails to load if path contains non-ASCII.
|
||||
if not target_lib_dir.isascii():
|
||||
temp_dir = os.path.join(tempfile.gettempdir(), 'hxops_oracle_client')
|
||||
safe_lib_dir = os.path.join(temp_dir, os.path.basename(target_lib_dir))
|
||||
if not os.path.exists(safe_lib_dir) and os.path.exists(target_lib_dir):
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
shutil.copytree(target_lib_dir, safe_lib_dir)
|
||||
target_lib_dir = safe_lib_dir
|
||||
|
||||
if target_lib_dir:
|
||||
oracledb.init_oracle_client(lib_dir=target_lib_dir)
|
||||
else:
|
||||
oracledb.init_oracle_client()
|
||||
cls._oracle_client_initialized = True
|
||||
|
||||
@classmethod
|
||||
def _jdbc_dir(cls) -> Path:
|
||||
return Path(cls._backend_dir()) / "jdbc"
|
||||
|
||||
@classmethod
|
||||
def _ensure_jdbc_driver_jar(cls) -> str:
|
||||
env_path = (os.getenv("ERP_JDBC_JAR") or "").strip()
|
||||
if env_path and os.path.exists(env_path):
|
||||
return env_path
|
||||
|
||||
jar_dir = cls._jdbc_dir()
|
||||
jar_dir.mkdir(parents=True, exist_ok=True)
|
||||
jar_path = jar_dir / "ojdbc8-19.25.0.0.jar"
|
||||
if jar_path.exists():
|
||||
return str(jar_path)
|
||||
|
||||
import requests
|
||||
|
||||
driver_url = os.getenv("ERP_JDBC_JAR_URL", cls._jdbc_driver_url).strip() or cls._jdbc_driver_url
|
||||
with requests.get(driver_url, stream=True, timeout=120) as resp:
|
||||
resp.raise_for_status()
|
||||
with open(jar_path, "wb") as f:
|
||||
for chunk in resp.iter_content(chunk_size=1024 * 256):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
return str(jar_path)
|
||||
|
||||
@staticmethod
|
||||
def _dsn_to_jdbc_url(dsn: str) -> str:
|
||||
dsn = (dsn or "").strip()
|
||||
if not dsn:
|
||||
raise ValueError("ERP_DB_DSN is empty")
|
||||
if dsn.startswith("jdbc:oracle:thin:@"):
|
||||
return dsn
|
||||
if dsn.startswith("("):
|
||||
return f"jdbc:oracle:thin:@{dsn}"
|
||||
match = re.match(r"^(?P<host>[^:/]+)(?::(?P<port>\d+))?/(?P<service>.+)$", dsn)
|
||||
if match:
|
||||
host = match.group("host")
|
||||
port = match.group("port") or "1521"
|
||||
service = match.group("service")
|
||||
return f"jdbc:oracle:thin:@//{host}:{port}/{service}"
|
||||
return f"jdbc:oracle:thin:@{dsn}"
|
||||
|
||||
@classmethod
|
||||
def _execute_sql_via_jdbc(cls, sql: str, user: str, password: str, dsn: str):
|
||||
import jaydebeapi
|
||||
|
||||
jar_path = cls._ensure_jdbc_driver_jar()
|
||||
jdbc_url = cls._dsn_to_jdbc_url(dsn)
|
||||
connection = jaydebeapi.connect(
|
||||
"oracle.jdbc.OracleDriver",
|
||||
jdbc_url,
|
||||
{
|
||||
"user": user,
|
||||
"password": password,
|
||||
"oracle.jdbc.timezoneAsRegion": "false",
|
||||
},
|
||||
jar_path,
|
||||
)
|
||||
cursor = connection.cursor()
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
columns = [col[0] for col in cursor.description] if cursor.description else []
|
||||
rows = cursor.fetchall() if columns else []
|
||||
return columns, rows
|
||||
finally:
|
||||
try:
|
||||
cursor.close()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
if cls._schema_text is None:
|
||||
@@ -392,9 +508,14 @@ class Text2SQLService:
|
||||
|
||||
user = "EXT_VIEW_USER"
|
||||
password = "extviewuser"
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
cls._ensure_oracle_client_initialized(oracledb)
|
||||
dsn = os.getenv("ERP_DB_DSN", "192.168.8.24:1521/topprod")
|
||||
|
||||
try:
|
||||
# Old ERP Oracle versions require python-oracledb thick mode.
|
||||
cls._init_oracle_client(oracledb)
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Failed to init thick mode: {e}")
|
||||
|
||||
try:
|
||||
connection = oracledb.connect(user=user, password=password, dsn=dsn)
|
||||
@@ -409,7 +530,15 @@ class Text2SQLService:
|
||||
|
||||
return columns, rows
|
||||
except Exception as e:
|
||||
return ["Error"], [[cls._format_connection_error(str(e))]]
|
||||
error_text = str(e)
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Oracle direct query failed, trying JDBC fallback: {error_text}")
|
||||
if "DPY-3010" in error_text or "DPI-1047" in error_text:
|
||||
try:
|
||||
return cls._execute_sql_via_jdbc(sql, user, password, dsn)
|
||||
except Exception as jdbc_error:
|
||||
return ["Error"], [[f"{error_text} | JDBC fallback failed: {jdbc_error}"]]
|
||||
return ["Error"], [[error_text]]
|
||||
|
||||
@classmethod
|
||||
def format_result(cls, columns, rows, sql, original_query):
|
||||
@@ -439,28 +568,88 @@ class Text2SQLService:
|
||||
"""Yields SSE events to frontend just like DifyService"""
|
||||
start_time = time.time()
|
||||
final_conversation_id = conversation_id or f"erp_{int(time.time())}"
|
||||
|
||||
# 1. Generate SQL
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n"
|
||||
sql = Text2SQLService.generate_sql(query)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n"
|
||||
|
||||
# 2. Execute SQL
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||
try:
|
||||
# 1. Generate SQL
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
sql = Text2SQLService.generate_sql(query)
|
||||
generate_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] generate_sql done conversation_id=%s elapsed_ms=%s sql_preview=%s",
|
||||
final_conversation_id,
|
||||
generate_sql_ms,
|
||||
(sql or "")[:300],
|
||||
)
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n"
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
# 2. Execute SQL
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
if columns == ["Error"] and rows and rows[0]:
|
||||
error_message = str(rows[0][0] or "")
|
||||
if Text2SQLService._is_repairable_sql_error(error_message):
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '检测到字段或表结构不匹配,正在依据现有 Schema 自动修正 SQL...\n'})}\n\n"
|
||||
repair_stage_start = time.time()
|
||||
repaired_sql = Text2SQLService.repair_sql(query, sql, error_message)
|
||||
repair_sql_ms = int((time.time() - repair_stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] repair_sql done conversation_id=%s elapsed_ms=%s sql_changed=%s",
|
||||
final_conversation_id,
|
||||
repair_sql_ms,
|
||||
bool(repaired_sql and repaired_sql != sql),
|
||||
)
|
||||
if repaired_sql and repaired_sql != sql:
|
||||
sql = repaired_sql
|
||||
stage_start = time.time()
|
||||
columns, rows = Text2SQLService.execute_sql(sql)
|
||||
execute_sql_ms = int((time.time() - stage_start) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] execute_sql retry done conversation_id=%s elapsed_ms=%s columns=%s row_count=%s",
|
||||
final_conversation_id,
|
||||
execute_sql_ms,
|
||||
len(columns or []),
|
||||
len(rows or []),
|
||||
)
|
||||
|
||||
# 3. Format result
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
||||
stage_start = time.time()
|
||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[text2sql] format_result done conversation_id=%s elapsed_ms=%s total_ms=%s",
|
||||
final_conversation_id,
|
||||
format_result_ms,
|
||||
latency,
|
||||
)
|
||||
except Exception as exc:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[text2sql] stream_chat failed conversation_id=%s query=%s",
|
||||
final_conversation_id,
|
||||
query,
|
||||
)
|
||||
error_data = {
|
||||
'event': 'error',
|
||||
'message': str(exc) or 'ERP 问数执行失败',
|
||||
'conversation_id': final_conversation_id,
|
||||
}
|
||||
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
# Create ChatLog
|
||||
from app.models import ChatLog, db
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
integration smoke text
|
||||
@@ -37,5 +37,6 @@ daemon = False
|
||||
# 进程名称
|
||||
proc_name = "hxops_backend"
|
||||
|
||||
# 预加载应用 (加快启动速度)
|
||||
preload_app = True
|
||||
# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork,
|
||||
# 导致 worker 继承损坏的数据库连接。
|
||||
preload_app = False
|
||||
@@ -0,0 +1 @@
|
||||
"""Enterprise KB Skill System orchestrator package."""
|
||||
@@ -0,0 +1,167 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import typer
|
||||
|
||||
from edkb_system.config import SystemConfig
|
||||
from edkb_system.contracts import Context
|
||||
from edkb_system.controller import build_knowledge
|
||||
from edkb_system.skills import (
|
||||
flow_reconstruct,
|
||||
loader_excel,
|
||||
loader_pdf,
|
||||
table_linearize,
|
||||
)
|
||||
|
||||
app = typer.Typer(help="Enterprise KB multi-skill orchestrator")
|
||||
|
||||
|
||||
def _write_failed_files_report(out_dir: Path, failed: list[dict]) -> tuple[Path, Path]:
|
||||
txt_path = out_dir / "_failed_files.txt"
|
||||
json_path = out_dir / "_failed_files.json"
|
||||
if not failed:
|
||||
for p in [txt_path, json_path]:
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
return txt_path, json_path
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
lines: list[str] = []
|
||||
payload: list[dict] = []
|
||||
for idx, item in enumerate(failed, start=1):
|
||||
file_name = str(item.get("file") or "unknown").strip() or "unknown"
|
||||
reason = str(item.get("error") or "unknown error")
|
||||
elapsed_ms = int(item.get("elapsed_ms") or 0)
|
||||
elapsed_s = f"{elapsed_ms / 1000:.3f}s"
|
||||
is_timeout = "timed out" in reason.lower()
|
||||
payload.append(
|
||||
{
|
||||
"index": idx,
|
||||
"file": file_name,
|
||||
"reason": reason,
|
||||
"elapsed_ms": elapsed_ms,
|
||||
"timed_out": is_timeout,
|
||||
}
|
||||
)
|
||||
lines.extend(
|
||||
[
|
||||
f"[{idx}] {file_name}",
|
||||
f"reason: {reason}",
|
||||
f"elapsed: {elapsed_s}",
|
||||
f"timed_out: {'true' if is_timeout else 'false'}",
|
||||
"",
|
||||
]
|
||||
)
|
||||
|
||||
txt_path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
||||
json_path.write_text(
|
||||
json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
return txt_path, json_path
|
||||
|
||||
|
||||
@app.command("build")
|
||||
def build_cmd(
|
||||
input_path: str = typer.Argument(..., metavar="PATH"),
|
||||
out: str = typer.Option(..., "--out"),
|
||||
config: str | None = typer.Option(None, "--config"),
|
||||
skip: list[str] | None = typer.Option(
|
||||
None,
|
||||
"--skip",
|
||||
help="Skip files by glob pattern (match name or relative path, repeatable)",
|
||||
),
|
||||
resume: bool = typer.Option(
|
||||
False,
|
||||
"--resume/--no-resume",
|
||||
help="Skip files whose target markdown already exists",
|
||||
),
|
||||
prune_stale: bool = typer.Option(
|
||||
False,
|
||||
"--prune-stale/--keep-stale",
|
||||
help="Remove stale markdown/intermediate leftovers in output before build",
|
||||
),
|
||||
) -> None:
|
||||
cfg = SystemConfig.load(config)
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
temp_dir = root / "work" / "cache"
|
||||
in_path = Path(input_path)
|
||||
if not in_path.exists():
|
||||
typer.echo(f"Input path not found: {in_path}")
|
||||
typer.echo("Create the folder and put documents in it, e.g. work/input")
|
||||
raise typer.Exit(code=2)
|
||||
results = build_knowledge(
|
||||
in_path,
|
||||
Path(out),
|
||||
cfg,
|
||||
temp_dir,
|
||||
skip_patterns=skip or [],
|
||||
resume=resume,
|
||||
prune_stale_output=prune_stale,
|
||||
)
|
||||
ok = [r for r in results if r.get("status") == "success"]
|
||||
failed = [r for r in results if r.get("status") == "failed"]
|
||||
skipped = [r for r in results if r.get("status") == "skipped"]
|
||||
typer.echo(
|
||||
"Completed files: "
|
||||
f"{len(results)} (success={len(ok)}, failed={len(failed)}, skipped={len(skipped)})"
|
||||
)
|
||||
if failed:
|
||||
txt_path, json_path = _write_failed_files_report(Path(out), failed)
|
||||
for r in failed:
|
||||
file_name = str(r.get("file", "")).strip() or "unknown"
|
||||
reason = str(r.get("error") or "unknown error")
|
||||
typer.echo(f"- Failed: {file_name}")
|
||||
typer.echo(f" - reason: {reason}")
|
||||
typer.echo(f"- Failed list: {txt_path}")
|
||||
typer.echo(f"- Failed json: {json_path}")
|
||||
else:
|
||||
_write_failed_files_report(Path(out), [])
|
||||
typer.echo(f"- Output dir: {Path(out)}")
|
||||
|
||||
|
||||
@app.command("inspect-flow")
|
||||
def inspect_flow_cmd(
|
||||
file: str = typer.Argument(..., metavar="FILE"),
|
||||
out: str = typer.Option(..., "--out"),
|
||||
) -> None:
|
||||
ctx = Context(file_type="pdf")
|
||||
blocks = loader_pdf.run({"file_path": file}, ctx)
|
||||
data = flow_reconstruct.run(blocks, ctx)
|
||||
out_dir = Path(out)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "inspect_flow.md").write_text(
|
||||
"\n\n".join(data.get("flow_markdowns", [])), encoding="utf-8"
|
||||
)
|
||||
(out_dir / "inspect_flow_debug.json").write_text(
|
||||
json.dumps(data.get("debug", []), ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
typer.echo("inspect-flow done")
|
||||
|
||||
|
||||
@app.command("inspect-excel")
|
||||
def inspect_excel_cmd(
|
||||
file: str = typer.Argument(..., metavar="FILE"),
|
||||
out: str = typer.Option(..., "--out"),
|
||||
) -> None:
|
||||
ctx = Context(file_type="xlsx")
|
||||
tables = loader_excel.run({"file_path": file, "work_dir": str(Path(out))}, ctx)
|
||||
md = table_linearize.run(tables, ctx)
|
||||
out_dir = Path(out)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
(out_dir / "inspect_excel.md").write_text(md, encoding="utf-8")
|
||||
(out_dir / "inspect_excel_schema.json").write_text(
|
||||
json.dumps(
|
||||
[{"sheet": t.get("sheet"), "headers": t.get("headers")} for t in tables],
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
typer.echo("inspect-excel done")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app()
|
||||
@@ -0,0 +1,53 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class RouterConfig(BaseModel):
|
||||
scan_likelihood_threshold: float = 0.6
|
||||
flow_likelihood_threshold: float = 0.5
|
||||
table_likelihood_threshold: float = 0.5
|
||||
|
||||
|
||||
class OCRConfig(BaseModel):
|
||||
enable: bool = True
|
||||
engine: str = "rapidocr"
|
||||
min_confidence: float = 0.3
|
||||
|
||||
|
||||
class ChunkConfig(BaseModel):
|
||||
enable: bool = True
|
||||
max_chars: int = 1200
|
||||
overlap_chars: int = 150
|
||||
add_heading_path_prefix: bool = True
|
||||
|
||||
|
||||
class CleanConfig(BaseModel):
|
||||
dedup_min_repeats: int = 3
|
||||
merge_short_line_chars: int = 15
|
||||
|
||||
|
||||
class SystemConfig(BaseModel):
|
||||
router: RouterConfig = Field(default_factory=RouterConfig)
|
||||
ocr: OCRConfig = Field(default_factory=OCRConfig)
|
||||
chunk: ChunkConfig = Field(default_factory=ChunkConfig)
|
||||
clean: CleanConfig = Field(default_factory=CleanConfig)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str | None) -> "SystemConfig":
|
||||
if not path:
|
||||
return cls()
|
||||
p = Path(path)
|
||||
raw = p.read_text(encoding="utf-8")
|
||||
if p.suffix.lower() in {".yaml", ".yml"}:
|
||||
import yaml
|
||||
|
||||
data = yaml.safe_load(raw) or {}
|
||||
elif p.suffix.lower() == ".json":
|
||||
data = json.loads(raw)
|
||||
else:
|
||||
raise ValueError("config only supports yaml/yml/json")
|
||||
return cls.model_validate(data)
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass
|
||||
class Block:
|
||||
id: str
|
||||
page: int
|
||||
type: str
|
||||
text: str
|
||||
bbox: tuple[float, float, float, float]
|
||||
meta: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def cx(self) -> float:
|
||||
return (self.bbox[0] + self.bbox[2]) / 2.0
|
||||
|
||||
def cy(self) -> float:
|
||||
return (self.bbox[1] + self.bbox[3]) / 2.0
|
||||
|
||||
|
||||
@dataclass
|
||||
class Chunk:
|
||||
id: str
|
||||
heading_path: str
|
||||
text: str
|
||||
index: int
|
||||
source: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Context:
|
||||
file_type: str = ""
|
||||
pages: int = 0
|
||||
images: int = 0
|
||||
ocr_characters: int = 0
|
||||
flows_detected: int = 0
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
confidence: float = 1.0
|
||||
extras: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DocumentProfile:
|
||||
file_type: str
|
||||
text_density: float
|
||||
has_images: bool
|
||||
has_tables: bool
|
||||
flow_likelihood: float
|
||||
scan_likelihood: float
|
||||
table_likelihood: float
|
||||
language_hint: str
|
||||
recommended_pipeline: list[str]
|
||||
@@ -0,0 +1,893 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import fnmatch
|
||||
import multiprocessing as mp
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.config import SystemConfig
|
||||
from edkb_system.contracts import Context
|
||||
from edkb_system.discovery import discover
|
||||
from edkb_system.skills import (
|
||||
chunk,
|
||||
clean,
|
||||
doc_to_pdf,
|
||||
export,
|
||||
flow_reconstruct,
|
||||
intake_router,
|
||||
loader_csv,
|
||||
loader_docx,
|
||||
loader_excel,
|
||||
loader_pdf,
|
||||
loader_pptx,
|
||||
ocr,
|
||||
postcheck,
|
||||
quality_gate,
|
||||
table_linearize,
|
||||
)
|
||||
from edkb_system.skills.common import blocks_to_plain_markdown
|
||||
from edkb_system.skills.word_bridge import _kill_winword_pids, _list_winword_pids
|
||||
|
||||
|
||||
_STEP_ALIAS = {
|
||||
"edkb-intake-router": "route",
|
||||
"edkb-loader-docx": "docx",
|
||||
"edkb-doc-to-pdf": "doc2pdf",
|
||||
"edkb-loader-pdf": "pdf",
|
||||
"edkb-loader-pptx": "pptx",
|
||||
"edkb-loader-excel": "excel",
|
||||
"edkb-loader-csv": "csv",
|
||||
"edkb-ocr": "ocr",
|
||||
"edkb-flow-reconstruct": "flow",
|
||||
"edkb-table-linearize": "table",
|
||||
"edkb-clean": "clean",
|
||||
"edkb-chunk": "chunk",
|
||||
"edkb-quality-gate": "qgate",
|
||||
"edkb-export": "export",
|
||||
"edkb-postcheck": "check",
|
||||
}
|
||||
|
||||
|
||||
def _step_alias(step: str) -> str:
|
||||
return _STEP_ALIAS.get(step, step.replace("edkb-", ""))
|
||||
|
||||
|
||||
def _extract_doc_header_from_flow(flow_mds: list[str]) -> str | None:
|
||||
if not flow_mds:
|
||||
return None
|
||||
for line in "\n".join(flow_mds).splitlines():
|
||||
if "文件编号" not in line or "文件级别" not in line or "版本" not in line:
|
||||
continue
|
||||
s = " ".join(line.split())
|
||||
m = re.search(r"文件编号\s*(\S+)\s*文件级别\s*(\S+)\s*版本\s*(\S+)", s)
|
||||
if m:
|
||||
return f"文件编号 {m.group(1)} 文件级别 {m.group(2)} 版本 {m.group(3)}"
|
||||
return None
|
||||
|
||||
|
||||
def _inject_doc_header_from_flow(text: str, flow_mds: list[str]) -> str:
|
||||
if "文件编号" in text:
|
||||
return text
|
||||
meta = _extract_doc_header_from_flow(flow_mds)
|
||||
if not meta:
|
||||
return text
|
||||
if text.startswith("制定部门"):
|
||||
i = text.find("\n")
|
||||
if i >= 0:
|
||||
return text[: i + 1] + meta + "\n" + text[i + 1 :]
|
||||
return meta + "\n" + text
|
||||
|
||||
|
||||
def _inject_source_title_if_missing(text: str, source_stem: str) -> str:
|
||||
if not source_stem:
|
||||
return text
|
||||
preview = "\n".join(text.splitlines()[:20])
|
||||
norm_preview = re.sub(r"\s+", "", preview)
|
||||
norm_source = re.sub(r"\s+", "", source_stem)
|
||||
if norm_source in norm_preview:
|
||||
return text
|
||||
return source_stem + "\n" + text
|
||||
|
||||
|
||||
def _promote_title_above_meta(text: str) -> str:
|
||||
lines = text.splitlines()
|
||||
if len(lines) < 2:
|
||||
return text
|
||||
|
||||
first_idx = next((i for i, x in enumerate(lines) if x.strip()), None)
|
||||
if first_idx is None:
|
||||
return text
|
||||
second_idx = next(
|
||||
(i for i in range(first_idx + 1, len(lines)) if lines[i].strip()), None
|
||||
)
|
||||
if second_idx is None:
|
||||
return text
|
||||
|
||||
first = lines[first_idx].strip()
|
||||
second = lines[second_idx].strip()
|
||||
if "文件编号" not in first:
|
||||
return text
|
||||
if (
|
||||
re.match(r"^[一二三四五六七八九十]+、", second)
|
||||
or second.startswith("制定部门")
|
||||
or second.startswith("文件修订履历")
|
||||
or "文件编号" in second
|
||||
):
|
||||
return text
|
||||
if len(second) > 80:
|
||||
return text
|
||||
|
||||
lines[first_idx], lines[second_idx] = lines[second_idx], lines[first_idx]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _promote_dept_header_near_top(text: str) -> str:
|
||||
lines = text.splitlines()
|
||||
pat = re.compile(r"制定部门.+制/修订日期.+页码\s*\d+\s*/\s*\d+")
|
||||
idx = next(
|
||||
(i for i, ln in enumerate(lines) if pat.search(" ".join(ln.split()))), None
|
||||
)
|
||||
if idx is None or idx <= 4:
|
||||
return text
|
||||
|
||||
line = lines.pop(idx)
|
||||
insert_at = 1
|
||||
for i, ln in enumerate(lines[:6]):
|
||||
if ln.strip().startswith("文件编号"):
|
||||
insert_at = i + 1
|
||||
break
|
||||
lines.insert(insert_at, line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _ocr_payload_map(blocks: list) -> dict[str, str]:
|
||||
out: dict[str, str] = {}
|
||||
for b in blocks:
|
||||
if getattr(b, "type", "") != "ocr_text" or not str(
|
||||
getattr(b, "id", "")
|
||||
).startswith("ocr-"):
|
||||
continue
|
||||
txt = (getattr(b, "text", "") or "").strip()
|
||||
if txt.startswith("OCR_TEXT:"):
|
||||
txt = txt[len("OCR_TEXT:") :].strip()
|
||||
txt = re.sub(r"(?m)^\s*-\s*", "", txt)
|
||||
txt = " ".join(x.strip() for x in txt.splitlines() if x.strip())
|
||||
if txt and txt != "<empty>":
|
||||
out[str(b.id)[len("ocr-") :]] = txt
|
||||
return out
|
||||
|
||||
|
||||
def _has_non_flow_image_content(blocks: list) -> bool:
|
||||
img_ids = [str(b.id) for b in blocks if getattr(b, "type", "") == "image"]
|
||||
if not img_ids:
|
||||
return False
|
||||
ocr_map = _ocr_payload_map(blocks)
|
||||
info_kw = re.compile(r"分数值|频繁程度|严重性|LEC|评分基准|风险积分|事故发生")
|
||||
flow_kw = re.compile(r"备料|取样|资料确认|品质检验|判定|产品出货|NG|OK|不合格品")
|
||||
|
||||
for iid in img_ids:
|
||||
payload = ocr_map.get(iid, "")
|
||||
if not payload:
|
||||
continue
|
||||
if info_kw.search(payload):
|
||||
return True
|
||||
if len(payload) >= 80 and len(flow_kw.findall(payload)) <= 2:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _derive_source_category(file_path: Path, input_path: Path) -> str:
|
||||
if input_path.is_dir():
|
||||
try:
|
||||
rel = file_path.relative_to(input_path)
|
||||
if len(rel.parts) >= 2:
|
||||
return rel.parts[0]
|
||||
return input_path.name or "uncategorized"
|
||||
except Exception:
|
||||
return file_path.parent.name or "uncategorized"
|
||||
return input_path.parent.name or "uncategorized"
|
||||
|
||||
|
||||
def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
|
||||
if input_path.is_dir():
|
||||
try:
|
||||
rel = file_path.relative_to(input_path)
|
||||
except Exception:
|
||||
rel = Path(file_path.name)
|
||||
if len(rel.parts) == 1:
|
||||
root_name = input_path.name
|
||||
if root_name and root_name.lower() not in {"input", "work"}:
|
||||
rel = Path(root_name) / rel
|
||||
else:
|
||||
parent_name = file_path.parent.name
|
||||
if parent_name and parent_name.lower() not in {"input", "work"}:
|
||||
rel = Path(parent_name) / file_path.name
|
||||
else:
|
||||
rel = Path(file_path.name)
|
||||
return rel.with_suffix(".md")
|
||||
|
||||
|
||||
def _normalize_path_for_match(p: Path | str) -> str:
|
||||
return str(p).replace("\\", "/")
|
||||
|
||||
|
||||
def _file_timeout_sec() -> int | None:
|
||||
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
value = 0
|
||||
return value if value > 0 else None
|
||||
|
||||
|
||||
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
|
||||
if input_path.is_file():
|
||||
candidates = [input_path]
|
||||
elif input_path.exists():
|
||||
candidates = [p for p in input_path.rglob("*") if p.is_file()]
|
||||
else:
|
||||
return []
|
||||
|
||||
removed: list[Path] = []
|
||||
for file in candidates:
|
||||
name = file.name
|
||||
if not (name.startswith("~$") or name.startswith("~WRL")):
|
||||
continue
|
||||
try:
|
||||
file.unlink()
|
||||
except Exception:
|
||||
continue
|
||||
removed.append(file)
|
||||
return removed
|
||||
|
||||
|
||||
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
|
||||
if not patterns:
|
||||
return None
|
||||
lowered_candidates = [c.lower() for c in candidates if c]
|
||||
for pat in patterns:
|
||||
norm_pat = _normalize_path_for_match(pat).strip().lower()
|
||||
if not norm_pat:
|
||||
continue
|
||||
for cand in lowered_candidates:
|
||||
if fnmatch.fnmatch(cand, norm_pat):
|
||||
return pat
|
||||
return None
|
||||
|
||||
|
||||
def _prune_stale_markdowns(output_dir: Path, expected: set[Path]) -> None:
|
||||
keep_names = {"INDEX.md", "POSTCHECK_ISSUES.md"}
|
||||
expected_resolved = {p.resolve() for p in expected}
|
||||
|
||||
for md in output_dir.rglob("*.md"):
|
||||
if md.name in keep_names:
|
||||
continue
|
||||
try:
|
||||
resolved = md.resolve()
|
||||
except Exception:
|
||||
resolved = md
|
||||
if resolved in expected_resolved:
|
||||
continue
|
||||
try:
|
||||
md.unlink()
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def _run_one_worker(payload: dict, queue: mp.Queue) -> None:
|
||||
try:
|
||||
cfg = SystemConfig.model_validate(payload["config"])
|
||||
res = _run_one(
|
||||
Path(payload["file_path"]),
|
||||
Path(payload["out_root"]),
|
||||
Path(payload["temp_dir"]),
|
||||
cfg,
|
||||
source_root=Path(payload["source_root"])
|
||||
if payload.get("source_root")
|
||||
else None,
|
||||
source_category=payload.get("source_category"),
|
||||
final_md_path=(
|
||||
Path(payload["final_md_path"]) if payload.get("final_md_path") else None
|
||||
),
|
||||
progress_label=payload.get("progress_label"),
|
||||
)
|
||||
queue.put({"ok": True, "result": res})
|
||||
except Exception as exc:
|
||||
queue.put({"ok": False, "error": str(exc), "detail": traceback.format_exc()})
|
||||
|
||||
|
||||
def _run_one_with_timeout(
|
||||
file_path: Path,
|
||||
out_root: Path,
|
||||
temp_dir: Path,
|
||||
cfg: SystemConfig,
|
||||
source_root: Path | None = None,
|
||||
source_category: str | None = None,
|
||||
final_md_path: Path | None = None,
|
||||
progress_label: str | None = None,
|
||||
) -> dict:
|
||||
timeout = _file_timeout_sec()
|
||||
if not timeout:
|
||||
return _run_one(
|
||||
file_path,
|
||||
out_root,
|
||||
temp_dir,
|
||||
cfg,
|
||||
source_root=source_root,
|
||||
source_category=source_category,
|
||||
final_md_path=final_md_path,
|
||||
progress_label=progress_label,
|
||||
)
|
||||
|
||||
ctx = mp.get_context("spawn")
|
||||
queue: mp.Queue = ctx.Queue()
|
||||
before_pids = _list_winword_pids()
|
||||
payload = {
|
||||
"file_path": str(file_path),
|
||||
"out_root": str(out_root),
|
||||
"temp_dir": str(temp_dir),
|
||||
"config": cfg.model_dump(),
|
||||
"source_root": str(source_root) if source_root else None,
|
||||
"source_category": source_category,
|
||||
"final_md_path": str(final_md_path) if final_md_path else None,
|
||||
"progress_label": progress_label,
|
||||
}
|
||||
proc = ctx.Process(target=_run_one_worker, args=(payload, queue))
|
||||
proc.start()
|
||||
proc.join(timeout)
|
||||
if proc.is_alive():
|
||||
proc.terminate()
|
||||
proc.join(5)
|
||||
after_pids = _list_winword_pids()
|
||||
_kill_winword_pids(after_pids - before_pids)
|
||||
raise TimeoutError(
|
||||
f"file processing timed out after {timeout}s: {file_path.name}"
|
||||
)
|
||||
if queue.empty():
|
||||
if proc.exitcode not in {0, None}:
|
||||
raise RuntimeError(
|
||||
f"file worker exited unexpectedly (code={proc.exitcode}): {file_path.name}"
|
||||
)
|
||||
raise RuntimeError(f"file worker returned no result: {file_path.name}")
|
||||
message = queue.get()
|
||||
if message.get("ok"):
|
||||
return message["result"]
|
||||
detail = str(message.get("detail") or "")
|
||||
raise RuntimeError(str(message.get("error") or detail or "unknown worker error"))
|
||||
|
||||
marker_files = {
|
||||
"01_raw_layout.json",
|
||||
"02_flow_procedure.md",
|
||||
"03_clean.md",
|
||||
"04_chunks.jsonl",
|
||||
"report.md",
|
||||
"trace_pipeline.json",
|
||||
"postcheck.json",
|
||||
}
|
||||
for d in list(output_dir.iterdir()):
|
||||
if not d.is_dir():
|
||||
continue
|
||||
try:
|
||||
names = {p.name for p in d.iterdir()}
|
||||
except Exception:
|
||||
continue
|
||||
if names & marker_files:
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
for d in sorted(output_dir.rglob("*"), key=lambda x: len(x.parts), reverse=True):
|
||||
if not d.is_dir():
|
||||
continue
|
||||
try:
|
||||
if d == output_dir:
|
||||
continue
|
||||
next(d.iterdir())
|
||||
except StopIteration:
|
||||
try:
|
||||
d.rmdir()
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def _run_one(
|
||||
file_path: Path,
|
||||
out_root: Path,
|
||||
temp_dir: Path,
|
||||
cfg: SystemConfig,
|
||||
source_root: Path | None = None,
|
||||
source_category: str | None = None,
|
||||
final_md_path: Path | None = None,
|
||||
progress_label: str | None = None,
|
||||
) -> dict:
|
||||
ctx = Context()
|
||||
trace_steps: list[str] = []
|
||||
timings_ms: dict[str, int] = {}
|
||||
|
||||
def _mark(step: str, started: float) -> None:
|
||||
timings_ms[step] = int((time.perf_counter() - started) * 1000)
|
||||
|
||||
def _announce(stage: str) -> None:
|
||||
if not progress_label:
|
||||
return
|
||||
print(f"{progress_label} stage: {stage}", flush=True)
|
||||
|
||||
out_dir = out_root / file_path.stem
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
for stale in [
|
||||
out_dir / "inspect_flow_debug.json",
|
||||
out_dir / "trace_pipeline.json",
|
||||
out_dir / "postcheck.json",
|
||||
]:
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
|
||||
t0 = time.perf_counter()
|
||||
profile = intake_router.run({"file_path": str(file_path)}, ctx, cfg.router)
|
||||
_mark("edkb-intake-router", t0)
|
||||
trace_steps.append("edkb-intake-router")
|
||||
|
||||
blocks = []
|
||||
tables = None
|
||||
text = ""
|
||||
flow_mds: list[str] = []
|
||||
|
||||
if profile.file_type in {"doc", "docx"}:
|
||||
_announce("doc/docx parse")
|
||||
t0 = time.perf_counter()
|
||||
docx_blocks = loader_docx.run(
|
||||
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
|
||||
)
|
||||
_mark("edkb-loader-docx", t0)
|
||||
trace_steps.append("edkb-loader-docx")
|
||||
|
||||
table_blocks = sum(1 for b in docx_blocks if b.type == "table")
|
||||
prefer_docx = table_blocks > 0
|
||||
docx_images = [b for b in docx_blocks if b.type == "image"]
|
||||
docx_non_images = [b for b in docx_blocks if b.type != "image"]
|
||||
pdf_blocks = None
|
||||
|
||||
if "edkb-doc-to-pdf" in profile.recommended_pipeline and (
|
||||
(profile.file_type == "doc" and not prefer_docx) or not docx_blocks
|
||||
):
|
||||
_announce("doc to pdf")
|
||||
t0 = time.perf_counter()
|
||||
conv = doc_to_pdf.run(
|
||||
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
|
||||
)
|
||||
_mark("edkb-doc-to-pdf", t0)
|
||||
trace_steps.append("edkb-doc-to-pdf")
|
||||
pdf_path = conv.get("pdf_path")
|
||||
if pdf_path:
|
||||
_announce("pdf load")
|
||||
t0 = time.perf_counter()
|
||||
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
|
||||
_mark("edkb-loader-pdf", t0)
|
||||
trace_steps.append("edkb-loader-pdf")
|
||||
blocks = pdf_blocks
|
||||
else:
|
||||
blocks = docx_blocks
|
||||
else:
|
||||
blocks = docx_blocks
|
||||
|
||||
if (
|
||||
profile.file_type == "doc"
|
||||
and "edkb-doc-to-pdf" in profile.recommended_pipeline
|
||||
and (not prefer_docx or not docx_blocks)
|
||||
):
|
||||
if pdf_blocks is None:
|
||||
_announce("doc to pdf")
|
||||
t0 = time.perf_counter()
|
||||
conv = doc_to_pdf.run(
|
||||
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
|
||||
)
|
||||
_mark("edkb-doc-to-pdf", t0)
|
||||
trace_steps.append("edkb-doc-to-pdf")
|
||||
pdf_path = conv.get("pdf_path")
|
||||
if pdf_path:
|
||||
_announce("pdf load")
|
||||
t0 = time.perf_counter()
|
||||
pdf_blocks = loader_pdf.run({"file_path": str(pdf_path)}, ctx)
|
||||
_mark("edkb-loader-pdf", t0)
|
||||
trace_steps.append("edkb-loader-pdf")
|
||||
if pdf_blocks is not None:
|
||||
pdf_images = [b for b in pdf_blocks if b.type == "image"]
|
||||
if pdf_images and len(pdf_images) > len(docx_images):
|
||||
blocks = docx_non_images + pdf_images
|
||||
ctx.warnings.append(
|
||||
f"doc image source switched to pdf: {len(docx_images)} -> {len(pdf_images)}"
|
||||
)
|
||||
elif not blocks:
|
||||
blocks = pdf_blocks
|
||||
elif profile.file_type == "pdf":
|
||||
_announce("pdf load")
|
||||
t0 = time.perf_counter()
|
||||
blocks = loader_pdf.run({"file_path": str(file_path)}, ctx)
|
||||
_mark("edkb-loader-pdf", t0)
|
||||
trace_steps.append("edkb-loader-pdf")
|
||||
elif profile.file_type in {"ppt", "pptx"}:
|
||||
_announce("ppt/pptx load")
|
||||
t0 = time.perf_counter()
|
||||
blocks = loader_pptx.run(
|
||||
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
|
||||
)
|
||||
_mark("edkb-loader-pptx", t0)
|
||||
trace_steps.append("edkb-loader-pptx")
|
||||
elif profile.file_type in {"xls", "xlsx"}:
|
||||
_announce("excel load")
|
||||
t0 = time.perf_counter()
|
||||
tables = loader_excel.run(
|
||||
{"file_path": str(file_path), "work_dir": str(temp_dir)}, ctx
|
||||
)
|
||||
_mark("edkb-loader-excel", t0)
|
||||
trace_steps.append("edkb-loader-excel")
|
||||
elif profile.file_type == "csv":
|
||||
t0 = time.perf_counter()
|
||||
tables = loader_csv.run({"file_path": str(file_path)}, ctx)
|
||||
_mark("edkb-loader-csv", t0)
|
||||
trace_steps.append("edkb-loader-csv")
|
||||
else:
|
||||
ctx.warnings.append(f"unsupported file type: {profile.file_type}")
|
||||
|
||||
if blocks:
|
||||
ctx.images = sum(1 for b in blocks if b.type == "image")
|
||||
should_ocr = cfg.ocr.enable and (
|
||||
"edkb-ocr" in profile.recommended_pipeline
|
||||
or any(b.type == "image" for b in blocks)
|
||||
)
|
||||
if profile.file_type in {"ppt", "pptx"}:
|
||||
should_ocr = False
|
||||
if should_ocr:
|
||||
_announce("ocr")
|
||||
t0 = time.perf_counter()
|
||||
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
|
||||
_mark("edkb-ocr", t0)
|
||||
trace_steps.append("edkb-ocr")
|
||||
|
||||
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
|
||||
policy_text = doc_kind == "policy_text"
|
||||
has_non_flow_info = _has_non_flow_image_content(blocks)
|
||||
has_page_image_mode = bool(ctx.extras.get("pdf_page_image_mode_pages"))
|
||||
has_figure_anchor = any(
|
||||
(b.text or "")
|
||||
and re.search(
|
||||
r"^\s*\d+(?:\.\d+){1,3}\s*[^\n]{0,40}(?:示意图|图示)\s*$",
|
||||
b.text,
|
||||
)
|
||||
for b in blocks
|
||||
if b.type in {"heading", "paragraph"}
|
||||
)
|
||||
suppress_images = False
|
||||
if profile.file_type not in {"ppt", "pptx"} and not has_figure_anchor:
|
||||
if policy_text and not has_non_flow_info and not has_page_image_mode:
|
||||
suppress_images = True
|
||||
elif (
|
||||
doc_kind == "flow_procedure"
|
||||
and not has_non_flow_info
|
||||
and not has_page_image_mode
|
||||
):
|
||||
suppress_images = True
|
||||
if suppress_images:
|
||||
blocks = [b for b in blocks if b.type not in {"image", "ocr_text"}]
|
||||
trace_steps.append("edkb-image-suppress(no_figure_anchor)")
|
||||
|
||||
flow_info = {}
|
||||
if "edkb-flow-reconstruct" in profile.recommended_pipeline:
|
||||
_announce("flow reconstruct")
|
||||
t0 = time.perf_counter()
|
||||
flow_info = flow_reconstruct.run(blocks, ctx)
|
||||
_mark("edkb-flow-reconstruct", t0)
|
||||
trace_steps.append("edkb-flow-reconstruct")
|
||||
flow_mds = flow_info.get("flow_markdowns", [])
|
||||
if flow_info.get("debug"):
|
||||
(out_dir / "inspect_flow_debug.json").write_text(
|
||||
json.dumps(flow_info["debug"], ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
text = blocks_to_plain_markdown(blocks)
|
||||
text = _inject_doc_header_from_flow(text, flow_mds)
|
||||
elif tables is not None:
|
||||
_announce("table linearize")
|
||||
t0 = time.perf_counter()
|
||||
text = table_linearize.run(tables, ctx)
|
||||
_mark("edkb-table-linearize", t0)
|
||||
trace_steps.append("edkb-table-linearize")
|
||||
|
||||
_announce("clean")
|
||||
t0 = time.perf_counter()
|
||||
clean_md = clean.run(
|
||||
text, ctx, cfg.clean.dedup_min_repeats, cfg.clean.merge_short_line_chars
|
||||
)
|
||||
_mark("edkb-clean", t0)
|
||||
clean_md = _inject_source_title_if_missing(clean_md, file_path.stem)
|
||||
clean_md = _promote_title_above_meta(clean_md)
|
||||
meta = _extract_doc_header_from_flow(flow_mds)
|
||||
has_meta_line = bool(
|
||||
re.search(r"文件编号\s+\S+\s+文件级别\s+\S+\s+版本\s+\S+", clean_md)
|
||||
or ("| 文件编号 |" in clean_md and "| 文件级别 |" in clean_md)
|
||||
)
|
||||
if meta and not has_meta_line:
|
||||
if clean_md.startswith("制定部门"):
|
||||
i = clean_md.find("\n")
|
||||
if i >= 0:
|
||||
clean_md = clean_md[: i + 1] + meta + "\n" + clean_md[i + 1 :]
|
||||
else:
|
||||
clean_md = clean_md + "\n" + meta + "\n"
|
||||
else:
|
||||
clean_md = meta + "\n" + clean_md
|
||||
clean_md = _promote_title_above_meta(clean_md)
|
||||
clean_md = _promote_dept_header_near_top(clean_md)
|
||||
trace_steps.append("edkb-clean")
|
||||
|
||||
chunks = []
|
||||
if cfg.chunk.enable:
|
||||
_announce("chunk")
|
||||
t0 = time.perf_counter()
|
||||
chunks = chunk.run(
|
||||
{"source": file_path.name, "text": clean_md},
|
||||
ctx,
|
||||
max_chars=cfg.chunk.max_chars,
|
||||
overlap_chars=cfg.chunk.overlap_chars,
|
||||
add_heading_path_prefix=cfg.chunk.add_heading_path_prefix,
|
||||
)
|
||||
_mark("edkb-chunk", t0)
|
||||
trace_steps.append("edkb-chunk")
|
||||
t0 = time.perf_counter()
|
||||
chunks = quality_gate.run(chunks, ctx)
|
||||
_mark("edkb-quality-gate", t0)
|
||||
trace_steps.append("edkb-quality-gate")
|
||||
else:
|
||||
ctx.warnings.append(
|
||||
"chunk disabled by config: skip edkb-chunk/edkb-quality-gate"
|
||||
)
|
||||
trace_steps.append("edkb-chunk(skipped)")
|
||||
trace_steps.append("edkb-quality-gate(skipped)")
|
||||
|
||||
source_rel_path = file_path.name
|
||||
if source_root is not None:
|
||||
try:
|
||||
source_rel_path = str(file_path.relative_to(source_root))
|
||||
except Exception:
|
||||
source_rel_path = file_path.name
|
||||
|
||||
target_md_path = final_md_path
|
||||
if target_md_path is None:
|
||||
target_md_path = out_root / f"{file_path.stem}.md"
|
||||
|
||||
_announce("export")
|
||||
t0 = time.perf_counter()
|
||||
export.run(
|
||||
{
|
||||
"out_dir": str(out_dir),
|
||||
"source_file": file_path.name,
|
||||
"source_rel_path": source_rel_path,
|
||||
"source_category": source_category or "",
|
||||
"flat_md_path": str(target_md_path),
|
||||
"clean_md": clean_md,
|
||||
"chunks": chunks,
|
||||
"blocks": blocks,
|
||||
"flow_markdowns": flow_mds,
|
||||
},
|
||||
ctx,
|
||||
)
|
||||
_mark("edkb-export", t0)
|
||||
trace_steps.append("edkb-export")
|
||||
|
||||
exported_clean_md = clean_md
|
||||
exported_clean_path = out_dir / "03_clean.md"
|
||||
if exported_clean_path.exists():
|
||||
try:
|
||||
exported_clean_md = exported_clean_path.read_text(encoding="utf-8")
|
||||
except Exception:
|
||||
exported_clean_md = clean_md
|
||||
|
||||
_announce("postcheck")
|
||||
t0 = time.perf_counter()
|
||||
check = postcheck.run({"out_dir": str(out_dir), "clean_md": exported_clean_md}, ctx)
|
||||
_mark("edkb-postcheck", t0)
|
||||
(out_dir / "postcheck.json").write_text(
|
||||
json.dumps(check, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
if check.get("status") != "pass":
|
||||
failed = ", ".join(check.get("failed_required", []))
|
||||
ctx.warnings.append(f"postcheck failed: {failed}")
|
||||
if check.get("issue_count", 0) > 0:
|
||||
issue_codes: list[str] = []
|
||||
for it in check.get("issues", [])[:3]:
|
||||
code = str(it.get("code", "")).strip()
|
||||
if code and code not in issue_codes:
|
||||
issue_codes.append(code)
|
||||
if issue_codes:
|
||||
ctx.warnings.append(
|
||||
f"postcheck issues: {check.get('issue_count', 0)} ({', '.join(issue_codes)})"
|
||||
)
|
||||
else:
|
||||
ctx.warnings.append(f"postcheck issues: {check.get('issue_count', 0)}")
|
||||
trace_steps.append("edkb-postcheck")
|
||||
|
||||
(out_dir / "trace_pipeline.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"file": file_path.name,
|
||||
"recommended_pipeline": profile.recommended_pipeline,
|
||||
"executed_steps": trace_steps,
|
||||
"timings_ms": timings_ms,
|
||||
"intake": ctx.extras.get("intake", {}),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
return {
|
||||
"file": file_path.name,
|
||||
"out_dir": str(out_dir),
|
||||
"warnings": ctx.warnings,
|
||||
"timings_ms": timings_ms,
|
||||
}
|
||||
|
||||
|
||||
def build_knowledge(
|
||||
input_path: Path,
|
||||
output_dir: Path,
|
||||
config: SystemConfig,
|
||||
temp_dir: Path,
|
||||
skip_patterns: list[str] | None = None,
|
||||
resume: bool = False,
|
||||
prune_stale_output: bool = False,
|
||||
) -> list[dict]:
|
||||
removed_temp_files = _cleanup_input_temp_files(input_path)
|
||||
if removed_temp_files:
|
||||
for removed in removed_temp_files:
|
||||
print(f"cleanup-temp: {removed}", flush=True)
|
||||
|
||||
files = discover(input_path)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
temp_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
patterns = [p for p in (skip_patterns or []) if str(p).strip()]
|
||||
|
||||
for stale in [output_dir / "INDEX.md", output_dir / "POSTCHECK_ISSUES.md"]:
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
for lock_md in output_dir.glob("~$*.md"):
|
||||
if lock_md.is_file():
|
||||
lock_md.unlink()
|
||||
|
||||
if prune_stale_output:
|
||||
expected_paths = {
|
||||
(output_dir / _derive_output_rel_md(file, input_path)).resolve()
|
||||
for file in files
|
||||
}
|
||||
_prune_stale_markdowns(output_dir, expected_paths)
|
||||
|
||||
source_root = input_path if input_path.is_dir() else input_path.parent
|
||||
|
||||
results: list[dict] = []
|
||||
total = len(files)
|
||||
for idx, file in enumerate(files, start=1):
|
||||
flat_out = output_dir / f"{file.stem}.md"
|
||||
mirror_out = output_dir / _derive_output_rel_md(file, input_path)
|
||||
|
||||
source_rel_path = file.name
|
||||
try:
|
||||
source_rel_path = _normalize_path_for_match(file.relative_to(source_root))
|
||||
except Exception:
|
||||
source_rel_path = _normalize_path_for_match(file)
|
||||
|
||||
matched_pattern = _matches_pattern(
|
||||
[
|
||||
_normalize_path_for_match(file),
|
||||
source_rel_path,
|
||||
file.name,
|
||||
],
|
||||
patterns,
|
||||
)
|
||||
if matched_pattern:
|
||||
print(
|
||||
f"[{idx}/{total}] skipped(pattern): {source_rel_path} ({matched_pattern})",
|
||||
flush=True,
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"file": file.name,
|
||||
"out_dir": str(output_dir / file.stem),
|
||||
"warnings": [],
|
||||
"status": "skipped",
|
||||
"skip_reason": f"pattern:{matched_pattern}",
|
||||
"elapsed_ms": 0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
if resume and mirror_out.exists() and mirror_out.stat().st_size > 0:
|
||||
print(f"[{idx}/{total}] skipped(resume): {source_rel_path}", flush=True)
|
||||
results.append(
|
||||
{
|
||||
"file": file.name,
|
||||
"out_dir": str(output_dir / file.stem),
|
||||
"warnings": [],
|
||||
"status": "skipped",
|
||||
"skip_reason": "resume-existing-output",
|
||||
"elapsed_ms": 0,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
print(f"[{idx}/{total}] processing: {file.name}", flush=True)
|
||||
if flat_out.exists():
|
||||
flat_out.unlink()
|
||||
if mirror_out != flat_out and mirror_out.exists():
|
||||
mirror_out.unlink()
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
source_category = _derive_source_category(file, input_path)
|
||||
res = _run_one_with_timeout(
|
||||
file,
|
||||
output_dir,
|
||||
temp_dir,
|
||||
config,
|
||||
source_root=source_root,
|
||||
source_category=source_category,
|
||||
final_md_path=mirror_out,
|
||||
progress_label=f"[{idx}/{total}] {file.name}",
|
||||
)
|
||||
elapsed_ms = int((time.perf_counter() - started) * 1000)
|
||||
res["status"] = "success"
|
||||
res["elapsed_ms"] = elapsed_ms
|
||||
results.append(res)
|
||||
print(
|
||||
f"[{idx}/{total}] success: {file.name} ({elapsed_ms / 1000:.3f}s)",
|
||||
flush=True,
|
||||
)
|
||||
timings = res.get("timings_ms", {}) or {}
|
||||
if timings:
|
||||
top = sorted(timings.items(), key=lambda x: x[1], reverse=True)[:3]
|
||||
top_text = ", ".join(
|
||||
f"{_step_alias(k)}={v / 1000:.3f}s" for k, v in top
|
||||
)
|
||||
print(f"[{idx}/{total}] time: {top_text}", flush=True)
|
||||
|
||||
out_dir_str = str(res.get("out_dir", "")).strip()
|
||||
doc_artifact_dir = Path(out_dir_str) if out_dir_str else None
|
||||
if (
|
||||
doc_artifact_dir is not None
|
||||
and doc_artifact_dir.exists()
|
||||
and doc_artifact_dir.parent == output_dir
|
||||
):
|
||||
shutil.rmtree(doc_artifact_dir)
|
||||
except Exception as exc:
|
||||
elapsed_ms = int((time.perf_counter() - started) * 1000)
|
||||
detail = traceback.format_exc()
|
||||
doc_artifact_dir = output_dir / file.stem
|
||||
if doc_artifact_dir.exists():
|
||||
shutil.rmtree(doc_artifact_dir)
|
||||
if flat_out.exists():
|
||||
flat_out.unlink()
|
||||
if mirror_out.exists() and mirror_out != flat_out:
|
||||
mirror_out.unlink()
|
||||
results.append(
|
||||
{
|
||||
"file": file.name,
|
||||
"out_dir": str(output_dir / file.stem),
|
||||
"warnings": [str(exc)],
|
||||
"status": "failed",
|
||||
"elapsed_ms": elapsed_ms,
|
||||
"error": str(exc),
|
||||
"error_detail": detail,
|
||||
}
|
||||
)
|
||||
print(
|
||||
f"[{idx}/{total}] failed: {file.name} ({elapsed_ms / 1000:.3f}s)",
|
||||
flush=True,
|
||||
)
|
||||
print(f"[{idx}/{total}] reason: {exc}", flush=True)
|
||||
print(detail.rstrip(), flush=True)
|
||||
return results
|
||||
@@ -0,0 +1,22 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
SUPPORTED_EXTS = {".doc", ".docx", ".pdf", ".xls", ".xlsx", ".csv", ".ppt", ".pptx"}
|
||||
|
||||
|
||||
def discover(path: Path) -> list[Path]:
|
||||
if path.is_file():
|
||||
if path.name.startswith("~$"):
|
||||
return []
|
||||
return [path] if path.suffix.lower() in SUPPORTED_EXTS else []
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(path)
|
||||
files = [
|
||||
p
|
||||
for p in path.rglob("*")
|
||||
if p.is_file()
|
||||
and not p.name.startswith("~$")
|
||||
and p.suffix.lower() in SUPPORTED_EXTS
|
||||
]
|
||||
return sorted(files, key=lambda x: str(x))
|
||||
@@ -0,0 +1 @@
|
||||
"""Atomic skills for enterprise KB pipeline."""
|
||||
@@ -0,0 +1,90 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
from edkb_system.contracts import Chunk, Context
|
||||
|
||||
|
||||
HEAD_RE = re.compile(r"^(#{1,6})\s+(.*)$")
|
||||
|
||||
|
||||
def _chunk_id(source: str, heading: str, index: int, text: str) -> str:
|
||||
raw = f"{source}|{heading}|{index}|{text}"
|
||||
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def run(
|
||||
input_data: dict,
|
||||
context: Context,
|
||||
max_chars: int = 1200,
|
||||
overlap_chars: int = 150,
|
||||
add_heading_path_prefix: bool = True,
|
||||
) -> list[Chunk]:
|
||||
source = input_data["source"]
|
||||
md = input_data["text"]
|
||||
lines = md.splitlines()
|
||||
|
||||
stack: list[str] = []
|
||||
sections: list[tuple[str, str]] = []
|
||||
buf: list[str] = []
|
||||
|
||||
def heading() -> str:
|
||||
return " > ".join(stack) if stack else "ROOT"
|
||||
|
||||
for ln in lines:
|
||||
m = HEAD_RE.match(ln.strip())
|
||||
if m:
|
||||
if buf:
|
||||
sections.append((heading(), "\n".join(buf).strip()))
|
||||
buf = []
|
||||
level = len(m.group(1))
|
||||
text = m.group(2).strip()
|
||||
while len(stack) >= level:
|
||||
stack.pop()
|
||||
stack.append(text)
|
||||
else:
|
||||
buf.append(ln)
|
||||
if buf:
|
||||
sections.append((heading(), "\n".join(buf).strip()))
|
||||
|
||||
out: list[Chunk] = []
|
||||
idx = 0
|
||||
for hp, body in sections:
|
||||
paras = [p.strip() for p in body.split("\n\n") if p.strip()]
|
||||
acc = ""
|
||||
for p in paras:
|
||||
cand = (acc + "\n\n" + p).strip() if acc else p
|
||||
if len(cand) <= max_chars:
|
||||
acc = cand
|
||||
continue
|
||||
if acc:
|
||||
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
|
||||
out.append(
|
||||
Chunk(
|
||||
id=_chunk_id(source, hp, idx, txt),
|
||||
heading_path=hp,
|
||||
text=txt,
|
||||
index=idx,
|
||||
source=source,
|
||||
)
|
||||
)
|
||||
idx += 1
|
||||
overlap = txt[-overlap_chars:] if overlap_chars > 0 else ""
|
||||
acc = (overlap + "\n\n" + p).strip()
|
||||
else:
|
||||
acc = p[:max_chars]
|
||||
if acc:
|
||||
txt = f"# {hp}\n{acc}" if add_heading_path_prefix else acc
|
||||
out.append(
|
||||
Chunk(
|
||||
id=_chunk_id(source, hp, idx, txt),
|
||||
heading_path=hp,
|
||||
text=txt,
|
||||
index=idx,
|
||||
source=source,
|
||||
)
|
||||
)
|
||||
idx += 1
|
||||
|
||||
return out
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,244 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from edkb_system.contracts import Block
|
||||
|
||||
|
||||
def hash_text(text: str) -> str:
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def hash_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
while True:
|
||||
chunk = f.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def _page_image_structured_lines(payload: str) -> list[str]:
|
||||
tokens = [x.strip() for x in payload.split(";") if x.strip()]
|
||||
if not tokens:
|
||||
return []
|
||||
cert_context_hits = 0
|
||||
cert_context_pat = re.compile(
|
||||
r"證明書|证明书|CERTIFICATE|材质|材質|TEST CERTIFICATE|ROHS|MSDS|"
|
||||
r"检测报告|測試報告|材质证明|物性表",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
for tok in tokens:
|
||||
if cert_context_pat.search(tok):
|
||||
cert_context_hits += 1
|
||||
if cert_context_hits < 2:
|
||||
return []
|
||||
|
||||
def _find(pattern: str) -> str:
|
||||
rx = re.compile(pattern, re.IGNORECASE)
|
||||
for tok in tokens:
|
||||
if rx.search(tok):
|
||||
return tok
|
||||
return ""
|
||||
|
||||
def _find_match(pattern: str) -> str:
|
||||
rx = re.compile(pattern, re.IGNORECASE)
|
||||
for tok in tokens:
|
||||
m = rx.search(tok)
|
||||
if m:
|
||||
return m.group(0)
|
||||
return ""
|
||||
|
||||
def _find_after(anchor_pat: str, value_pat: str = r".+") -> str:
|
||||
anchor_rx = re.compile(anchor_pat, re.IGNORECASE)
|
||||
value_rx = re.compile(value_pat, re.IGNORECASE)
|
||||
for idx, tok in enumerate(tokens):
|
||||
if not anchor_rx.search(tok):
|
||||
continue
|
||||
for cand in tokens[idx + 1 : idx + 8]:
|
||||
if value_rx.search(cand) and not anchor_rx.search(cand):
|
||||
return cand
|
||||
return ""
|
||||
|
||||
def _uniq(values: list[tuple[str, str]]) -> list[tuple[str, str]]:
|
||||
out: list[tuple[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for key, value in values:
|
||||
v = value.strip()
|
||||
if not v:
|
||||
continue
|
||||
marker = f"{key}:{v.lower()}"
|
||||
if marker in seen:
|
||||
continue
|
||||
seen.add(marker)
|
||||
out.append((key, v))
|
||||
return out
|
||||
|
||||
certificate_no = ""
|
||||
cert_anchor = re.compile(
|
||||
r"證明書编号|證明書編號|CERTIFICATE\s*(?:NO|NUMBER)?", re.IGNORECASE
|
||||
)
|
||||
cert_value = re.compile(r"(?=.*\d)[A-Z0-9][A-Z0-9/-]{5,}", re.IGNORECASE)
|
||||
for idx, tok in enumerate(tokens):
|
||||
if not cert_anchor.search(tok):
|
||||
continue
|
||||
for cand in tokens[idx + 1 : idx + 8]:
|
||||
if re.search(r"fax|tel|date", cand, re.IGNORECASE):
|
||||
continue
|
||||
if cert_value.fullmatch(cand):
|
||||
certificate_no = cand
|
||||
break
|
||||
if certificate_no:
|
||||
break
|
||||
if not certificate_no:
|
||||
certificate_no = _find_match(
|
||||
r"\b(?=[A-Z0-9-]*\d)[A-Z0-9]{4,}-[A-Z0-9-]+\b"
|
||||
) or _find_match(r"\b\d{6,}[A-Z0-9/-]*\b")
|
||||
issue_date = _find(
|
||||
r"(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)[A-Z.]*\s*\d{1,2},?\s*\d{4}"
|
||||
)
|
||||
spec = _find(r"JIS\s*G\d+|SGCC|EN\s*\d+")
|
||||
product = _find_after(r"PRODUCT", r"[A-Z]{2,}[-A-Z0-9 ]{3,}|COIL") or _find(
|
||||
r"HDG[-A-Z0-9 ]*COIL"
|
||||
)
|
||||
customer = _find(r"CORPORATION|COMPANY|STEEL")
|
||||
order_no = _find_after(r"ORDER|訂單|订单", r"[A-Z0-9/-]{5,}") or _find(
|
||||
r"[A-Z]{0,3}\d{3,}[A-Z0-9/-]*"
|
||||
)
|
||||
weight = ""
|
||||
for idx, tok in enumerate(tokens):
|
||||
if tok.lower() == "kg" and idx > 0:
|
||||
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?", tokens[idx - 1])
|
||||
weight = (m.group(0) if m else tokens[idx - 1]) + " kg"
|
||||
break
|
||||
m = re.search(r"\d{1,3}(?:,\d{3})*(?:\.\d+)?\s*kg", tok, re.IGNORECASE)
|
||||
if m:
|
||||
weight = m.group(0)
|
||||
break
|
||||
|
||||
tensile: list[tuple[str, str]] = []
|
||||
for idx, tok in enumerate(tokens):
|
||||
if tok in {"降伏", "抗拉", "硬度"}:
|
||||
for cand in tokens[idx + 1 : idx + 4]:
|
||||
if re.fullmatch(r"\d+(?:\.\d+)?", cand):
|
||||
tensile.append((tok, cand))
|
||||
break
|
||||
|
||||
fields = _uniq(
|
||||
[
|
||||
("证书编号", certificate_no),
|
||||
("日期", issue_date),
|
||||
("客户", customer),
|
||||
("产品", product),
|
||||
("规格", spec),
|
||||
("订单/追踪号", order_no),
|
||||
("重量", weight),
|
||||
]
|
||||
)
|
||||
|
||||
if not fields and not tensile:
|
||||
return []
|
||||
|
||||
lines = ["## 识别整理版", ""]
|
||||
for key, value in fields:
|
||||
lines.append(f"- {key}:{value}")
|
||||
if tensile:
|
||||
if fields:
|
||||
lines.append("")
|
||||
lines.append("### 关键数值")
|
||||
lines.append("")
|
||||
lines.append("| 项目 | 数值 |")
|
||||
lines.append("| --- | --- |")
|
||||
for key, value in _uniq(tensile):
|
||||
lines.append(f"| {key} | {value} |")
|
||||
lines.extend(["", "## 原始识别结果", ""])
|
||||
return lines
|
||||
|
||||
|
||||
def blocks_to_plain_markdown(blocks: list[Block]) -> str:
|
||||
def _ocr_payload(txt: str) -> str:
|
||||
payload = txt
|
||||
if payload.startswith("OCR_TEXT:"):
|
||||
payload = payload[len("OCR_TEXT:") :].strip()
|
||||
if not payload or payload == "<empty>":
|
||||
return ""
|
||||
payload = re.sub(r"(?m)^\s*-\s*", "", payload)
|
||||
payload = ";".join(x.strip() for x in payload.splitlines() if x.strip())
|
||||
return payload
|
||||
|
||||
ocr_by_image: dict[str, str] = {}
|
||||
for b in blocks:
|
||||
if b.type != "ocr_text" or not b.id.startswith("ocr-"):
|
||||
continue
|
||||
payload = _ocr_payload((b.text or "").strip())
|
||||
if payload:
|
||||
ocr_by_image[b.id[len("ocr-") :]] = payload
|
||||
|
||||
page_text_chars: dict[int, int] = {}
|
||||
page_body_chars: dict[int, int] = {}
|
||||
for b in blocks:
|
||||
if b.type in {"ocr_text", "image"}:
|
||||
continue
|
||||
txt = (b.text or "").strip()
|
||||
if not txt:
|
||||
continue
|
||||
page_text_chars[b.page] = page_text_chars.get(b.page, 0) + len(txt)
|
||||
if b.type != "heading":
|
||||
page_body_chars[b.page] = page_body_chars.get(b.page, 0) + len(txt)
|
||||
|
||||
lines: list[str] = []
|
||||
image_idx = 0
|
||||
for b in sorted(
|
||||
[x for x in blocks if x.type != "ocr_text"],
|
||||
key=lambda x: (x.page, x.cy(), x.cx()),
|
||||
):
|
||||
txt = (b.text or "").strip()
|
||||
if not txt and b.type != "image":
|
||||
continue
|
||||
if b.type == "heading":
|
||||
lines.append(f"## {txt}")
|
||||
elif b.type == "image":
|
||||
data_uri = b.meta.get("data_uri") if b.meta else None
|
||||
if data_uri:
|
||||
image_idx += 1
|
||||
if b.meta and b.meta.get("page_image"):
|
||||
lines.append(f"")
|
||||
else:
|
||||
lines.append(f"")
|
||||
ocr_text = ocr_by_image.get(b.id)
|
||||
if ocr_text:
|
||||
suppress_pptx_ocr = bool(
|
||||
b.meta and b.meta.get("page_image_source") == "pptx"
|
||||
) and (
|
||||
page_body_chars.get(b.page, 0) >= 15
|
||||
or page_text_chars.get(b.page, 0) >= 40
|
||||
)
|
||||
if (
|
||||
b.meta
|
||||
and b.meta.get("page_image")
|
||||
and b.meta.get("page_image_source") != "pptx"
|
||||
):
|
||||
lines.extend(_page_image_structured_lines(ocr_text))
|
||||
if not suppress_pptx_ocr:
|
||||
lines.append(f"图中文字:{ocr_text}")
|
||||
else:
|
||||
lines.append("![image]")
|
||||
else:
|
||||
lines.append(txt)
|
||||
return "\n\n".join(lines).strip() + "\n"
|
||||
|
||||
|
||||
def dump_json(path: Path, data: Any) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def block_to_dict(block: Block) -> dict[str, Any]:
|
||||
return asdict(block)
|
||||
@@ -0,0 +1,83 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
from edkb_system.skills.word_bridge import convert_with_word
|
||||
|
||||
|
||||
def _find_soffice() -> str | None:
|
||||
candidates = [
|
||||
os.environ.get("EDKB_SOFFICE"),
|
||||
r"C:\Program Files\LibreOffice\program\soffice.exe",
|
||||
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
|
||||
"soffice",
|
||||
]
|
||||
for c in candidates:
|
||||
if not c:
|
||||
continue
|
||||
if c == "soffice":
|
||||
return c
|
||||
if Path(c).exists():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def _convert_with_word(path: Path, out_dir: Path) -> Path:
|
||||
output = out_dir / f"{path.stem}.pdf"
|
||||
return convert_with_word(path.resolve(), output.resolve(), 17)
|
||||
|
||||
|
||||
def _convert_with_soffice(path: Path, out_dir: Path, soffice: str) -> Path:
|
||||
output = out_dir / f"{path.stem}.pdf"
|
||||
cmd = [
|
||||
soffice,
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"pdf",
|
||||
str(path),
|
||||
"--outdir",
|
||||
str(out_dir),
|
||||
]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
stderr = (proc.stderr or "").strip() or "no stderr"
|
||||
raise RuntimeError(
|
||||
f"soffice conversion failed (code={proc.returncode}): {stderr}"
|
||||
)
|
||||
if not output.exists():
|
||||
raise RuntimeError(f"soffice conversion produced no output: {output}")
|
||||
return output
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> dict:
|
||||
file_path = Path(input_data["file_path"])
|
||||
work_dir = Path(input_data["work_dir"])
|
||||
out_dir = work_dir / "flow_pdf"
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
errors: list[str] = []
|
||||
if os.name == "nt":
|
||||
try:
|
||||
pdf = _convert_with_word(file_path, out_dir)
|
||||
return {"pdf_path": str(pdf), "converter": "word"}
|
||||
except Exception as exc:
|
||||
errors.append(f"word: {exc}")
|
||||
|
||||
soffice = _find_soffice()
|
||||
if soffice:
|
||||
try:
|
||||
pdf = _convert_with_soffice(file_path, out_dir, soffice)
|
||||
return {"pdf_path": str(pdf), "converter": "soffice"}
|
||||
except Exception as exc:
|
||||
errors.append(f"soffice: {exc}")
|
||||
else:
|
||||
errors.append("soffice: not found")
|
||||
|
||||
context.warnings.append(
|
||||
"doc->pdf conversion unavailable; fallback to docx text parser"
|
||||
)
|
||||
context.warnings.append("doc->pdf details: " + "; ".join(errors))
|
||||
return {"pdf_path": None, "converter": None}
|
||||
@@ -0,0 +1,567 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
from dataclasses import asdict, replace
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlparse
|
||||
|
||||
from edkb_system.contracts import Block, Chunk, Context
|
||||
|
||||
|
||||
def _write(path: Path, text: str) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
|
||||
|
||||
_EMBEDDED_IMG_RE = re.compile(
|
||||
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
_EMBEDDED_IMG_LOOSE_RE = re.compile(
|
||||
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
_EMBEDDED_IMG_ANY_RE = re.compile(
|
||||
r"!\[[^\]]*\]\(data:image/.*?\)",
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
|
||||
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
|
||||
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
|
||||
|
||||
|
||||
def _bool_env(name: str, default: bool) -> bool:
|
||||
raw = os.getenv(name)
|
||||
if raw is None:
|
||||
return default
|
||||
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _sanitize_segment(raw: str) -> str:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
return "untitled"
|
||||
s = re.sub(r"\s+", "_", s)
|
||||
s = s.replace("/", "_").replace("\\", "_")
|
||||
s = re.sub(r"[:*?\"<>|]", "_", s)
|
||||
s = re.sub(r"_+", "_", s).strip("._")
|
||||
return s or "untitled"
|
||||
|
||||
|
||||
def _build_object_prefix(
|
||||
source_category: str, source_rel_path: str, source_file: str
|
||||
) -> str:
|
||||
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
|
||||
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
|
||||
|
||||
category = _sanitize_segment(source_category)
|
||||
if not category:
|
||||
if len(parts) >= 2:
|
||||
category = _sanitize_segment(parts[0])
|
||||
else:
|
||||
category = "uncategorized"
|
||||
|
||||
if parts and _sanitize_segment(parts[0]) == category:
|
||||
parts = parts[1:]
|
||||
|
||||
if parts:
|
||||
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
|
||||
else:
|
||||
doc_parts = [Path(source_file or "document").stem or "document"]
|
||||
|
||||
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
|
||||
normalized = [p for p in normalized if p]
|
||||
return "/".join(normalized)
|
||||
|
||||
|
||||
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
|
||||
endpoint = (raw_endpoint or "").strip()
|
||||
secure_default = False
|
||||
if "://" in endpoint:
|
||||
parsed = urlparse(endpoint)
|
||||
secure_default = parsed.scheme.lower() == "https"
|
||||
endpoint = parsed.netloc or parsed.path
|
||||
endpoint = endpoint.strip().rstrip("/")
|
||||
return endpoint, secure_default
|
||||
|
||||
|
||||
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
|
||||
base = (raw_base or "").strip().rstrip("/")
|
||||
if not base:
|
||||
scheme = "https" if secure else "http"
|
||||
return f"{scheme}://{endpoint}".rstrip("/")
|
||||
if "://" not in base:
|
||||
scheme = "https" if secure else "http"
|
||||
return f"{scheme}://{base}".rstrip("/")
|
||||
return base.rstrip("/")
|
||||
|
||||
|
||||
def _quote_object_name(object_name: str) -> str:
|
||||
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
|
||||
|
||||
|
||||
def _ext_from_blob(blob: bytes) -> str | None:
|
||||
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
return "png"
|
||||
if blob.startswith(b"\xff\xd8\xff"):
|
||||
return "jpg"
|
||||
if blob.startswith((b"GIF87a", b"GIF89a")):
|
||||
return "gif"
|
||||
if blob.startswith(b"BM"):
|
||||
return "bmp"
|
||||
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
|
||||
return "webp"
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_ext(fmt: str, blob: bytes) -> str:
|
||||
f = (fmt or "").lower().strip()
|
||||
if f in {"jpeg", "jpg"}:
|
||||
return "jpg"
|
||||
if f in {"png", "gif", "bmp", "webp"}:
|
||||
return f
|
||||
guessed = _ext_from_blob(blob)
|
||||
return guessed or "png"
|
||||
|
||||
|
||||
def _content_type_for_ext(ext: str) -> str:
|
||||
if ext == "jpg":
|
||||
return "image/jpeg"
|
||||
if ext == "png":
|
||||
return "image/png"
|
||||
if ext == "gif":
|
||||
return "image/gif"
|
||||
if ext == "bmp":
|
||||
return "image/bmp"
|
||||
if ext == "webp":
|
||||
return "image/webp"
|
||||
return "application/octet-stream"
|
||||
|
||||
|
||||
def _is_valid_image_blob(blob: bytes) -> bool:
|
||||
if len(blob) < 8:
|
||||
return False
|
||||
if _ext_from_blob(blob):
|
||||
return True
|
||||
# Unknown format fallback: keep only if not tiny garbage.
|
||||
return len(blob) >= 64
|
||||
|
||||
|
||||
class _MinioStorage:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
endpoint: str,
|
||||
bucket_name: str,
|
||||
access_key: str,
|
||||
secret_key: str,
|
||||
secure: bool,
|
||||
public_base: str,
|
||||
) -> None:
|
||||
import importlib
|
||||
|
||||
minio_mod = importlib.import_module("minio")
|
||||
minio_ctor = getattr(minio_mod, "Minio")
|
||||
|
||||
self.bucket_name = bucket_name
|
||||
self.public_base = public_base.rstrip("/")
|
||||
self.client = minio_ctor(
|
||||
endpoint,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
)
|
||||
if not self.client.bucket_exists(bucket_name):
|
||||
self.client.make_bucket(bucket_name)
|
||||
|
||||
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
|
||||
stream = io.BytesIO(blob)
|
||||
self.client.put_object(
|
||||
self.bucket_name,
|
||||
object_name,
|
||||
stream,
|
||||
len(blob),
|
||||
content_type=content_type,
|
||||
)
|
||||
|
||||
def list_prefix(self, prefix: str) -> list[str]:
|
||||
return [
|
||||
obj.object_name
|
||||
for obj in self.client.list_objects(
|
||||
self.bucket_name,
|
||||
prefix=prefix,
|
||||
recursive=True,
|
||||
)
|
||||
]
|
||||
|
||||
def remove_object(self, object_name: str) -> None:
|
||||
self.client.remove_object(self.bucket_name, object_name)
|
||||
|
||||
def build_url(self, object_name: str) -> str:
|
||||
return (
|
||||
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
|
||||
)
|
||||
|
||||
|
||||
class _RemoteImageRewriter:
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
context: Context,
|
||||
source_file: str,
|
||||
source_rel_path: str,
|
||||
source_category: str,
|
||||
) -> None:
|
||||
self.context = context
|
||||
self.source_file = source_file
|
||||
self.source_rel_path = source_rel_path
|
||||
self.source_category = source_category
|
||||
self.object_prefix = _build_object_prefix(
|
||||
source_category, source_rel_path, source_file
|
||||
)
|
||||
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
|
||||
|
||||
self.storage: _MinioStorage | None = None
|
||||
self._storage_initialized = False
|
||||
self.uri_cache: dict[str, str] = {}
|
||||
self.sha_cache: dict[str, tuple[str, str]] = {}
|
||||
self.referenced_objects: set[str] = set()
|
||||
|
||||
self.uploaded_count = 0
|
||||
self.reused_count = 0
|
||||
self.invalid_removed_count = 0
|
||||
self.kept_embedded_count = 0
|
||||
self.stale_removed_count = 0
|
||||
self._upload_error_warn_count = 0
|
||||
self._saw_embedded_image = False
|
||||
self._next_image_index = 1
|
||||
|
||||
def _build_storage(self) -> _MinioStorage | None:
|
||||
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
|
||||
if self.allow_embed_fallback:
|
||||
self.context.warnings.append(
|
||||
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
|
||||
)
|
||||
return None
|
||||
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
|
||||
|
||||
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
|
||||
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
|
||||
secure = _bool_env("MINIO_SECURE", secure_default)
|
||||
|
||||
if not endpoint:
|
||||
if self.allow_embed_fallback:
|
||||
self.context.warnings.append(
|
||||
"image-hosting disabled: MINIO_ENDPOINT is empty"
|
||||
)
|
||||
return None
|
||||
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
|
||||
|
||||
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
|
||||
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
|
||||
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
|
||||
public_base = _normalize_public_base(
|
||||
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
|
||||
)
|
||||
|
||||
try:
|
||||
return _MinioStorage(
|
||||
endpoint=endpoint,
|
||||
bucket_name=bucket_name,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=secure,
|
||||
public_base=public_base,
|
||||
)
|
||||
except Exception as exc:
|
||||
if self.allow_embed_fallback:
|
||||
self.context.warnings.append(
|
||||
f"image-hosting unavailable, keep embedded image: {exc}"
|
||||
)
|
||||
return None
|
||||
raise RuntimeError(f"image-hosting unavailable: {exc}")
|
||||
|
||||
def _warn_upload_error(self, msg: str) -> None:
|
||||
if self._upload_error_warn_count < 5:
|
||||
self.context.warnings.append(msg)
|
||||
self._upload_error_warn_count += 1
|
||||
|
||||
def _ensure_storage(self) -> None:
|
||||
if self._storage_initialized:
|
||||
return
|
||||
self.storage = self._build_storage()
|
||||
self._storage_initialized = True
|
||||
|
||||
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
|
||||
cached = self.uri_cache.get(uri)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
fmt = (fmt or "png").lower()
|
||||
b64_clean = re.sub(r"\s+", "", b64_raw)
|
||||
try:
|
||||
blob = base64.b64decode(b64_clean, validate=False)
|
||||
except Exception:
|
||||
self.invalid_removed_count += 1
|
||||
self.uri_cache[uri] = _DROP_IMAGE
|
||||
return _DROP_IMAGE
|
||||
|
||||
if not _is_valid_image_blob(blob):
|
||||
self.invalid_removed_count += 1
|
||||
self.uri_cache[uri] = _DROP_IMAGE
|
||||
return _DROP_IMAGE
|
||||
|
||||
self._ensure_storage()
|
||||
if self.storage is None:
|
||||
if not self.allow_embed_fallback:
|
||||
raise RuntimeError(
|
||||
"image-hosting unavailable: embedded fallback is disabled"
|
||||
)
|
||||
self.kept_embedded_count += 1
|
||||
self.uri_cache[uri] = _KEEP_IMAGE
|
||||
return _KEEP_IMAGE
|
||||
|
||||
sha = hashlib.sha256(blob).hexdigest()
|
||||
cached_sha = self.sha_cache.get(sha)
|
||||
if cached_sha is not None:
|
||||
url, object_name = cached_sha
|
||||
self.referenced_objects.add(object_name)
|
||||
self.reused_count += 1
|
||||
self.uri_cache[uri] = url
|
||||
return url
|
||||
|
||||
ext = _normalize_ext(fmt, blob)
|
||||
content_type = _content_type_for_ext(ext)
|
||||
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
|
||||
self._next_image_index += 1
|
||||
object_name = (
|
||||
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
|
||||
)
|
||||
|
||||
try:
|
||||
self.storage.put_bytes(object_name, blob, content_type)
|
||||
url = self.storage.build_url(object_name)
|
||||
self.sha_cache[sha] = (url, object_name)
|
||||
self.referenced_objects.add(object_name)
|
||||
self.uploaded_count += 1
|
||||
self.uri_cache[uri] = url
|
||||
return url
|
||||
except Exception as exc:
|
||||
if not self.allow_embed_fallback:
|
||||
raise RuntimeError(
|
||||
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
|
||||
) from exc
|
||||
self.kept_embedded_count += 1
|
||||
self.uri_cache[uri] = _KEEP_IMAGE
|
||||
self._warn_upload_error(
|
||||
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
|
||||
)
|
||||
return _KEEP_IMAGE
|
||||
|
||||
def _process_match(self, m: re.Match[str]) -> str:
|
||||
return self._process_embedded_uri(
|
||||
m.group("uri"),
|
||||
m.group("fmt") or "png",
|
||||
m.group("b64") or "",
|
||||
)
|
||||
|
||||
def _process_loose_uri(self, uri: str) -> str:
|
||||
cached = self.uri_cache.get(uri)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
head, sep, b64_raw = uri.partition(",")
|
||||
if not sep:
|
||||
self.invalid_removed_count += 1
|
||||
self.uri_cache[uri] = _DROP_IMAGE
|
||||
return _DROP_IMAGE
|
||||
|
||||
fmt = "png"
|
||||
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
|
||||
if m:
|
||||
fmt = (m.group("fmt") or "png").lower()
|
||||
|
||||
return self._process_embedded_uri(uri, fmt, b64_raw)
|
||||
|
||||
def replace_text(self, text: str) -> str:
|
||||
if not text or "data:image/" not in text:
|
||||
return text
|
||||
self._saw_embedded_image = True
|
||||
|
||||
def repl(m: re.Match[str]) -> str:
|
||||
alt = m.group("alt") or "image"
|
||||
decision = self._process_match(m)
|
||||
if decision == _DROP_IMAGE:
|
||||
return ""
|
||||
if decision == _KEEP_IMAGE:
|
||||
return m.group(0)
|
||||
return f""
|
||||
|
||||
out = _EMBEDDED_IMG_RE.sub(repl, text)
|
||||
if "data:image/" in out:
|
||||
|
||||
def loose_repl(m: re.Match[str]) -> str:
|
||||
alt = m.group("alt") or "image"
|
||||
decision = self._process_loose_uri(m.group("uri") or "")
|
||||
if decision == _DROP_IMAGE:
|
||||
return ""
|
||||
if decision == _KEEP_IMAGE:
|
||||
return m.group(0)
|
||||
return f""
|
||||
|
||||
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
|
||||
if not self.allow_embed_fallback and "data:image/" in out:
|
||||
dropped_before = self.invalid_removed_count
|
||||
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
|
||||
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
|
||||
removed = self.invalid_removed_count - dropped_before
|
||||
if "data:image/" in out:
|
||||
self.context.warnings.append(
|
||||
"image-hosting left non-markdown data:image content; kept as-is"
|
||||
)
|
||||
else:
|
||||
self.context.warnings.append(
|
||||
"image-hosting removed unsupported embedded images"
|
||||
+ (f": {removed}" if removed > 0 else "")
|
||||
)
|
||||
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
|
||||
return out
|
||||
|
||||
def finalize(self) -> None:
|
||||
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
|
||||
self._ensure_storage()
|
||||
|
||||
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
|
||||
prefix = f"{self.object_prefix}/"
|
||||
try:
|
||||
for object_name in self.storage.list_prefix(prefix):
|
||||
if object_name in self.referenced_objects:
|
||||
continue
|
||||
self.storage.remove_object(object_name)
|
||||
self.stale_removed_count += 1
|
||||
except Exception as exc:
|
||||
self.context.warnings.append(
|
||||
f"image-hosting cleanup failed ({self.source_file}): {exc}"
|
||||
)
|
||||
|
||||
if self.invalid_removed_count > 0:
|
||||
self.context.warnings.append(
|
||||
f"image-hosting removed invalid images: {self.invalid_removed_count}"
|
||||
)
|
||||
|
||||
if self.kept_embedded_count > 0 and self.storage is None:
|
||||
self.context.warnings.append(
|
||||
"image-hosting unavailable: keep legacy data:image embeds"
|
||||
)
|
||||
|
||||
if (
|
||||
self.uploaded_count > 0
|
||||
or self.reused_count > 0
|
||||
or self.stale_removed_count > 0
|
||||
):
|
||||
self.context.warnings.append(
|
||||
"image-hosting synced "
|
||||
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
|
||||
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
|
||||
)
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> dict:
|
||||
out_dir = Path(input_data["out_dir"])
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
source_file = input_data.get("source_file", "")
|
||||
source_rel_path = input_data.get("source_rel_path", source_file)
|
||||
source_category = input_data.get("source_category", "")
|
||||
source_stem = Path(source_file).stem if source_file else out_dir.name
|
||||
flat_clean_path = Path(
|
||||
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
|
||||
)
|
||||
view_clean_path = out_dir / "03_clean_view.md"
|
||||
view_images_dir = out_dir / "images_view"
|
||||
|
||||
for p in [
|
||||
out_dir / "01_raw_layout.json",
|
||||
out_dir / "02_flow_procedure.md",
|
||||
out_dir / "03_clean.md",
|
||||
out_dir / "04_chunks.jsonl",
|
||||
out_dir / "report.md",
|
||||
view_clean_path,
|
||||
flat_clean_path,
|
||||
]:
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
chunks_dir = out_dir / "chunks"
|
||||
if chunks_dir.exists():
|
||||
shutil.rmtree(chunks_dir)
|
||||
if view_images_dir.exists():
|
||||
shutil.rmtree(view_images_dir)
|
||||
|
||||
clean_md: str = input_data.get("clean_md", "")
|
||||
chunks: list[Chunk] = input_data.get("chunks", [])
|
||||
blocks: list[Block] = input_data.get("blocks", [])
|
||||
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
|
||||
|
||||
rewriter = _RemoteImageRewriter(
|
||||
context=context,
|
||||
source_file=source_file,
|
||||
source_rel_path=source_rel_path,
|
||||
source_category=source_category,
|
||||
)
|
||||
|
||||
clean_md = rewriter.replace_text(clean_md)
|
||||
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
|
||||
rewriter.finalize()
|
||||
|
||||
_write(out_dir / "03_clean.md", clean_md)
|
||||
_write(flat_clean_path, clean_md)
|
||||
|
||||
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
|
||||
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
|
||||
|
||||
chunks_dir.mkdir(parents=True, exist_ok=True)
|
||||
for c in exported_chunks:
|
||||
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
|
||||
|
||||
if flow_markdowns:
|
||||
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
|
||||
|
||||
_write(
|
||||
out_dir / "01_raw_layout.json",
|
||||
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
|
||||
)
|
||||
|
||||
report_lines = [
|
||||
f"# Report: {input_data.get('source_file', '')}",
|
||||
"",
|
||||
f"- pages: {context.pages}",
|
||||
f"- images: {context.images}",
|
||||
f"- ocr_characters: {context.ocr_characters}",
|
||||
f"- flows_detected: {context.flows_detected}",
|
||||
f"- confidence: {context.confidence:.2f}",
|
||||
"",
|
||||
"## warnings",
|
||||
]
|
||||
if context.warnings:
|
||||
report_lines.extend([f"- {w}" for w in context.warnings])
|
||||
else:
|
||||
report_lines.append("- none")
|
||||
|
||||
report_lines.extend(
|
||||
[
|
||||
"",
|
||||
"## recommended_dify_settings",
|
||||
"- Index: High Quality",
|
||||
"- Retrieval: Hybrid",
|
||||
"- Chunking: General",
|
||||
"",
|
||||
]
|
||||
)
|
||||
_write(out_dir / "report.md", "\n".join(report_lines))
|
||||
|
||||
return {"out_dir": str(out_dir)}
|
||||
@@ -0,0 +1,142 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import networkx as nx
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
|
||||
@dataclass
|
||||
class Node:
|
||||
id: str
|
||||
text: str
|
||||
page: int
|
||||
kind: str
|
||||
bbox: tuple[float, float, float, float]
|
||||
|
||||
|
||||
def _is_decision(text: str) -> bool:
|
||||
kws = ["判定", "判断", "是否", "if", "check"]
|
||||
s = text.lower()
|
||||
return any(k in s for k in kws)
|
||||
|
||||
|
||||
def _dist(a: Node, b: Node) -> float:
|
||||
ax = (a.bbox[0] + a.bbox[2]) / 2.0
|
||||
ay = (a.bbox[1] + a.bbox[3]) / 2.0
|
||||
bx = (b.bbox[0] + b.bbox[2]) / 2.0
|
||||
by = (b.bbox[1] + b.bbox[3]) / 2.0
|
||||
return ((ax - bx) ** 2 + (ay - by) ** 2) ** 0.5
|
||||
|
||||
|
||||
def run(input_data: list[Block], context: Context) -> dict:
|
||||
blocks = [
|
||||
b
|
||||
for b in input_data
|
||||
if b.type in {"textbox", "shape", "diamond", "arrow_label", "paragraph"}
|
||||
and b.text.strip()
|
||||
]
|
||||
by_page: dict[int, list[Block]] = {}
|
||||
for b in blocks:
|
||||
by_page.setdefault(b.page, []).append(b)
|
||||
|
||||
page_markdowns: list[str] = []
|
||||
debug: list[dict] = []
|
||||
|
||||
for page in sorted(by_page):
|
||||
cands = by_page[page]
|
||||
nodes: list[Node] = []
|
||||
labels: list[Node] = []
|
||||
for b in cands:
|
||||
text = b.text.strip()
|
||||
if b.type == "arrow_label" or text.upper() in {
|
||||
"NG",
|
||||
"OK",
|
||||
"Y",
|
||||
"N",
|
||||
"YES",
|
||||
"NO",
|
||||
}:
|
||||
labels.append(Node(b.id, text, b.page, "label", b.bbox))
|
||||
continue
|
||||
kind = "decision" if (_is_decision(text) or b.type == "diamond") else "step"
|
||||
nodes.append(Node(b.id, text, b.page, kind, b.bbox))
|
||||
nodes = sorted(
|
||||
nodes,
|
||||
key=lambda n: (
|
||||
(n.bbox[1] + n.bbox[3]) / 2.0,
|
||||
(n.bbox[0] + n.bbox[2]) / 2.0,
|
||||
),
|
||||
)
|
||||
if not nodes:
|
||||
continue
|
||||
|
||||
g = nx.DiGraph()
|
||||
for n in nodes:
|
||||
g.add_node(n.id, node=n)
|
||||
|
||||
for i, src in enumerate(nodes[:-1]):
|
||||
dst = nodes[i + 1]
|
||||
g.add_edge(src.id, dst.id, label=None)
|
||||
|
||||
for dec in [n for n in nodes if n.kind == "decision"]:
|
||||
right_steps = [
|
||||
n
|
||||
for n in nodes
|
||||
if ((n.bbox[0] + n.bbox[2]) / 2.0) > ((dec.bbox[0] + dec.bbox[2]) / 2.0)
|
||||
]
|
||||
if right_steps:
|
||||
target = min(right_steps, key=lambda x: _dist(dec, x))
|
||||
label_node = None
|
||||
right_labels = [
|
||||
l
|
||||
for l in labels
|
||||
if ((l.bbox[0] + l.bbox[2]) / 2.0)
|
||||
> ((dec.bbox[0] + dec.bbox[2]) / 2.0)
|
||||
]
|
||||
if right_labels:
|
||||
label_node = min(right_labels, key=lambda x: _dist(dec, x))
|
||||
g.add_edge(
|
||||
dec.id, target.id, label=(label_node.text if label_node else "分支")
|
||||
)
|
||||
|
||||
ordered = nodes
|
||||
idx_map = {n.id: i + 1 for i, n in enumerate(ordered)}
|
||||
cycles = list(nx.simple_cycles(g))
|
||||
cyc_nodes = {nid for cyc in cycles for nid in cyc}
|
||||
|
||||
lines = [f"## Page {page} Procedure"]
|
||||
for n in ordered:
|
||||
title = n.text
|
||||
if n.kind == "decision" and not title.startswith("判定"):
|
||||
title = f"判定:{title}"
|
||||
lines.append(f"{idx_map[n.id]}. {title}")
|
||||
if n.kind == "decision":
|
||||
for _, dst, data in g.out_edges(n.id, data=True):
|
||||
if data.get("label") is None:
|
||||
continue
|
||||
label = data.get("label") or "分支"
|
||||
if dst in cyc_nodes:
|
||||
lines.append(f"- {label} -> 返回到步骤{idx_map.get(dst, '?')}")
|
||||
else:
|
||||
dst_text = g.nodes[dst]["node"].text
|
||||
lines.append(f"- {label} -> {dst_text}")
|
||||
|
||||
page_markdowns.append("\n".join(lines))
|
||||
debug.append(
|
||||
{
|
||||
"page": page,
|
||||
"nodes": [
|
||||
{"id": n.id, "text": n.text, "kind": n.kind, "bbox": list(n.bbox)}
|
||||
for n in nodes
|
||||
],
|
||||
"edges": [
|
||||
{"src": s, "dst": d, "label": data.get("label")}
|
||||
for s, d, data in g.edges(data=True)
|
||||
],
|
||||
}
|
||||
)
|
||||
|
||||
context.flows_detected = len(page_markdowns)
|
||||
return {"flow_markdowns": page_markdowns, "debug": debug}
|
||||
@@ -0,0 +1,419 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.config import RouterConfig
|
||||
from edkb_system.contracts import Context, DocumentProfile
|
||||
|
||||
|
||||
_DOC_KIND_STRATEGY = {
|
||||
"flow_procedure": {
|
||||
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
||||
"disable": set(),
|
||||
},
|
||||
"policy_text": {
|
||||
"enable": set(),
|
||||
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
||||
},
|
||||
"tabular_record": {
|
||||
"enable": set(),
|
||||
"disable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
||||
},
|
||||
"mixed": {
|
||||
"enable": {"edkb-doc-to-pdf", "edkb-flow-reconstruct"},
|
||||
"disable": set(),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _keyword_score(name: str, keywords: dict[str, float]) -> float:
|
||||
score = 0.0
|
||||
for k, w in keywords.items():
|
||||
if k in name:
|
||||
score += w
|
||||
return score
|
||||
|
||||
|
||||
def _score_text_keywords(text: str, keywords: dict[str, float]) -> float:
|
||||
score = 0.0
|
||||
for k, w in keywords.items():
|
||||
if k in text:
|
||||
score += w
|
||||
return score
|
||||
|
||||
|
||||
def _has_flow_evidence(stem: str, content: dict) -> bool:
|
||||
name = stem.lower()
|
||||
strong_name_hit = any(
|
||||
k in name for k in ["流程", "流程图", "判定", "作业标准", "检验作业"]
|
||||
)
|
||||
flow_hits = int(content.get("flow_hits", 0) or 0)
|
||||
shape_hits = int(content.get("shape_hits", 0) or 0)
|
||||
if flow_hits >= 6:
|
||||
return True
|
||||
if flow_hits >= 3 and shape_hits >= 1:
|
||||
return True
|
||||
return strong_name_hit
|
||||
|
||||
|
||||
def _probe_docx_xml(path: Path) -> dict:
|
||||
signals = {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
try:
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
xml_parts = [
|
||||
n for n in zf.namelist() if n.startswith("word/") and n.endswith(".xml")
|
||||
]
|
||||
xml_blob = ""
|
||||
for n in xml_parts[:12]:
|
||||
try:
|
||||
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
return signals
|
||||
|
||||
if not xml_blob:
|
||||
return signals
|
||||
|
||||
text = xml_blob.lower()
|
||||
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
|
||||
signals["table_hits"] = text.count("<w:tbl")
|
||||
signals["image_hits"] = text.count("<a:blip") + text.count("<v:imagedata")
|
||||
signals["shape_hits"] = (
|
||||
text.count("<w:drawing") + text.count("<v:shape") + text.count("<wps:wsp")
|
||||
)
|
||||
flow_kw = {
|
||||
"流程": 0.3,
|
||||
"流程图": 0.4,
|
||||
"判定": 0.25,
|
||||
"检验": 0.2,
|
||||
"作业": 0.15,
|
||||
}
|
||||
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
|
||||
return signals
|
||||
|
||||
|
||||
def _probe_pdf(path: Path) -> dict:
|
||||
signals = {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
try:
|
||||
blob = path.read_bytes()[: 2 * 1024 * 1024]
|
||||
except Exception:
|
||||
return signals
|
||||
|
||||
text = blob.decode("latin-1", errors="ignore")
|
||||
signals["image_hits"] = text.count("/Subtype /Image") + text.count("/Image")
|
||||
text_ops = text.count(" BT") + text.count(" ET")
|
||||
signals["has_text"] = text_ops >= 10
|
||||
return signals
|
||||
|
||||
|
||||
def _probe_pptx(path: Path) -> dict:
|
||||
signals = {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
try:
|
||||
with zipfile.ZipFile(path) as zf:
|
||||
xml_parts = [
|
||||
n
|
||||
for n in zf.namelist()
|
||||
if n.startswith("ppt/slides/") and n.endswith(".xml")
|
||||
]
|
||||
xml_blob = ""
|
||||
for n in xml_parts[:20]:
|
||||
try:
|
||||
xml_blob += zf.read(n).decode("utf-8", errors="ignore")
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
return signals
|
||||
|
||||
if not xml_blob:
|
||||
return signals
|
||||
text = xml_blob.lower()
|
||||
signals["has_text"] = bool(re.search(r"[a-z\u4e00-\u9fff]{2,}", text))
|
||||
signals["table_hits"] = text.count("<a:tbl")
|
||||
signals["image_hits"] = text.count("<a:blip")
|
||||
signals["shape_hits"] = text.count("<p:sp") + text.count("<p:cxnsp")
|
||||
flow_kw = {"流程": 0.4, "流程图": 0.5, "送样": 0.3, "承认": 0.3, "判定": 0.25}
|
||||
signals["flow_hits"] = int(_score_text_keywords(text, flow_kw) * 10)
|
||||
return signals
|
||||
|
||||
|
||||
def _probe_content(file_path: Path, ext: str) -> dict:
|
||||
if ext == ".docx":
|
||||
return _probe_docx_xml(file_path)
|
||||
if ext == ".doc":
|
||||
cache_docx = file_path.parents[1] / "cache" / f"{file_path.stem}.docx"
|
||||
if cache_docx.exists():
|
||||
return _probe_docx_xml(cache_docx)
|
||||
return {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
if ext == ".pdf":
|
||||
return _probe_pdf(file_path)
|
||||
if ext == ".pptx":
|
||||
return _probe_pptx(file_path)
|
||||
if ext == ".ppt":
|
||||
cache_pptx = file_path.parents[1] / "cache" / f"{file_path.stem}.pptx"
|
||||
if cache_pptx.exists():
|
||||
return _probe_pptx(cache_pptx)
|
||||
return {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
if ext in {".xls", ".xlsx", ".csv"}:
|
||||
return {
|
||||
"has_text": True,
|
||||
"table_hits": 8,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
return {
|
||||
"has_text": False,
|
||||
"table_hits": 0,
|
||||
"flow_hits": 0,
|
||||
"image_hits": 0,
|
||||
"shape_hits": 0,
|
||||
}
|
||||
|
||||
|
||||
def _build_pipeline(
|
||||
ext: str,
|
||||
doc_kind: str,
|
||||
scan_likelihood: float,
|
||||
cfg: RouterConfig,
|
||||
) -> list[str]:
|
||||
strategy = _DOC_KIND_STRATEGY.get(doc_kind, _DOC_KIND_STRATEGY["mixed"])
|
||||
enable = set(strategy["enable"])
|
||||
disable = set(strategy["disable"])
|
||||
|
||||
pipeline: list[str] = []
|
||||
if ext in {".doc", ".docx"}:
|
||||
pipeline.append("edkb-loader-docx")
|
||||
if "edkb-doc-to-pdf" in enable and "edkb-doc-to-pdf" not in disable:
|
||||
pipeline.append("edkb-doc-to-pdf")
|
||||
elif ext == ".pdf":
|
||||
pipeline.append("edkb-loader-pdf")
|
||||
elif ext in {".ppt", ".pptx"}:
|
||||
pipeline.append("edkb-loader-pptx")
|
||||
elif ext in {".xls", ".xlsx"}:
|
||||
pipeline.extend(["edkb-loader-excel", "edkb-table-linearize"])
|
||||
elif ext == ".csv":
|
||||
pipeline.extend(["edkb-loader-csv", "edkb-table-linearize"])
|
||||
|
||||
if ext in {".doc", ".docx", ".pdf", ".ppt", ".pptx"}:
|
||||
if scan_likelihood >= cfg.scan_likelihood_threshold:
|
||||
pipeline.append("edkb-ocr")
|
||||
if "edkb-flow-reconstruct" in enable and "edkb-flow-reconstruct" not in disable:
|
||||
pipeline.append("edkb-flow-reconstruct")
|
||||
|
||||
pipeline.extend(
|
||||
[
|
||||
"edkb-clean",
|
||||
"edkb-chunk",
|
||||
"edkb-quality-gate",
|
||||
"edkb-export",
|
||||
"edkb-postcheck",
|
||||
]
|
||||
)
|
||||
return pipeline
|
||||
|
||||
|
||||
def _decide_doc_kind(
|
||||
stem: str, ext: str, content: dict
|
||||
) -> tuple[str, float, float, float, list[str]]:
|
||||
s = stem.lower()
|
||||
reasons: list[str] = []
|
||||
|
||||
flow_pos = {
|
||||
"流程图": 0.5,
|
||||
"作业流程": 0.45,
|
||||
"流程": 0.25,
|
||||
"检验": 0.25,
|
||||
"作业标准": 0.35,
|
||||
"sop": 0.35,
|
||||
"判定": 0.2,
|
||||
"oqc": 0.2,
|
||||
"iqc": 0.2,
|
||||
}
|
||||
flow_neg = {
|
||||
"管理办法": 0.35,
|
||||
"制度": 0.3,
|
||||
"守则": 0.3,
|
||||
"规定": 0.25,
|
||||
"手册": 0.2,
|
||||
}
|
||||
table_pos = {
|
||||
"台账": 0.45,
|
||||
"清单": 0.35,
|
||||
"记录": 0.25,
|
||||
"表单": 0.4,
|
||||
"excel": 0.4,
|
||||
}
|
||||
|
||||
flow_raw = 0.35 + _keyword_score(s, flow_pos) - _keyword_score(s, flow_neg)
|
||||
table_raw = 0.15 + _keyword_score(s, table_pos)
|
||||
|
||||
if ext in {".xls", ".xlsx", ".csv"}:
|
||||
table_raw += 0.55
|
||||
if ext == ".pdf":
|
||||
flow_raw += 0.05
|
||||
if ext in {".ppt", ".pptx"}:
|
||||
flow_raw += 0.1
|
||||
|
||||
flow_raw += min(0.45, 0.04 * content.get("flow_hits", 0))
|
||||
flow_raw += min(0.25, 0.02 * content.get("shape_hits", 0))
|
||||
table_raw += min(0.55, 0.08 * content.get("table_hits", 0))
|
||||
if content.get("image_hits", 0) >= 2 and ext in {
|
||||
".doc",
|
||||
".docx",
|
||||
".pdf",
|
||||
".ppt",
|
||||
".pptx",
|
||||
}:
|
||||
flow_raw += 0.05
|
||||
|
||||
flow_likelihood = max(0.05, min(0.95, flow_raw))
|
||||
table_likelihood = max(0.05, min(0.95, table_raw))
|
||||
text_density = 0.55
|
||||
flow_evidence = _has_flow_evidence(stem, content)
|
||||
|
||||
if not flow_evidence:
|
||||
flow_likelihood = min(flow_likelihood, 0.59)
|
||||
if content.get("table_hits", 0) >= 1:
|
||||
table_likelihood = max(table_likelihood, 0.65)
|
||||
|
||||
if (
|
||||
flow_evidence
|
||||
and flow_likelihood >= 0.65
|
||||
and (table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1)
|
||||
):
|
||||
doc_kind = "mixed"
|
||||
reasons.append("content indicates mixed flow+table document")
|
||||
elif table_likelihood >= 0.75 and (flow_likelihood < 0.6 or not flow_evidence):
|
||||
doc_kind = "tabular_record"
|
||||
reasons.append("content indicates table-like document")
|
||||
elif not flow_evidence and (
|
||||
table_likelihood >= 0.5 or content.get("table_hits", 0) >= 1
|
||||
):
|
||||
doc_kind = "tabular_record"
|
||||
reasons.append("content indicates text+table document without flow")
|
||||
elif flow_evidence and flow_likelihood >= 0.65:
|
||||
doc_kind = "flow_procedure"
|
||||
reasons.append("content indicates flow/procedure document")
|
||||
elif flow_likelihood <= 0.35 or not flow_evidence:
|
||||
doc_kind = "policy_text"
|
||||
reasons.append("content indicates policy/management text")
|
||||
else:
|
||||
doc_kind = "mixed"
|
||||
reasons.append("content indicates mixed document")
|
||||
|
||||
return doc_kind, flow_likelihood, table_likelihood, text_density, reasons
|
||||
|
||||
|
||||
def _derive_content_modes(
|
||||
ext: str,
|
||||
stem: str,
|
||||
content: dict,
|
||||
flow_likelihood: float,
|
||||
table_likelihood: float,
|
||||
) -> list[str]:
|
||||
modes: set[str] = set()
|
||||
if content.get("has_text") or ext in {
|
||||
".doc",
|
||||
".docx",
|
||||
".pdf",
|
||||
".ppt",
|
||||
".pptx",
|
||||
".xls",
|
||||
".xlsx",
|
||||
".csv",
|
||||
}:
|
||||
modes.add("text")
|
||||
if content.get("image_hits", 0) > 0:
|
||||
modes.add("image")
|
||||
if table_likelihood >= 0.65 or content.get("table_hits", 0) >= 1:
|
||||
modes.add("table")
|
||||
if _has_flow_evidence(stem, content) and flow_likelihood >= 0.6:
|
||||
modes.add("flow")
|
||||
return sorted(modes)
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context, cfg: RouterConfig) -> DocumentProfile:
|
||||
file_path = Path(input_data["file_path"])
|
||||
ext = file_path.suffix.lower()
|
||||
file_type = ext.lstrip(".")
|
||||
|
||||
size = file_path.stat().st_size if file_path.exists() else 0
|
||||
has_tables = ext in {".xls", ".xlsx", ".csv"}
|
||||
content_signals = _probe_content(file_path, ext)
|
||||
doc_kind, flow_likelihood, table_likelihood, text_density, reasons = (
|
||||
_decide_doc_kind(file_path.stem, ext, content_signals)
|
||||
)
|
||||
content_modes = _derive_content_modes(
|
||||
ext, file_path.stem, content_signals, flow_likelihood, table_likelihood
|
||||
)
|
||||
|
||||
scan_likelihood = 0.2
|
||||
if ext == ".pdf" and size > 3 * 1024 * 1024:
|
||||
scan_likelihood = 0.65
|
||||
|
||||
has_images = ext in {".pdf", ".doc", ".docx", ".ppt", ".pptx"}
|
||||
|
||||
pipeline = _build_pipeline(ext, doc_kind, scan_likelihood, cfg)
|
||||
|
||||
context.file_type = file_type
|
||||
context.extras["intake"] = {
|
||||
"doc_kind": doc_kind,
|
||||
"content_modes": content_modes,
|
||||
"route_reasons": reasons,
|
||||
"strategy": {
|
||||
"enable": sorted(_DOC_KIND_STRATEGY.get(doc_kind, {}).get("enable", set())),
|
||||
"disable": sorted(
|
||||
_DOC_KIND_STRATEGY.get(doc_kind, {}).get("disable", set())
|
||||
),
|
||||
},
|
||||
"content_signals": content_signals,
|
||||
"flow_likelihood": round(flow_likelihood, 3),
|
||||
"table_likelihood": round(table_likelihood, 3),
|
||||
"scan_likelihood": round(scan_likelihood, 3),
|
||||
"pipeline": pipeline,
|
||||
}
|
||||
|
||||
return DocumentProfile(
|
||||
file_type=file_type,
|
||||
text_density=text_density,
|
||||
has_images=has_images,
|
||||
has_tables=has_tables,
|
||||
flow_likelihood=flow_likelihood,
|
||||
scan_likelihood=scan_likelihood,
|
||||
table_likelihood=table_likelihood,
|
||||
language_hint="zh",
|
||||
recommended_pipeline=pipeline,
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> dict:
|
||||
file_path = Path(input_data["file_path"])
|
||||
raw = None
|
||||
for enc in ("utf-8-sig", "utf-8", "gb18030"):
|
||||
try:
|
||||
raw = file_path.read_text(encoding=enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if raw is None:
|
||||
raw = file_path.read_text(errors="ignore")
|
||||
|
||||
sample = raw[:4096]
|
||||
try:
|
||||
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t")
|
||||
delim = dialect.delimiter
|
||||
except Exception:
|
||||
delim = ","
|
||||
|
||||
rows = [
|
||||
r
|
||||
for r in csv.reader(raw.splitlines(), delimiter=delim)
|
||||
if any(c.strip() for c in r)
|
||||
]
|
||||
table = {
|
||||
"sheet": "csv",
|
||||
"headers": rows[0] if rows else [],
|
||||
"rows": rows[1:] if len(rows) > 1 else [],
|
||||
}
|
||||
context.extras["tables_count"] = 1
|
||||
return table
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,89 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
|
||||
|
||||
def _soffice_candidates() -> list[str]:
|
||||
return [
|
||||
os.environ.get("EDKB_SOFFICE", "").strip(),
|
||||
r"C:\Program Files\LibreOffice\program\soffice.exe",
|
||||
r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
|
||||
"soffice",
|
||||
]
|
||||
|
||||
|
||||
def _convert_xls_to_xlsx(path: Path, out_dir: Path) -> Path:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
output = out_dir / f"{path.stem}.xlsx"
|
||||
errors: list[str] = []
|
||||
for soffice in _soffice_candidates():
|
||||
if not soffice:
|
||||
continue
|
||||
cmd = [
|
||||
soffice,
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"xlsx",
|
||||
str(path),
|
||||
"--outdir",
|
||||
str(out_dir),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
except FileNotFoundError:
|
||||
errors.append(f"soffice not found: {soffice}")
|
||||
continue
|
||||
if proc.returncode == 0 and output.exists():
|
||||
return output
|
||||
stderr = (proc.stderr or "").strip()
|
||||
errors.append(
|
||||
f"soffice failed ({soffice}, code={proc.returncode}): {stderr or 'no stderr'}"
|
||||
)
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(
|
||||
".xls 转 .xlsx 失败。请安装 LibreOffice(soffice)或设置 EDKB_SOFFICE。"
|
||||
f" details: {joined}"
|
||||
)
|
||||
|
||||
|
||||
def _norm(v) -> str:
|
||||
return "" if v is None else str(v).strip()
|
||||
|
||||
|
||||
def _trim_trailing_empty(vals: list[str]) -> list[str]:
|
||||
end = len(vals)
|
||||
while end > 0 and not vals[end - 1]:
|
||||
end -= 1
|
||||
return vals[:end]
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> list[dict]:
|
||||
file_path = Path(input_data["file_path"])
|
||||
work_dir = Path(input_data["work_dir"])
|
||||
if file_path.suffix.lower() == ".xls":
|
||||
file_path = _convert_xls_to_xlsx(file_path, work_dir)
|
||||
|
||||
wb = load_workbook(str(file_path), data_only=True)
|
||||
tables: list[dict] = []
|
||||
for ws in wb.worksheets:
|
||||
rows: list[list[str]] = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
vals = _trim_trailing_empty([_norm(v) for v in row])
|
||||
if any(vals):
|
||||
rows.append(vals)
|
||||
if not rows:
|
||||
continue
|
||||
width = max(len(r) for r in rows)
|
||||
normalized = [r + [""] * (width - len(r)) for r in rows]
|
||||
tables.append(
|
||||
{"sheet": ws.title, "headers": normalized[0], "rows": normalized[1:]}
|
||||
)
|
||||
context.extras["tables_count"] = len(tables)
|
||||
return tables
|
||||
@@ -0,0 +1,250 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
|
||||
def _is_scanned(text_chars: int, pages: int) -> bool:
|
||||
return text_chars < int(300 * max(pages, 1) / 10)
|
||||
|
||||
|
||||
def _to_data_uri(blob: bytes, content_type: str = "image/png") -> str:
|
||||
b64 = base64.b64encode(blob).decode("ascii")
|
||||
return f"data:{content_type};base64,{b64}"
|
||||
|
||||
|
||||
def _normalize_box(
|
||||
bounds: tuple[float, float, float, float],
|
||||
) -> tuple[float, float, float, float]:
|
||||
x0, y0, x1, y1 = bounds
|
||||
left = min(x0, x1)
|
||||
right = max(x0, x1)
|
||||
top = min(y0, y1)
|
||||
bottom = max(y0, y1)
|
||||
return (left, top, right, bottom)
|
||||
|
||||
|
||||
def _page_image_stats(
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
image_boxes: list[tuple[float, float, float, float]],
|
||||
) -> dict[str, float]:
|
||||
if page_width <= 0 or page_height <= 0 or not image_boxes:
|
||||
return {
|
||||
"count": float(len(image_boxes)),
|
||||
"largest_ratio": 0.0,
|
||||
"total_ratio": 0.0,
|
||||
}
|
||||
|
||||
page_area = max(page_width * page_height, 1.0)
|
||||
largest_ratio = 0.0
|
||||
total_ratio = 0.0
|
||||
for raw in image_boxes:
|
||||
x0, y0, x1, y1 = _normalize_box(raw)
|
||||
width = max(x1 - x0, 0.0)
|
||||
height = max(y1 - y0, 0.0)
|
||||
ratio = min((width * height) / page_area, 1.0)
|
||||
largest_ratio = max(largest_ratio, ratio)
|
||||
total_ratio += ratio
|
||||
return {
|
||||
"count": float(len(image_boxes)),
|
||||
"largest_ratio": largest_ratio,
|
||||
"total_ratio": min(total_ratio, 1.5),
|
||||
}
|
||||
|
||||
|
||||
def _should_use_page_image_mode(
|
||||
*,
|
||||
scan_likely: bool,
|
||||
text_chars: int,
|
||||
image_count: int,
|
||||
largest_ratio: float,
|
||||
total_ratio: float,
|
||||
) -> bool:
|
||||
if scan_likely:
|
||||
if image_count == 0:
|
||||
return True
|
||||
if largest_ratio >= 0.55 or total_ratio >= 0.65 or image_count >= 3:
|
||||
return True
|
||||
if text_chars <= 120 and (
|
||||
largest_ratio >= 0.72 or (image_count >= 5 and total_ratio >= 0.45)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _collect_image_boxes(
|
||||
file_path: Path, page_count: int
|
||||
) -> dict[int, list[tuple[float, float, float, float]]]:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
import pypdfium2.raw as pdfium_c
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
out: dict[int, list[tuple[float, float, float, float]]] = {}
|
||||
doc = None
|
||||
try:
|
||||
doc = pdfium.PdfDocument(str(file_path))
|
||||
for page_idx in range(page_count):
|
||||
page = doc[page_idx]
|
||||
boxes: list[tuple[float, float, float, float]] = []
|
||||
try:
|
||||
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
|
||||
try:
|
||||
bounds = obj.get_bounds()
|
||||
except Exception:
|
||||
bounds = obj.get_pos()
|
||||
boxes.append(tuple(float(v) for v in bounds))
|
||||
except Exception:
|
||||
boxes = []
|
||||
out[page_idx + 1] = boxes
|
||||
except Exception:
|
||||
return {}
|
||||
finally:
|
||||
try:
|
||||
if doc is not None:
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def _render_page_png(
|
||||
file_path: Path, page_number: int, scale: float = 2.0
|
||||
) -> bytes | None:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
doc = None
|
||||
try:
|
||||
doc = pdfium.PdfDocument(str(file_path))
|
||||
page = doc[page_number - 1]
|
||||
bitmap = page.render(scale=scale)
|
||||
pil_image = bitmap.to_pil()
|
||||
buf = io.BytesIO()
|
||||
pil_image.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
try:
|
||||
if doc is not None:
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> list[Block]:
|
||||
file_path = Path(input_data["file_path"])
|
||||
blocks: list[Block] = []
|
||||
|
||||
try:
|
||||
from pypdf import PdfReader
|
||||
|
||||
reader = PdfReader(str(file_path))
|
||||
context.pages = len(reader.pages)
|
||||
text_chars = 0
|
||||
page_payloads: list[dict] = []
|
||||
for page_idx, p in enumerate(reader.pages, start=1):
|
||||
text = (p.extract_text() or "").strip()
|
||||
images: list[dict] = []
|
||||
if text:
|
||||
text_chars += len(text)
|
||||
|
||||
try:
|
||||
for img_idx, img in enumerate(getattr(p, "images", []) or [], start=1):
|
||||
data = getattr(img, "data", None)
|
||||
if not data:
|
||||
continue
|
||||
ext = (getattr(img, "image_format", "") or "").lower()
|
||||
ct = f"image/{ext}" if ext else "image/png"
|
||||
images.append({"id": img_idx, "data": data, "content_type": ct})
|
||||
except Exception:
|
||||
pass
|
||||
page_payloads.append({"page": page_idx, "text": text, "images": images})
|
||||
|
||||
scan_likely = _is_scanned(text_chars, context.pages)
|
||||
image_boxes_by_page = _collect_image_boxes(file_path, context.pages)
|
||||
page_image_mode_pages: list[int] = []
|
||||
|
||||
for payload in page_payloads:
|
||||
page_idx = int(payload["page"])
|
||||
text = str(payload["text"] or "")
|
||||
page_images = list(payload["images"])
|
||||
image_boxes = image_boxes_by_page.get(page_idx, [])
|
||||
stats = _page_image_stats(1000.0, 1000.0, image_boxes)
|
||||
use_page_image_mode = _should_use_page_image_mode(
|
||||
scan_likely=scan_likely,
|
||||
text_chars=len(text),
|
||||
image_count=len(page_images) or int(stats["count"]),
|
||||
largest_ratio=float(stats["largest_ratio"]),
|
||||
total_ratio=float(stats["total_ratio"]),
|
||||
)
|
||||
|
||||
if text:
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pdf-{page_idx}",
|
||||
page=page_idx,
|
||||
type="paragraph",
|
||||
text=text,
|
||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||
)
|
||||
)
|
||||
|
||||
if use_page_image_mode:
|
||||
rendered = _render_page_png(file_path, page_idx)
|
||||
if rendered:
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pdf-page-{page_idx}",
|
||||
page=page_idx,
|
||||
type="image",
|
||||
text="",
|
||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||
meta={
|
||||
"data_uri": _to_data_uri(rendered, "image/png"),
|
||||
"page_image": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
context.images += 1
|
||||
page_image_mode_pages.append(page_idx)
|
||||
continue
|
||||
|
||||
for item in page_images:
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pdf-{page_idx}-img-{item['id']}",
|
||||
page=page_idx,
|
||||
type="image",
|
||||
text="",
|
||||
bbox=(0.0, 0.0, 1000.0, 1000.0),
|
||||
meta={
|
||||
"data_uri": _to_data_uri(
|
||||
item["data"], str(item["content_type"])
|
||||
)
|
||||
},
|
||||
)
|
||||
)
|
||||
context.images += 1
|
||||
|
||||
if scan_likely:
|
||||
context.warnings.append("pdf likely scanned; OCR recommended")
|
||||
context.extras["scan_likely"] = True
|
||||
if page_image_mode_pages:
|
||||
context.extras["pdf_page_image_mode_pages"] = page_image_mode_pages
|
||||
context.warnings.append(
|
||||
"pdf page-image mode pages: "
|
||||
+ ", ".join(str(x) for x in page_image_mode_pages)
|
||||
)
|
||||
except Exception as exc:
|
||||
context.warnings.append(f"PDF parse failed: {exc}")
|
||||
|
||||
return blocks
|
||||
@@ -0,0 +1,478 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
|
||||
def _to_data_uri(blob: bytes, content_type: str) -> str:
|
||||
return f"data:{content_type};base64,{base64.b64encode(blob).decode('ascii')}"
|
||||
|
||||
|
||||
def _convert_ppt_to_pptx(path: Path, out_dir: Path) -> Path:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [
|
||||
"soffice",
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"pptx",
|
||||
str(path),
|
||||
"--outdir",
|
||||
str(out_dir),
|
||||
]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
|
||||
output = out_dir / f"{path.stem}.pptx"
|
||||
if not output.exists():
|
||||
raise RuntimeError("Install LibreOffice to convert .ppt to .pptx")
|
||||
return output
|
||||
|
||||
|
||||
def _convert_presentation_to_pdf(path: Path, out_dir: Path) -> Path | None:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
cmd = [
|
||||
"soffice",
|
||||
"--headless",
|
||||
"--convert-to",
|
||||
"pdf",
|
||||
str(path),
|
||||
"--outdir",
|
||||
str(out_dir),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
if proc.returncode != 0:
|
||||
return None
|
||||
output = out_dir / f"{path.stem}.pdf"
|
||||
return output if output.exists() else None
|
||||
|
||||
|
||||
def _export_slide_pngs(path: Path, out_dir: Path) -> dict[int, bytes]:
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
app = None
|
||||
pres = None
|
||||
output: dict[int, bytes] = {}
|
||||
try:
|
||||
from win32com.client import DispatchEx
|
||||
|
||||
app = DispatchEx("PowerPoint.Application")
|
||||
pres = app.Presentations.Open(str(path), WithWindow=False)
|
||||
for idx, slide in enumerate(pres.Slides, start=1):
|
||||
target = out_dir / f"slide_{idx:03d}.png"
|
||||
slide.Export(str(target), "PNG")
|
||||
if target.exists():
|
||||
output[idx] = target.read_bytes()
|
||||
except Exception:
|
||||
return {}
|
||||
finally:
|
||||
if pres is not None:
|
||||
try:
|
||||
pres.Close()
|
||||
except Exception:
|
||||
pass
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
return output
|
||||
|
||||
|
||||
def _norm_text(text: str) -> str:
|
||||
return "\n".join(x.strip() for x in (text or "").splitlines() if x.strip()).strip()
|
||||
|
||||
|
||||
def _shape_bbox(shape) -> tuple[float, float, float, float]:
|
||||
left = float(getattr(shape, "left", 0))
|
||||
top = float(getattr(shape, "top", 0))
|
||||
width = float(getattr(shape, "width", 0))
|
||||
height = float(getattr(shape, "height", 0))
|
||||
return (left, top, left + width, top + height)
|
||||
|
||||
|
||||
def _image_pixel_size(blob: bytes) -> tuple[int, int]:
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(blob)) as im:
|
||||
return int(im.width), int(im.height)
|
||||
except Exception:
|
||||
return (0, 0)
|
||||
|
||||
|
||||
def _is_small_decorative_image(
|
||||
blob: bytes, bbox: tuple[float, float, float, float], slide_area: float
|
||||
) -> bool:
|
||||
width_px, height_px = _image_pixel_size(blob)
|
||||
pixel_area = max(width_px, 0) * max(height_px, 0)
|
||||
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
|
||||
if (
|
||||
width_px
|
||||
and height_px
|
||||
and (width_px <= 48 or height_px <= 48 or pixel_area <= 6400)
|
||||
):
|
||||
return True
|
||||
if slide_area > 0 and box_area / slide_area <= 0.015 and pixel_area <= 20000:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _is_dominant_picture(
|
||||
bbox: tuple[float, float, float, float], slide_area: float
|
||||
) -> bool:
|
||||
box_area = max(bbox[2] - bbox[0], 0.0) * max(bbox[3] - bbox[1], 0.0)
|
||||
if slide_area <= 0:
|
||||
return False
|
||||
return box_area / slide_area >= 0.45
|
||||
|
||||
|
||||
def _table_to_markdown(table) -> str:
|
||||
rows: list[list[str]] = []
|
||||
for row in table.rows:
|
||||
vals = [
|
||||
" ".join(
|
||||
p.text.strip() for p in cell.text_frame.paragraphs if p.text.strip()
|
||||
)
|
||||
for cell in row.cells
|
||||
]
|
||||
vals = [v.strip() for v in vals]
|
||||
if any(vals):
|
||||
rows.append(vals)
|
||||
if not rows:
|
||||
return ""
|
||||
width = max(len(r) for r in rows)
|
||||
norm = [r + [""] * (width - len(r)) for r in rows]
|
||||
header = norm[0]
|
||||
body = norm[1:]
|
||||
lines = [
|
||||
"| " + " | ".join(header) + " |",
|
||||
"| " + " | ".join(["---"] * width) + " |",
|
||||
]
|
||||
lines.extend("| " + " | ".join(r) + " |" for r in body)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _render_pdf_page_png(
|
||||
pdf_path: Path, page_number: int, scale: float = 2.0
|
||||
) -> bytes | None:
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
doc = None
|
||||
try:
|
||||
doc = pdfium.PdfDocument(str(pdf_path))
|
||||
page = doc[page_number - 1]
|
||||
bitmap = page.render(scale=scale)
|
||||
pil_image = bitmap.to_pil()
|
||||
buf = io.BytesIO()
|
||||
pil_image.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
except Exception:
|
||||
return None
|
||||
finally:
|
||||
try:
|
||||
if doc is not None:
|
||||
doc.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _crop_rendered_region(
|
||||
rendered: bytes,
|
||||
*,
|
||||
crop_bbox: tuple[float, float, float, float],
|
||||
slide_width: float,
|
||||
slide_height: float,
|
||||
padding: float = 0.03,
|
||||
) -> bytes | None:
|
||||
try:
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(rendered)) as im:
|
||||
x0, y0, x1, y1 = crop_bbox
|
||||
pad_x = slide_width * padding
|
||||
pad_y = slide_height * padding
|
||||
x0 = max(0.0, x0 - pad_x)
|
||||
y0 = max(0.0, y0 - pad_y)
|
||||
x1 = min(slide_width, x1 + pad_x)
|
||||
y1 = min(slide_height, y1 + pad_y)
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return None
|
||||
scale_x = im.width / max(slide_width, 1.0)
|
||||
scale_y = im.height / max(slide_height, 1.0)
|
||||
box = (
|
||||
int(x0 * scale_x),
|
||||
int(y0 * scale_y),
|
||||
int(x1 * scale_x),
|
||||
int(y1 * scale_y),
|
||||
)
|
||||
cropped = im.crop(box)
|
||||
buf = io.BytesIO()
|
||||
cropped.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _union_bboxes(
|
||||
boxes: list[tuple[float, float, float, float]],
|
||||
) -> tuple[float, float, float, float] | None:
|
||||
if not boxes:
|
||||
return None
|
||||
x0 = min(b[0] for b in boxes)
|
||||
y0 = min(b[1] for b in boxes)
|
||||
x1 = max(b[2] for b in boxes)
|
||||
y1 = max(b[3] for b in boxes)
|
||||
return (x0, y0, x1, y1)
|
||||
|
||||
|
||||
def _bbox_overlap_ratio(
|
||||
a: tuple[float, float, float, float], b: tuple[float, float, float, float]
|
||||
) -> float:
|
||||
ax0, ay0, ax1, ay1 = a
|
||||
bx0, by0, bx1, by1 = b
|
||||
ix0 = max(ax0, bx0)
|
||||
iy0 = max(ay0, by0)
|
||||
ix1 = min(ax1, bx1)
|
||||
iy1 = min(ay1, by1)
|
||||
if ix1 <= ix0 or iy1 <= iy0:
|
||||
return 0.0
|
||||
inter = (ix1 - ix0) * (iy1 - iy0)
|
||||
area = max((ax1 - ax0) * (ay1 - ay0), 1.0)
|
||||
return inter / area
|
||||
|
||||
|
||||
def _pick_slide_title(flat_shapes) -> str:
|
||||
candidates: list[tuple[float, float, str]] = []
|
||||
for shape in flat_shapes:
|
||||
if not getattr(shape, "has_text_frame", False):
|
||||
continue
|
||||
txt = _norm_text(getattr(shape, "text", ""))
|
||||
if not txt:
|
||||
continue
|
||||
top = float(getattr(shape, "top", 0))
|
||||
left = float(getattr(shape, "left", 0))
|
||||
candidates.append((top, left, txt))
|
||||
if not candidates:
|
||||
return ""
|
||||
candidates.sort(key=lambda x: (x[0], x[1]))
|
||||
preferred_pat = re.compile(r"^(?:[一二三四五六七八九十]+、|\d+(?:\.\d+){0,2})")
|
||||
for top, left, txt in candidates[:6]:
|
||||
first_line = txt.splitlines()[0].strip()
|
||||
if preferred_pat.match(first_line) and top <= 1200000:
|
||||
return first_line
|
||||
for top, left, txt in candidates[:6]:
|
||||
first_line = txt.splitlines()[0].strip()
|
||||
if 2 <= len(first_line) <= 30 and top <= 1800000:
|
||||
return first_line
|
||||
return candidates[0][2].splitlines()[0].strip()
|
||||
|
||||
|
||||
def _iter_shapes(shapes):
|
||||
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
||||
|
||||
for shape in shapes:
|
||||
yield shape
|
||||
if getattr(shape, "shape_type", None) == MSO_SHAPE_TYPE.GROUP:
|
||||
for child in _iter_shapes(shape.shapes):
|
||||
yield child
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> list[Block]:
|
||||
file_path = Path(input_data["file_path"])
|
||||
work_dir = Path(input_data["work_dir"])
|
||||
if file_path.suffix.lower() == ".ppt":
|
||||
file_path = _convert_ppt_to_pptx(file_path, work_dir)
|
||||
|
||||
from pptx import Presentation
|
||||
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
||||
|
||||
prs = Presentation(str(file_path))
|
||||
slide_pngs = _export_slide_pngs(file_path, work_dir / f"{file_path.stem}_slides")
|
||||
pdf_path = None if slide_pngs else _convert_presentation_to_pdf(file_path, work_dir)
|
||||
context.pages = len(prs.slides)
|
||||
blocks: list[Block] = []
|
||||
img_idx = 0
|
||||
blk_idx = 0
|
||||
slide_area = float(prs.slide_width) * float(prs.slide_height)
|
||||
|
||||
for slide_no, slide in enumerate(prs.slides, start=1):
|
||||
flat_shapes = list(_iter_shapes(slide.shapes))
|
||||
title_text = _norm_text(
|
||||
getattr(getattr(slide.shapes, "title", None), "text", "")
|
||||
)
|
||||
if not title_text:
|
||||
title_text = _pick_slide_title(flat_shapes)
|
||||
heading_text = f"第{slide_no}页"
|
||||
if title_text:
|
||||
heading_text = f"第{slide_no}页 {title_text}"
|
||||
blk_idx += 1
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pptx-{slide_no}-heading-{blk_idx}",
|
||||
page=slide_no,
|
||||
type="heading",
|
||||
text=heading_text,
|
||||
bbox=(0.0, 0.0, 0.0, 0.0),
|
||||
)
|
||||
)
|
||||
|
||||
seen_image_hashes: set[str] = set()
|
||||
dominant_pictures = 0
|
||||
shape_heavy = 0
|
||||
flow_boxes: list[tuple[float, float, float, float]] = []
|
||||
suppress_all_images = title_text == "目录"
|
||||
|
||||
for shape in flat_shapes:
|
||||
try:
|
||||
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
|
||||
image = shape.image
|
||||
bbox = _shape_bbox(shape)
|
||||
blob_hash = hashlib.sha1(image.blob).hexdigest()
|
||||
if blob_hash in seen_image_hashes:
|
||||
continue
|
||||
seen_image_hashes.add(blob_hash)
|
||||
if _is_small_decorative_image(image.blob, bbox, slide_area):
|
||||
continue
|
||||
if _is_dominant_picture(bbox, slide_area):
|
||||
dominant_pictures += 1
|
||||
elif shape.shape_type in {
|
||||
MSO_SHAPE_TYPE.AUTO_SHAPE,
|
||||
MSO_SHAPE_TYPE.LINE,
|
||||
MSO_SHAPE_TYPE.FREEFORM,
|
||||
}:
|
||||
shape_heavy += 1
|
||||
bbox = _shape_bbox(shape)
|
||||
mid_x = (bbox[0] + bbox[2]) / 2.0
|
||||
if (
|
||||
bbox[2] > bbox[0]
|
||||
and bbox[3] > bbox[1]
|
||||
and mid_x >= float(prs.slide_width) * 0.18
|
||||
):
|
||||
flow_boxes.append(bbox)
|
||||
except Exception as exc:
|
||||
context.warnings.append(f"pptx picture skipped: {exc}")
|
||||
|
||||
seen_image_hashes.clear()
|
||||
render_flow_focus = (
|
||||
(not suppress_all_images)
|
||||
and bool(slide_pngs or pdf_path)
|
||||
and shape_heavy >= 8
|
||||
and dominant_pictures == 0
|
||||
)
|
||||
flow_crop: tuple[float, float, float, float] | None = None
|
||||
if render_flow_focus:
|
||||
rendered = slide_pngs.get(slide_no)
|
||||
if rendered is None and pdf_path is not None:
|
||||
rendered = _render_pdf_page_png(pdf_path, slide_no)
|
||||
if rendered:
|
||||
flow_crop = (0.0, 0.0, float(prs.slide_width), float(prs.slide_height))
|
||||
img_idx += 1
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pptx-flow-{slide_no}-{img_idx}",
|
||||
page=slide_no,
|
||||
type="image",
|
||||
text="",
|
||||
bbox=flow_crop,
|
||||
meta={
|
||||
"data_uri": _to_data_uri(rendered, "image/png"),
|
||||
"flow_focus": True,
|
||||
"flow_focus_source": "pptx",
|
||||
"rendered_slide": True,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
for shape in flat_shapes:
|
||||
try:
|
||||
if getattr(shape, "has_table", False):
|
||||
table_md = _table_to_markdown(shape.table)
|
||||
if table_md:
|
||||
blk_idx += 1
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pptx-{slide_no}-table-{blk_idx}",
|
||||
page=slide_no,
|
||||
type="table",
|
||||
text=table_md,
|
||||
bbox=_shape_bbox(shape),
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
|
||||
if render_flow_focus or suppress_all_images:
|
||||
continue
|
||||
is_dominant = False
|
||||
image = shape.image
|
||||
bbox = _shape_bbox(shape)
|
||||
blob_hash = hashlib.sha1(image.blob).hexdigest()
|
||||
if blob_hash in seen_image_hashes:
|
||||
continue
|
||||
seen_image_hashes.add(blob_hash)
|
||||
if _is_small_decorative_image(image.blob, bbox, slide_area):
|
||||
continue
|
||||
is_dominant = _is_dominant_picture(bbox, slide_area)
|
||||
img_idx += 1
|
||||
ext = (getattr(image, "ext", "png") or "png").lower()
|
||||
ct = f"image/{'jpeg' if ext == 'jpg' else ext}"
|
||||
meta: dict[str, object] = {
|
||||
"data_uri": _to_data_uri(image.blob, ct),
|
||||
"blob_sha1": blob_hash,
|
||||
}
|
||||
if is_dominant:
|
||||
meta["page_image"] = True
|
||||
meta["page_image_source"] = "pptx"
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pptx-img-{slide_no}-{img_idx}",
|
||||
page=slide_no,
|
||||
type="image",
|
||||
text="",
|
||||
bbox=bbox,
|
||||
meta=meta,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
if getattr(shape, "has_text_frame", False):
|
||||
txt = _norm_text(shape.text)
|
||||
bbox = _shape_bbox(shape)
|
||||
if not txt or txt == title_text:
|
||||
continue
|
||||
if title_text and txt.startswith(title_text):
|
||||
txt = txt[len(title_text) :].lstrip("\n ::;;,,")
|
||||
txt = _norm_text(txt)
|
||||
if not txt:
|
||||
continue
|
||||
if re.fullmatch(r"\d+", txt):
|
||||
continue
|
||||
if flow_crop is not None and len(txt) <= 28:
|
||||
continue
|
||||
if txt and txt != title_text:
|
||||
blk_idx += 1
|
||||
blocks.append(
|
||||
Block(
|
||||
id=f"pptx-{slide_no}-text-{blk_idx}",
|
||||
page=slide_no,
|
||||
type="paragraph",
|
||||
text=txt,
|
||||
bbox=bbox,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
context.warnings.append(f"pptx shape skipped: {exc}")
|
||||
|
||||
context.extras["slides_count"] = len(prs.slides)
|
||||
return blocks
|
||||
@@ -0,0 +1,97 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import re
|
||||
|
||||
from edkb_system.contracts import Block, Context
|
||||
|
||||
|
||||
def _decode_data_uri_image(data_uri: str):
|
||||
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
raw = base64.b64decode(m.group(1), validate=False)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
with Image.open(io.BytesIO(raw)) as im:
|
||||
return np.array(im.convert("RGB"))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def run(
|
||||
input_data: list[Block], context: Context, min_confidence: float = 0.3
|
||||
) -> list[Block]:
|
||||
blocks = input_data
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR # type: ignore
|
||||
except Exception:
|
||||
context.warnings.append("RapidOCR unavailable; skip OCR")
|
||||
return blocks
|
||||
|
||||
engine = RapidOCR()
|
||||
out: list[Block] = []
|
||||
for b in blocks:
|
||||
out.append(b)
|
||||
if b.type != "image":
|
||||
continue
|
||||
context.images += 1
|
||||
image_obj = b.meta.get("image")
|
||||
if image_obj is None and b.meta and b.meta.get("data_uri"):
|
||||
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
|
||||
if image_obj is None:
|
||||
out.append(
|
||||
Block(
|
||||
id=f"ocr-{b.id}",
|
||||
page=b.page,
|
||||
type="ocr_text",
|
||||
text="OCR_TEXT: <empty>",
|
||||
bbox=b.bbox,
|
||||
)
|
||||
)
|
||||
continue
|
||||
|
||||
try:
|
||||
result, _ = engine(image_obj)
|
||||
lines = []
|
||||
for it in result or []:
|
||||
if len(it) < 3:
|
||||
continue
|
||||
txt = str(it[1]).strip()
|
||||
conf = float(it[2])
|
||||
if txt and conf >= min_confidence:
|
||||
lines.append(txt)
|
||||
if lines:
|
||||
text = "OCR_TEXT:\n" + "\n".join(f"- {x}" for x in lines)
|
||||
context.ocr_characters += sum(len(x) for x in lines)
|
||||
else:
|
||||
text = "OCR_TEXT: <empty>"
|
||||
out.append(
|
||||
Block(
|
||||
id=f"ocr-{b.id}",
|
||||
page=b.page,
|
||||
type="ocr_text",
|
||||
text=text,
|
||||
bbox=b.bbox,
|
||||
)
|
||||
)
|
||||
except Exception as exc:
|
||||
context.warnings.append(f"OCR failed: {exc}")
|
||||
out.append(
|
||||
Block(
|
||||
id=f"ocr-{b.id}",
|
||||
page=b.page,
|
||||
type="ocr_text",
|
||||
text="OCR_TEXT: <empty>",
|
||||
bbox=b.bbox,
|
||||
)
|
||||
)
|
||||
|
||||
return out
|
||||
@@ -0,0 +1,192 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
|
||||
|
||||
def _has_doc_meta(text: str) -> bool:
|
||||
flat = " ".join(text.split())
|
||||
has_header = bool(
|
||||
re.search(r"制定部门.+制/修订日期.+页码", flat)
|
||||
or re.search(r"Created Dept\..+Date.+Page", flat)
|
||||
)
|
||||
has_meta = bool(
|
||||
re.search(r"文件编号.+文件级别.+版本", flat)
|
||||
or re.search(r"Doc\.\s*No\..+File\s*Level.+Rev\.?", flat)
|
||||
)
|
||||
return has_header or has_meta
|
||||
|
||||
|
||||
def _expect_doc_meta(text: str) -> bool:
|
||||
keys = ["文件编号", "文件级别", "制/修订日期", "制定部门", "页码"]
|
||||
return any(k in text for k in keys)
|
||||
|
||||
|
||||
def _expect_flow_artifacts(text: str) -> bool:
|
||||
if "作业流程图" not in text:
|
||||
return False
|
||||
hints = ["序号", "流程说明", "责任", "相关记录"]
|
||||
return sum(1 for h in hints if h in text) >= 2
|
||||
|
||||
|
||||
def _expect_related_forms_table(text: str) -> bool:
|
||||
if "相关表单" not in text:
|
||||
return False
|
||||
return ("表单编号" in text) or bool(re.search(r"PB-\d{2,}", text))
|
||||
|
||||
|
||||
def _has_source_images(out_dir: Path) -> bool:
|
||||
raw = out_dir / "01_raw_layout.json"
|
||||
if not raw.exists():
|
||||
return False
|
||||
try:
|
||||
data = json.loads(raw.read_text(encoding="utf-8"))
|
||||
if isinstance(data, list):
|
||||
for b in data:
|
||||
if isinstance(b, dict) and b.get("type") == "image":
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
return False
|
||||
|
||||
|
||||
def _has_markdown_image_reference(text: str) -> bool:
|
||||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
||||
target = (m.group(1) or "").strip()
|
||||
if target.startswith("data:image/"):
|
||||
return True
|
||||
if target.startswith("http://") or target.startswith("https://"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _has_remote_image_url(text: str) -> bool:
|
||||
for m in re.finditer(r"!\[[^\]]*\]\(([^)]+)\)", text):
|
||||
target = (m.group(1) or "").strip()
|
||||
if target.startswith("http://") or target.startswith("https://"):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _expect_revision_table(text: str) -> bool:
|
||||
if "文件修订履历" in text:
|
||||
return True
|
||||
hint = ["日期", "修订章节", "主要修订内容", "版本", "修改人"]
|
||||
return sum(1 for h in hint if h in text) >= 4
|
||||
|
||||
|
||||
def _collect_issues(text: str) -> list[dict]:
|
||||
issues: list[dict] = []
|
||||
lines = text.splitlines()
|
||||
num_pat = re.compile(r"^\s*\d+(?:\.\d+){1,4}\s+")
|
||||
|
||||
non_empty = [(i + 1, ln.strip()) for i, ln in enumerate(lines) if ln.strip()]
|
||||
if len(non_empty) >= 2:
|
||||
l1, s1 = non_empty[0]
|
||||
l2, s2 = non_empty[1]
|
||||
if "文件编号" in s1 and "文件编号" not in s2 and not s2.startswith("制定部门"):
|
||||
if not re.match(r"^[一二三四五六七八九十]+、", s2):
|
||||
issues.append(
|
||||
{
|
||||
"code": "title_below_meta",
|
||||
"line": l1,
|
||||
"text": f"meta before title: {s1[:80]}",
|
||||
}
|
||||
)
|
||||
|
||||
for i, ln in enumerate(lines, start=1):
|
||||
s = ln.strip()
|
||||
if not s:
|
||||
continue
|
||||
if s.startswith("|"):
|
||||
continue
|
||||
|
||||
if re.search(r"\d+\.\d+(?:\.\d+)?\s+.+\s+\d+\.\d+(?:\.\d+)?\s+", s):
|
||||
issues.append(
|
||||
{"code": "inline_numbered_sections", "line": i, "text": s[:180]}
|
||||
)
|
||||
|
||||
if re.search(r"[七八]、参考文件\s+[七八]、相关表单", s):
|
||||
issues.append({"code": "inline_section_titles", "line": i, "text": s[:180]})
|
||||
|
||||
for i in range(1, len(lines) - 1):
|
||||
if lines[i].strip():
|
||||
continue
|
||||
prev = lines[i - 1].strip()
|
||||
nxt = lines[i + 1].strip()
|
||||
if num_pat.match(prev) and num_pat.match(nxt):
|
||||
issues.append(
|
||||
{
|
||||
"code": "blank_between_numbered_sections",
|
||||
"line": i + 1,
|
||||
"text": f"{prev[:70]} / {nxt[:70]}",
|
||||
}
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
def run(input_data: dict, context: Context) -> dict:
|
||||
out_dir = Path(input_data["out_dir"])
|
||||
clean_md = input_data.get("clean_md", "")
|
||||
|
||||
checks = {
|
||||
"has_doc_meta": _has_doc_meta(clean_md),
|
||||
"has_revision_table": bool(
|
||||
(re.search(r"\|\s*(?:日期|文件日期)\b", clean_md) is not None)
|
||||
and re.search(r"\|\s*.*修订章节", clean_md)
|
||||
and re.search(r"\|\s*版本\b", clean_md)
|
||||
),
|
||||
"has_flow_table": "| 序号 | 流程说明 | 责任部门 | 相关记录 |" in clean_md,
|
||||
"has_related_forms_table": bool(
|
||||
re.search(r"\|\s*表单编号\s*\|", clean_md)
|
||||
and re.search(r"\|\s*[-:]{3,}\s*\|", clean_md)
|
||||
),
|
||||
"has_flow_file": (out_dir / "02_flow_procedure.md").exists(),
|
||||
"has_embedded_images": _has_markdown_image_reference(clean_md),
|
||||
"has_remote_image_urls": _has_remote_image_url(clean_md),
|
||||
}
|
||||
|
||||
flow_expected = _expect_flow_artifacts(clean_md)
|
||||
expected = {
|
||||
"has_doc_meta": _expect_doc_meta(clean_md),
|
||||
"has_revision_table": _expect_revision_table(clean_md),
|
||||
"has_flow_table": flow_expected,
|
||||
"has_related_forms_table": _expect_related_forms_table(clean_md),
|
||||
"has_flow_file": flow_expected,
|
||||
"has_embedded_images": _has_source_images(out_dir),
|
||||
}
|
||||
|
||||
failed_required = [k for k, v in expected.items() if v and not checks.get(k, False)]
|
||||
status = "pass" if not failed_required else "fail"
|
||||
issues = _collect_issues(clean_md)
|
||||
if expected["has_embedded_images"] and not checks["has_embedded_images"]:
|
||||
issues.append(
|
||||
{
|
||||
"code": "image_not_embedded",
|
||||
"line": 0,
|
||||
"text": "source has image blocks but markdown has no image references",
|
||||
}
|
||||
)
|
||||
|
||||
if "data:image/" in clean_md:
|
||||
issues.append(
|
||||
{
|
||||
"code": "legacy_base64_image",
|
||||
"line": 0,
|
||||
"text": "markdown still contains legacy data:image base64 payload",
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"status": status,
|
||||
"checks": checks,
|
||||
"expected": expected,
|
||||
"failed_required": failed_required,
|
||||
"issues": issues,
|
||||
"issue_count": len(issues),
|
||||
"warnings_count": len(context.warnings),
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from edkb_system.contracts import Chunk, Context
|
||||
|
||||
|
||||
def run(input_data: list[Chunk], context: Context) -> list[Chunk]:
|
||||
chunks = input_data
|
||||
if not chunks:
|
||||
context.warnings.append("quality_gate: no chunks generated")
|
||||
context.confidence = min(context.confidence, 0.5)
|
||||
return chunks
|
||||
|
||||
short_count = sum(1 for c in chunks if len(c.text.strip()) < 60)
|
||||
if short_count:
|
||||
context.warnings.append(f"quality_gate: {short_count} short chunks")
|
||||
context.confidence = min(context.confidence, 0.8)
|
||||
|
||||
unique_texts = len({c.text for c in chunks})
|
||||
if unique_texts < len(chunks):
|
||||
context.warnings.append("quality_gate: duplicate chunks detected")
|
||||
context.confidence = min(context.confidence, 0.75)
|
||||
|
||||
return chunks
|
||||
@@ -0,0 +1,55 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from edkb_system.contracts import Context
|
||||
|
||||
|
||||
COND_KWS = ["条件", "判定", "if", "IF"]
|
||||
ACT_KWS = ["处理", "动作", "措施", "结果", "输出"]
|
||||
OWN_KWS = ["责任", "负责人", "部门", "岗位"]
|
||||
|
||||
|
||||
def _find_col(headers: list[str], kws: list[str]) -> int | None:
|
||||
for i, h in enumerate(headers):
|
||||
s = (h or "").lower()
|
||||
if any(k.lower() in s for k in kws):
|
||||
return i
|
||||
return None
|
||||
|
||||
|
||||
def _to_table_md(headers: list[str], rows: list[list[str]]) -> str:
|
||||
hs = [h or "-" for h in headers]
|
||||
out = ["| " + " | ".join(hs) + " |", "| " + " | ".join(["---"] * len(hs)) + " |"]
|
||||
for r in rows:
|
||||
vals = [r[i] if i < len(r) else "" for i in range(len(hs))]
|
||||
out.append("| " + " | ".join(vals) + " |")
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def run(input_data: list[dict] | dict, context: Context) -> str:
|
||||
tables = input_data if isinstance(input_data, list) else [input_data]
|
||||
parts: list[str] = []
|
||||
|
||||
for t in tables:
|
||||
headers = [str(x).strip() for x in t.get("headers", [])]
|
||||
rows = [[str(c).strip() for c in row] for row in t.get("rows", [])]
|
||||
parts.append(f"## Sheet: {t.get('sheet', 'Sheet1')}")
|
||||
|
||||
cidx = _find_col(headers, COND_KWS)
|
||||
aidx = _find_col(headers, ACT_KWS)
|
||||
oidx = _find_col(headers, OWN_KWS)
|
||||
if cidx is not None and aidx is not None:
|
||||
for row in rows:
|
||||
cond = row[cidx] if cidx < len(row) else "满足条件"
|
||||
act = row[aidx] if aidx < len(row) else "执行处理"
|
||||
owner = (
|
||||
row[oidx] if oidx is not None and oidx < len(row) else "相关责任方"
|
||||
)
|
||||
parts.append(
|
||||
f"- 当 {cond or '满足条件'} 时,{owner or '相关责任方'} 执行 {act or '执行处理'}。"
|
||||
)
|
||||
else:
|
||||
parts.append(_to_table_md(headers, rows))
|
||||
|
||||
parts.append("")
|
||||
|
||||
return "\n".join(parts).strip() + "\n"
|
||||
@@ -0,0 +1,249 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import ctypes
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _list_winword_pids() -> set[int]:
|
||||
if os.name != "nt":
|
||||
return set()
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
["tasklist", "/FO", "CSV", "/NH", "/FI", "IMAGENAME eq WINWORD.EXE"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
return set()
|
||||
|
||||
out: set[int] = set()
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("INFO:"):
|
||||
continue
|
||||
cols = [part.strip().strip('"') for part in line.split('","')]
|
||||
if len(cols) < 2:
|
||||
cols = [part.strip().strip('"') for part in line.split(",")]
|
||||
if len(cols) < 2:
|
||||
continue
|
||||
try:
|
||||
out.add(int(cols[1]))
|
||||
except ValueError:
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def _kill_winword_pids(pids: set[int]) -> None:
|
||||
if os.name != "nt":
|
||||
return
|
||||
for pid in sorted(pids):
|
||||
try:
|
||||
subprocess.run(
|
||||
["taskkill", "/PID", str(pid), "/F"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
|
||||
def _word_timeout_sec() -> int:
|
||||
raw = str(os.environ.get("EDKB_WORD_TIMEOUT_SEC", "120")).strip()
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
value = 120
|
||||
return max(value, 10)
|
||||
|
||||
|
||||
def _should_accept_word_dialog(
|
||||
window_title: str, child_texts: list[str], button_texts: list[str]
|
||||
) -> bool:
|
||||
text_blob = "\n".join(x.strip().lower() for x in child_texts if x.strip())
|
||||
if not text_blob:
|
||||
return False
|
||||
|
||||
has_repair_prompt = any(
|
||||
token in text_blob
|
||||
for token in [
|
||||
"出现严重错误",
|
||||
"是否仍要打开",
|
||||
"serious error",
|
||||
"do you still want to open",
|
||||
]
|
||||
)
|
||||
if not has_repair_prompt:
|
||||
return False
|
||||
|
||||
return any(
|
||||
text.strip().lower().startswith(("是", "yes")) or "&y" in text.lower()
|
||||
for text in button_texts
|
||||
)
|
||||
|
||||
|
||||
def _start_word_dialog_watcher() -> tuple[threading.Event, threading.Thread | None]:
|
||||
stop_event = threading.Event()
|
||||
if os.name != "nt":
|
||||
return stop_event, None
|
||||
|
||||
def _window_text(user32, hwnd: int) -> str:
|
||||
length = user32.GetWindowTextLengthW(hwnd)
|
||||
if length <= 0:
|
||||
return ""
|
||||
buf = ctypes.create_unicode_buffer(length + 1)
|
||||
user32.GetWindowTextW(hwnd, buf, length + 1)
|
||||
return buf.value
|
||||
|
||||
def _class_name(user32, hwnd: int) -> str:
|
||||
buf = ctypes.create_unicode_buffer(256)
|
||||
user32.GetClassNameW(hwnd, buf, 255)
|
||||
return buf.value
|
||||
|
||||
def _click_yes_if_needed() -> None:
|
||||
user32 = ctypes.windll.user32
|
||||
bm_click = 0x00F5
|
||||
vk_return = 0x0D
|
||||
wm_keydown = 0x0100
|
||||
wm_keyup = 0x0101
|
||||
|
||||
while not stop_event.is_set():
|
||||
windows: list[int] = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
|
||||
def enum_windows(hwnd, lparam):
|
||||
windows.append(int(hwnd))
|
||||
return True
|
||||
|
||||
user32.EnumWindows(enum_windows, 0)
|
||||
for hwnd in windows:
|
||||
title = _window_text(user32, hwnd)
|
||||
cls = _class_name(user32, hwnd).lower()
|
||||
if "Microsoft Word" not in title and cls != "#32770":
|
||||
continue
|
||||
|
||||
child_hwnds: list[int] = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)
|
||||
def enum_children(child_hwnd, lparam):
|
||||
child_hwnds.append(int(child_hwnd))
|
||||
return True
|
||||
|
||||
user32.EnumChildWindows(hwnd, enum_children, 0)
|
||||
child_texts = [_window_text(user32, child) for child in child_hwnds]
|
||||
button_hwnds = [
|
||||
child
|
||||
for child in child_hwnds
|
||||
if _class_name(user32, child).lower() == "button"
|
||||
]
|
||||
button_texts = [_window_text(user32, child) for child in button_hwnds]
|
||||
if not _should_accept_word_dialog(title, child_texts, button_texts):
|
||||
continue
|
||||
user32.SetForegroundWindow(hwnd)
|
||||
for child, text in zip(button_hwnds, button_texts):
|
||||
normalized = text.strip().lower()
|
||||
if normalized.startswith(("是", "yes")) or "&y" in normalized:
|
||||
user32.SendMessageW(child, bm_click, 0, 0)
|
||||
break
|
||||
else:
|
||||
user32.PostMessageW(hwnd, wm_keydown, vk_return, 0)
|
||||
user32.PostMessageW(hwnd, wm_keyup, vk_return, 0)
|
||||
stop_event.wait(0.5)
|
||||
|
||||
thread = threading.Thread(target=_click_yes_if_needed, daemon=True)
|
||||
thread.start()
|
||||
return stop_event, thread
|
||||
|
||||
|
||||
def convert_with_word(path: Path, output: Path, file_format: int) -> Path:
|
||||
timeout = _word_timeout_sec()
|
||||
before_pids = _list_winword_pids()
|
||||
cmd = [
|
||||
sys.executable,
|
||||
"-m",
|
||||
"edkb_system.skills.word_bridge",
|
||||
str(path),
|
||||
str(output),
|
||||
str(file_format),
|
||||
]
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
check=False,
|
||||
)
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
after_pids = _list_winword_pids()
|
||||
_kill_winword_pids(after_pids - before_pids)
|
||||
raise RuntimeError(
|
||||
f"Word conversion timed out after {timeout}s: {path.name}"
|
||||
) from exc
|
||||
|
||||
if proc.returncode != 0:
|
||||
err = (proc.stderr or proc.stdout or "unknown error").strip()
|
||||
raise RuntimeError(f"Word conversion failed: {err}")
|
||||
|
||||
if not output.exists() or output.stat().st_size <= 0:
|
||||
raise RuntimeError(f"Word conversion produced no output: {output}")
|
||||
return output
|
||||
|
||||
|
||||
def _child_main(argv: list[str]) -> int:
|
||||
if len(argv) != 4:
|
||||
print("usage: word_bridge <input> <output> <file_format>", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
src = Path(argv[1]).resolve()
|
||||
out = Path(argv[2]).resolve()
|
||||
file_format = int(argv[3])
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
stop_event, watcher = _start_word_dialog_watcher()
|
||||
|
||||
word = None
|
||||
doc = None
|
||||
try:
|
||||
from win32com.client import DispatchEx
|
||||
|
||||
word = DispatchEx("Word.Application")
|
||||
word.Visible = False
|
||||
word.DisplayAlerts = 0
|
||||
try:
|
||||
word.Options.SaveNormalPrompt = False
|
||||
except Exception:
|
||||
pass
|
||||
doc = word.Documents.Open(
|
||||
FileName=str(src),
|
||||
ReadOnly=True,
|
||||
AddToRecentFiles=False,
|
||||
ConfirmConversions=False,
|
||||
NoEncodingDialog=True,
|
||||
OpenAndRepair=True,
|
||||
)
|
||||
doc.SaveAs(str(out), FileFormat=file_format)
|
||||
finally:
|
||||
stop_event.set()
|
||||
if watcher is not None:
|
||||
watcher.join(timeout=1)
|
||||
if doc is not None:
|
||||
try:
|
||||
doc.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
if word is not None:
|
||||
try:
|
||||
word.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_child_main(sys.argv))
|
||||
@@ -26,3 +26,7 @@ keepalive = 5
|
||||
accesslog = "-"
|
||||
errorlog = "-"
|
||||
loglevel = "info"
|
||||
|
||||
# 应用启动时会访问数据库加载持久化配置;预加载会让主进程先建立连接再 fork,
|
||||
# 导致 worker 继承损坏的数据库连接。
|
||||
preload_app = False
|
||||
@@ -0,0 +1,26 @@
|
||||
"""add message_type and payload to chatlog
|
||||
|
||||
Revision ID: 1ebc0253f9f6
|
||||
Revises: 2a4b6c8d0e1f
|
||||
Create Date: 2026-05-15 14:18:31.665105
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '1ebc0253f9f6'
|
||||
down_revision = '2a4b6c8d0e1f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade():
|
||||
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('message_type', sa.String(length=50), nullable=True))
|
||||
batch_op.add_column(sa.Column('payload', sa.JSON(), nullable=True))
|
||||
|
||||
def downgrade():
|
||||
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
|
||||
batch_op.drop_column('payload')
|
||||
batch_op.drop_column('message_type')
|
||||
@@ -0,0 +1,185 @@
|
||||
"""add kb foundation tables
|
||||
|
||||
Revision ID: 2a4b6c8d0e1f
|
||||
Revises: 1c2d3e4f5a6b
|
||||
Create Date: 2026-05-08 23:10:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '2a4b6c8d0e1f'
|
||||
down_revision = '1c2d3e4f5a6b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
'kb_groups',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('name', sa.String(length=128), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('department_id', sa.Integer(), nullable=True),
|
||||
sa.Column('is_active', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('dify_dataset_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('dify_dataset_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('created_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('updated_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('department_id', 'name', name='uq_kb_groups_department_name'),
|
||||
)
|
||||
op.create_index('ix_kb_groups_name', 'kb_groups', ['name'])
|
||||
op.create_index('ix_kb_groups_department_id', 'kb_groups', ['department_id'])
|
||||
op.create_index('ix_kb_groups_department_active', 'kb_groups', ['department_id', 'is_active'])
|
||||
op.create_index('ix_kb_groups_dify_dataset_id', 'kb_groups', ['dify_dataset_id'])
|
||||
|
||||
op.create_table(
|
||||
'kb_documents',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('group_id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(length=255), nullable=False),
|
||||
sa.Column('description', sa.Text(), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='draft'),
|
||||
sa.Column('source_type', sa.String(length=32), nullable=True),
|
||||
sa.Column('is_deleted', sa.Boolean(), nullable=False, server_default=sa.text('false')),
|
||||
sa.Column('created_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('updated_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']),
|
||||
sa.ForeignKeyConstraint(['updated_by_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('group_id', 'title', name='uq_kb_documents_group_title'),
|
||||
)
|
||||
op.create_index('ix_kb_documents_status', 'kb_documents', ['status'])
|
||||
op.create_index('ix_kb_documents_is_deleted', 'kb_documents', ['is_deleted'])
|
||||
op.create_index('ix_kb_documents_group_status', 'kb_documents', ['group_id', 'status'])
|
||||
|
||||
op.create_table(
|
||||
'kb_document_versions',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('document_id', sa.Integer(), nullable=False),
|
||||
sa.Column('version_no', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='uploaded'),
|
||||
sa.Column('is_current', sa.Boolean(), nullable=False, server_default=sa.text('true')),
|
||||
sa.Column('source_file_name', sa.String(length=255), nullable=False),
|
||||
sa.Column('source_file_path', sa.Text(), nullable=False),
|
||||
sa.Column('source_file_ext', sa.String(length=32), nullable=True),
|
||||
sa.Column('source_file_size', sa.Integer(), nullable=True),
|
||||
sa.Column('cleaned_file_path', sa.Text(), nullable=True),
|
||||
sa.Column('cleaned_preview_path', sa.Text(), nullable=True),
|
||||
sa.Column('sha256', sa.String(length=64), nullable=True),
|
||||
sa.Column('word_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('warnings_json', sa.JSON(), nullable=True),
|
||||
sa.Column('uploaded_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column('converted_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']),
|
||||
sa.ForeignKeyConstraint(['uploaded_by_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('document_id', 'version_no', name='uq_kb_document_versions_doc_version'),
|
||||
)
|
||||
op.create_index('ix_kb_document_versions_status', 'kb_document_versions', ['status'])
|
||||
op.create_index('ix_kb_document_versions_is_current', 'kb_document_versions', ['is_current'])
|
||||
op.create_index('ix_kb_document_versions_doc_status', 'kb_document_versions', ['document_id', 'status'])
|
||||
op.create_index('ix_kb_document_versions_sha256', 'kb_document_versions', ['sha256'])
|
||||
|
||||
op.create_table(
|
||||
'kb_jobs',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('job_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='queued'),
|
||||
sa.Column('queue_job_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('group_id', sa.Integer(), nullable=True),
|
||||
sa.Column('document_id', sa.Integer(), nullable=True),
|
||||
sa.Column('document_version_id', sa.Integer(), nullable=True),
|
||||
sa.Column('progress', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('message', sa.Text(), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('payload_json', sa.JSON(), nullable=True),
|
||||
sa.Column('result_json', sa.JSON(), nullable=True),
|
||||
sa.Column('created_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column('started_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('finished_at', sa.DateTime(), nullable=True),
|
||||
sa.ForeignKeyConstraint(['created_by_id'], ['users.id']),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']),
|
||||
sa.ForeignKeyConstraint(['document_version_id'], ['kb_document_versions.id']),
|
||||
sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_kb_jobs_status', 'kb_jobs', ['status'])
|
||||
op.create_index('ix_kb_jobs_job_type', 'kb_jobs', ['job_type'])
|
||||
op.create_index('ix_kb_jobs_document_version_id', 'kb_jobs', ['document_version_id'])
|
||||
op.create_index('ix_kb_jobs_status_created', 'kb_jobs', ['status', 'created_at'])
|
||||
|
||||
op.create_table(
|
||||
'kb_dify_sync_records',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('group_id', sa.Integer(), nullable=True),
|
||||
sa.Column('document_id', sa.Integer(), nullable=True),
|
||||
sa.Column('document_version_id', sa.Integer(), nullable=False),
|
||||
sa.Column('dataset_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('dataset_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('remote_document_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('remote_document_name', sa.String(length=255), nullable=True),
|
||||
sa.Column('status', sa.String(length=32), nullable=False, server_default='pending'),
|
||||
sa.Column('sync_hash', sa.String(length=64), nullable=True),
|
||||
sa.Column('error_message', sa.Text(), nullable=True),
|
||||
sa.Column('synced_by_id', sa.Integer(), nullable=True),
|
||||
sa.Column('synced_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False, server_default=sa.func.now()),
|
||||
sa.ForeignKeyConstraint(['document_id'], ['kb_documents.id']),
|
||||
sa.ForeignKeyConstraint(['document_version_id'], ['kb_document_versions.id']),
|
||||
sa.ForeignKeyConstraint(['group_id'], ['kb_groups.id']),
|
||||
sa.ForeignKeyConstraint(['synced_by_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint(
|
||||
'document_version_id',
|
||||
'remote_document_id',
|
||||
name='uq_kb_dify_sync_records_version_remote',
|
||||
),
|
||||
)
|
||||
op.create_index('ix_kb_dify_sync_records_document_version_id', 'kb_dify_sync_records', ['document_version_id'])
|
||||
op.create_index('ix_kb_dify_sync_records_dataset_id', 'kb_dify_sync_records', ['dataset_id'])
|
||||
op.create_index('ix_kb_dify_sync_records_status', 'kb_dify_sync_records', ['status'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_kb_dify_sync_records_status', table_name='kb_dify_sync_records')
|
||||
op.drop_index('ix_kb_dify_sync_records_dataset_id', table_name='kb_dify_sync_records')
|
||||
op.drop_index('ix_kb_dify_sync_records_document_version_id', table_name='kb_dify_sync_records')
|
||||
op.drop_table('kb_dify_sync_records')
|
||||
|
||||
op.drop_index('ix_kb_jobs_status_created', table_name='kb_jobs')
|
||||
op.drop_index('ix_kb_jobs_document_version_id', table_name='kb_jobs')
|
||||
op.drop_index('ix_kb_jobs_job_type', table_name='kb_jobs')
|
||||
op.drop_index('ix_kb_jobs_status', table_name='kb_jobs')
|
||||
op.drop_table('kb_jobs')
|
||||
|
||||
op.drop_index('ix_kb_document_versions_sha256', table_name='kb_document_versions')
|
||||
op.drop_index('ix_kb_document_versions_doc_status', table_name='kb_document_versions')
|
||||
op.drop_index('ix_kb_document_versions_is_current', table_name='kb_document_versions')
|
||||
op.drop_index('ix_kb_document_versions_status', table_name='kb_document_versions')
|
||||
op.drop_table('kb_document_versions')
|
||||
|
||||
op.drop_index('ix_kb_documents_group_status', table_name='kb_documents')
|
||||
op.drop_index('ix_kb_documents_is_deleted', table_name='kb_documents')
|
||||
op.drop_index('ix_kb_documents_status', table_name='kb_documents')
|
||||
op.drop_table('kb_documents')
|
||||
|
||||
op.drop_index('ix_kb_groups_dify_dataset_id', table_name='kb_groups')
|
||||
op.drop_index('ix_kb_groups_department_active', table_name='kb_groups')
|
||||
op.drop_index('ix_kb_groups_department_id', table_name='kb_groups')
|
||||
op.drop_index('ix_kb_groups_name', table_name='kb_groups')
|
||||
op.drop_table('kb_groups')
|
||||
@@ -16,4 +16,21 @@ pycryptodome
|
||||
PyJWT
|
||||
cryptography
|
||||
oracledb
|
||||
jaydebeapi
|
||||
JPype1
|
||||
pyodbc
|
||||
pywin32; sys_platform == "win32"
|
||||
|
||||
# File Parsing & edkb_system dependencies from xinxin2
|
||||
networkx==3.5
|
||||
python-docx==1.2.0
|
||||
rapidocr-onnxruntime==1.4.4
|
||||
opencv-python-headless
|
||||
pillow==11.3.0
|
||||
numpy==2.3.3
|
||||
pypdf==6.1.0
|
||||
pypdfium2==5.0.0
|
||||
python-pptx==1.0.2
|
||||
beautifulsoup4==4.14.2
|
||||
lxml==6.0.2
|
||||
typer==0.17.4
|
||||
@@ -0,0 +1,44 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.services.knowledge_cleaning.edkb_adapter import build_clean_result
|
||||
from app.services.knowledge_cleaning.tasks import _normalized_source_filename
|
||||
|
||||
|
||||
def test_build_clean_result_generates_markdown_for_xlsx(tmp_path):
|
||||
workbook = Workbook()
|
||||
sheet = workbook.active
|
||||
sheet.title = 'Sheet1'
|
||||
sheet.append(['部门', '指标'])
|
||||
sheet.append(['供应链', '能耗'])
|
||||
|
||||
source_path = tmp_path / 'sample.xlsx'
|
||||
workbook.save(source_path)
|
||||
|
||||
target_dir = tmp_path / 'output'
|
||||
result = build_clean_result(source_path, target_dir)
|
||||
|
||||
cleaned_path = Path(result['cleaned_file_path'])
|
||||
assert result['mode'] == 'edkb_system'
|
||||
assert cleaned_path == target_dir / 'document.md'
|
||||
assert cleaned_path.exists()
|
||||
assert result['cleaned_preview_path'] == str(cleaned_path)
|
||||
|
||||
content = cleaned_path.read_text(encoding='utf-8')
|
||||
assert '供应链' in content
|
||||
assert '能耗' in content
|
||||
|
||||
|
||||
def test_normalized_source_filename_infers_xlsx_extension(tmp_path):
|
||||
workbook = Workbook()
|
||||
workbook.active.append(['部门', '指标'])
|
||||
source_with_ext = tmp_path / 'sample.xlsx'
|
||||
workbook.save(source_with_ext)
|
||||
|
||||
source_without_ext = tmp_path / 'xlsx'
|
||||
source_with_ext.rename(source_without_ext)
|
||||
|
||||
version = SimpleNamespace(source_file_name='xlsx', source_file_ext=None)
|
||||
assert _normalized_source_filename(version, source_without_ext) == 'xlsx.xlsx'
|
||||
@@ -0,0 +1,400 @@
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.models import KbDocument, KbDifySyncRecord, User
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
from app.services.knowledge_cleaning import tasks as kb_tasks_module
|
||||
|
||||
|
||||
def _configure_app(app, tmp_path):
|
||||
app.config.update(
|
||||
SECRET_KEY='test-secret-key-with-sufficient-length-123456',
|
||||
KB_STORAGE_ROOT=str(tmp_path / 'kb-storage'),
|
||||
WECOM_PUBLIC_BASE_URL='https://ai.example.com',
|
||||
INTEGRATION_API_KEY='test-integration-key',
|
||||
INTEGRATION_API_MODE='local',
|
||||
)
|
||||
|
||||
|
||||
def _ensure_user(username: str, role: str) -> User:
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
if user:
|
||||
return user
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
role=role,
|
||||
status='active',
|
||||
)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def _auth_headers_for(app, username: str) -> dict[str, str]:
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username=username).first()
|
||||
token = issue_local_access_token(user)
|
||||
return {
|
||||
'Authorization': f'Bearer {token}',
|
||||
}
|
||||
|
||||
|
||||
def _create_group(client, headers: dict[str, str], *, name: str) -> int:
|
||||
response = client.post(
|
||||
'/api/kb/groups',
|
||||
json={'name': name, 'description': 'test group'},
|
||||
headers=headers,
|
||||
)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()['id']
|
||||
|
||||
|
||||
def _create_document(client, headers: dict[str, str], group_id: int, *, title: str) -> int:
|
||||
response = client.post(
|
||||
f'/api/kb/groups/{group_id}/files',
|
||||
json={'title': title, 'description': 'test doc'},
|
||||
headers=headers,
|
||||
)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()['id']
|
||||
|
||||
|
||||
def _upload_document(client, headers: dict[str, str], document_id: int, *, content: str, filename: str):
|
||||
response = client.post(
|
||||
f'/api/kb/documents/{document_id}/upload',
|
||||
headers=headers,
|
||||
data={'file': (io.BytesIO(content.encode('utf-8')), filename)},
|
||||
content_type='multipart/form-data',
|
||||
)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def test_kb_document_upload_and_sync_flow(app, client, monkeypatch, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
|
||||
group_id = _create_group(client, admin_headers, name='知识库测试分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='员工手册')
|
||||
|
||||
version_payload = _upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='第一行\n第二行\n第三行',
|
||||
filename='employee-handbook.txt',
|
||||
)
|
||||
assert version_payload['version_no'] == 1
|
||||
assert version_payload['status'] == 'cleaned'
|
||||
assert version_payload['source_file_name'] == 'employee-handbook.txt'
|
||||
|
||||
groups_response = client.get('/api/kb/groups', headers=admin_headers)
|
||||
assert groups_response.status_code == 200
|
||||
groups_payload = groups_response.get_json()
|
||||
assert groups_payload[0]['document_count'] == 1
|
||||
|
||||
documents_response = client.get(f'/api/kb/groups/{group_id}/files', headers=admin_headers)
|
||||
assert documents_response.status_code == 200
|
||||
documents_payload = documents_response.get_json()
|
||||
assert len(documents_payload) == 1
|
||||
assert documents_payload[0]['latest_version']['status'] == 'cleaned'
|
||||
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'ensure_dataset',
|
||||
lambda self, group: ('ds_test_001', 'Test Dataset'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_test_001', 'name': name}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
assert sync_response.status_code == 200, sync_response.get_json()
|
||||
sync_job_payload = sync_response.get_json()
|
||||
assert sync_job_payload['job_type'] == 'sync_dify'
|
||||
assert sync_job_payload['status'] == 'success'
|
||||
|
||||
sync_records_response = client.get(f'/api/kb/documents/{document_id}/sync-records', headers=admin_headers)
|
||||
assert sync_records_response.status_code == 200
|
||||
sync_records_payload = sync_records_response.get_json()
|
||||
assert len(sync_records_payload) == 1
|
||||
assert sync_records_payload[0]['dataset_id'] == 'ds_test_001'
|
||||
assert sync_records_payload[0]['remote_document_id'] == 'doc_test_001'
|
||||
|
||||
|
||||
def test_integration_api_resolves_synced_document(app, client, monkeypatch, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
integration_headers = {'X-Integration-Key': app.config['INTEGRATION_API_KEY']}
|
||||
|
||||
group_id = _create_group(client, admin_headers, name='集成测试分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='集成文件')
|
||||
_upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='integration file content',
|
||||
filename='integration-source.txt',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'ensure_dataset',
|
||||
lambda self, group: ('ds_integration_001', 'Integration Dataset'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_integration_001', 'name': name}},
|
||||
)
|
||||
|
||||
sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
assert sync_response.status_code == 200, sync_response.get_json()
|
||||
|
||||
dify_file_response = client.get(
|
||||
'/api/integration/dify-file',
|
||||
headers=integration_headers,
|
||||
query_string={
|
||||
'dataset_id': 'ds_integration_001',
|
||||
'remote_document_id': 'doc_integration_001',
|
||||
},
|
||||
)
|
||||
assert dify_file_response.status_code == 200
|
||||
dify_file_payload = dify_file_response.get_json()
|
||||
assert dify_file_payload['document_id'] == document_id
|
||||
assert dify_file_payload['source_filename'] == 'integration-source.txt'
|
||||
assert dify_file_payload['source_download_url'].endswith(
|
||||
f'/api/integration/files/{document_id}/download?kind=source'
|
||||
)
|
||||
|
||||
resolve_response = client.post(
|
||||
'/api/integration/dify-files/resolve',
|
||||
headers=integration_headers,
|
||||
json={'items': [{'dataset_id': 'ds_integration_001', 'remote_document_id': 'doc_integration_001'}]},
|
||||
)
|
||||
assert resolve_response.status_code == 200
|
||||
resolve_payload = resolve_response.get_json()['data']
|
||||
assert len(resolve_payload) == 1
|
||||
assert resolve_payload[0]['found'] is True
|
||||
assert resolve_payload[0]['document']['document_id'] == document_id
|
||||
|
||||
download_response = client.get(
|
||||
f'/api/integration/files/{document_id}/download',
|
||||
headers=integration_headers,
|
||||
query_string={'kind': 'source'},
|
||||
)
|
||||
assert download_response.status_code == 200
|
||||
assert download_response.data == b'integration file content'
|
||||
|
||||
with app.app_context():
|
||||
document = db.session.get(KbDocument, document_id)
|
||||
assert document is not None
|
||||
assert db.session.query(KbDifySyncRecord).filter_by(document_id=document_id).count() == 1
|
||||
|
||||
|
||||
def test_sync_recreates_missing_remote_document_for_same_hash(app, client, monkeypatch, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
|
||||
group_id = _create_group(client, admin_headers, name='同步补偿分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='同步补偿文档')
|
||||
_upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='same content for repeated sync',
|
||||
filename='sync-recreate.txt',
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'ensure_dataset',
|
||||
lambda self, group: ('ds_recreate_001', 'Recreate Dataset'),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_old_001', 'name': name}},
|
||||
)
|
||||
|
||||
first_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
assert first_sync_response.status_code == 200, first_sync_response.get_json()
|
||||
|
||||
def _missing_remote_document(self, *, dataset_id: str, document_id: str):
|
||||
raise dify_sync_module.KbDifySyncError(
|
||||
'Dify API GET /datasets/ds_recreate_001/documents/doc_old_001 failed: '
|
||||
'404 {"code":"not_found","message":"Document not found."}'
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'get_document',
|
||||
_missing_remote_document,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dify_sync_module.KbDifySyncService,
|
||||
'create_document_by_text',
|
||||
lambda self, dataset_id, name, text: {'document': {'id': 'doc_new_001', 'name': name}},
|
||||
)
|
||||
|
||||
second_sync_response = client.post(f'/api/kb/documents/{document_id}/sync', headers=admin_headers)
|
||||
assert second_sync_response.status_code == 200, second_sync_response.get_json()
|
||||
|
||||
with app.app_context():
|
||||
records = (
|
||||
db.session.query(KbDifySyncRecord)
|
||||
.filter_by(document_id=document_id)
|
||||
.order_by(KbDifySyncRecord.id.asc())
|
||||
.all()
|
||||
)
|
||||
assert len(records) == 2
|
||||
assert records[0].remote_document_id == 'doc_old_001'
|
||||
assert records[1].remote_document_id == 'doc_new_001'
|
||||
assert records[1].status == 'synced'
|
||||
|
||||
|
||||
def test_document_markdown_can_be_viewed_and_saved(app, client, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
group_id = _create_group(client, admin_headers, name='Markdown 编辑分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='Markdown 编辑文档')
|
||||
|
||||
_upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='第一行\n第二行\n第三行',
|
||||
filename='editable.txt',
|
||||
)
|
||||
|
||||
read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers)
|
||||
assert read_response.status_code == 200, read_response.get_json()
|
||||
read_payload = read_response.get_json()
|
||||
assert read_payload['kind'] == 'markdown'
|
||||
assert '第二行' in read_payload['content']
|
||||
|
||||
updated_content = '# 手工修订\n\n这是一段修改后的 Markdown。'
|
||||
save_response = client.patch(
|
||||
f'/api/kb/documents/{document_id}/markdown',
|
||||
headers=admin_headers,
|
||||
json={'content': updated_content},
|
||||
)
|
||||
assert save_response.status_code == 200, save_response.get_json()
|
||||
save_payload = save_response.get_json()
|
||||
assert save_payload['content'] == updated_content
|
||||
assert save_payload['version']['cleaned_file_path'].endswith('document.md')
|
||||
|
||||
with app.app_context():
|
||||
document = db.session.get(KbDocument, document_id)
|
||||
version = next(item for item in document.versions if item.is_current)
|
||||
markdown_path = Path(version.cleaned_file_path)
|
||||
assert markdown_path.exists()
|
||||
assert markdown_path.read_text(encoding='utf-8') == updated_content
|
||||
|
||||
|
||||
def test_document_markdown_save_upgrades_preview_to_markdown(app, client, monkeypatch, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
group_id = _create_group(client, admin_headers, name='Preview 编辑分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='Preview 编辑文档')
|
||||
|
||||
def _raise_build_clean_result(source_path, target_dir):
|
||||
raise RuntimeError('forced preview fallback')
|
||||
|
||||
monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _raise_build_clean_result)
|
||||
|
||||
_upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='原始文本内容',
|
||||
filename='preview-source.txt',
|
||||
)
|
||||
|
||||
read_response = client.get(f'/api/kb/documents/{document_id}/markdown', headers=admin_headers)
|
||||
assert read_response.status_code == 200, read_response.get_json()
|
||||
read_payload = read_response.get_json()
|
||||
assert read_payload['kind'] == 'preview'
|
||||
assert 'forced preview fallback' in read_payload['content']
|
||||
|
||||
updated_content = '# 兜底转正\n\n预览文件已改为正式 Markdown。'
|
||||
save_response = client.patch(
|
||||
f'/api/kb/documents/{document_id}/markdown',
|
||||
headers=admin_headers,
|
||||
json={'content': updated_content},
|
||||
)
|
||||
assert save_response.status_code == 200, save_response.get_json()
|
||||
save_payload = save_response.get_json()
|
||||
assert save_payload['kind'] == 'markdown'
|
||||
|
||||
with app.app_context():
|
||||
document = db.session.get(KbDocument, document_id)
|
||||
version = next(item for item in document.versions if item.is_current)
|
||||
assert version.cleaned_file_path is not None
|
||||
assert version.cleaned_file_path.endswith('document.md')
|
||||
assert version.cleaned_preview_path == version.cleaned_file_path
|
||||
markdown_path = Path(version.cleaned_file_path)
|
||||
assert markdown_path.exists()
|
||||
assert markdown_path.read_text(encoding='utf-8') == updated_content
|
||||
|
||||
|
||||
def test_upload_preserves_excel_extension_for_non_ascii_filename(app, client, monkeypatch, tmp_path):
|
||||
_configure_app(app, tmp_path)
|
||||
|
||||
with app.app_context():
|
||||
_ensure_user('admin', 'admin')
|
||||
|
||||
admin_headers = _auth_headers_for(app, 'admin')
|
||||
group_id = _create_group(client, admin_headers, name='中文文件名分组')
|
||||
document_id = _create_document(client, admin_headers, group_id, title='中文 Excel 文档')
|
||||
captured = {}
|
||||
|
||||
def _fake_build_clean_result(source_path, target_dir):
|
||||
captured['source_name'] = source_path.name
|
||||
cleaned_path = target_dir / 'document.md'
|
||||
cleaned_path.write_text('# ok', encoding='utf-8')
|
||||
return {
|
||||
'mode': 'edkb_system',
|
||||
'cleaned_file_path': str(cleaned_path),
|
||||
'cleaned_preview_path': str(cleaned_path),
|
||||
'word_count': 1,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(kb_tasks_module, 'build_clean_result', _fake_build_clean_result)
|
||||
|
||||
version_payload = _upload_document(
|
||||
client,
|
||||
admin_headers,
|
||||
document_id,
|
||||
content='fake excel bytes',
|
||||
filename='能源管理体系文件清单.xlsx',
|
||||
)
|
||||
|
||||
assert version_payload['source_file_name'].endswith('.xlsx')
|
||||
assert captured['source_name'].endswith('.xlsx')
|
||||
@@ -0,0 +1,232 @@
|
||||
from types import SimpleNamespace
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService
|
||||
|
||||
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
|
||||
|
||||
def _make_template():
|
||||
request_info = ET.Element(f'{{{WORKFLOW_NS}}}WorkflowRequestInfo')
|
||||
ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}creatorId').text = ''
|
||||
ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}creatorName').text = ''
|
||||
ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}requestLevel').text = ''
|
||||
ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}requestName').text = ''
|
||||
|
||||
workflow_base = ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}workflowBaseInfo')
|
||||
ET.SubElement(workflow_base, f'{{{WORKFLOW_NS}}}workflowId').text = ''
|
||||
|
||||
main_table = ET.SubElement(request_info, f'{{{WORKFLOW_NS}}}workflowMainTableInfo')
|
||||
request_records = ET.SubElement(main_table, f'{{{WORKFLOW_NS}}}requestRecords')
|
||||
record = ET.SubElement(request_records, f'{{{WORKFLOW_NS}}}WorkflowRequestTableRecord')
|
||||
|
||||
for field_name in [
|
||||
'requestname',
|
||||
'tdrgh',
|
||||
'sqrgh',
|
||||
'tdrxm',
|
||||
'sqrxm',
|
||||
'dlrgh',
|
||||
'dlrxm',
|
||||
'dlrlogid',
|
||||
'jb',
|
||||
'jbbh',
|
||||
'kssj',
|
||||
'kssk',
|
||||
'jssj',
|
||||
'jssk',
|
||||
'qjsc',
|
||||
'sfwgs',
|
||||
'sfwc',
|
||||
'bz',
|
||||
]:
|
||||
field = ET.SubElement(record, f'{{{WORKFLOW_NS}}}WorkflowRequestTableField')
|
||||
ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldName').text = field_name
|
||||
ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldValue').text = ''
|
||||
ET.SubElement(field, f'{{{WORKFLOW_NS}}}fieldShowValue').text = ''
|
||||
return request_info
|
||||
|
||||
|
||||
def _field_values(request_info, field_name: str):
|
||||
for field in request_info.iter(f'{{{WORKFLOW_NS}}}WorkflowRequestTableField'):
|
||||
name = field.findtext(f'{{{WORKFLOW_NS}}}fieldName')
|
||||
if name == field_name:
|
||||
return (
|
||||
field.findtext(f'{{{WORKFLOW_NS}}}fieldValue'),
|
||||
field.findtext(f'{{{WORKFLOW_NS}}}fieldShowValue'),
|
||||
)
|
||||
raise AssertionError(f'field not found: {field_name}')
|
||||
|
||||
|
||||
def test_build_request_info_uses_full_leave_type_label_map(app, monkeypatch):
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'_get_template_request_info',
|
||||
classmethod(lambda cls, workflow_id, oa_user_id: _make_template()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_creator_oa_user',
|
||||
classmethod(
|
||||
lambda cls, employee_id, real_name=None: {
|
||||
'employee_id': employee_id,
|
||||
'user_id': '21823',
|
||||
'name': real_name or '刘义亮',
|
||||
}
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_agent_oa_user',
|
||||
classmethod(
|
||||
lambda cls, employee_id, real_name=None: {
|
||||
'employee_id': employee_id,
|
||||
'user_id': '21784',
|
||||
'name': real_name or '梁春艳',
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
form_data = {
|
||||
'applicantName': '刘义亮',
|
||||
'employeeId': '26040006',
|
||||
'agentEmployeeId': '26030025',
|
||||
'agentName': '梁春艳',
|
||||
'leaveType': '408',
|
||||
'startTime': '2026-05-15T09:00',
|
||||
'endTime': '2026-05-15T18:00',
|
||||
'durationHours': 9,
|
||||
'isOutOfOffice': 1,
|
||||
'isWorkInjury': 1,
|
||||
'remark': '测试提交',
|
||||
}
|
||||
current_user = SimpleNamespace(real_name='刘义亮', username='26040006', employee_id='26040006')
|
||||
|
||||
request_info, filler, creator, agent = OALeaveWorkflowService.build_request_info(form_data, current_user)
|
||||
|
||||
assert creator == {'employee_id': '26040006', 'user_id': '21823', 'name': '刘义亮'}
|
||||
assert agent == {'employee_id': '26030025', 'user_id': '21784', 'name': '梁春艳'}
|
||||
assert _field_values(request_info, 'jb') == ('408', '育儿假(小时)')
|
||||
assert _field_values(request_info, 'jbbh') == ('408', '')
|
||||
assert _field_values(request_info, 'sfwc') == ('1', '否')
|
||||
assert _field_values(request_info, 'sfwgs') == ('1', '否')
|
||||
|
||||
|
||||
def test_build_request_info_resolves_creator_from_oa_sqlserver(app, monkeypatch):
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'_get_template_request_info',
|
||||
classmethod(lambda cls, workflow_id, oa_user_id: _make_template()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_agent_oa_user',
|
||||
classmethod(
|
||||
lambda cls, employee_id, real_name=None: {
|
||||
'employee_id': employee_id,
|
||||
'user_id': '21784',
|
||||
'name': real_name or '梁春艳',
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
captured = {}
|
||||
|
||||
def _fake_resolve_creator(cls, employee_id, real_name=None):
|
||||
captured['employee_id'] = employee_id
|
||||
captured['real_name'] = real_name
|
||||
return {
|
||||
'employee_id': '26040006',
|
||||
'user_id': '21823',
|
||||
'name': '刘义亮',
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_creator_oa_user',
|
||||
classmethod(_fake_resolve_creator),
|
||||
)
|
||||
|
||||
form_data = {
|
||||
'applicantName': '刘义亮',
|
||||
'employeeId': '26040006',
|
||||
'agentEmployeeId': '26030025',
|
||||
'agentName': '梁春艳',
|
||||
'leaveType': '010',
|
||||
'startTime': '2026-05-15T09:00',
|
||||
'endTime': '2026-05-15T18:00',
|
||||
'durationHours': 9,
|
||||
'isOutOfOffice': 1,
|
||||
'isWorkInjury': 1,
|
||||
'remark': '测试提交',
|
||||
}
|
||||
current_user = SimpleNamespace(real_name='其他姓名', username='26040006', employee_id='26040006')
|
||||
|
||||
request_info, filler, creator, _agent = OALeaveWorkflowService.build_request_info(form_data, current_user)
|
||||
|
||||
assert captured == {'employee_id': '26040006', 'real_name': '刘义亮'}
|
||||
assert creator == {'employee_id': '26040006', 'user_id': '21823', 'name': '刘义亮'}
|
||||
assert request_info.findtext(f'{{{WORKFLOW_NS}}}creatorId') == '21823'
|
||||
assert request_info.findtext(f'{{{WORKFLOW_NS}}}creatorName') == '刘义亮'
|
||||
|
||||
|
||||
def test_build_request_info_resolves_agent_from_oa_sqlserver(app, monkeypatch):
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'_get_template_request_info',
|
||||
classmethod(lambda cls, workflow_id, oa_user_id: _make_template()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_creator_oa_user',
|
||||
classmethod(
|
||||
lambda cls, employee_id, real_name=None: {
|
||||
'employee_id': employee_id,
|
||||
'user_id': '21823',
|
||||
'name': real_name or '刘义亮',
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
captured = {}
|
||||
|
||||
def _fake_resolve_agent(cls, employee_id, real_name=None):
|
||||
captured['employee_id'] = employee_id
|
||||
captured['real_name'] = real_name
|
||||
return {
|
||||
'employee_id': '26050003',
|
||||
'user_id': '21888',
|
||||
'name': '曹惠鹏',
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
OALeaveWorkflowService,
|
||||
'resolve_agent_oa_user',
|
||||
classmethod(_fake_resolve_agent),
|
||||
)
|
||||
|
||||
form_data = {
|
||||
'applicantName': '刘义亮',
|
||||
'employeeId': '26040006',
|
||||
'agentEmployeeId': '26050003',
|
||||
'agentName': '曹惠鹏',
|
||||
'leaveType': '010',
|
||||
'startTime': '2026-05-15T09:00',
|
||||
'endTime': '2026-05-15T18:00',
|
||||
'durationHours': 9,
|
||||
'isOutOfOffice': 1,
|
||||
'isWorkInjury': 1,
|
||||
'remark': '测试提交',
|
||||
}
|
||||
current_user = SimpleNamespace(real_name='刘义亮', username='26040006', employee_id='26040006')
|
||||
|
||||
request_info, filler, _creator, agent = OALeaveWorkflowService.build_request_info(form_data, current_user)
|
||||
|
||||
assert captured == {'employee_id': '26050003', 'real_name': '曹惠鹏'}
|
||||
assert agent == {'employee_id': '26050003', 'user_id': '21888', 'name': '曹惠鹏'}
|
||||
assert _field_values(request_info, 'dlrxm') == ('21888', '曹惠鹏')
|
||||
assert _field_values(request_info, 'dlrlogid') == ('21888', '')
|
||||
@@ -84,3 +84,28 @@ def test_chat_messages_history(client):
|
||||
assert len(msgs) == 2 # User + Assistant
|
||||
assert msgs[0]['content'] == 'Hi'
|
||||
assert msgs[1]['content'] == 'Hello'
|
||||
|
||||
|
||||
def test_chat_sessions_keep_latest_non_empty_query_as_title(client):
|
||||
headers = get_headers(client)
|
||||
|
||||
with client.application.app_context():
|
||||
user = User.query.filter_by(username='testuser').first()
|
||||
agent = Agent.query.filter_by(name='Test Agent').first()
|
||||
db.session.add(ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id='conv1',
|
||||
query='',
|
||||
answer='请填写请假表单',
|
||||
message_type='leave-form',
|
||||
created_at=datetime(2026, 1, 2),
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
res = client.get('/api/chat/sessions?agent_id=1', headers=headers)
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert len(data) == 1
|
||||
assert data[0]['conversation_id'] == 'conv1'
|
||||
assert data[0]['title'] == 'Hi'
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
backend/worker_kb.py
|
||||
文件用途:知识库最小 worker 入口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
from app import create_app
|
||||
from app.services.knowledge_cleaning.queue_service import process_next_clean_job
|
||||
|
||||
|
||||
def _resolve_config_name() -> str:
|
||||
"""Keep the worker aligned with container/runtime environment selection."""
|
||||
explicit = os.getenv('APP_CONFIG')
|
||||
if explicit:
|
||||
return explicit.strip().lower()
|
||||
|
||||
flask_env = os.getenv('FLASK_ENV', 'production').strip().lower()
|
||||
mapping = {
|
||||
'dev': 'development',
|
||||
'development': 'development',
|
||||
'test': 'testing',
|
||||
'testing': 'testing',
|
||||
'prod': 'production',
|
||||
'production': 'production',
|
||||
}
|
||||
return mapping.get(flask_env, 'production')
|
||||
|
||||
|
||||
def main():
|
||||
app = create_app(_resolve_config_name())
|
||||
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2))
|
||||
|
||||
with app.app_context():
|
||||
print(f'[kb-worker] started, poll_seconds={poll_seconds}')
|
||||
while True:
|
||||
processed, message = process_next_clean_job()
|
||||
if not processed:
|
||||
time.sleep(poll_seconds)
|
||||
continue
|
||||
print(f'[kb-worker] processed job: {message}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+68
-6
@@ -1,4 +1,19 @@
|
||||
services:
|
||||
# ==============================================================================
|
||||
# kb-redis: 知识库任务/后续异步能力预留的 Redis 服务
|
||||
# ==============================================================================
|
||||
kb-redis:
|
||||
image: ${KB_REDIS_IMAGE:-redis:7-alpine}
|
||||
container_name: hxops-kb-redis
|
||||
restart: always
|
||||
profiles:
|
||||
- kb-redis
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- hxops_redis_data:/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# hxops-backend: Flask 后端服务 (端口: 5000)
|
||||
# ==============================================================================
|
||||
@@ -7,10 +22,15 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: backend/Dockerfile
|
||||
args:
|
||||
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
|
||||
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
|
||||
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
|
||||
container_name: hxops-backend
|
||||
restart: always
|
||||
# 与 scripts/deploy_compose.sh 使用的 .env.<ENV_NAME> 对齐(通过 COMPOSE_ENV_BASENAME)
|
||||
env_file:
|
||||
- ${COMPOSE_SHARED_ENV_BASENAME:-.env.shared}
|
||||
- ${COMPOSE_ENV_BASENAME:-.env.dev}
|
||||
environment:
|
||||
# 数据库连接 (在环境变量中配置)
|
||||
@@ -20,19 +40,55 @@ services:
|
||||
- ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client}
|
||||
- ORACLE_HOME=/app/oracle_client/instantclient_19_31
|
||||
- LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
- REDIS_URL=${REDIS_URL:-redis://kb-redis:6379/0}
|
||||
- KB_STORAGE_ROOT=${KB_STORAGE_ROOT:-/app/data/kb}
|
||||
- KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker}
|
||||
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
|
||||
|
||||
# 允许容器访问宿主机服务 (如数据库)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
# 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露
|
||||
ports:
|
||||
- "5052:5052"
|
||||
# 持久化运行时可写文件:
|
||||
# - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写,
|
||||
# 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动
|
||||
# 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。
|
||||
volumes:
|
||||
- ./backend/.env:/app/.env
|
||||
- ./oracle_client:/app/oracle_client:ro
|
||||
- hxops_runtime_data:/app/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# hxops-kb-worker: 知识库清洗/同步最小 worker
|
||||
# ==============================================================================
|
||||
hxops-kb-worker:
|
||||
image: ${BACKEND_IMAGE:-hxops-backend:local}
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
|
||||
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
|
||||
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
|
||||
container_name: hxops-kb-worker
|
||||
restart: always
|
||||
command: ["python", "worker_kb.py"]
|
||||
depends_on:
|
||||
- hxops-backend
|
||||
env_file:
|
||||
- ${COMPOSE_SHARED_ENV_BASENAME:-.env.shared}
|
||||
- ${COMPOSE_ENV_BASENAME:-.env.dev}
|
||||
environment:
|
||||
DATABASE_URL:
|
||||
SECRET_KEY:
|
||||
FLASK_APP: ${FLASK_APP:-run.py}
|
||||
FLASK_ENV: ${FLASK_ENV:-production}
|
||||
REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0}
|
||||
KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb}
|
||||
KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker}
|
||||
KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
- hxops_runtime_data:/app/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
@@ -44,6 +100,9 @@ services:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine}
|
||||
NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine}
|
||||
container_name: hxops-frontend
|
||||
restart: always
|
||||
depends_on:
|
||||
@@ -62,3 +121,6 @@ networks:
|
||||
name: ai-platform
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
hxops_runtime_data:
|
||||
hxops_redis_data:
|
||||
@@ -0,0 +1,130 @@
|
||||
services:
|
||||
# ==============================================================================
|
||||
# kb-redis: 知识库任务/后续异步能力预留的 Redis 服务
|
||||
# ==============================================================================
|
||||
kb-redis:
|
||||
image: ${KB_REDIS_IMAGE:-redis:7-alpine}
|
||||
container_name: hxops-kb-redis
|
||||
restart: always
|
||||
profiles:
|
||||
- kb-redis
|
||||
command: ["redis-server", "--appendonly", "yes"]
|
||||
volumes:
|
||||
- hxops_redis_data:/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# hxops-backend: Flask 后端服务 (端口: 5000)
|
||||
# ==============================================================================
|
||||
hxops-backend:
|
||||
image: ${BACKEND_IMAGE:-hxops-backend:local}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: backend/Dockerfile
|
||||
args:
|
||||
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
|
||||
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
|
||||
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
|
||||
container_name: hxops-backend
|
||||
restart: always
|
||||
# 与 scripts/deploy_compose.sh 使用的 .env.<ENV_NAME> 对齐(通过 COMPOSE_ENV_BASENAME)
|
||||
env_file:
|
||||
- ${COMPOSE_ENV_BASENAME:-.env.dev}
|
||||
environment:
|
||||
# 数据库连接 (在环境变量中配置)
|
||||
- DATABASE_URL=${DATABASE_URL}
|
||||
- FLASK_APP=${FLASK_APP:-run.py}
|
||||
- FLASK_ENV=${FLASK_ENV:-production}
|
||||
- ORACLE_CLIENT_LIB_DIR=${ORACLE_CLIENT_LIB_DIR:-/app/oracle_client}
|
||||
- ORACLE_HOME=/app/oracle_client/instantclient_19_31
|
||||
- LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
- REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0}
|
||||
- KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb}
|
||||
- KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker}
|
||||
- KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2}
|
||||
|
||||
# 允许容器访问宿主机服务 (如数据库)
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
# 如果需要在宿主机调试,可暴露端口;生产环境建议只在网络内暴露
|
||||
ports:
|
||||
- "5052:5052"
|
||||
# 持久化运行时可写文件:
|
||||
# - backend/.env 用于保存管理员后台修改的企业微信等配置(与数据库双写,
|
||||
# 防止容器重建后从镜像基线读取丢失修改)。文件不存在时 docker 会自动
|
||||
# 把它当作目录挂载,因此先确保宿主机上存在该文件再启动。
|
||||
volumes:
|
||||
- ./backend/.env:/app/.env
|
||||
- hxops_runtime_data:/app/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# hxops-kb-worker: 知识库清洗/同步最小 worker
|
||||
# ==============================================================================
|
||||
hxops-kb-worker:
|
||||
image: ${BACKEND_IMAGE:-hxops-backend:local}
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
PYTHON_BASE_IMAGE: ${PYTHON_BASE_IMAGE:-python:3.12-slim}
|
||||
PIP_INDEX_URL: ${PIP_INDEX_URL:-https://mirrors.aliyun.com/pypi/simple}
|
||||
PIP_EXTRA_INDEX_URL: ${PIP_EXTRA_INDEX_URL:-}
|
||||
container_name: hxops-kb-worker
|
||||
restart: always
|
||||
command: ["python", "worker_kb.py"]
|
||||
depends_on:
|
||||
- hxops-backend
|
||||
env_file:
|
||||
- ./backend/.env
|
||||
environment:
|
||||
DATABASE_URL:
|
||||
SECRET_KEY:
|
||||
FLASK_APP: ${FLASK_APP:-run.py}
|
||||
FLASK_ENV: ${FLASK_ENV:-production}
|
||||
REDIS_URL: ${REDIS_URL:-redis://kb-redis:6379/0}
|
||||
KB_STORAGE_ROOT: ${KB_STORAGE_ROOT:-/app/data/kb}
|
||||
KB_TASK_EXECUTION_MODE: ${KB_TASK_EXECUTION_MODE:-worker}
|
||||
KB_WORKER_POLL_SECONDS: ${KB_WORKER_POLL_SECONDS:-2}
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
- ./backend/.env:/app/.env
|
||||
- hxops_runtime_data:/app/data
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# hxops-frontend: Vue 前端静态资源 + Nginx 反向代理 (端口: 80)
|
||||
# ==============================================================================
|
||||
hxops-frontend:
|
||||
image: ${FRONTEND_IMAGE:-hxops-frontend:local}
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
args:
|
||||
NODE_BASE_IMAGE: ${NODE_BASE_IMAGE:-node:22-alpine}
|
||||
NGINX_BASE_IMAGE: ${NGINX_BASE_IMAGE:-nginx:alpine}
|
||||
container_name: hxops-frontend
|
||||
restart: always
|
||||
depends_on:
|
||||
- hxops-backend
|
||||
# 前端容器暴露 80 端口,映射到宿主机 8890 (或其他端口供 nginx-gateway 访问)
|
||||
ports:
|
||||
- "8890:80"
|
||||
networks:
|
||||
- ai-platform
|
||||
|
||||
# ==============================================================================
|
||||
# 网络配置
|
||||
# ==============================================================================
|
||||
networks:
|
||||
ai-platform:
|
||||
name: ai-platform
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
hxops_runtime_data:
|
||||
hxops_redis_data:
|
||||
@@ -0,0 +1,63 @@
|
||||
# AI知识库对接HR系统
|
||||
|
||||
- DB:192.168.100.191:1433
|
||||
- UserName:AI\_Knowledge\_Base\_Hr
|
||||
- Password:hoo-thai\@123\_AI\_HR
|
||||
- 默认数据库:NH\_N8\_HEXIN
|
||||
|
||||
## 用途:年假记录表
|
||||
|
||||
- 视图:VIEW\_D044
|
||||
\| 字段名称 | 类型 | 长度 | 字段说明 |
|
||||
\| --- | --- | --- | --- |
|
||||
\| c001001 | nvarchar | 200 | 部门编号 |
|
||||
\| c001002 | nvarchar | 200 | 部门名称(小部门) |
|
||||
\| a008003 | nvarchar | 200 | 上级部门名称(大部门) |
|
||||
\| c002001 | nvarchar | 200 | 员工工号 |
|
||||
\| c002002 | nvarchar | 200 | 员工姓名 |
|
||||
\| d072001 | int | - | 年份 |
|
||||
\| d072002 | int | - | 总育儿假时数 |
|
||||
\| d072003 | int | - | 已休育儿假时数 |
|
||||
\| d072004 | int | - | 未休育儿假时数 |
|
||||
|
||||
## 用途:育儿假记录表
|
||||
|
||||
- 视图:VIEW\_D072
|
||||
\| 字段名称 | 类型 | 长度 | 字段说明 |
|
||||
\| --- | --- | --- | --- |
|
||||
\| c001001 | nvarchar | 200 | 部门编号 |
|
||||
\| c001002 | nvarchar | 200 | 部门名称(小部门) |
|
||||
\| a008003 | nvarchar | 200 | 上级部门名称(大部门) |
|
||||
\| c002001 | nvarchar | 200 | 员工工号 |
|
||||
\| c002002 | nvarchar | 200 | 员工姓名 |
|
||||
\| d072001 | int | - | 年份 |
|
||||
\| d072002 | int | - | 总育儿假时数 |
|
||||
\| d072003 | int | - | 已休育儿假时数 |
|
||||
\| d072004 | int | - | 未休育儿假时数 |
|
||||
|
||||
|
||||
# OA数据对接AI知识库-请假流程相关视图
|
||||
|
||||
- DB:192.168.100.225:1433
|
||||
- UserName:AI_Knowledge_Base_OA
|
||||
- Password:hoo-thai@123_AI_OA
|
||||
- 默认数据库:ecology
|
||||
|
||||
## 用途:流程当前节点视图
|
||||
|
||||
- 视图:v_workflow_requestbase
|
||||
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| requestid | int | int | 流程ID |
|
||||
| status | varchar | varchar(500) | 流程状态 |
|
||||
| workflowid | int | int | 流程类型ID |
|
||||
| nodename | varchar | varchar(1000) | 当前节点名称 |
|
||||
|
||||
## 用途:员工信息视图
|
||||
|
||||
- 视图:userInfo_view
|
||||
| 字段名称 | 字段类型 | 字符长度 | 字段说明 |
|
||||
| --- | --- | --- | --- |
|
||||
| workcode | varchar | varchar(1000) | 员工工号 |
|
||||
| lastname | varchar | varchar(1000) | 员工姓名 |
|
||||
| id | int | int | 员工ID |
|
||||
@@ -0,0 +1,178 @@
|
||||
# Git Commit Message 规范(团队版)
|
||||
|
||||
本文档用于统一团队 Git 提交信息写法,提升可读性、可追溯性和自动化能力(如 changelog、版本发布)。
|
||||
|
||||
## 1. 目标与原则
|
||||
|
||||
- 一个提交只做一件事(或同一类紧密相关的事)。
|
||||
- 提交信息要让不了解上下文的人也能快速理解“改了什么、为什么改”。
|
||||
- 优先使用英文提交信息,避免中英文混用造成解析不一致。
|
||||
- 所有人遵循同一格式,减少代码评审和回溯成本。
|
||||
|
||||
## 2. 标准格式(必须)
|
||||
|
||||
```text
|
||||
<type>(<scope>): <subject>
|
||||
|
||||
[body]
|
||||
|
||||
[footer]
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
- `type`:变更类型(必填)。
|
||||
- `scope`:影响范围(选填,但推荐填写)。
|
||||
- `subject`:一句话概述(必填)。
|
||||
- `body`:详细说明(选填,建议在复杂改动时填写)。
|
||||
- `footer`:关联任务、破坏性变更等(选填)。
|
||||
|
||||
## 3. Header 书写规则(必须)
|
||||
|
||||
Header 即第一行:`<type>(<scope>): <subject>`
|
||||
|
||||
- 必须小写 `type`,后接英文冒号和空格。
|
||||
- `subject` 使用祈使语气,简明描述动作,如 `add` `fix` `remove` `refactor`。
|
||||
- 不以句号结尾。
|
||||
- Header 最大长度建议不超过 100 个字符。
|
||||
|
||||
正确示例:
|
||||
|
||||
```text
|
||||
feat(auth): add SMS login support
|
||||
fix(order): handle null coupon in checkout
|
||||
refactor(api): split user service and repository
|
||||
```
|
||||
|
||||
错误示例:
|
||||
|
||||
```text
|
||||
Feat: Added login feature.
|
||||
fix: bug
|
||||
update code
|
||||
```
|
||||
|
||||
## 4. Type 定义(必须使用以下枚举)
|
||||
|
||||
- `feat`:新增功能(会体现在发布说明中)。
|
||||
- `fix`:缺陷修复(会体现在发布说明中)。
|
||||
- `docs`:文档变更(仅文档)。
|
||||
- `style`:代码格式调整(不影响逻辑,如空格、分号、格式化)。
|
||||
- `refactor`:重构(非新增功能、非修复缺陷)。
|
||||
- `perf`:性能优化。
|
||||
- `test`:测试相关(新增/修改测试用例)。
|
||||
- `build`:构建系统或依赖变更(如 webpack、vite、gradle、npm 依赖)。
|
||||
- `ci`:CI/CD 配置或脚本变更。
|
||||
- `chore`:杂项维护(不属于上述分类)。
|
||||
- `revert`:回滚某次提交。
|
||||
|
||||
## 5. Scope 约定(推荐)
|
||||
|
||||
Scope 用于快速识别改动模块,建议使用以下命名:
|
||||
|
||||
- 按业务域:`auth` `order` `payment` `user`
|
||||
- 按技术层:`api` `db` `ui` `deps` `config`
|
||||
- 按工程对象:`docker` `github-actions` `eslint`
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
fix(payment): prevent duplicate callback handling
|
||||
ci(github-actions): cache pnpm store
|
||||
build(deps): upgrade axios to v1.9.0
|
||||
```
|
||||
|
||||
## 6. Body 编写建议(复杂改动强烈建议)
|
||||
|
||||
Body 与 Header 空一行,重点写“为什么”和“影响面”:
|
||||
|
||||
- 变更动机:为什么要改。
|
||||
- 关键方案:采用了什么实现策略。
|
||||
- 影响范围:是否影响接口、数据、兼容性。
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
feat(order): support partial shipment
|
||||
|
||||
Allow splitting one order into multiple shipment packages to support
|
||||
warehouse stock differences. This change updates shipment status flow
|
||||
and adds validation for package-level tracking numbers.
|
||||
```
|
||||
|
||||
## 7. Footer 约定(推荐)
|
||||
|
||||
### 7.1 关联任务
|
||||
|
||||
- `Refs #123`:关联但不关闭任务。
|
||||
- `Closes #123`:合并后自动关闭任务。
|
||||
|
||||
### 7.2 破坏性变更
|
||||
|
||||
若存在不兼容修改,必须明确标注:
|
||||
|
||||
```text
|
||||
BREAKING CHANGE: remove legacy /v1/login endpoint, use /v2/login instead.
|
||||
```
|
||||
|
||||
## 8. 常见场景示例
|
||||
|
||||
新增功能:
|
||||
|
||||
```text
|
||||
feat(profile): add avatar upload API
|
||||
```
|
||||
|
||||
修复问题:
|
||||
|
||||
```text
|
||||
fix(cart): recalculate total when item quantity is zero
|
||||
```
|
||||
|
||||
依赖升级:
|
||||
|
||||
```text
|
||||
build(deps): bump spring-boot to 3.3.2
|
||||
```
|
||||
|
||||
仅文档:
|
||||
|
||||
```text
|
||||
docs(readme): add local development instructions
|
||||
```
|
||||
|
||||
回滚提交:
|
||||
|
||||
```text
|
||||
revert: feat(payment): support WeChat QR checkout
|
||||
```
|
||||
|
||||
## 9. Pull Request 要求(建议)
|
||||
|
||||
- PR 标题建议复用同样格式:`type(scope): subject`
|
||||
- 一个 PR 尽量聚焦一个主题。
|
||||
- 合并前整理提交历史,避免大量无意义提交(如 `update` `fix` `test`)。
|
||||
|
||||
## 10. 禁止事项
|
||||
|
||||
- 禁止无语义提交信息:`update` `fix bug` `modify` `111`
|
||||
- 禁止把多个无关改动放在同一提交中。
|
||||
- 禁止漏写破坏性变更说明。
|
||||
|
||||
## 11. 自检清单(提交前)
|
||||
|
||||
- 提交类型是否正确(`feat/fix/...`)?
|
||||
- `subject` 是否清晰说明“做了什么”?
|
||||
- 是否需要 `scope` 来提升可读性?
|
||||
- 是否存在破坏性变更,若有是否标注 `BREAKING CHANGE`?
|
||||
- 是否关联了任务编号(`Refs/Closes #id`)?
|
||||
|
||||
## 12. 推荐工具(落地执行)
|
||||
|
||||
- `commitlint`:校验提交信息格式。
|
||||
- `husky`:在 `commit-msg` 钩子自动校验。
|
||||
- 可选:`commitizen` 或 `cz-git` 提供交互式提交,降低学习成本。
|
||||
|
||||
---
|
||||
|
||||
维护建议:本规范由团队共同维护,若新增 `type` 或调整规则,请在评审通过后更新本文档并同步工具配置。
|
||||
File renamed without changes.
@@ -0,0 +1,268 @@
|
||||
# 智能HR请假管理需求
|
||||
|
||||
## 1. 项目背景
|
||||
|
||||
当前系统已经具备以下基础能力:
|
||||
|
||||
- 员工可通过 AI Agent 查询本人假期余额。
|
||||
- 系统已支持按员工工号查询 OA/HR SQL Server 视图中的假期数据。
|
||||
- 系统已具备企业微信消息通知基础能力。
|
||||
|
||||
现阶段希望在此基础上,继续建设一个完整的“智能 HR 请假管理”闭环,让员工能够通过 AI Agent 完成“查询假期、发起请假、跟踪状态、接收通知”全流程操作。
|
||||
|
||||
## 2. 项目目标
|
||||
|
||||
建设一个面向员工的智能 HR 请假 Agent,实现以下业务闭环:
|
||||
|
||||
1. 员工通过 AI Agent 查询本人假期余额与明细。
|
||||
2. 员工通过 AI Agent 发起请假申请。
|
||||
3. 系统自动将请假单推送到 OA 工作流。
|
||||
4. 系统定时查询请假单状态变化。
|
||||
5. 系统在状态变化时通过企业微信通知对应员工。
|
||||
|
||||
## 3. 范围说明
|
||||
|
||||
### 3.1 本期范围
|
||||
|
||||
- 查询员工本人假期余额
|
||||
- 根据工号查询 OA 用户标识
|
||||
- 调用 OA WorkflowService 创建请假流程单
|
||||
- 定时查询请假单审批状态
|
||||
- 推送审批状态消息到员工企微
|
||||
- 在 AI 聊天中承接“请假申请”与“请假状态查询”类意图
|
||||
|
||||
### 3.2 非本期范围
|
||||
|
||||
- OA 请假流程模板本身改造
|
||||
- OA 组织架构主数据治理
|
||||
- 复杂排班/跨班次/补卡/调班流程
|
||||
- 多工作流并行编排平台建设
|
||||
- 移动端原生页面开发
|
||||
|
||||
## 4. 业务角色
|
||||
|
||||
| 角色 | 说明 |
|
||||
| --- | --- |
|
||||
| 员工 | 发起假期查询、请假申请、查询请假状态 |
|
||||
| AI Agent | 识别用户意图,查询数据,发起流程,回传结果 |
|
||||
| OA WorkflowService | 接收请假单并进入 OA 审批流 |
|
||||
| SQL Server OA 数据库 | 提供假期余额、OA userID、请假单状态查询 |
|
||||
| 企业微信通知服务 | 向员工推送请假状态变化消息 |
|
||||
| 管理员/运维 | 配置接口参数、监控任务、排查异常 |
|
||||
|
||||
## 5. 业务目标拆解
|
||||
|
||||
### 5.1 查询类目标
|
||||
|
||||
- 员工在 `企业知识库` 或 `ERP知识库` 中,针对“我还有多少假期”“我的年假还有多少”等强意图问题,可以直接获取本人假期数据。
|
||||
- 流程/制度类问题仍继续走知识库问答,不进入数据库强查询。
|
||||
|
||||
### 5.2 申请类目标
|
||||
|
||||
- 员工可以通过 AI Agent 提交请假所需信息,例如:
|
||||
- 请假类型
|
||||
- 开始时间
|
||||
- 结束时间
|
||||
- 请假时长
|
||||
- 请假原因
|
||||
- AI Agent 将结构化参数转为 OA 工作流接口参数并提交到 OA。
|
||||
|
||||
### 5.3 跟踪类目标
|
||||
|
||||
- 系统保存“本地申请记录 <-> OA 请求 <-> OA 流程单”映射。
|
||||
- 系统定时轮询 OA 数据库,请假状态变更时触发通知。
|
||||
- 员工可在聊天中查询“我的请假单到哪一步了”。
|
||||
|
||||
## 6. 核心业务流程
|
||||
|
||||
### 6.1 查询本人假期
|
||||
|
||||
1. 员工在聊天框提问“我今年年假还剩多少”
|
||||
2. Agent 识别为“个人假期强意图查询”
|
||||
3. 系统读取当前登录用户工号
|
||||
4. 查询 SQL Server 视图返回结果
|
||||
5. Agent 组织答案并返回
|
||||
|
||||
### 6.2 发起请假
|
||||
|
||||
1. 员工输入“我要请明天下午半天假”或“我要帮张三请假”
|
||||
2. Agent 识别为“请假申请意图”
|
||||
3. Agent 提取或追问缺失参数
|
||||
4. 员工在表单中确认“请假人”(默认当前用户,支持选择其他员工)及“代理人”
|
||||
5. 系统根据工号查询 OA userID
|
||||
6. 系统调用 OA WorkflowService 创建请假流程(workflow=652),其中“填单人”固定为当前登录用户,“请假人”为所选员工
|
||||
7. 保存本地申请记录与 OA 返回信息
|
||||
8. 返回员工“已提交”结果
|
||||
|
||||
### 6.3 跟踪审批状态
|
||||
|
||||
1. 后端定时任务轮询 OA 数据库中的请假单状态
|
||||
2. 若发现状态变化,则记录状态日志
|
||||
3. 触发企业微信消息通知员工
|
||||
4. 员工点击通知可跳转系统查看详情
|
||||
|
||||
## 7. 功能需求
|
||||
|
||||
### 7.1 已完成
|
||||
|
||||
- AI Agent 通过员工工号查询 OA SQL Server 视图中的本人假期
|
||||
|
||||
### 7.2 待建设
|
||||
|
||||
#### FR-01 查询 OA userID
|
||||
|
||||
- 输入:员工工号
|
||||
- 输出:OA userID
|
||||
- 要求:
|
||||
- 支持根据工号精确匹配
|
||||
- 查询不到时可返回清晰错误提示
|
||||
- 建议支持本地缓存,减少重复查询
|
||||
|
||||
#### FR-02 AI 发起请假申请
|
||||
|
||||
- 输入:
|
||||
- 请假类型
|
||||
- 开始时间
|
||||
- 结束时间
|
||||
- 时长
|
||||
- 原因
|
||||
- 请假人信息(默认当前登录用户,可选择其他无 OA 账号的普通员工)
|
||||
- 填单人信息(固定当前登录用户)
|
||||
- 输出:
|
||||
- OA 请求结果
|
||||
- OA 流程单号/请求号
|
||||
- 本地申请记录
|
||||
- 要求:
|
||||
- 调用 `http://oa.well-trust.com:8888/services/WorkflowService?wsdl`
|
||||
- workflow 固定为 `652`
|
||||
- 参数映射必须配置化
|
||||
- 接口失败时可追踪、可重试
|
||||
|
||||
#### FR-03 定时查询请假单状态
|
||||
|
||||
- 输入:本地待跟踪请假单
|
||||
- 输出:最新 OA 状态
|
||||
- 要求:
|
||||
- 可配置轮询频率
|
||||
- 仅轮询未完结状态
|
||||
- 状态变化时写入状态日志
|
||||
|
||||
#### FR-04 推送企微通知
|
||||
|
||||
- 输入:状态变化事件
|
||||
- 输出:企业微信文本卡片通知
|
||||
- 要求:
|
||||
- 通知发送到对应员工的 `wecom_userid`
|
||||
- 支持“已提交 / 审批通过 / 审批驳回 / 已撤销”等不同模板
|
||||
- 发送失败要有审计日志
|
||||
|
||||
#### FR-05 聊天态交互
|
||||
|
||||
- 输入:自然语言问题/请求
|
||||
- 输出:查询结果/提交流程结果/状态结果
|
||||
- 要求:
|
||||
- 强意图“本人假期查询”走数据库
|
||||
- “如何请假/请假制度/请假流程”继续走知识库 Dify
|
||||
- “我要请假”进入结构化申请流程
|
||||
- “我的请假单怎么样了”进入状态查询流程
|
||||
|
||||
## 8. 非功能需求
|
||||
|
||||
### 8.1 安全
|
||||
|
||||
- OA 接口账号、数据库账号、企微密钥需存放在后端配置中,不写死前端
|
||||
- 聊天查询只能查询当前登录用户本人数据,不允许跨人工号查询
|
||||
- 所有外部接口调用都要有日志与错误审计
|
||||
|
||||
### 8.2 性能
|
||||
|
||||
- 假期余额查询目标响应时间:3 秒内
|
||||
- 请假申请接口提交目标响应时间:5 秒内
|
||||
- 状态轮询任务需支持批量处理
|
||||
|
||||
### 8.3 可运维性
|
||||
|
||||
- 支持查看接口请求日志与失败原因
|
||||
- 支持按申请单查询本地记录与 OA 状态
|
||||
- 支持重新触发状态同步
|
||||
|
||||
## 9. 依赖与前置条件
|
||||
|
||||
- OA SQL Server 可访问
|
||||
- OA WorkflowService WSDL 可调用
|
||||
- 已明确 workflow=652 的字段映射规则
|
||||
- 已确认“工号 -> OA userID”对应关系来源表/视图
|
||||
- 当前用户表中已绑定 `employee_id` 与 `wecom_userid`
|
||||
- 企业微信应用配置可用
|
||||
|
||||
## 10. 风险与关键问题
|
||||
|
||||
### 10.1 高风险项
|
||||
|
||||
- OA WorkflowService 为 SOAP/WSDL 接口,字段要求与编码格式可能较严格
|
||||
- OA 请假单状态表/视图字段尚未完全明确
|
||||
- OA userID 查询来源尚未在现有文档中明确
|
||||
- workflow=652 的入参字段、枚举值、明细表结构需进一步确认
|
||||
|
||||
### 10.2 待确认问题
|
||||
|
||||
1. OA userID 查询来源表/视图是什么?
|
||||
2. workflow=652 所需字段清单、字段名、字段类型分别是什么?
|
||||
3. 请假类型编码是否由 OA 字典维护?
|
||||
4. 请假状态查询使用哪张表/视图?
|
||||
5. OA 返回值中哪个字段是唯一流程单号/请求号?
|
||||
6. 审批驳回原因是否可查询并通知给员工?
|
||||
|
||||
## 11. 可执行实施方案
|
||||
|
||||
### 阶段一:数据打通
|
||||
|
||||
- 完成 OA userID 查询服务
|
||||
- 明确 workflow=652 的 SOAP 入参结构
|
||||
- 明确请假状态查询视图/表
|
||||
- 完成本地表结构设计
|
||||
|
||||
### 阶段二:提交流程
|
||||
|
||||
- 新增“请假申请服务”
|
||||
- 增加聊天意图识别与结构化参数收集
|
||||
- 接入 OA WorkflowService 创建请假单
|
||||
- 保存本地申请记录
|
||||
|
||||
### 阶段三:状态跟踪与通知
|
||||
|
||||
- 新增请假单轮询任务
|
||||
- 新增状态日志落表
|
||||
- 接入企微消息模板
|
||||
- 完成状态变更通知
|
||||
|
||||
### 阶段四:联调与上线
|
||||
|
||||
- 与 OA 联调创建流程
|
||||
- 与 OA 联调状态更新
|
||||
- 联调企微消息
|
||||
- 灰度验证真实员工场景
|
||||
|
||||
## 12. 验收标准
|
||||
|
||||
1. 员工可在聊天中查询本人假期余额
|
||||
2. 员工可通过聊天提交请假申请
|
||||
3. 系统成功调用 OA WorkflowService 创建流程单
|
||||
4. 本地系统可查询并展示请假单状态
|
||||
5. 状态变化后员工能收到企微通知
|
||||
6. 非本人数据无法被越权查询
|
||||
|
||||
## 13. 结论
|
||||
|
||||
该需求具备明确的业务价值与可执行性,建议基于现有项目能力快速扩展:
|
||||
|
||||
- 复用现有 AI 聊天分流能力
|
||||
- 复用现有 SQL Server HR 查询能力
|
||||
- 复用现有企业微信通知与审计能力
|
||||
- 参考现有最小任务调度器扩展请假状态轮询任务
|
||||
|
||||
本期优先目标建议聚焦为:
|
||||
|
||||
1. 打通 OA userID 查询
|
||||
2. 打通 workflow=652 请假单提交
|
||||
3. 打通请假单状态轮询与企微通知
|
||||
@@ -0,0 +1,63 @@
|
||||
# 环境变量加载规则与优先级
|
||||
|
||||
## 1. 目标
|
||||
|
||||
统一环境变量管理方式,减少重复维护和覆盖冲突。
|
||||
|
||||
## 2. 当前文件结构
|
||||
|
||||
- `.env.shared`:跨环境共享变量(dev/test/prod 一致)。
|
||||
- `.env.dev` / `.env.test` / `.env.prod`:环境差异变量。
|
||||
- `.env.local`:本地开发覆盖变量(仅本地使用,不提交)。
|
||||
|
||||
## 3. 当前优先级(从高到低)
|
||||
|
||||
### 3.1 本地环境(`ENV_NAME=dev`)
|
||||
|
||||
1. 系统环境变量(OS/终端注入)
|
||||
2. `.env.local`
|
||||
3. `.env.dev`
|
||||
4. `.env.shared`
|
||||
5. `config.py` 中少量通用兜底值
|
||||
|
||||
解释:本地以 `.env.local` 为最高文件优先级;若 `.env.local` 未配置某项,则回退到 `.env.dev`,再回退到 `.env.shared`。
|
||||
|
||||
### 3.2 线上部署(Jenkins/CI,`ENV_NAME=test|prod`)
|
||||
|
||||
1. 系统环境变量(Jenkins/CI/Docker 注入)
|
||||
2. `.env.<ENV_NAME>`(`.env.test` 或 `.env.prod`)
|
||||
3. `.env.shared`
|
||||
4. `config.py` 中少量通用兜底值
|
||||
|
||||
解释:线上部署不使用 `.env.local`;仅使用目标环境文件与共享文件。
|
||||
|
||||
## 4. 历史对比(改造前 -> 改造后)
|
||||
|
||||
改造前(从高到低):
|
||||
|
||||
1. 系统环境变量
|
||||
2. `backend/.env`
|
||||
3. `config.py` 默认值
|
||||
|
||||
改造后(从高到低):
|
||||
|
||||
1. 系统环境变量
|
||||
2. 本地:`.env.local`;线上:`.env.<ENV_NAME>`
|
||||
3. `.env.<ENV_NAME>`(本地为 `.env.dev`)
|
||||
4. `.env.shared`
|
||||
5. `config.py` 少量通用兜底
|
||||
|
||||
说明:`backend/.env` 不再作为主配置入口。
|
||||
|
||||
## 5. 各文件职责
|
||||
|
||||
- `.env.shared`:只放三环境完全一致的变量。
|
||||
- `.env.dev` / `.env.test` / `.env.prod`:放环境差异值(DB 地址、域名、回调、密钥等)。
|
||||
- `.env.local`:开发者个人覆盖项(端口、代理、个人测试 key)。
|
||||
|
||||
## 6. 维护建议
|
||||
|
||||
- 可能存在环境差异的变量,优先放 `.env.<ENV_NAME>`。
|
||||
- 生产密钥不要放 `.env.shared`。
|
||||
- 新增变量同步更新对应 env 文件和本文档。
|
||||
- 继续清理对 `backend/.env` 的历史依赖。
|
||||
@@ -0,0 +1,351 @@
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 1. 功能总览
|
||||
|
||||
| 模块 | 功能项 | 状态 | 优先级 |
|
||||
| --- | --- | --- | --- |
|
||||
| 假期查询 | AI Agent 查询本人假期余额 | 已完成 | P0 |
|
||||
| 用户映射 | 根据工号查询 OA userID | 待建设 | P0 |
|
||||
| 请假申请 | AI Agent 发起请假申请 | 待建设 | P0 |
|
||||
| 状态跟踪 | 定时查询 OA 请假单状态 | 待建设 | P0 |
|
||||
| 消息通知 | 企微通知请假状态变化 | 待建设 | P0 |
|
||||
| 聊天路由 | 强意图分流 HR 查询 / Dify 知识库 | 已部分完成 | P0 |
|
||||
| 申请记录 | 本地保存请假申请主记录 | 待建设 | P0 |
|
||||
| 状态日志 | 本地保存状态变化日志 | 待建设 | P1 |
|
||||
| 运维管理 | 重试失败任务 / 查看日志 | 待建设 | P1 |
|
||||
|
||||
## 2. 详细功能拆分
|
||||
|
||||
### F-01 本人假期查询
|
||||
|
||||
#### 目标
|
||||
|
||||
员工在聊天中可查询自己的年假、育儿假等余额信息。
|
||||
|
||||
#### 输入
|
||||
|
||||
- 当前登录用户工号
|
||||
- 用户自然语言问题
|
||||
|
||||
#### 输出
|
||||
|
||||
- 假期总时数
|
||||
- 已休时数
|
||||
- 剩余时数
|
||||
- 对应年份
|
||||
|
||||
#### 规则
|
||||
|
||||
- 仅允许查询当前登录用户本人数据
|
||||
- 强意图问题走 SQL Server
|
||||
- 制度/流程类问题仍走知识库
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 输入“我今年年假还剩多少”可返回本人数据
|
||||
- 输入“请假流程是什么”不会误走 SQL 查询
|
||||
|
||||
### F-02 OA userID 查询
|
||||
|
||||
#### 目标
|
||||
|
||||
通过当前登录员工工号,查询 OA 系统中的 userID,用于创建工作流。
|
||||
|
||||
#### 输入
|
||||
|
||||
- employee_id
|
||||
|
||||
#### 输出
|
||||
|
||||
- oa_user_id
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 支持工号精确查找
|
||||
- 查询失败时返回清晰错误
|
||||
- 支持结果缓存
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 给定工号可以稳定返回唯一 OA userID
|
||||
- 查询失败时系统可记录日志
|
||||
|
||||
### F-03 AI 请假申请意图识别
|
||||
|
||||
#### 目标
|
||||
|
||||
员工表达“我要请假”时,系统识别为流程提交意图,而不是知识库问答。
|
||||
|
||||
#### 典型问法
|
||||
|
||||
- 我要请假
|
||||
- 我想请半天年假
|
||||
- 我要请明天下午假
|
||||
- 帮我提一个请假单
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 识别“申请类意图”
|
||||
- 提取已给出的结构化字段
|
||||
- 对缺失字段进行追问
|
||||
|
||||
#### 必填字段
|
||||
|
||||
- 请假人(支持为没有 OA 账号的普通员工代请)
|
||||
- 代理人
|
||||
- 请假类型
|
||||
- 开始时间
|
||||
- 结束时间
|
||||
- 时长
|
||||
- 请假原因
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 用户信息不完整时,Agent 会继续追问
|
||||
- 信息完整后,进入 OA 提交流程
|
||||
|
||||
### F-04 OA 请假单创建
|
||||
|
||||
#### 目标
|
||||
|
||||
通过 OA WorkflowService 创建请假流程单。
|
||||
|
||||
#### 接口
|
||||
|
||||
- `http://oa.well-trust.com:8888/services/WorkflowService?wsdl`
|
||||
- workflow=`652`
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 构造 SOAP 请求
|
||||
- 映射业务字段到 workflow 652 表单字段
|
||||
- 处理 OA 返回结果
|
||||
- 记录 requestId / workflowId / 单号等信息
|
||||
|
||||
#### 输出
|
||||
|
||||
- 提交成功/失败
|
||||
- OA 请求唯一标识
|
||||
- 错误原因
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 成功创建 OA 请假流程
|
||||
- 本地可保存一条请假申请记录
|
||||
|
||||
### F-05 本地请假申请记录
|
||||
|
||||
#### 目标
|
||||
|
||||
对每次 AI 发起的请假申请进行本地落表,形成可追踪主记录。
|
||||
|
||||
#### 建议字段
|
||||
|
||||
- id
|
||||
- user_id
|
||||
- employee_id
|
||||
- oa_user_id
|
||||
- workflow_code
|
||||
- oa_request_id
|
||||
- leave_type
|
||||
- start_time
|
||||
- end_time
|
||||
- duration_hours
|
||||
- reason
|
||||
- current_status
|
||||
- submit_payload
|
||||
- oa_response_payload
|
||||
- created_at
|
||||
- updated_at
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 每次发起请假申请后,本地有唯一记录
|
||||
- 可根据 request_id 查到整条申请链路
|
||||
|
||||
### F-06 定时查询请假单状态
|
||||
|
||||
#### 目标
|
||||
|
||||
对未完结请假单定时查询 OA 状态,确保审批状态同步。
|
||||
|
||||
#### 输入
|
||||
|
||||
- 本地未完结请假记录
|
||||
|
||||
#### 输出
|
||||
|
||||
- 最新 OA 审批状态
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 批量轮询
|
||||
- 可配置轮询周期
|
||||
- 仅轮询未结束单据
|
||||
- 状态变化触发后续动作
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- OA 状态发生变化后,本地可同步到最新状态
|
||||
- 不重复处理已完结单据
|
||||
|
||||
### F-07 请假状态日志
|
||||
|
||||
#### 目标
|
||||
|
||||
记录请假单每次状态变化,用于审计和追踪。
|
||||
|
||||
#### 建议字段
|
||||
|
||||
- id
|
||||
- leave_request_id
|
||||
- old_status
|
||||
- new_status
|
||||
- status_text
|
||||
- oa_raw_payload
|
||||
- changed_at
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 每次状态变化都会新增一条日志
|
||||
- 可回溯完整审批过程
|
||||
|
||||
### F-08 企微状态通知
|
||||
|
||||
#### 目标
|
||||
|
||||
请假单状态发生变化时,推送企微消息给员工。
|
||||
|
||||
#### 通知场景
|
||||
|
||||
- 已提交
|
||||
- 审批中
|
||||
- 审批通过
|
||||
- 审批驳回
|
||||
- 已撤销
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 使用员工 `wecom_userid`
|
||||
- 根据状态选择不同通知模板
|
||||
- 写入通知审计
|
||||
- 支持点击查看详情
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 状态变化后员工收到企微消息
|
||||
- 发送失败可查询原因
|
||||
|
||||
### F-09 AI 查询请假单状态
|
||||
|
||||
#### 目标
|
||||
|
||||
员工在聊天中可以问“我的请假单怎么样了”。
|
||||
|
||||
#### 输入
|
||||
|
||||
- 当前登录员工
|
||||
- 最近请假申请记录
|
||||
|
||||
#### 输出
|
||||
|
||||
- 最近一条或指定一条请假单状态
|
||||
- 审批节点说明
|
||||
- 最近更新时间
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 输入状态类问题时,能返回本地同步后的最新状态
|
||||
|
||||
### F-10 运维与管理能力
|
||||
|
||||
#### 目标
|
||||
|
||||
便于管理员和运维排查问题、重试失败任务。
|
||||
|
||||
#### 功能点
|
||||
|
||||
- 查看请假单主记录
|
||||
- 查看状态变更日志
|
||||
- 查看 OA 请求/响应
|
||||
- 查看企微通知审计
|
||||
- 重试状态同步任务
|
||||
- 手工补发企微通知
|
||||
|
||||
#### 验收标准
|
||||
|
||||
- 运维可定位每一条失败记录的原因
|
||||
|
||||
## 3. 聊天意图清单
|
||||
|
||||
### 3.1 走 SQL Server 直接查询
|
||||
|
||||
- 我今年年假还剩多少
|
||||
- 我的育儿假情况
|
||||
- 我还有多少假期
|
||||
- 我的年假记录
|
||||
|
||||
### 3.2 走 OA 流程申请
|
||||
|
||||
- 我要请假
|
||||
- 我想请明天下午半天年假
|
||||
- 帮我提交请假单
|
||||
|
||||
### 3.3 走本地状态查询
|
||||
|
||||
- 我的请假单怎么样了
|
||||
- 我刚刚提的请假通过了吗
|
||||
- 我的请假审批到哪一步了
|
||||
|
||||
### 3.4 继续走 Dify 知识库
|
||||
|
||||
- 请假流程是什么
|
||||
- 如何请假
|
||||
- 请假制度有哪些
|
||||
- 年假规则是什么
|
||||
|
||||
## 4. 数据源清单
|
||||
|
||||
| 数据源 | 用途 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| OA SQL Server 视图 | 查询假期余额 | 已完成接入 |
|
||||
| OA SQL Server 用户映射表/视图 | 查询 OA userID | 待确认 |
|
||||
| OA WorkflowService | 创建请假流程单 | 待接入 |
|
||||
| OA 请假单状态表/视图 | 查询审批状态 | 待确认 |
|
||||
| 本地 PostgreSQL | 保存申请记录、状态日志、通知审计 | 现有主库 |
|
||||
| 企业微信 API | 推送通知 | 已具备底层能力 |
|
||||
|
||||
## 5. 里程碑清单
|
||||
|
||||
### M1 基础数据打通
|
||||
|
||||
- 完成 OA userID 查询
|
||||
- 明确 workflow 652 字段映射
|
||||
- 明确状态查询来源表/视图
|
||||
|
||||
### M2 请假提交流程打通
|
||||
|
||||
- 新增 SOAP 接口适配层
|
||||
- 聊天中支持请假申请
|
||||
- 保存本地申请记录
|
||||
|
||||
### M3 状态同步与通知
|
||||
|
||||
- 新增轮询任务
|
||||
- 新增状态日志
|
||||
- 新增企微通知模板
|
||||
|
||||
### M4 联调验收
|
||||
|
||||
- OA 联调
|
||||
- 企微联调
|
||||
- 真实账号验证
|
||||
|
||||
## 6. 验收清单
|
||||
|
||||
- 能查询本人假期
|
||||
- 能创建 OA 请假单
|
||||
- 能查到 OA 流程状态
|
||||
- 能收到企微通知
|
||||
- 流程类问题仍走知识库
|
||||
- 所有操作都有日志可追踪
|
||||
@@ -0,0 +1,171 @@
|
||||
# 主平台知识库运行时部署说明
|
||||
|
||||
## 目标
|
||||
|
||||
将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。
|
||||
|
||||
当前主平台 `docker-compose.yml` 已接入:
|
||||
|
||||
- `kb-redis`
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- 共享卷 `hxops_runtime_data`
|
||||
|
||||
## 容器职责
|
||||
|
||||
### `hxops-backend`
|
||||
|
||||
- 提供主平台 API
|
||||
- 提供知识库 API:`/api/kb/*`
|
||||
- 提供集成 API:`/api/integration/*`
|
||||
- 挂载知识库存储根目录到 `/app/data`
|
||||
|
||||
### `hxops-kb-worker`
|
||||
|
||||
- 轮询执行知识库 `clean` 任务
|
||||
- 复用后端镜像,避免维护第二套依赖
|
||||
- 与后端共享数据库、Redis、知识库存储卷
|
||||
|
||||
### `kb-redis`
|
||||
|
||||
- 提供知识库异步任务所需 Redis
|
||||
- 当前主要用于主平台知识库运行时接入与后续队列化扩展
|
||||
|
||||
## 关键环境变量
|
||||
|
||||
部署主平台知识库运行时时,至少确认以下变量:
|
||||
|
||||
| 变量名 | 用途 | 建议值/说明 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 |
|
||||
| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 |
|
||||
| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` |
|
||||
| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` |
|
||||
| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` |
|
||||
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 |
|
||||
| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` |
|
||||
| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 |
|
||||
| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 |
|
||||
| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 |
|
||||
| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 |
|
||||
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 |
|
||||
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` |
|
||||
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` |
|
||||
| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 |
|
||||
| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 |
|
||||
|
||||
补充说明:
|
||||
|
||||
- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。
|
||||
- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。
|
||||
- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。
|
||||
- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。
|
||||
- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。
|
||||
- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。
|
||||
- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。
|
||||
- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。
|
||||
|
||||
## 启动步骤
|
||||
|
||||
### 1. 构建并启动
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若使用私有镜像仓库,可先设置:
|
||||
|
||||
```bash
|
||||
$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine"
|
||||
$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim"
|
||||
$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine"
|
||||
$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine"
|
||||
$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若需要同时启用内置 Redis,再改为:
|
||||
|
||||
```bash
|
||||
docker compose --profile kb-redis up -d --build
|
||||
```
|
||||
|
||||
### 2. 执行数据库迁移
|
||||
|
||||
```bash
|
||||
docker compose exec hxops-backend flask db upgrade
|
||||
```
|
||||
|
||||
### 3. 检查服务状态
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
预期:
|
||||
|
||||
- `hxops-backend` 为 `Up`
|
||||
- `hxops-kb-worker` 为 `Up`
|
||||
- `hxops-frontend` 为 `Up`
|
||||
|
||||
若启用了 `kb-redis` profile,则额外确认:
|
||||
|
||||
- `kb-redis` 为 `Up`
|
||||
|
||||
### 4. 检查 worker 日志
|
||||
|
||||
```bash
|
||||
docker compose logs -f hxops-kb-worker
|
||||
```
|
||||
|
||||
预期可见:
|
||||
|
||||
```text
|
||||
[kb-worker] started, poll_seconds=2.0
|
||||
```
|
||||
|
||||
## 端口与卷
|
||||
|
||||
当前主平台容器端口关系:
|
||||
|
||||
- 宿主机 `5002` -> `hxops-backend:5000`
|
||||
- 宿主机 `8890` -> `hxops-frontend:80`
|
||||
|
||||
当前关键卷:
|
||||
|
||||
- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录
|
||||
- `hxops_redis_data`:Redis 持久化数据
|
||||
|
||||
## 切换前检查
|
||||
|
||||
切换 `xinxin2` 运行时前,至少确认:
|
||||
|
||||
1. 主平台已完成数据库迁移
|
||||
2. 主平台后台可正常打开知识库管理页
|
||||
3. 上传文件后会生成 `upload/clean` 任务
|
||||
4. `hxops-kb-worker` 能持续消费待执行任务
|
||||
5. Dify 设置已在主平台管理端保存并通过健康检查
|
||||
6. 聊天侧 `INTEGRATION_API_MODE=local`
|
||||
7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名
|
||||
|
||||
## 切换后冒烟清单
|
||||
|
||||
建议按顺序验证:
|
||||
|
||||
1. 登录主平台并进入知识库工作台
|
||||
2. 新建一个分组和一个文档条目
|
||||
3. 上传一个 `txt` 或 `md` 文件
|
||||
4. 确认任务状态从 `pending/running` 进入 `success`
|
||||
5. 在文档详情里触发一次 Dify 同步
|
||||
6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射
|
||||
7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台
|
||||
|
||||
## 常见注意事项
|
||||
|
||||
- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。
|
||||
- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。
|
||||
- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。
|
||||
- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。
|
||||
- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。
|
||||
- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。
|
||||
@@ -0,0 +1,653 @@
|
||||
# 智能HR请假管理技术架构
|
||||
|
||||
## 1. 架构目标
|
||||
|
||||
在现有 `hxops` 项目基础上,扩展一个可落地的智能 HR 请假管理架构,实现:
|
||||
|
||||
- 聊天侧承接假期查询、请假申请、状态查询
|
||||
- 数据侧打通 OA SQL Server 与 OA WorkflowService
|
||||
- 平台侧提供状态轮询、通知、审计与可运维能力
|
||||
|
||||
## 2. 现有可复用能力
|
||||
|
||||
### 2.1 已有聊天路由能力
|
||||
|
||||
- 后端 `chat` 接口已支持按意图分流
|
||||
- `企业知识库` / `ERP知识库` 场景已支持“强意图个人假期查询 -> SQL Server”
|
||||
- 流程/制度类问题默认走 Dify
|
||||
|
||||
### 2.2 已有 SQL Server 假期查询能力
|
||||
|
||||
- 已实现通过当前登录用户工号查询本人假期
|
||||
- 已具备员工工号从 `employee_id / username` 提取能力
|
||||
|
||||
### 2.3 已有企微通知能力
|
||||
|
||||
- 已支持发送企业微信文本卡片消息
|
||||
- 已具备通知审计日志
|
||||
- 已具备点击消息追踪能力
|
||||
|
||||
### 2.4 已有最小任务调度能力
|
||||
|
||||
- 已有最小 worker 轮询模式
|
||||
- 可复用于“请假状态同步”任务
|
||||
|
||||
## 3. 目标架构总览
|
||||
|
||||
```text
|
||||
员工
|
||||
-> 前端聊天页
|
||||
-> 后端 /api/chat/completions
|
||||
-> 意图路由器
|
||||
-> HR SQL 查询服务(本人假期查询)
|
||||
-> OA 请假申请服务(WorkflowService SOAP)
|
||||
-> 请假状态查询服务(本地记录 + OA状态同步)
|
||||
-> Dify 知识库服务(流程制度类问答)
|
||||
|
||||
后端异步任务
|
||||
-> 请假状态轮询任务
|
||||
-> OA SQL Server 状态表/视图
|
||||
-> 本地状态日志
|
||||
-> 企微通知服务
|
||||
```
|
||||
|
||||
## 4. 组件设计
|
||||
|
||||
### 4.1 Chat Intent Router
|
||||
|
||||
#### 作用
|
||||
|
||||
负责把聊天问题路由到不同业务服务。
|
||||
|
||||
#### 路由策略
|
||||
|
||||
1. 本人假期强意图查询 -> HRLeaveSQLServerService
|
||||
2. 请假申请意图 -> OALeaveWorkflowService
|
||||
3. 请假状态查询意图 -> LeaveStatusQueryService
|
||||
4. 其余问题 -> DifyService
|
||||
|
||||
#### 建议新增意图分类
|
||||
|
||||
- `leave_balance_query`
|
||||
- `leave_apply_create`
|
||||
- `leave_apply_status`
|
||||
- `leave_process_qa`
|
||||
|
||||
### 4.2 HR SQL Query Service
|
||||
|
||||
#### 作用
|
||||
|
||||
负责查询 OA SQL Server 中与请假/假期相关的视图或表。
|
||||
|
||||
#### 现状
|
||||
|
||||
- 已用于本人假期余额查询
|
||||
- 当前通过 `pyodbc + SQL Server ODBC Driver` 访问数据库
|
||||
|
||||
#### 可扩展能力
|
||||
|
||||
- 查询 OA userID
|
||||
- 查询请假单状态
|
||||
- 查询员工最近请假记录
|
||||
|
||||
#### 建议拆分
|
||||
|
||||
- `HRLeaveSQLServerService`:假期余额查询
|
||||
- `OAUserDirectoryService`:工号 -> OA userID
|
||||
- `OALeaveStatusSyncService`:请假单状态查询
|
||||
|
||||
### 4.3 OA Workflow SOAP Adapter
|
||||
|
||||
#### 作用
|
||||
|
||||
负责调用 OA 的 WorkflowService WSDL 接口创建请假流程单。
|
||||
|
||||
#### 接口
|
||||
|
||||
- `http://oa.well-trust.com:8888/services/WorkflowService?wsdl`
|
||||
|
||||
#### 建议实现方式
|
||||
|
||||
优先推荐:
|
||||
|
||||
- Python `zeep` 作为 SOAP/WSDL 客户端
|
||||
|
||||
备选:
|
||||
|
||||
- `requests + 手写 SOAP XML`
|
||||
|
||||
#### 推荐原因
|
||||
|
||||
- `zeep` 对 WSDL 解析更稳定
|
||||
- 字段结构变更时更容易调试
|
||||
- 更适合复杂嵌套 SOAP 请求
|
||||
|
||||
#### 建议封装服务
|
||||
|
||||
- `OALeaveWorkflowService`
|
||||
|
||||
#### 核心方法
|
||||
|
||||
- `resolve_oa_user_id(employee_id)`
|
||||
- `build_workflow_payload(leave_request)`
|
||||
- `submit_leave_request(leave_request)`
|
||||
- `parse_workflow_response(response)`
|
||||
|
||||
#### 实测确认的 WSDL 调用方式
|
||||
|
||||
基于实际读取 `WorkflowService?wsdl` 与 OA 请假页验证,workflow=652 当前建议采用以下方式:
|
||||
|
||||
- 获取建单模板:`getCreateWorkflowRequestInfo(workflowId, userId)`
|
||||
- 提交流程单:`doCreateWorkflowRequest(WorkflowRequestInfo, userId)`
|
||||
|
||||
已确认的关键点:
|
||||
|
||||
- `getCreateWorkflowRequestInfo` 的参数顺序是:
|
||||
- `in0 = workflowId`
|
||||
- `in1 = userId`
|
||||
- `getCreateWorkflowRequestInfo(652, 21823)` 可返回可编辑模板
|
||||
- `getCreateWorkflowRequestInfo(21823, 652)` 返回 `nil`
|
||||
- 因此后端实现建议固定走“先取模板,再按字段名回填,再调用 `doCreateWorkflowRequest`”的流程
|
||||
|
||||
#### 现有 XML 建单参考
|
||||
|
||||
当前 `docs/请假建单数据XML格式.txt` 可作为 OA 建单报文结构参考,核心结构如下:
|
||||
|
||||
```xml
|
||||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<requestinfo>
|
||||
<maintable>
|
||||
<fields>...</fields>
|
||||
<creater>...</creater>
|
||||
<wfid>652</wfid>
|
||||
<level>0</level>
|
||||
<requestname>...</requestname>
|
||||
...
|
||||
</maintable>
|
||||
</requestinfo>
|
||||
```
|
||||
|
||||
可直接复用的结构性结论:
|
||||
|
||||
- 根节点使用 `requestinfo`
|
||||
- 主表数据节点使用 `maintable`
|
||||
- `wfid=652` 为请假流程工作流编号
|
||||
- `creater` 为创建人 OA ID
|
||||
- `requestname` 为流程标题
|
||||
- 返回结果需同时处理“创建失败”和“返回 request id 异常”两类错误
|
||||
|
||||
#### 现有错误码处理参考
|
||||
|
||||
`docs/XML.txt` 中已整理出一套现成的错误码语义,可直接作为后端错误映射参考:
|
||||
|
||||
| 错误码 | 含义 |
|
||||
| ---- | ---------- |
|
||||
| `-1` | 创建流程失败 |
|
||||
| `-2` | 用户没有流程创建权限 |
|
||||
| `-3` | 创建流程基本信息失败 |
|
||||
| `-4` | 保存表单主表信息失败 |
|
||||
| `-5` | 更新紧急程度失败 |
|
||||
| `-6` | 流程操作者失败 |
|
||||
| `-7` | 流转至下一节点失败 |
|
||||
| `-8` | 节点附加操作失败 |
|
||||
|
||||
#### 使用提醒
|
||||
|
||||
- 当前 `docs/XML.txt` 中展示的字段内容更像“开票/客户”类流程样例,不可直接作为请假字段映射使用
|
||||
- 但其 XML 包装结构、`createwflc` 调用方式、错误码语义、`requestname/creater/wfid` 等关键节点,对请假流程对接仍有很高参考价值
|
||||
- 因此建议:`XML.txt` 用于参考“报文骨架与错误处理”,请假字段映射以 workflow=652 的真实字段配置为准
|
||||
|
||||
### 4.4 Leave Request Domain Service
|
||||
|
||||
#### 作用
|
||||
|
||||
管理请假申请的领域逻辑与本地落表。
|
||||
|
||||
#### 主要职责
|
||||
|
||||
- 校验请假参数
|
||||
- 处理 AI 结构化申请数据
|
||||
- 保存本地主记录
|
||||
- 调用 OA Workflow SOAP Adapter
|
||||
- 记录 OA 返回结果
|
||||
|
||||
#### 建议封装服务
|
||||
|
||||
- `LeaveRequestService`
|
||||
|
||||
#### 关键方法
|
||||
|
||||
- `create_draft_from_chat(user, slots)`
|
||||
- `submit_to_oa(leave_request_id)`
|
||||
- `update_submit_result(leave_request_id, response)`
|
||||
|
||||
### 4.5 Leave Status Polling Service
|
||||
|
||||
#### 作用
|
||||
|
||||
定时轮询 OA 中请假单状态,并同步到本地。
|
||||
|
||||
#### 核心逻辑
|
||||
|
||||
1. 扫描本地未完结请假单
|
||||
2. 根据 OA request\_id / workflow request id 查询 OA 状态
|
||||
3. 比较新旧状态
|
||||
4. 若状态变化则写状态日志
|
||||
5. 触发企微通知
|
||||
|
||||
#### 建议封装服务
|
||||
|
||||
- `LeaveStatusSyncService`
|
||||
|
||||
#### 建议执行模式
|
||||
|
||||
- 复用现有最小 worker 思路
|
||||
- 独立增加 `leave_status_sync` 类型任务
|
||||
- 由系统计划任务每 1\~5 分钟触发一次
|
||||
|
||||
### 4.6 WeCom Notification Service
|
||||
|
||||
#### 作用
|
||||
|
||||
在请假单状态变化时向员工发送企微消息。
|
||||
|
||||
#### 复用能力
|
||||
|
||||
- 复用现有 `send_wecom_event_message`
|
||||
- 复用 `wecom_notify_audits`
|
||||
|
||||
#### 建议新增事件类型
|
||||
|
||||
- `leave_request_submitted`
|
||||
- `leave_request_approved`
|
||||
- `leave_request_rejected`
|
||||
- `leave_request_revoked`
|
||||
- `leave_request_status_changed`
|
||||
|
||||
## 5. 数据流设计
|
||||
|
||||
### 5.1 假期查询链路
|
||||
|
||||
```text
|
||||
用户提问
|
||||
-> Chat API
|
||||
-> Intent Router
|
||||
-> HRLeaveSQLServerService
|
||||
-> SQL Server 视图
|
||||
-> 结果格式化
|
||||
-> 聊天返回
|
||||
```
|
||||
|
||||
### 5.2 请假申请链路
|
||||
|
||||
```text
|
||||
用户提问“我要请假”
|
||||
-> Chat API
|
||||
-> Intent Router
|
||||
-> LeaveRequestService
|
||||
-> OAUserDirectoryService 查询 OA userID
|
||||
-> OALeaveWorkflowService 调用 WorkflowService
|
||||
-> 本地保存请假记录
|
||||
-> 聊天返回提交结果
|
||||
```
|
||||
|
||||
### 5.3 状态同步与通知链路
|
||||
|
||||
```text
|
||||
定时任务触发
|
||||
-> LeaveStatusSyncService
|
||||
-> 查询本地未完结请假单
|
||||
-> 查询 OA 状态
|
||||
-> 写入状态日志
|
||||
-> send_wecom_event_message
|
||||
-> 员工收到企微通知
|
||||
```
|
||||
|
||||
## 6. 数据模型设计
|
||||
|
||||
### 6.1 leave\_requests
|
||||
|
||||
请假申请主表,建议新增。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --------------------- | ------------ | ------------- |
|
||||
| id | bigint | 主键 |
|
||||
| user\_id | bigint | 本地用户ID |
|
||||
| employee\_id | varchar(50) | 员工工号 |
|
||||
| oa\_user\_id | varchar(100) | OA 用户ID |
|
||||
| workflow\_code | varchar(50) | 固定值 652 |
|
||||
| oa\_request\_id | varchar(100) | OA 返回唯一请求号 |
|
||||
| leave\_type | varchar(50) | 请假类型 |
|
||||
| start\_time | datetime | 开始时间 |
|
||||
| end\_time | datetime | 结束时间 |
|
||||
| duration\_hours | decimal | 请假时长 |
|
||||
| reason | text | 请假原因 |
|
||||
| current\_status | varchar(50) | 当前状态 |
|
||||
| source\_channel | varchar(30) | 来源,如 ai\_chat |
|
||||
| submit\_payload | json/jsonb | 提交 OA 原始报文 |
|
||||
| oa\_response\_payload | json/jsonb | OA 返回原始报文 |
|
||||
| last\_synced\_at | datetime | 最近同步时间 |
|
||||
| created\_at | datetime | 创建时间 |
|
||||
| updated\_at | datetime | 更新时间 |
|
||||
|
||||
### 6.2 leave\_request\_status\_logs
|
||||
|
||||
请假状态变化日志表,建议新增。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------------ | ------------ | --------- |
|
||||
| id | bigint | 主键 |
|
||||
| leave\_request\_id | bigint | 关联主表 |
|
||||
| old\_status | varchar(50) | 旧状态 |
|
||||
| new\_status | varchar(50) | 新状态 |
|
||||
| status\_text | varchar(255) | 状态文案 |
|
||||
| oa\_raw\_payload | json/jsonb | OA 原始状态报文 |
|
||||
| changed\_at | datetime | 状态变化时间 |
|
||||
| created\_at | datetime | 创建时间 |
|
||||
|
||||
### 6.3 oa\_user\_mapping\_cache
|
||||
|
||||
工号与 OA userID 映射缓存表,可选。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| ------------- | ------------ | ------- |
|
||||
| id | bigint | 主键 |
|
||||
| employee\_id | varchar(50) | 工号 |
|
||||
| oa\_user\_id | varchar(100) | OA 用户ID |
|
||||
| source\_table | varchar(100) | 来源表/视图 |
|
||||
| synced\_at | datetime | 最近同步时间 |
|
||||
|
||||
### 6.4 workflow=652 表单字段映射参考
|
||||
|
||||
以下内容由 `docs/请假单表字段整理.md` 归并而来,作为 workflow=652 请假流程字段映射参考。
|
||||
|
||||
#### 主表关键字段
|
||||
|
||||
| 字段名称 | 字段显示名 | 表现形式 | 字段类型 | 说明 |
|
||||
| ---------- | ------- | ----- | ----- | ------------- |
|
||||
| `lcbh` | 流程编号 | 单行文本框 | 文本 | 系统生成或 OA 自动回填 |
|
||||
| `tdrgs` | 填单人公司 | 浏览按钮 | 分部 | 填单人所属公司 |
|
||||
| `tdrbm` | 填单人部门 | 浏览按钮 | 部门 | 填单人所属部门 |
|
||||
| `tdrgh` | 填单人工号 | 单行文本框 | 文本 | 对应前端填单人工号 |
|
||||
| `tdrxm` | 填单人姓名 | 浏览按钮 | 人力资源 | 对应前端填单人姓名 |
|
||||
| `tdrzw` | 填单人职务 | 浏览按钮 | 岗位 | 可后续扩展 |
|
||||
| `sqrgh` | 请假人工号 | 单行文本框 | 文本 | 对应请假人工号 |
|
||||
| `sqrxm` | 请假人姓名 | 浏览按钮 | 人力资源 | 对应请假人姓名 |
|
||||
| `sqrgs` | 请假人公司 | 浏览按钮 | 分部 | 请假人所属公司 |
|
||||
| `sqrbm` | 请假人部门 | 浏览按钮 | 部门 | 请假人所属部门 |
|
||||
| `sqrzw` | 请假人职务 | 浏览按钮 | 岗位 | 可后续扩展 |
|
||||
| `dlrgh` | 代理人工号 | 单行文本框 | 文本 | 对应代理人工号 |
|
||||
| `dlrxm` | 代理人姓名 | 浏览按钮 | 人力资源 | 对应代理人姓名 |
|
||||
| `dlrlogid` | 代理人登录ID | 单行文本框 | 文本 | 代理人 OA 登录 ID |
|
||||
| `kssj` | 开始时间 | 浏览按钮 | 日期 | 开始日期 |
|
||||
| `kssk` | 开始时刻 | 浏览按钮 | 时间 | 开始时刻 |
|
||||
| `jssj` | 结束时间 | 浏览按钮 | 日期 | 结束日期 |
|
||||
| `jssk` | 结束时刻 | 浏览按钮 | 时间 | 结束时刻 |
|
||||
| `qjsc` | 请假时长 | 单行文本框 | 浮点数 | 请假时长 |
|
||||
| `sfwgs` | 是否为工伤 | 选择框 | 是否 | 当前前端默认 `否` |
|
||||
| `sfwc` | 是否外出 | 选择框 | 是否 | 当前前端默认 `否` |
|
||||
| `bz` | 备注 | 多行文本框 | 多行文本框 | 可后续在前端补充 |
|
||||
| `xglc` | 相关流程 | 浏览按钮 | 流程 | 可选扩展 |
|
||||
| `xgfj` | 相关附件 | 附件上传 | 上传文件 | 可选扩展 |
|
||||
| `qc` | 厂区 | 选择框 | 一厂/二厂 | 待确认是否必填 |
|
||||
| `jb` | 假别 | 浏览按钮 | 自定义单选 | 已确认对应请假类型选择字段 |
|
||||
|
||||
#### 实测确认的关键字段编号
|
||||
|
||||
以下字段编号来自真实 OA 请假页 `AddRequestIframe.jsp` 抓取结果,可直接用于前后端对照与排障:
|
||||
|
||||
| 字段名称 | 字段显示名 | 实际字段编号 |
|
||||
| --- | --- | --- |
|
||||
| `tdrgh` | 填单人工号 | `field6901` |
|
||||
| `sqrgh` | 请假人工号 | `field6902` |
|
||||
| `tdrxm` | 填单人姓名 | `field6903` |
|
||||
| `sqrxm` | 请假人姓名 | `field6904` |
|
||||
| `dlrgh` | 代理人工号 | `field6907` |
|
||||
| `dlrxm` | 代理人姓名 | `field6908` |
|
||||
| `dlrlogid` | 代理人登录ID | `field9974` |
|
||||
| `jb` | 假别 | `field8378` |
|
||||
| `jbbh` | 假别编号 | `field8379` |
|
||||
| `sfwc` | 是否外出 | `field18966` |
|
||||
| `kssj` | 开始日期 | `field6910` |
|
||||
| `kssk` | 开始时刻 | `field6911` |
|
||||
| `jssj` | 结束日期 | `field6912` |
|
||||
| `jssk` | 结束时刻 | `field6913` |
|
||||
| `qjsc` | 请假时长 | `field6914` |
|
||||
| `sfwgs` | 是否为工伤 | `field6915` |
|
||||
| `bz` | 备注 | `field6916` |
|
||||
|
||||
补充说明:
|
||||
|
||||
- `sfwgs`、`sfwc` 的枚举值已确认:
|
||||
- `0 = 是`
|
||||
- `1 = 否`
|
||||
|
||||
#### 假期与规则辅助字段
|
||||
|
||||
| 字段名称 | 字段显示名 | 说明 |
|
||||
| -------- | ------- | ---------- |
|
||||
| `txhjss` | 调休合计时长 | 调休相关计算字段 |
|
||||
| `kqnjts` | 可请年假天数 | 年假额度相关字段 |
|
||||
| `kqyjts` | 可请育儿假时数 | 育儿假额度相关字段 |
|
||||
| `txrq` | 调休日期 | 调休场景可能使用 |
|
||||
| `njsxsj` | 年假生效时间 | 年假规则相关字段 |
|
||||
| `fjf` | 上传附件否 | 附件要求开关 |
|
||||
| `chsm` | 出差说明标题 | 特殊字段,自定义链接 |
|
||||
| `chglbf` | 出差管理办法 | 特殊字段,自定义链接 |
|
||||
| `chsmsa` | 出差说明其四 | 截图显示名待确认 |
|
||||
| `pljqsm` | 批量请假说明 | 特殊字段,自定义链接 |
|
||||
|
||||
#### 明细字段参考
|
||||
|
||||
| 字段名称 | 字段显示名 | 说明 |
|
||||
| ------- | ----- | ------ |
|
||||
| `gh` | 工号 | 明细字段 |
|
||||
| `bh` | 编号 | 明细字段 |
|
||||
| `idi` | ID | 明细字段 |
|
||||
| `jbrq` | 加班日期 | 调休来源相关 |
|
||||
| `jblx` | 加班类型 | 调休来源相关 |
|
||||
| `jbss` | 加班时数 | 调休来源相关 |
|
||||
| `ytss` | 已调时数 | 调休来源相关 |
|
||||
| `wtss` | 未调时数 | 调休来源相关 |
|
||||
| `txss` | 调休时数 | 调休来源相关 |
|
||||
| `spzss` | 审批中时数 | 调休来源相关 |
|
||||
| `kyss` | 可用时数 | 调休来源相关 |
|
||||
| `txrq` | 调休日期 | 明细字段日期 |
|
||||
| `ksrq` | 开始日期 | 明细字段日期 |
|
||||
| `kssj` | 开始时间 | 明细字段时间 |
|
||||
| `jsrq` | 结束日期 | 明细字段日期 |
|
||||
| `jssj` | 结束时间 | 明细字段时间 |
|
||||
| `qjsc` | 请假时长 | 明细字段时长 |
|
||||
|
||||
#### 当前前端已接字段
|
||||
|
||||
当前聊天请假表单已接入的字段如下:
|
||||
|
||||
| 前端字段 | 对应含义 | 备注 |
|
||||
| ----------------- | ------- | ---------- |
|
||||
| `applicantName` | 请假人 | 默认当前登录用户姓名,可选择修改 |
|
||||
| `employeeId` | 工号 | 对应请假人工号 |
|
||||
| `applicantUid` | 请假人UID | 对应请假人 OA UID |
|
||||
| `applyTime` | 创建时间 | 默认当前时间 |
|
||||
| `fillerName` | 填单人 | 默认当前登录用户姓名 |
|
||||
| `agentUid` | 代理人 UID | 当前先使用模拟数据 |
|
||||
| `agentEmployeeId` | 代理人工号 | 当前先使用模拟数据 |
|
||||
| `agentName` | 代理人姓名 | 当前先使用模拟数据 |
|
||||
| `leaveType` | 假别 | 前端下拉选择 |
|
||||
| `startTime` | 开始时间 | 日期时间控件 |
|
||||
| `endTime` | 结束时间 | 日期时间控件 |
|
||||
| `durationHours` | 时长 | 自动计算 |
|
||||
| `isOutOfOffice` | 是否外出 | 当前默认 `否` |
|
||||
| `isWorkInjury` | 是否为工伤 | 当前默认 `否` |
|
||||
|
||||
#### 待确认项
|
||||
|
||||
- `chsmsa` 显示名截图较模糊,需在 OA 后台再次确认
|
||||
- 部分字段显示顺序存在相同编号,需以 OA 配置页最终数据为准
|
||||
- 主表中的 `开始时间/结束时间` 与明细中的 `开始日期/开始时间/结束日期/结束时间` 是否需同时提交,需结合真实 workflow=652 配置确认
|
||||
|
||||
## 7. 接口设计
|
||||
|
||||
### 7.1 聊天接口
|
||||
|
||||
继续复用:
|
||||
|
||||
- `POST /api/chat/completions`
|
||||
|
||||
不建议新增单独前端入口,优先在后端根据意图分流。
|
||||
|
||||
### 7.2 内部服务接口建议
|
||||
|
||||
#### OA 用户查询
|
||||
|
||||
- `OAUserDirectoryService.get_oa_user_id(employee_id)`
|
||||
|
||||
#### OA 请假提交流程
|
||||
|
||||
- `OALeaveWorkflowService.submit(workflow_code, payload)`
|
||||
|
||||
#### 状态同步
|
||||
|
||||
- `LeaveStatusSyncService.sync_one(leave_request_id)`
|
||||
- `LeaveStatusSyncService.sync_pending()`
|
||||
|
||||
### 7.3 管理接口建议
|
||||
|
||||
建议新增:
|
||||
|
||||
- `GET /api/admin/leave-requests`
|
||||
- `GET /api/admin/leave-requests/<id>`
|
||||
- `POST /api/admin/leave-requests/<id>/resync`
|
||||
- `POST /api/admin/leave-requests/<id>/renotify`
|
||||
|
||||
## 8. 配置设计
|
||||
|
||||
建议新增以下后端配置项:
|
||||
|
||||
```env
|
||||
OA_WORKFLOW_WSDL_URL=http://oa.well-trust.com:8888/services/WorkflowService?wsdl
|
||||
OA_LEAVE_WORKFLOW_CODE=879
|
||||
OA_SQLSERVER_HOST=
|
||||
OA_SQLSERVER_PORT=1433
|
||||
OA_SQLSERVER_DATABASE=
|
||||
OA_SQLSERVER_USERNAME=
|
||||
OA_SQLSERVER_PASSWORD=
|
||||
OA_SQLSERVER_DRIVER=SQL Server
|
||||
OA_STATUS_SYNC_INTERVAL_SECONDS=300
|
||||
OA_STATUS_SYNC_BATCH_SIZE=100
|
||||
```
|
||||
|
||||
如 OA userID 查询与假期查询使用同一 SQL Server,可共用当前 HR SQL Server 配置,但建议逻辑上拆分服务,不直接耦合。
|
||||
|
||||
## 9. 任务调度方案
|
||||
|
||||
### 9.1 推荐方案
|
||||
|
||||
- 继续沿用现有“最小任务调度器”思路
|
||||
- 增加新的 job\_type:
|
||||
- `leave_status_sync`
|
||||
- `leave_submit_retry`
|
||||
|
||||
### 9.2 运行模式
|
||||
|
||||
- `sync`:开发调试使用
|
||||
- `worker`:生产推荐
|
||||
- `manual`:问题排查时可人工触发
|
||||
|
||||
### 9.3 触发方式
|
||||
|
||||
- 容器外部 cron
|
||||
- Windows 计划任务
|
||||
- 独立 worker 进程循环调用同步入口
|
||||
|
||||
## 10. 错误处理设计
|
||||
|
||||
### 10.1 OA userID 查询失败
|
||||
|
||||
- 返回“未找到 OA 用户映射”
|
||||
- 记录错误日志
|
||||
- 不允许继续提交流程
|
||||
|
||||
### 10.2 SOAP 提交失败
|
||||
|
||||
- 保存失败报文
|
||||
- 返回可读错误提示给用户
|
||||
- 支持管理员重试
|
||||
|
||||
### 10.3 OA 状态查询失败
|
||||
|
||||
- 标记同步失败次数
|
||||
- 不影响已存在主记录
|
||||
- 下次轮询继续补偿
|
||||
|
||||
### 10.4 企微发送失败
|
||||
|
||||
- 审计落表
|
||||
- 不回滚主业务状态
|
||||
- 支持后续补发
|
||||
|
||||
## 11. 安全设计
|
||||
|
||||
- 所有请假相关查询都基于当前登录用户身份,不允许传入其他工号直接查询
|
||||
- OA 接口与数据库账号存放在后端配置,不暴露到前端
|
||||
- 本地保存 SOAP 请求/响应时,对敏感字段做脱敏
|
||||
- 管理接口必须具备管理员权限
|
||||
|
||||
## 12. 性能建议
|
||||
|
||||
- OA userID 查询加缓存
|
||||
- 状态轮询只处理未完结记录
|
||||
- 单批同步建议分页处理
|
||||
- 聊天申请提交与状态同步分离,避免一次请求内串行过多外部依赖
|
||||
|
||||
## 13. 建议实施顺序
|
||||
|
||||
### 第一步
|
||||
|
||||
- 确认 OA userID 查询来源表/视图
|
||||
- 确认 workflow=652 字段映射
|
||||
|
||||
### 第二步
|
||||
|
||||
- 实现 SOAP Adapter
|
||||
- 实现本地请假主表
|
||||
- 打通“聊天 -> 创建 OA 请假单”
|
||||
|
||||
### 第三步
|
||||
|
||||
- 实现状态同步服务
|
||||
- 实现状态日志落表
|
||||
- 实现企微通知模板
|
||||
|
||||
### 第四步
|
||||
|
||||
- 补充管理后台与重试机制
|
||||
- 补充告警与监控
|
||||
|
||||
## 14. 推荐代码落点
|
||||
|
||||
### 建议新增文件
|
||||
|
||||
- `backend/app/services/oa_user_directory.py`
|
||||
- `backend/app/services/oa_leave_workflow.py`
|
||||
- `backend/app/services/leave_request_service.py`
|
||||
- `backend/app/services/leave_status_sync.py`
|
||||
- `backend/app/services/leave_intent_router.py`
|
||||
|
||||
### 建议修改文件
|
||||
|
||||
- `backend/app/api/chat.py`
|
||||
- `backend/app/models.py`
|
||||
- `backend/app/api/admin.py`
|
||||
- `backend/app/services/wecom_notify.py`
|
||||
- `backend/app/services/knowledge_cleaning/queue_service.py`
|
||||
|
||||
## 15. 结论
|
||||
|
||||
该需求技术上完全可落地,最关键的实现路径是:
|
||||
|
||||
1. 聊天侧做意图路由
|
||||
2. 数据侧打通 OA userID + WorkflowService + 状态查询
|
||||
3. 平台侧补齐主记录表、状态日志表、轮询任务、通知模板
|
||||
|
||||
现有项目已经具备聊天路由、SQL Server 查询、企微通知、最小任务调度四个核心基础能力,因此本需求适合采用“增量扩展”的方式推进,而不需要重做一套独立系统。
|
||||
@@ -0,0 +1,213 @@
|
||||
# `xinxin2` 迁移收尾清单(第一版)
|
||||
|
||||
## 目标
|
||||
|
||||
将 `xinxin2` 从“独立运行的文档清洗平台”收敛为:
|
||||
|
||||
- 代码能力已并入 `hxops&xinxin`
|
||||
- 登录入口统一使用 `hxops&xinxin`
|
||||
- 聊天侧与外部系统优先访问 `hxops&xinxin` 的知识库与集成 API
|
||||
- `xinxin2` 仅在少量未切换的部署职责上临时保留
|
||||
|
||||
## 当前已完成的迁移能力
|
||||
|
||||
主平台 `hxops&xinxin` 当前已经具备以下能力:
|
||||
|
||||
- 知识库分组管理
|
||||
- 文档条目管理
|
||||
- 文件上传
|
||||
- 文档版本记录
|
||||
- 自动 `clean` 任务执行
|
||||
- `edkb_system` 轻量接入
|
||||
- Dify 同步第一版
|
||||
- Dify 设置与健康检查面板
|
||||
- `/api/integration/*` 集成查询接口
|
||||
- 聊天侧默认优先指向主平台自身 integration API
|
||||
- 基础回归测试:分组/文档/上传/同步/集成 API
|
||||
|
||||
## 结论摘要
|
||||
|
||||
### 可立即下线
|
||||
|
||||
这些入口已经被主平台完全替代,继续保留只会造成双入口混淆:
|
||||
|
||||
| `xinxin2` 项 | 当前状态 | 处理建议 |
|
||||
| --- | --- | --- |
|
||||
| `frontend/src/views/LoginView.vue` | 已由主平台登录替代 | 停用 |
|
||||
| `frontend/src/lib/auth.ts` | 已由主平台鉴权替代 | 停用 |
|
||||
| `frontend/src/main.ts` | 不再需要独立前端入口 | 停用 |
|
||||
| `frontend/src/router/index.ts` | 不再需要独立路由壳 | 停用 |
|
||||
| `backend/app/api/auth.py` | 不再需要独立登录 API | 停用 |
|
||||
| `backend/app/main.py` | 不再需要独立 FastAPI 入口 | 停用 |
|
||||
| `start-local-frontend.ps1` | 不再需要独立前端启动 | 停用 |
|
||||
| `start-local-dev.ps1` | 不再需要独立双进程启动 | 停用 |
|
||||
|
||||
### 待切换后下线
|
||||
|
||||
这些职责在主平台里已有对应实现,但部署或调用方还需要完成切换:
|
||||
|
||||
| `xinxin2` 项 | 当前替代物 | 下线前条件 |
|
||||
| --- | --- | --- |
|
||||
| `backend/app/api/integration.py` | `hxops&xinxin/backend/app/api/integration.py` | 确认所有调用方都改指向主平台 |
|
||||
| `frontend/src/views/WorkspaceView.vue` | `hxops&xinxin/frontend/src/views/KbWorkspaceView.vue` | 用户不再访问 `8891` 前端 |
|
||||
| `frontend/src/views/AdminView.vue` | `hxops&xinxin/frontend/src/views/KbAdminView.vue` | 管理员改从主平台进入 |
|
||||
| `backend/app/api/groups.py` | `hxops&xinxin/backend/app/api/knowledge_base.py` | 验证分组管理不再依赖旧服务 |
|
||||
| `backend/app/api/files.py` | 主平台 `knowledge_base.py` 已覆盖核心主链路 | 如需高级下载/批量功能,先补齐后再停 |
|
||||
| `backend/app/tasks.py` | `hxops&xinxin/backend/app/services/knowledge_cleaning/tasks.py` | 生产环境切到主平台 worker/sync 模式 |
|
||||
| `backend/worker.py` | `hxops&xinxin/backend/worker_kb.py` | 主平台部署接入 worker 后再停 |
|
||||
|
||||
### 暂时保留
|
||||
|
||||
这些项暂时还建议保留,不是因为业务没迁,而是因为主平台部署面还没完全接住:
|
||||
|
||||
| `xinxin2` 项 | 暂时保留原因 | 建议 |
|
||||
| --- | --- | --- |
|
||||
| `docker-compose.yml` | 主平台已补 `redis` / `worker_kb` / 知识库存储卷,但切换后仍需观察一段时间 | 切换稳定后再停 |
|
||||
| `backend/Dockerfile` | 主平台镜像未完全吸收文档清洗依赖时,仍是参考来源 | 保留作为迁移参考 |
|
||||
| `start-local-backend.ps1` | 主平台本地脚本还未完全覆盖知识库依赖检查 | 保留到本地开发文档更新完成 |
|
||||
| `backend/edkb_system/*` 原仓库副本 | 主平台已轻量接入,但若要完全停旧仓库,需要确认无外部脚本再直接引用旧路径 | 短期保留 |
|
||||
| `backend/tests/*` | 主平台只补了核心主链路测试,尚未完整迁入所有旧测试 | 保留到测试迁移完成 |
|
||||
|
||||
## 当前最大阻塞
|
||||
|
||||
### 阻塞 1:主平台生产部署已接住知识库运行时,但仍需完成切换验证
|
||||
|
||||
当前主平台 `docker-compose.yml` 已新增:
|
||||
|
||||
- `kb-redis`
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- `hxops_runtime_data`
|
||||
- `hxops_redis_data`
|
||||
|
||||
影响:
|
||||
|
||||
- 现在的重点已从“补部署件”转为“验证切换链路”
|
||||
- 如果线上有专门的 `8891` 文件存储目录,切换前仍要确认主平台 `KB_STORAGE_ROOT` 已指向迁移后的新位置
|
||||
- 若要正式下线旧 worker,需观察主平台 `hxops-kb-worker` 实际消费任务是否稳定
|
||||
|
||||
### 阻塞 2:调用方地址切换要做最终确认
|
||||
|
||||
虽然聊天侧已经默认优先用主平台自身 `/api/integration/*`,但仍建议确认:
|
||||
|
||||
- `INTEGRATION_API_MODE=local`
|
||||
- `WECOM_PUBLIC_BASE_URL` 正确配置
|
||||
- 旧的 `INTEGRATION_API_BASE` 不再被外部系统直接依赖
|
||||
|
||||
### 阻塞 3:部分高级能力仍是“第一版”
|
||||
|
||||
当前主平台已跑通主链路,但以下能力仍属于增强项,不建议在未验证前立刻删除旧仓库参考:
|
||||
|
||||
- 更完整的 `edkb_system` skill 支持
|
||||
- 批量下载与更多文件格式处理
|
||||
- 完整异步队列化执行策略
|
||||
- 更完整的 Dify diff / import 行为
|
||||
|
||||
## 建议的切换顺序
|
||||
|
||||
### 第一步:停独立入口
|
||||
|
||||
先停掉所有“用户可见的独立入口”:
|
||||
|
||||
- `xinxin2` 独立登录页
|
||||
- `xinxin2` 独立前端 Vite 本地启动
|
||||
- `xinxin2` 独立前端对外访问入口
|
||||
|
||||
判定标准:
|
||||
|
||||
- 用户和管理员都只从 `hxops&xinxin` 访问知识库模块
|
||||
|
||||
### 第二步:切集成地址
|
||||
|
||||
确认聊天链路和外部系统都使用主平台集成接口:
|
||||
|
||||
- `/api/integration/dify-file`
|
||||
- `/api/integration/dify-files/resolve`
|
||||
- `/api/integration/files/<id>/download`
|
||||
|
||||
判定标准:
|
||||
|
||||
- 旧 `xinxin2` 集成 API 日志无实际流量
|
||||
|
||||
### 第三步:切运行时
|
||||
|
||||
把知识库运行时职责切到主平台:
|
||||
|
||||
- 在主平台 compose 中加入 `redis`
|
||||
- 在主平台 compose 中加入 `worker_kb`
|
||||
- 确认 `KB_STORAGE_ROOT` 与卷映射
|
||||
|
||||
判定标准:
|
||||
|
||||
- 上传、自动 clean、sync_dify 都在主平台运行完成
|
||||
|
||||
### 第四步:停旧后端服务
|
||||
|
||||
当以下条件同时满足时,可停 `xinxin2` 的 `api` / `worker`:
|
||||
|
||||
- 主平台知识库 API 正常
|
||||
- 主平台 integration API 正常
|
||||
- 主平台 worker 正常
|
||||
- 旧服务近一段时间无流量或仅剩探测流量
|
||||
|
||||
## 具体可下线项清单
|
||||
|
||||
### 现在就可以停
|
||||
|
||||
- `xinxin2/frontend/src/views/LoginView.vue`
|
||||
- `xinxin2/frontend/src/lib/auth.ts`
|
||||
- `xinxin2/frontend/src/main.ts`
|
||||
- `xinxin2/frontend/src/router/index.ts`
|
||||
- `xinxin2/backend/app/api/auth.py`
|
||||
- `xinxin2/backend/app/main.py`
|
||||
- `xinxin2/start-local-frontend.ps1`
|
||||
- `xinxin2/start-local-dev.ps1`
|
||||
|
||||
### 完成部署切换后可停
|
||||
|
||||
- `xinxin2/frontend/Dockerfile`
|
||||
- `xinxin2/frontend/src/views/WorkspaceView.vue`
|
||||
- `xinxin2/frontend/src/views/AdminView.vue`
|
||||
- `xinxin2/backend/app/api/groups.py`
|
||||
- `xinxin2/backend/app/api/files.py`
|
||||
- `xinxin2/backend/app/api/integration.py`
|
||||
- `xinxin2/backend/app/tasks.py`
|
||||
- `xinxin2/backend/worker.py`
|
||||
- `xinxin2/docker-compose.yml`
|
||||
|
||||
### 暂时保留参考
|
||||
|
||||
- `xinxin2/backend/edkb_system/*`
|
||||
- `xinxin2/backend/tests/*`
|
||||
- `xinxin2/project-governance/*`
|
||||
- `xinxin2/README.md`
|
||||
- `xinxin2/EXTERNAL-INTEGRATION-API.md`
|
||||
|
||||
## 建议新增的主平台收尾工作
|
||||
|
||||
为了真正完成下线,主平台还建议补这几项:
|
||||
|
||||
- 观察主平台 `worker_kb` 切换后一段时间的稳定性
|
||||
- 为知识库模块补部署文档(见 `docs/knowledge_base_runtime_deploy.md`)
|
||||
- 在主平台 README 或 docs 中补本地运行步骤
|
||||
- 继续迁移 `xinxin2` 测试到主平台 `backend/tests/`
|
||||
- 补一版“切换完成后的 smoke checklist”
|
||||
|
||||
## 切换完成判定
|
||||
|
||||
满足以下条件,可认为 `xinxin2` 已完成业务下线:
|
||||
|
||||
- 用户只从 `hxops&xinxin` 登录和使用知识库
|
||||
- 聊天侧 source 文件映射只访问主平台 integration API
|
||||
- 文档上传、clean、sync 都由主平台完成
|
||||
- 主平台部署已具备所需 worker/存储能力
|
||||
- `xinxin2` 的外部访问流量归零
|
||||
|
||||
## 当前建议
|
||||
|
||||
下一步优先做:
|
||||
|
||||
1. 按 `docs/knowledge_base_runtime_deploy.md` 完成一轮主平台知识库运行时冒烟验证
|
||||
2. 观察主平台 `worker_kb`、`/api/integration/*` 与文件下载链路是否稳定
|
||||
3. 再决定是否正式停掉 `xinxin2` 的 `api/worker/frontend`
|
||||
@@ -0,0 +1,238 @@
|
||||
# `xinxin2` 正式下线执行文档
|
||||
|
||||
## 文档目标
|
||||
|
||||
用于记录 `xinxin2` 向主平台 `hxops&xinxin` 完成迁移后的正式下线执行方案、当前实机执行结果、回滚预案与生产切换注意事项。
|
||||
|
||||
## 当前结论
|
||||
|
||||
当前主平台 `hxops&xinxin` 已实机跑通以下完整链路:
|
||||
|
||||
- 知识库分组创建
|
||||
- 文档创建
|
||||
- 文件上传
|
||||
- 自动 `clean`
|
||||
- 同步到本地 Dify
|
||||
- `/api/integration/files/*`
|
||||
- `/api/integration/dify-file`
|
||||
- 源文件与 Markdown 下载
|
||||
|
||||
本地环境当前结论:
|
||||
|
||||
- `xinxin2` 已满足下线条件
|
||||
- 主平台已具备替代 `xinxin2` 的完整知识库主链路能力
|
||||
- 生产环境正式切换前,仅需把本地测试用公开地址替换为真实可访问域名
|
||||
|
||||
## 本次实机执行结果
|
||||
|
||||
### 1. 主平台状态
|
||||
|
||||
当前正在运行:
|
||||
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- `hxops-kb-redis`
|
||||
|
||||
当前已验证:
|
||||
|
||||
- 前端访问正常:`http://127.0.0.1:8890/`
|
||||
- 后端访问正常:`http://127.0.0.1:5002/`
|
||||
- 知识库上传/清洗/同步/集成接口全部通过
|
||||
|
||||
### 2. Dify 测试配置
|
||||
|
||||
当前本地测试使用:
|
||||
|
||||
- `DIFY_API_BASE=http://host.docker.internal/v1`
|
||||
- `DIFY_API_KEY=dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
|
||||
|
||||
说明:
|
||||
|
||||
- 由于主平台运行在 Docker 容器中,容器内访问宿主机 Dify 不能使用 `localhost`
|
||||
- 本地测试时应使用 `http://host.docker.internal/v1`
|
||||
|
||||
### 3. Public Base 测试配置
|
||||
|
||||
当前本地测试使用:
|
||||
|
||||
- `WECOM_PUBLIC_BASE_URL=http://127.0.0.1:5002`
|
||||
|
||||
作用:
|
||||
|
||||
- 让 `/api/integration/*` 返回的下载地址直接指向本机可访问的主平台后端
|
||||
|
||||
说明:
|
||||
|
||||
- 该值只适用于本地验证
|
||||
- 生产环境必须替换为真实公网或内网可访问域名
|
||||
|
||||
### 4. `xinxin2` 当前运行状态
|
||||
|
||||
本机实机检查结果:
|
||||
|
||||
- `docker compose ps -a`(在 `xinxin2` 目录执行)为空
|
||||
- `http://127.0.0.1:8891/` 当前不可达
|
||||
|
||||
结论:
|
||||
|
||||
- 当前机器上不存在正在运行的 `xinxin2` Docker 前端/API/worker 实例
|
||||
- 因此“停止旧服务”这一步在本机已是完成状态
|
||||
|
||||
## 正式下线执行顺序
|
||||
|
||||
### 第一步:统一入口
|
||||
|
||||
执行项:
|
||||
|
||||
- 停止 `xinxin2` 独立前端入口
|
||||
- 用户与管理员统一从 `hxops&xinxin` 登录
|
||||
- 不再对外暴露 `8891` 知识库前端入口
|
||||
|
||||
判定标准:
|
||||
|
||||
- 用户只从主平台访问知识库
|
||||
- `8891` 无用户流量
|
||||
|
||||
### 第二步:统一调用地址
|
||||
|
||||
执行项:
|
||||
|
||||
- 外部调用方统一切换到主平台 `/api/integration/*`
|
||||
- 聊天侧继续使用主平台本地 integration API
|
||||
|
||||
判定标准:
|
||||
|
||||
- 旧 `xinxin2` integration API 流量归零
|
||||
|
||||
### 第三步:统一运行时
|
||||
|
||||
执行项:
|
||||
|
||||
- 使用主平台 `hxops-backend`
|
||||
- 使用主平台 `hxops-kb-worker`
|
||||
- 使用主平台知识库存储卷
|
||||
- 使用主平台知识库 Dify 配置
|
||||
|
||||
判定标准:
|
||||
|
||||
- 上传、`clean`、`sync_dify` 都在主平台成功完成
|
||||
|
||||
### 第四步:停止旧后端
|
||||
|
||||
执行项:
|
||||
|
||||
- 停止 `xinxin2` worker
|
||||
- 停止 `xinxin2` API
|
||||
- 停止 `xinxin2` 旧 compose 服务
|
||||
|
||||
判定标准:
|
||||
|
||||
- 主平台 API、worker、integration API 持续正常
|
||||
- 旧服务无有效访问流量
|
||||
|
||||
## 当前机器的执行状态
|
||||
|
||||
### 已完成
|
||||
|
||||
- 主平台知识库功能迁移
|
||||
- 主平台 Docker 运行时接入
|
||||
- 主平台 Dify 测试配置接入
|
||||
- 主平台 integration API 验证
|
||||
- `xinxin2` 旧前端入口不可达
|
||||
- `xinxin2` compose 无运行实例
|
||||
|
||||
### 当前无需再执行的停机动作
|
||||
|
||||
在这台机器上,以下动作已无需再做:
|
||||
|
||||
- `docker compose stop` `xinxin2` 前端
|
||||
- `docker compose stop` `xinxin2` API
|
||||
- `docker compose stop` `xinxin2` worker
|
||||
|
||||
原因:
|
||||
|
||||
- 当前本机 `xinxin2` 本就未运行
|
||||
|
||||
## 回滚预案
|
||||
|
||||
若主平台切换后出现异常,可按以下顺序回滚:
|
||||
|
||||
1. 恢复 `xinxin2` 前端入口
|
||||
2. 恢复 `xinxin2` API
|
||||
3. 恢复 `xinxin2` worker
|
||||
4. 将调用方 integration 地址切回旧服务
|
||||
5. 验证旧链路恢复后,再排查主平台问题
|
||||
|
||||
## 回滚时禁止直接删除
|
||||
|
||||
- `xinxin2` 数据库
|
||||
- `xinxin2` 历史文件目录
|
||||
- `xinxin2/docker-compose.yml`
|
||||
- `xinxin2/backend/tests/*`
|
||||
- `xinxin2/backend/edkb_system/*`
|
||||
|
||||
## 生产环境切换前必改项
|
||||
|
||||
### 1. `WECOM_PUBLIC_BASE_URL`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `http://127.0.0.1:5002`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为真实公网或内网可访问域名
|
||||
|
||||
### 2. `DIFY_API_BASE`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `http://host.docker.internal/v1`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为生产环境 Dify 可访问地址
|
||||
|
||||
### 3. `DIFY_API_KEY`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为生产可用的 Dify Key
|
||||
|
||||
### 4. 其他关键生产变量
|
||||
|
||||
切换前同时确认:
|
||||
|
||||
- `DATABASE_URL`
|
||||
- `SECRET_KEY`
|
||||
- `KB_STORAGE_ROOT`
|
||||
- `INTEGRATION_API_MODE=local`
|
||||
|
||||
## 生产切换后最小冒烟清单
|
||||
|
||||
建议逐项验证:
|
||||
|
||||
1. 登录主平台知识库工作台
|
||||
2. 新建分组
|
||||
3. 新建文档
|
||||
4. 上传 `txt` 或 `md`
|
||||
5. 确认 `clean` 成功
|
||||
6. 触发同步到 Dify
|
||||
7. 调用 `/api/integration/dify-file`
|
||||
8. 点击下载源文件与 Markdown
|
||||
|
||||
## 最终结论
|
||||
|
||||
在当前本地环境中:
|
||||
|
||||
- `xinxin2` 已可正式进入下线状态
|
||||
- 主平台 `hxops&xinxin` 已完成替代
|
||||
|
||||
在生产环境中:
|
||||
|
||||
- 只要把本地测试配置替换为真实生产配置,即可按本执行文档推进正式切换
|
||||
@@ -154,6 +154,12 @@ docker compose up -d --build
|
||||
- 后端:`5052:5052`
|
||||
|
||||
注意:当前项目中后端端口存在 `5000` 与 `5052` 并存配置,若容器联调异常,优先统一端口配置。
|
||||
- 后端:`5002:5000`
|
||||
|
||||
补充:
|
||||
|
||||
- 容器内后端监听 `5000`,宿主机对外暴露 `5002`
|
||||
- 知识库运行时部署说明见 `docs/knowledge_base_runtime_deploy.md`
|
||||
|
||||
## 6. 项目登录环境与账号配置
|
||||
|
||||
@@ -221,13 +227,22 @@ docker compose up -d --build
|
||||
| `SECRET_KEY` | Flask 密钥 | 随机长字符串 |
|
||||
| `DATABASE_URL` | 数据库连接 | `postgresql://user:pwd@host:5432/db` |
|
||||
| `REDIS_URL` | Redis 连接 | `redis://:pwd@host:6379/0` |
|
||||
| `KB_STORAGE_ROOT` | 知识库存储根目录 | `/app/data/kb` |
|
||||
| `KB_TASK_EXECUTION_MODE` | 知识库任务执行模式 | `worker` / `sync` / `manual` |
|
||||
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | `2` |
|
||||
| `KB_REDIS_IMAGE` | Redis 镜像来源 | `redis:7-alpine` 或私有仓库镜像 |
|
||||
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | `python:3.12-slim` 或私有仓库镜像 |
|
||||
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | `node:22-alpine` 或私有仓库镜像 |
|
||||
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | `nginx:alpine` 或私有仓库镜像 |
|
||||
| `DIFY_API_BASE` | Dify 地址 | `https://api.dify.ai/v1` |
|
||||
| `DIFY_API_KEY` | Dify 密钥 | `sk-...` |
|
||||
| `HR_WORKFLOW_IFRAME_URL` | HR 页面链接 | `https://...` |
|
||||
| `HR_WORKFLOW_API_BASE` | HR API 地址 | `https://...` |
|
||||
| `HR_WORKFLOW_API_KEY` | HR API 密钥 | `<待补>` |
|
||||
| `INTEGRATION_API_MODE` | 集成 API 模式 | `local` / `external` |
|
||||
| `INTEGRATION_API_BASE` | 集成 API 地址 | `https://...` |
|
||||
| `INTEGRATION_API_KEY` | 集成 API 密钥 | `<待补>` |
|
||||
| `WECOM_PUBLIC_BASE_URL` | 主平台公网基地址 | `https://<your-domain>` |
|
||||
| `WECOM_*` | 企业微信配置 | 见第 6.4 节 |
|
||||
| `CASDOOR_BASE_URL` | Casdoor 地址 | `http://192.168.100.230:8870` |
|
||||
| `CASDOOR_REDIRECT_URI` | OAuth 兜底回调 | 见 §6.2.1;须与 Casdoor 登记一致 |
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# 请假单表字段整理
|
||||
|
||||
## 说明
|
||||
- 本文档根据当前提供的 3 张 OA 表单字段截图人工整理。
|
||||
- 字段名称、显示名、表现形式、字段类型、显示顺序以截图可见内容为准。
|
||||
- 个别字段如存在截图模糊、顺序重复或命名识别误差,建议后续以 OA 后台字段配置页再次核对。
|
||||
- 本文档重点用于前端请假表单、后端字段映射、OA 提交流程对接时参考。
|
||||
|
||||
## 主表字段
|
||||
| 字段名称 | 字段显示名 | 字段位置 | 表现形式 | 字段类型 | 显示顺序 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `txhjss` | 调休合计时长 | 主表字段 | 单行文本框 | 浮点数 | `0.00` |
|
||||
| `kqnjts` | 可请年假天数 | 主表字段 | 单行文本框 | 浮点数 | `0.00` |
|
||||
| `txrq` | 调休日期 | 主表字段 | 浏览按钮 | 日期 | `0.00` |
|
||||
| `njsxsj` | 年假生效时间 | 主表字段 | 单行文本框 | 文本 | `0.00` |
|
||||
| `lcbh` | 流程编号 | 主表字段 | 单行文本框 | 文本 | `1.00` |
|
||||
| `tdrgs` | 填单人公司 | 主表字段 | 浏览按钮 | 分部 | `2.00` |
|
||||
| `tdrbm` | 填单人部门 | 主表字段 | 浏览按钮 | 部门 | `3.00` |
|
||||
| `tdrgh` | 填单人工号 | 主表字段 | 单行文本框 | 文本 | `4.00` |
|
||||
| `sqrgh` | 申请人工号 | 主表字段 | 单行文本框 | 文本 | `5.00` |
|
||||
| `tdrxm` | 填单人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `6.00` |
|
||||
| `sqrxm` | 申请人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `7.00` |
|
||||
| `dlrgh` | 代理人工号 | 主表字段 | 单行文本框 | 文本 | `10.00` |
|
||||
| `dlrxm` | 代理人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `11.00` |
|
||||
| `kssj` | 开始时间 | 主表字段 | 浏览按钮 | 日期 | `13.00` |
|
||||
| `kssk` | 开始时刻 | 主表字段 | 浏览按钮 | 时间 | `14.00` |
|
||||
| `jssj` | 结束时间 | 主表字段 | 浏览按钮 | 日期 | `15.00` |
|
||||
| `jssk` | 结束时刻 | 主表字段 | 浏览按钮 | 时间 | `16.00` |
|
||||
| `qjsc` | 请假时长 | 主表字段 | 单行文本框 | 浮点数 | `17.00` |
|
||||
| `sfwgs` | 是否为工伤 | 主表字段 | 选择框 | 是否 | `18.00` |
|
||||
| `bz` | 备注 | 主表字段 | 多行文本框 | 多行文本框 | `19.00` |
|
||||
| `xglc` | 相关流程 | 主表字段 | 浏览按钮 | 流程 | `20.00` |
|
||||
| `xgfj` | 相关附件 | 主表字段 | 附件上传 | 上传文件 | `21.00` |
|
||||
| `tdrzw` | 填单人职务 | 主表字段 | 浏览按钮 | 岗位 | `22.00` |
|
||||
| `sqrgs` | 申请人公司 | 主表字段 | 浏览按钮 | 分部 | `22.00` |
|
||||
| `sqrzw` | 申请人职务 | 主表字段 | 浏览按钮 | 岗位 | `23.00` |
|
||||
| `sqrbm` | 申请人部门 | 主表字段 | 浏览按钮 | 部门 | `23.00` |
|
||||
| `jb` | 级别 | 主表字段 | 浏览按钮 | 自定义单选 | `24.00` |
|
||||
| `jbbh` | 级别编号 | 主表字段 | 单行文本框 | 文本 | `24.00` |
|
||||
| `dlrlogid` | 代理人登录ID | 主表字段 | 单行文本框 | 文本 | `28.00` |
|
||||
| `sfwc` | 是否外出 | 主表字段 | 选择框 | 是否 | `29.00` |
|
||||
| `qc` | 厂区 | 主表字段 | 选择框 | 一厂/二厂 | `30.00` |
|
||||
| `fjf` | 上传附件否 | 主表字段 | 选择框 | 是否 | `31.00` |
|
||||
| `chsm` | 出差说明标题 | 主表字段 | 特殊字段 | 自定义链接 | `32.00` |
|
||||
| `chglbf` | 出差管理办法 | 主表字段 | 特殊字段 | 自定义链接 | `33.00` |
|
||||
| `kqyjts` | 可请育儿假时数 | 主表字段 | 单行文本框 | 浮点数 | `34.00` |
|
||||
| `chsmsa` | 出差说明其四 | 主表字段 | 特殊字段 | 自定义链接 | `36.00` |
|
||||
| `pljqsm` | 批量请假说明 | 主表字段 | 特殊字段 | 自定义链接 | `36.00` |
|
||||
|
||||
## 明细字段
|
||||
| 字段名称 | 字段显示名 | 字段位置 | 表现形式 | 字段类型 | 显示顺序 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `gh` | 工号 | 明细字段 | 单行文本框 | 文本 | `1.00` |
|
||||
| `bh` | 编号 | 明细字段 | 单行文本框 | 文本 | `2.00` |
|
||||
| `idi` | ID | 明细字段 | 单行文本框 | 文本 | `3.00` |
|
||||
| `jbrq` | 加班日期 | 明细字段 | 单行文本框 | 文本 | `4.00` |
|
||||
| `jblx` | 加班类型 | 明细字段 | 单行文本框 | 文本 | `5.00` |
|
||||
| `jbss` | 加班时数 | 明细字段 | 单行文本框 | 浮点数 | `6.00` |
|
||||
| `ytss` | 已调时数 | 明细字段 | 单行文本框 | 浮点数 | `7.00` |
|
||||
| `wtss` | 未调时数 | 明细字段 | 单行文本框 | 浮点数 | `8.00` |
|
||||
| `txss` | 调休时数 | 明细字段 | 单行文本框 | 浮点数 | `9.00` |
|
||||
| `spzss` | 审批中时数 | 明细字段 | 单行文本框 | 浮点数 | `10.00` |
|
||||
| `kyss` | 可用时数 | 明细字段 | 单行文本框 | 浮点数 | `11.00` |
|
||||
| `txrq` | 调休日期 | 明细字段 | 浏览按钮 | 日期 | `1.00` |
|
||||
| `ksrq` | 开始日期 | 明细字段 | 浏览按钮 | 日期 | `2.00` |
|
||||
| `kssj` | 开始时间 | 明细字段 | 浏览按钮 | 时间 | `3.00` |
|
||||
| `jsrq` | 结束日期 | 明细字段 | 浏览按钮 | 日期 | `4.00` |
|
||||
| `jssj` | 结束时间 | 明细字段 | 浏览按钮 | 时间 | `5.00` |
|
||||
| `qjsc` | 请假时长 | 明细字段 | 单行文本框 | 浮点数 | `6.00` |
|
||||
|
||||
## 当前前端已接字段
|
||||
以下字段已在当前聊天请假表单中接入或展示:
|
||||
|
||||
| 前端字段 | 含义 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| `applicantName` | 申请人 | 当前登录用户姓名 |
|
||||
| `employeeId` | 工号 | 当前登录用户工号 |
|
||||
| `applyTime` | 申请时间 | 默认当前时间 |
|
||||
| `fillerName` | 填单人 | 默认当前登录用户姓名 |
|
||||
| `agentUid` | 代理人 UID | 当前先为模拟选择数据 |
|
||||
| `agentEmployeeId` | 代理人工号 | 当前先为模拟选择数据 |
|
||||
| `agentName` | 代理人姓名 | 当前先为模拟选择数据 |
|
||||
| `leaveType` | 假别 | 下拉选择 |
|
||||
| `startTime` | 开始时间 | 前端日期时间控件 |
|
||||
| `endTime` | 结束时间 | 前端日期时间控件 |
|
||||
| `durationHours` | 时长 | 根据开始/结束时间自动计算 |
|
||||
| `isOutOfOffice` | 是否外出 | 当前默认 `否` |
|
||||
| `isWorkInjury` | 是否为工伤 | 当前默认 `否` |
|
||||
|
||||
## 对接建议
|
||||
- 后端对接 OA 创建请假单时,建议优先确认主表字段中的以下映射关系:
|
||||
- `tdrgh` / `tdrxm`:填单人工号、填单人姓名
|
||||
- `sqrgh` / `sqrxm`:申请人工号、申请人姓名
|
||||
- `dlrgh` / `dlrxm` / `dlrlogid`:代理人信息
|
||||
- `kssj` / `kssk` / `jssj` / `jssk`:开始结束日期时间
|
||||
- `qjsc`:请假时长
|
||||
- `sfwgs`:是否为工伤
|
||||
- `sfwc`:是否外出
|
||||
- `bz`:备注
|
||||
- 如需支持调休、年假、育儿假等复杂场景,应继续确认:
|
||||
- `txhjss`
|
||||
- `kqnjts`
|
||||
- `kqyjts`
|
||||
- 明细字段中的调休日期、加班日期、可用时数等是否参与提交流程
|
||||
|
||||
## 待确认项
|
||||
- `chsmsa` 的显示名截图较模糊,需在 OA 后台再次确认。
|
||||
- 部分字段显示顺序存在相同编号,可能是 OA 配置本身如此,也可能为截图显示问题。
|
||||
- 主表中的 `开始时间/结束时间` 与明细中的 `开始日期/开始时间/结束日期/结束时间` 是否同时必填,需要结合真实流程配置确认。
|
||||
@@ -0,0 +1,101 @@
|
||||
LET l_str1 = "<?xml version='1.0' encoding='utf-8'?>\n",
|
||||
"<requestinfo>\n",
|
||||
"<maintable>\n",
|
||||
"<fields>sqrgh,kpr,kpbm,zt,cb,kpdh,khbh,khqm,kprq,sz,hl,bz,khdzjdh,khsh,yjskrq,slhj,ybsqjehj,ybsehj,ybhsjehj,bbsqjehj,bbsehj,bbhsjehj,hth</fields>\n",
|
||||
"<creater>",l_tc_hratud03,"</creater>\n", #创建人id
|
||||
"<wfid>652</wfid>\n", #工作流idworkflow=652(请假固定)
|
||||
"<level>0</level>\n", #紧急程度
|
||||
"<requestname>",l_rn,"</requestname>\n", #流程标题
|
||||
"<sqrgh>",l_omf.omfuser,"</sqrgh>\n", #申请人工号
|
||||
"<kpr>",l_tc_hratud03,"</kpr>\n", #申请人姓名
|
||||
"<kpbm>",l_tc_hraoud03,"</kpbm>\n", #申请人部门
|
||||
"<zt>",g_plant,"</zt>\n", #账套
|
||||
"<cb>",l_zt,"</cb>\n", #厂别
|
||||
"<kpdh>",p_no,"</kpdh>\n", #开票单号
|
||||
"<khbh>",l_omf.omf05,"</khbh>\n", #客户编号
|
||||
"<khqm>",l_omf.occ18,"</khqm>\n", #客户全名
|
||||
"<kprq>",l_omf.omf31,"</kprq>\n", #开票日期
|
||||
"<sz>",l_omf.omf06,"</sz>\n", #税种
|
||||
"<hl>",l_omf.omf22,"</hl>\n", #汇率
|
||||
"<bz>",l_omf.omf07,"</bz>\n", #币种
|
||||
"<khdzjdh>",l_omf.occ241,"</khdzjdh>\n", #客户地址
|
||||
"<khsh>",l_omf.occ11,"</khsh>\n", #客户税号
|
||||
"<yjskrq>",l_omf.omfud02,"</yjskrq>\n", #预计收款日期
|
||||
"<slhj>",l_omf.omf16_sum,"</slhj>\n", #数量合计
|
||||
"<ybsqjehj>",l_omf.omf29_sum,"</ybsqjehj>\n", #原币税前金额合计
|
||||
"<ybsehj>",l_omf.omf29x_sum,"</ybsehj>\n", #原币税额合计
|
||||
"<ybhsjehj>",l_omf.omf29t_sum,"</ybhsjehj>\n", #原币含税金额合计
|
||||
"<bbsqjehj>",l_omf.omf19_sum,"</bbsqjehj>\n", #本币税前金额合计
|
||||
"<bbsehj>",l_omf.omf19x_sum,"</bbsehj>\n", #本币税额合计
|
||||
"<bbhsjehj>",l_omf.omf19t_sum,"</bbhsjehj>\n", #本币含税金额合计
|
||||
"<hth>",l_omf.omf02,"</hth>\n", #合同号
|
||||
"</maintable>\n" #主表 END
|
||||
|
||||
LET l_str1 =l_str1," </requestinfo>\n"
|
||||
|
||||
CALL createwflc(l_str1) RETURNING l_str, l_str2
|
||||
IF l_str<0 THEN
|
||||
IF l_str = -1 THEN
|
||||
LET l_msg='创建流程失败'
|
||||
END IF
|
||||
IF l_str = -2 THEN
|
||||
LET l_msg = '用户没有流程创建权限'
|
||||
END IF
|
||||
IF l_str = -3 THEN
|
||||
LET l_msg = '创建流程基本信息失败'
|
||||
END IF
|
||||
IF l_str = -4 THEN
|
||||
LET l_msg = '保存表单主表信息失败'
|
||||
END IF
|
||||
IF l_str = -5 THEN
|
||||
LET l_msg = '更新紧急程度失败'
|
||||
END IF
|
||||
IF l_str = -6 THEN
|
||||
LET l_msg = '流程操作者失败'
|
||||
END IF
|
||||
IF l_str = -7 THEN
|
||||
LET l_msg = '流转至下一节点失败'
|
||||
END IF
|
||||
IF l_str = -8 THEN
|
||||
LET l_msg = '节点附加操作失败'
|
||||
END IF
|
||||
CALL cl_err(l_msg,'!',1)
|
||||
LET l_str = "\n ",g_today," ",TIME,"报错信息 :",l_msg
|
||||
LET g_success = "N"
|
||||
ELSE
|
||||
IF l_str2<=0 THEN
|
||||
IF l_str2 = 0 THEN
|
||||
LET l_msg='返回的ID为0,请联系管理员!'
|
||||
END IF
|
||||
IF l_str2 = -1 THEN
|
||||
LET l_msg='创建流程失败'
|
||||
END IF
|
||||
IF l_str2 = -2 THEN
|
||||
LET l_msg = '用户没有流程创建权限'
|
||||
END IF
|
||||
IF l_str2 = -3 THEN
|
||||
LET l_msg = '创建流程基本信息失败'
|
||||
END IF
|
||||
IF l_str2 = -4 THEN
|
||||
LET l_msg = '保存表单主表信息失败'
|
||||
END IF
|
||||
IF l_str2 = -5 THEN
|
||||
LET l_msg = '更新紧急程度失败'
|
||||
END IF
|
||||
IF l_str2 = -6 THEN
|
||||
LET l_msg = '流程操作者失败'
|
||||
END IF
|
||||
IF l_str2 = -7 THEN
|
||||
LET l_msg = '流转至下一节点失败'
|
||||
END IF
|
||||
IF l_str2 = -8 THEN
|
||||
LET l_msg = '节点附加操作失败'
|
||||
END IF
|
||||
CALL cl_err(l_msg,'!',1)
|
||||
LET l_str2 = "\n ",g_today," ",TIME,"报错信息 :",l_msg
|
||||
LET g_success = "N"
|
||||
ELSE
|
||||
LET g_success = "Y"
|
||||
LET l_omfud11 = l_str2
|
||||
END IF
|
||||
END IF
|
||||
+5
-3
@@ -1,4 +1,6 @@
|
||||
FROM node:22-alpine AS builder
|
||||
ARG NODE_BASE_IMAGE=node:22-alpine
|
||||
ARG NGINX_BASE_IMAGE=nginx:alpine
|
||||
FROM ${NODE_BASE_IMAGE} AS builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
@@ -6,10 +8,10 @@ RUN npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
FROM ${NGINX_BASE_IMAGE}
|
||||
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
Vendored
+2
-2
@@ -10,8 +10,8 @@
|
||||
<meta name="apple-mobile-web-app-title" content="AI工作台" />
|
||||
<link rel="manifest" href="/manifest.webmanifest" />
|
||||
<title>AI工作台</title>
|
||||
<script type="module" crossorigin src="/assets/index-cKdfgj1g.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DY8VTReJ.css">
|
||||
<script type="module" crossorigin src="/assets/index-grYi-CaK.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/assets/index-DvLiupE9.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
|
||||
Vendored
-1
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 1.5 KiB |
+8
-3
@@ -1,6 +1,9 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
client_max_body_size 100m;
|
||||
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
|
||||
# 静态资源服务
|
||||
location / {
|
||||
@@ -11,9 +14,11 @@ server {
|
||||
|
||||
# API 代理到后端
|
||||
location /api/ {
|
||||
# 注意: 这里使用 Docker Compose 服务名
|
||||
# 使用 /api/ 后缀确保传递完整路径
|
||||
proxy_pass http://hxops-backend:5000/api/;
|
||||
# 通过 Docker 内置 DNS 动态解析后端服务,避免后端容器重建后
|
||||
# Nginx 继续使用启动时缓存的旧 IP 而出现 502。
|
||||
set $backend_upstream hxops-backend:5000;
|
||||
# 变量形式下不要附带 URI,保留原始 /api/... 路径透传给后端。
|
||||
proxy_pass http://$backend_upstream;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
Generated
-8
@@ -542,7 +542,6 @@
|
||||
"integrity": "sha512-oH72nZRfDv9lADUBSo104Aq7gPHpQZc4BTx38r9xf9pg5LfP6EzSyH2n7qFmmxRQXh7YlUXODcYsg6PuTDSxGg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"undici-types": "~7.16.0"
|
||||
}
|
||||
@@ -949,7 +948,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"baseline-browser-mapping": "^2.9.0",
|
||||
"caniuse-lite": "^1.0.30001759",
|
||||
@@ -2040,7 +2038,6 @@
|
||||
"resolved": "https://mirrors.tencent.com/npm/picomatch/-/picomatch-4.0.3.tgz",
|
||||
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
@@ -2085,7 +2082,6 @@
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.11",
|
||||
"picocolors": "^1.1.1",
|
||||
@@ -2444,7 +2440,6 @@
|
||||
"resolved": "https://mirrors.tencent.com/npm/tailwindcss/-/tailwindcss-3.4.17.tgz",
|
||||
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@alloc/quick-lru": "^5.2.0",
|
||||
"arg": "^5.0.2",
|
||||
@@ -2546,7 +2541,6 @@
|
||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
@@ -2605,7 +2599,6 @@
|
||||
"integrity": "sha512-RHX7IvsJlEfjyA1rS7MY0UsmF91etdLAamslHR5lfuO3W/BXRdXm2tRE64ztpSPZbKqB4wAAZ0AwtF6QzfKZLA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@oxc-project/runtime": "0.114.0",
|
||||
"lightningcss": "^1.31.1",
|
||||
@@ -2691,7 +2684,6 @@
|
||||
"resolved": "https://mirrors.tencent.com/npm/vue/-/vue-3.5.28.tgz",
|
||||
"integrity": "sha512-BRdrNfeoccSoIZeIhyPBfvWSLFP4q8J3u8Ju8Ug5vu3LdD+yTM13Sg4sKtljxozbnuMu1NB1X5HBHRYUzFocKg==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@vue/compiler-dom": "3.5.28",
|
||||
"@vue/compiler-sfc": "3.5.28",
|
||||
|
||||
+8
-44
@@ -1,53 +1,17 @@
|
||||
const CACHE_NAME = 'hxops-shell-v2';
|
||||
const OFFLINE_ASSETS = ['/', '/workspace', '/manifest.webmanifest', '/vite.svg'];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME).then((cache) => cache.addAll(OFFLINE_ASSETS)).catch(() => null)
|
||||
self.skipWaiting()
|
||||
);
|
||||
self.skipWaiting();
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys().then((keys) =>
|
||||
Promise.all(
|
||||
keys
|
||||
.filter((key) => key !== CACHE_NAME)
|
||||
.map((key) => caches.delete(key))
|
||||
)
|
||||
)
|
||||
);
|
||||
self.clients.claim();
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const request = event.request;
|
||||
if (request.method !== 'GET') return;
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== self.location.origin) return;
|
||||
if (url.pathname.startsWith('/api/')) return;
|
||||
if (url.pathname.startsWith('/@vite/')) return;
|
||||
if (url.pathname.includes('/__vite_ping')) return;
|
||||
|
||||
if (request.mode === 'navigate') {
|
||||
event.respondWith(
|
||||
fetch(request).catch(() => caches.match('/workspace').then((res) => res || caches.match('/')))
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
event.respondWith(
|
||||
caches.match(request).then((cached) => {
|
||||
if (cached) return cached;
|
||||
return fetch(request)
|
||||
.then((response) => {
|
||||
const copy = response.clone();
|
||||
caches.open(CACHE_NAME).then((cache) => cache.put(request, copy)).catch(() => null);
|
||||
return response;
|
||||
})
|
||||
.catch(() => caches.match('/vite.svg'));
|
||||
})
|
||||
(async () => {
|
||||
const keys = await caches.keys();
|
||||
await Promise.all(keys.map((key) => caches.delete(key)));
|
||||
await self.clients.claim();
|
||||
const registrations = await self.registration.unregister();
|
||||
return registrations;
|
||||
})()
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,557 @@
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
|
||||
export interface KbGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
department_id?: number | null;
|
||||
document_count?: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentItem {
|
||||
id: number;
|
||||
group_id?: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string;
|
||||
source_type?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string;
|
||||
version_count?: number;
|
||||
latest_version?: KbDocumentVersionItem | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentVersionItem {
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
status: string;
|
||||
is_current: boolean;
|
||||
source_file_name: string;
|
||||
source_file_ext?: string | null;
|
||||
source_file_size?: number | null;
|
||||
sha256?: string | null;
|
||||
cleaned_file_path?: string | null;
|
||||
cleaned_preview_path?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbSyncRecordItem {
|
||||
id: number;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id: number;
|
||||
dataset_id: string;
|
||||
dataset_name?: string | null;
|
||||
remote_document_id: string;
|
||||
remote_document_name?: string | null;
|
||||
status: string;
|
||||
sync_hash?: string | null;
|
||||
error_message?: string | null;
|
||||
synced_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentMarkdown {
|
||||
document_id: number;
|
||||
title: string;
|
||||
version: KbDocumentVersionItem | null;
|
||||
content: string;
|
||||
kind: 'markdown' | 'preview';
|
||||
}
|
||||
|
||||
export interface KbJob {
|
||||
id: number | string;
|
||||
job_type: string;
|
||||
status: string;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id?: number | null;
|
||||
progress?: number;
|
||||
message?: string | null;
|
||||
error_message?: string | null;
|
||||
payload_json?: Record<string, any> | null;
|
||||
result_json?: Record<string, any> | null;
|
||||
created_at?: string;
|
||||
started_at?: string | null;
|
||||
finished_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDifySettings {
|
||||
DIFY_API_BASE: string;
|
||||
DIFY_API_KEY: string;
|
||||
KB_DIFY_PERMISSION: string;
|
||||
KB_DIFY_INDEXING_TECHNIQUE: string;
|
||||
KB_DIFY_SEARCH_METHOD: string;
|
||||
KB_DIFY_DOC_FORM: string;
|
||||
dify_api_configured?: boolean;
|
||||
}
|
||||
|
||||
export interface KbDifyHealth {
|
||||
dify_base_url: string;
|
||||
dify_api_configured: boolean;
|
||||
api: {
|
||||
configured: boolean;
|
||||
reachable: boolean;
|
||||
dataset_count?: number | null;
|
||||
error?: string | null;
|
||||
};
|
||||
local_sync_health: {
|
||||
dataset_bound_groups: number;
|
||||
sync_records: number;
|
||||
syncing_versions: number;
|
||||
synced_versions: number;
|
||||
failed_sync_records: number;
|
||||
pending_sync_jobs: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface KbListResponse<T> {
|
||||
ok: boolean;
|
||||
data: T;
|
||||
error?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
||||
try {
|
||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
||||
if (!res.ok) return fallback;
|
||||
return (await res.json()) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
||||
try {
|
||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: data?.error || '知识库接口请求失败',
|
||||
status: res.status,
|
||||
};
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as T, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbGroups = async (): Promise<KbGroup[]> => {
|
||||
return getJson<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
|
||||
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
|
||||
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
|
||||
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const createKbGroup = async (payload: {
|
||||
name: string;
|
||||
description?: string;
|
||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const res = await fetch('/api/kb/groups', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '创建知识库分组失败' };
|
||||
}
|
||||
return { ok: true, group: (await res.json()) as KbGroup };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbJobs = async (): Promise<KbJob[]> => {
|
||||
return getJson<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
|
||||
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
|
||||
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
|
||||
};
|
||||
|
||||
export const updateKbDifySettings = async (
|
||||
payload: Partial<KbDifySettings>
|
||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||
try {
|
||||
const res = await fetch('/api/kb/dify/settings', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '保存 Dify 设置失败' };
|
||||
}
|
||||
return { ok: true, settings: (await res.json()) as KbDifySettings };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
|
||||
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
|
||||
};
|
||||
|
||||
export const runKbJob = async (
|
||||
jobId: number | string
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/jobs/${jobId}/run`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '执行任务失败' };
|
||||
}
|
||||
const job = (await res.json()) as KbJob & { run_result?: string };
|
||||
return { ok: true, job, run_result: job.run_result };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbDocument = async (
|
||||
groupId: number,
|
||||
payload: { title: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '创建文档失败' };
|
||||
}
|
||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocument = async (
|
||||
documentId: number,
|
||||
payload: { title: string; description?: string; status?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '更新文档失败' };
|
||||
}
|
||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbDocument = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '删除文档失败' };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentVersions = async (
|
||||
documentId: number
|
||||
): Promise<KbDocumentVersionItem[]> => {
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '读取原始文件失败' };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentSyncRecords = async (
|
||||
documentId: number
|
||||
): Promise<KbSyncRecordItem[]> => {
|
||||
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentMarkdown = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' };
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocumentMarkdown = async (
|
||||
documentId: number,
|
||||
payload: { content: string }
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '保存 Markdown 失败' };
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbDocumentVersion = async (
|
||||
documentId: number,
|
||||
file: File
|
||||
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
if (res.status === 413) {
|
||||
return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status };
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '上传文档版本失败', status: res.status };
|
||||
}
|
||||
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbPathUploadJob = async (
|
||||
groupId: number,
|
||||
payload: { total_files: number; selected_paths: string[] }
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status };
|
||||
}
|
||||
return { ok: true, job: data as KbJob, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
file: File,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('relative_path', relativePath);
|
||||
|
||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
body: formData,
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '上传路径文件失败' };
|
||||
}
|
||||
return { ok: true, job: data as KbJob };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const finalizeKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '提交路径上传任务失败' };
|
||||
}
|
||||
return { ok: true, job: data as KbJob };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const retryFailedKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
payload?: { relative_paths?: string[] },
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '重试失败文件失败', status: res.status };
|
||||
}
|
||||
return { ok: true, job: data as KbJob, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const syncKbDocumentToDify = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/sync`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' };
|
||||
}
|
||||
const job = (await res.json()) as KbJob & { run_result?: string };
|
||||
return { ok: true, job, run_result: job.run_result };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbGroup = async (
|
||||
groupId: number,
|
||||
payload: { name: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '更新知识库分组失败' };
|
||||
}
|
||||
return { ok: true, group: (await res.json()) as KbGroup };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbGroup = async (
|
||||
groupId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '删除知识库分组失败' };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue';
|
||||
import { getKbDifyHealth, type KbDifyHealth } from '../../api/kb';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
error: [message: string];
|
||||
}>();
|
||||
|
||||
const loading = ref(false);
|
||||
const payload = ref<KbDifyHealth | null>(null);
|
||||
|
||||
const close = () => emit('close');
|
||||
|
||||
const loadHealth = async () => {
|
||||
loading.value = true;
|
||||
payload.value = await getKbDifyHealth();
|
||||
loading.value = false;
|
||||
if (!payload.value) {
|
||||
emit('error', '加载 Dify 健康状态失败');
|
||||
}
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) {
|
||||
void loadHealth();
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
|
||||
@click="close"
|
||||
>
|
||||
<div class="w-full max-w-4xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 健康检查</h3>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
查看知识库模块当前的 Dify 连接情况和本地同步概况。
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="loadHealth">
|
||||
刷新
|
||||
</button>
|
||||
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在检测...</div>
|
||||
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dify API</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.api.reachable ? '可访问' : '不可访问' }}
|
||||
</div>
|
||||
<div class="mt-2 break-all text-xs text-slate-500 dark:text-slate-400">
|
||||
{{ payload.dify_base_url || '未配置' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Dataset 数量</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.api.dataset_count ?? '--' }}
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
|
||||
配置完成:{{ payload.dify_api_configured ? '是' : '否' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已绑定分组</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.local_sync_health.dataset_bound_groups }}
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-slate-500 dark:text-slate-400">
|
||||
本地同步记录:{{ payload.local_sync_health.sync_records }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">同步中版本</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.local_sync_health.syncing_versions }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">已同步版本</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.local_sync_health.synced_versions }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">待同步任务</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-slate-900 dark:text-slate-100">
|
||||
{{ payload.local_sync_health.pending_sync_jobs }}
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-rose-500" v-if="payload.api.error">
|
||||
{{ payload.api.error }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,134 @@
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, watch } from 'vue';
|
||||
import { getKbDifySettings, updateKbDifySettings } from '../../api/kb';
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: [];
|
||||
saved: [message: string];
|
||||
error: [message: string];
|
||||
}>();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const form = reactive({
|
||||
DIFY_API_BASE: '',
|
||||
DIFY_API_KEY: '',
|
||||
KB_DIFY_PERMISSION: 'only_me',
|
||||
KB_DIFY_INDEXING_TECHNIQUE: 'high_quality',
|
||||
KB_DIFY_SEARCH_METHOD: 'semantic_search',
|
||||
KB_DIFY_DOC_FORM: 'text_model',
|
||||
});
|
||||
|
||||
const close = () => emit('close');
|
||||
|
||||
const loadSettings = async () => {
|
||||
loading.value = true;
|
||||
const settings = await getKbDifySettings();
|
||||
loading.value = false;
|
||||
if (!settings) {
|
||||
emit('error', '加载 Dify 设置失败');
|
||||
return;
|
||||
}
|
||||
Object.assign(form, settings);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
saving.value = true;
|
||||
const result = await updateKbDifySettings(form);
|
||||
saving.value = false;
|
||||
if (!result.ok) {
|
||||
emit('error', result.error || '保存 Dify 设置失败');
|
||||
return;
|
||||
}
|
||||
emit('saved', 'Dify 设置已保存');
|
||||
emit('close');
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) {
|
||||
void loadSettings();
|
||||
}
|
||||
}
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-slate-950/35 px-4 py-8 backdrop-blur-sm"
|
||||
@click="close"
|
||||
>
|
||||
<div class="w-full max-w-3xl rounded-3xl border border-slate-200 bg-white p-6 shadow-xl dark:border-slate-700 dark:bg-slate-900" @click.stop>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">Dify 设置</h3>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
管理知识库模块使用的 Dify 连接和默认同步参数。
|
||||
</p>
|
||||
</div>
|
||||
<button class="rounded-2xl border border-slate-200 px-3 py-2 text-sm text-slate-600 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800" @click="close">
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="py-16 text-center text-sm text-slate-400">正在加载设置...</div>
|
||||
<div v-else class="mt-6 grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify Base URL</span>
|
||||
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
|
||||
</label>
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Dify API Key</span>
|
||||
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Permission</span>
|
||||
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
|
||||
<option value="only_me">only_me</option>
|
||||
<option value="all_team_members">all_team_members</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Indexing Technique</span>
|
||||
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
|
||||
<option value="high_quality">high_quality</option>
|
||||
<option value="economy">economy</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Search Method</span>
|
||||
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
|
||||
<option value="semantic_search">semantic_search</option>
|
||||
<option value="hybrid_search">hybrid_search</option>
|
||||
<option value="full_text_search">full_text_search</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">Doc Form</span>
|
||||
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
|
||||
<option value="text_model">text_model</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button class="rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800" @click="close">
|
||||
取消
|
||||
</button>
|
||||
<button
|
||||
class="rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:disabled="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ saving ? '保存中...' : '保存设置' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+13
-6
@@ -1,4 +1,4 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createApp } from 'vue'
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
@@ -52,10 +52,17 @@ createApp(App)
|
||||
.use(i18n)
|
||||
.mount('#app')
|
||||
|
||||
if (import.meta.env.PROD && 'serviceWorker' in navigator) {
|
||||
window.addEventListener('load', () => {
|
||||
navigator.serviceWorker.register('/sw.js').catch((err) => {
|
||||
console.error('Service worker registration failed:', err);
|
||||
});
|
||||
if ('serviceWorker' in navigator) {
|
||||
window.addEventListener('load', async () => {
|
||||
try {
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
await Promise.all(registrations.map((registration) => registration.unregister()));
|
||||
if ('caches' in window) {
|
||||
const cacheKeys = await window.caches.keys();
|
||||
await Promise.all(cacheKeys.map((key) => window.caches.delete(key)));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Service worker cleanup failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import ChatView from '../views/ChatView.vue';
|
||||
import AdminView from '../views/AdminView.vue';
|
||||
import ProfileView from '../views/ProfileView.vue';
|
||||
import ResetPasswordView from '../views/ResetPasswordView.vue';
|
||||
import KbWorkspaceView from '../views/KbWorkspaceView.vue';
|
||||
import KbAdminView from '../views/KbAdminView.vue';
|
||||
import { config } from '../config';
|
||||
import { getStoredAuthUser } from '../utils/auth';
|
||||
|
||||
@@ -45,6 +47,18 @@ const routes = [
|
||||
name: 'Admin',
|
||||
component: AdminView
|
||||
},
|
||||
{
|
||||
path: '/kb/workspace',
|
||||
name: 'KbWorkspace',
|
||||
component: KbWorkspaceView,
|
||||
meta: { title: '知识库工作台' }
|
||||
},
|
||||
{
|
||||
path: '/kb/admin',
|
||||
name: 'KbAdmin',
|
||||
component: KbAdminView,
|
||||
meta: { title: '知识库管理台' }
|
||||
},
|
||||
|
||||
];
|
||||
|
||||
|
||||
@@ -2544,6 +2544,13 @@ const handlePermissionImport = async (event: Event) => {
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-4">
|
||||
<button
|
||||
@click="router.push('/kb/admin')"
|
||||
class="hidden md:inline-flex items-center gap-2 rounded-xl border border-slate-200 px-4 py-2 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-slate-100"
|
||||
>
|
||||
<Settings2 class="w-4 h-4" />
|
||||
<span>知识库管理</span>
|
||||
</button>
|
||||
<ThemeToggleButton />
|
||||
<!-- Language Selector -->
|
||||
<div class="flex items-center gap-2">
|
||||
|
||||
+559
-152
@@ -10,10 +10,10 @@
|
||||
* - 支持从首页携带预设问题快速发起对话
|
||||
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
|
||||
*/
|
||||
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
|
||||
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useChat } from '../composables/useChat';
|
||||
import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink } from 'lucide-vue-next';
|
||||
import { Send, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, ChevronDown, Sparkles, Database, Mic, LogOut, MessageSquareText, Globe, ExternalLink, Search } from 'lucide-vue-next';
|
||||
import { marked } from 'marked';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { config } from '../config';
|
||||
@@ -32,6 +32,8 @@ const selectedKb = ref('企业知识库');
|
||||
const showKbDropdown = ref(false);
|
||||
const kbMenuRef = ref<HTMLElement | null>(null);
|
||||
const kbOptions = ['企业知识库', 'ERP知识库'];
|
||||
const chatScrollContainer = ref<HTMLElement | null>(null);
|
||||
let scrollToBottomFrame: number | null = null;
|
||||
|
||||
marked.setOptions({
|
||||
gfm: true,
|
||||
@@ -41,8 +43,10 @@ marked.setOptions({
|
||||
const currentUserDisplayName = computed(() => {
|
||||
const realName = currentUser.value?.real_name?.trim();
|
||||
if (realName) return realName;
|
||||
const aliasName = (currentUser.value as any)?.name?.trim?.() || (currentUser.value as any)?.wecom_name?.trim?.();
|
||||
if (aliasName) return aliasName;
|
||||
const username = currentUser.value?.username?.trim();
|
||||
if (username) return username;
|
||||
if (username && !/^\d+$/.test(username)) return username;
|
||||
return '当前用户';
|
||||
});
|
||||
|
||||
@@ -429,61 +433,47 @@ const { messages, isThinking, conversationId, sendMessage } = useChat();
|
||||
const input = ref('');
|
||||
const currentAgent = ref<any>(null);
|
||||
const showGeneralFeedbackDialog = ref(false);
|
||||
const showOALoginModal = ref(false);
|
||||
const oaLoginForm = ref({ username: '', password: '' });
|
||||
|
||||
const openOALoginModal = () => {
|
||||
oaLoginForm.value = {
|
||||
username: currentUserEmployeeId.value || currentUser.value?.username || '',
|
||||
password: ''
|
||||
};
|
||||
showOALoginModal.value = true;
|
||||
};
|
||||
const OA_LOGIN_URL = 'http://192.168.100.221:8888/login/Login.jsp?logintype=1';
|
||||
const OA_VERIFY_LOGIN_URL = 'http://192.168.100.221:8888/login/VerifyLogin.jsp';
|
||||
const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
|
||||
const OA_AUTO_LOGIN_USERNAME = '26040006';
|
||||
const OA_AUTO_LOGIN_PASSWORD = '26040006';
|
||||
const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
|
||||
|
||||
const submitOALogin = () => {
|
||||
if (!oaLoginForm.value.username || !oaLoginForm.value.password) {
|
||||
showMessageDialog('error', '请输入账号和密码');
|
||||
const openOALeaveRequestDirectly = () => {
|
||||
const popup = window.open(OA_LOGIN_URL, OA_AUTO_LOGIN_TARGET);
|
||||
if (!popup) {
|
||||
showMessageDialog('warning', '浏览器拦截了 OA 页面,请允许弹出窗口后重试。');
|
||||
return;
|
||||
}
|
||||
|
||||
// 要跳转的目标 OA 页面
|
||||
const targetUrl = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
|
||||
|
||||
// 创建隐藏表单进行 POST 提交到 OA 登录接口
|
||||
|
||||
const form = document.createElement('form');
|
||||
form.action = 'http://192.168.100.221:8888/login/VerifyLogin.jsp';
|
||||
form.action = OA_VERIFY_LOGIN_URL;
|
||||
form.method = 'POST';
|
||||
form.target = '_blank';
|
||||
|
||||
const inputLoginId = document.createElement('input');
|
||||
inputLoginId.type = 'hidden';
|
||||
inputLoginId.name = 'loginid';
|
||||
inputLoginId.value = oaLoginForm.value.username;
|
||||
form.appendChild(inputLoginId);
|
||||
|
||||
const inputPassword = document.createElement('input');
|
||||
inputPassword.type = 'hidden';
|
||||
inputPassword.name = 'userpassword';
|
||||
inputPassword.value = oaLoginForm.value.password;
|
||||
form.appendChild(inputPassword);
|
||||
|
||||
const inputGoPage = document.createElement('input');
|
||||
inputGoPage.type = 'hidden';
|
||||
inputGoPage.name = 'gopage';
|
||||
inputGoPage.value = targetUrl;
|
||||
form.appendChild(inputGoPage);
|
||||
|
||||
const inputLogintype = document.createElement('input');
|
||||
inputLogintype.type = 'hidden';
|
||||
inputLogintype.name = 'logintype';
|
||||
inputLogintype.value = '1';
|
||||
form.appendChild(inputLogintype);
|
||||
|
||||
form.target = OA_AUTO_LOGIN_TARGET;
|
||||
form.style.display = 'none';
|
||||
|
||||
const fields = {
|
||||
loginid: OA_AUTO_LOGIN_USERNAME,
|
||||
userpassword: OA_AUTO_LOGIN_PASSWORD,
|
||||
gopage: OA_LEAVE_APPLY_PATH,
|
||||
logintype: '1',
|
||||
};
|
||||
|
||||
Object.entries(fields).forEach(([name, value]) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'hidden';
|
||||
input.name = name;
|
||||
input.value = value;
|
||||
form.appendChild(input);
|
||||
});
|
||||
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
document.body.removeChild(form);
|
||||
|
||||
showOALoginModal.value = false;
|
||||
window.setTimeout(() => {
|
||||
form.submit();
|
||||
document.body.removeChild(form);
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const activeFeedbackMessageIndex = ref<number | null>(null);
|
||||
@@ -531,13 +521,18 @@ const LEAVE_RESULT_QUERY_URL = 'http://192.168.100.221:8888/';
|
||||
interface LeaveRequestFormData {
|
||||
applicantName: string;
|
||||
employeeId: string;
|
||||
applicantUid: string;
|
||||
applyTime: string;
|
||||
fillerName: string;
|
||||
agentUid: string;
|
||||
agentEmployeeId: string;
|
||||
agentName: string;
|
||||
leaveType: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
durationHours: number;
|
||||
isOutOfOffice: boolean;
|
||||
isWorkInjury: boolean;
|
||||
isOutOfOffice: 0 | 1 | null;
|
||||
isWorkInjury: 0 | 1 | null;
|
||||
}
|
||||
|
||||
interface LeaveFormPayload {
|
||||
@@ -559,9 +554,83 @@ interface LeaveResultPayload {
|
||||
success: boolean;
|
||||
referenceNo: string;
|
||||
submittedAt: string;
|
||||
requestName?: string;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
interface LeaveAgentOption {
|
||||
uid: string;
|
||||
employeeId: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
let leaveFlowCounter = 0;
|
||||
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
|
||||
const leaveAgentLoading = ref(false);
|
||||
const leaveAgentKeyword = ref('');
|
||||
const leaveAgentPage = ref(1);
|
||||
const leaveAgentHasMore = ref(true);
|
||||
|
||||
const fetchLeaveAgents = async (isLoadMore = false) => {
|
||||
if (leaveAgentLoading.value) return;
|
||||
if (!isLoadMore) {
|
||||
leaveAgentPage.value = 1;
|
||||
leaveAgentOptions.value = [];
|
||||
}
|
||||
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=${leaveAgentPage.value}&page_size=20&agent_id=${agentId}`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (isLoadMore) {
|
||||
leaveAgentOptions.value.push(...data.items);
|
||||
} else {
|
||||
leaveAgentOptions.value = data.items;
|
||||
}
|
||||
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load OA employees', e);
|
||||
} finally {
|
||||
leaveAgentLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleAgentSearch = () => {
|
||||
fetchLeaveAgents(false);
|
||||
};
|
||||
|
||||
const loadMoreAgents = () => {
|
||||
if (!leaveAgentHasMore.value) return;
|
||||
leaveAgentPage.value += 1;
|
||||
fetchLeaveAgents(true);
|
||||
};
|
||||
|
||||
const loadAllAgents = async () => {
|
||||
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=1&page_size=100000&agent_id=${agentId}`, {
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
leaveAgentOptions.value = data.items;
|
||||
leaveAgentHasMore.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to load all OA employees', e);
|
||||
} finally {
|
||||
leaveAgentLoading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const showLeaveAgentDialog = ref(false);
|
||||
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
|
||||
const activeLeaveAgentFormId = ref<string | null>(null);
|
||||
|
||||
const formatDateTime = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
@@ -605,13 +674,18 @@ const createLeaveFormData = (): LeaveRequestFormData => {
|
||||
return {
|
||||
applicantName: currentUserDisplayName.value,
|
||||
employeeId: currentUserEmployeeId.value,
|
||||
applicantUid: '',
|
||||
applyTime: formatDateTime(now),
|
||||
fillerName: currentUserDisplayName.value,
|
||||
agentUid: '',
|
||||
agentEmployeeId: '',
|
||||
agentName: '',
|
||||
leaveType: '',
|
||||
startTime,
|
||||
endTime,
|
||||
durationHours: calculateDurationHours(startTime, endTime),
|
||||
isOutOfOffice: false,
|
||||
isWorkInjury: false,
|
||||
isOutOfOffice: 1,
|
||||
isWorkInjury: 1,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -628,10 +702,45 @@ const getLeaveIntentNormalized = (content: string) => (content || '').replace(/\
|
||||
|
||||
const isStrongLeaveIntent = (content: string) => {
|
||||
const normalized = getLeaveIntentNormalized(content);
|
||||
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|我要走请假流程)/.test(normalized);
|
||||
// 弱意图(咨询流程/步骤)应走正常问答,不触发表单分流。
|
||||
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定)/;
|
||||
if (weakConsultationIntent.test(normalized)) return false;
|
||||
if (/^(请假|休假)$/.test(normalized)) return true;
|
||||
return /(我要请假|申请请假|发起请假|请假申请|我要休假|申请休假|我要请个假|想请假|帮我请假|代我请假|提交请假)/.test(normalized);
|
||||
};
|
||||
|
||||
const startLocalLeaveFlow = (content: string) => {
|
||||
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
|
||||
try {
|
||||
const res = await fetch('/api/chat/messages/local', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({
|
||||
conversation_id: conversationId.value,
|
||||
type: msg.type,
|
||||
content: msg.content,
|
||||
payload: msg.payload,
|
||||
query: userQuery,
|
||||
agent_id: agentId
|
||||
})
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (!conversationId.value && data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
msg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
}
|
||||
};
|
||||
|
||||
const startLocalLeaveFlow = async (content: string) => {
|
||||
const formId = newLocalMessageId('leave-form');
|
||||
const payload: LeaveFormPayload = {
|
||||
formId,
|
||||
@@ -639,15 +748,34 @@ const startLocalLeaveFlow = (content: string) => {
|
||||
submitting: false,
|
||||
confirmationGenerated: false,
|
||||
};
|
||||
|
||||
messages.value.push({ role: 'user', content, type: 'text' });
|
||||
messages.value.push({
|
||||
role: 'assistant',
|
||||
type: 'leave-form',
|
||||
const formMsg = {
|
||||
role: 'assistant' as const,
|
||||
type: 'leave-form' as const,
|
||||
content: '已为你生成请假申请表,请直接在下方填写并提交。或登录OA系统直接申请',
|
||||
payload,
|
||||
local_id: formId,
|
||||
local_only: true,
|
||||
});
|
||||
};
|
||||
messages.value.push(formMsg);
|
||||
|
||||
await saveLocalMessageToBackend(formMsg, content);
|
||||
|
||||
// 发送完成后刷新历史记录,确保新会话出现
|
||||
if (history.value.length === 0 || !history.value.some(h => h.conversation_id === conversationId.value)) {
|
||||
await loadHistory();
|
||||
}
|
||||
};
|
||||
|
||||
const handleChatMarkdownClick = (event: MouseEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
|
||||
if (!actionElement) return;
|
||||
const action = actionElement.getAttribute('data-leave-action');
|
||||
if (action !== 'start-leave-flow' || isThinking.value) return;
|
||||
event.preventDefault();
|
||||
startLocalLeaveFlow('我要请假');
|
||||
};
|
||||
|
||||
const getLeaveFormPayload = (msg: any): LeaveFormPayload | null => (
|
||||
@@ -662,13 +790,101 @@ const getLeaveResultPayload = (msg: any): LeaveResultPayload | null => (
|
||||
msg?.type === 'leave-result' && msg?.payload ? msg.payload as LeaveResultPayload : null
|
||||
);
|
||||
|
||||
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId);
|
||||
const findMessageIndexByLocalId = (localId: string) => messages.value.findIndex((msg: any) => msg?.local_id === localId || msg?.payload?.formId === localId);
|
||||
|
||||
const getLeaveAgentDisplayValue = (form: LeaveRequestFormData) => {
|
||||
if (!form.agentName) return '';
|
||||
const parts = [form.agentName];
|
||||
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
|
||||
return parts.join(' / ');
|
||||
};
|
||||
|
||||
const formatYesNoLabel = (value: 0 | 1 | null) => {
|
||||
if (value === 0) return '是';
|
||||
if (value === 1) return '否';
|
||||
return '未选择';
|
||||
};
|
||||
|
||||
const syncCurrentUserProfile = async () => {
|
||||
if (currentUser.value?.real_name?.trim()) return;
|
||||
try {
|
||||
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
currentUser.value = { ...currentUser.value, ...data };
|
||||
} catch (e) {
|
||||
console.error('Failed to load current user profile', e);
|
||||
}
|
||||
};
|
||||
|
||||
const openLeaveAgentDialog = (msg: any, role: 'agent' | 'applicant' = 'agent') => {
|
||||
const payload = getLeaveFormPayload(msg);
|
||||
if (!payload || payload.submitting || payload.confirmationGenerated) return;
|
||||
activeLeaveAgentFormId.value = payload.formId;
|
||||
leaveUserSelectRole.value = role;
|
||||
showLeaveAgentDialog.value = true;
|
||||
|
||||
leaveAgentKeyword.value = '';
|
||||
fetchLeaveAgents(false);
|
||||
};
|
||||
|
||||
const closeLeaveAgentDialog = () => {
|
||||
showLeaveAgentDialog.value = false;
|
||||
activeLeaveAgentFormId.value = null;
|
||||
};
|
||||
|
||||
const selectLeaveAgent = (option: LeaveAgentOption) => {
|
||||
if (!activeLeaveAgentFormId.value) return;
|
||||
const sourceIndex = findMessageIndexByLocalId(activeLeaveAgentFormId.value);
|
||||
if (sourceIndex < 0) {
|
||||
closeLeaveAgentDialog();
|
||||
return;
|
||||
}
|
||||
const payload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||||
if (!payload) {
|
||||
closeLeaveAgentDialog();
|
||||
return;
|
||||
}
|
||||
|
||||
if (leaveUserSelectRole.value === 'agent') {
|
||||
payload.form.agentUid = option.uid;
|
||||
payload.form.agentEmployeeId = option.employeeId;
|
||||
payload.form.agentName = option.name;
|
||||
} else {
|
||||
payload.form.applicantUid = option.uid;
|
||||
payload.form.employeeId = option.employeeId;
|
||||
payload.form.applicantName = option.name;
|
||||
}
|
||||
|
||||
closeLeaveAgentDialog();
|
||||
saveLocalMessageToBackend(messages.value[sourceIndex]);
|
||||
};
|
||||
|
||||
const browserPanelStyle = computed(() => {
|
||||
if (viewportWidth.value < 1024) return undefined;
|
||||
return { width: `${browserPanelWidth.value}px` };
|
||||
});
|
||||
|
||||
const scrollChatToBottom = async () => {
|
||||
await nextTick();
|
||||
const container = chatScrollContainer.value;
|
||||
if (!container) return;
|
||||
container.scrollTo({
|
||||
top: container.scrollHeight,
|
||||
behavior: 'auto',
|
||||
});
|
||||
};
|
||||
|
||||
const scheduleScrollChatToBottom = () => {
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
}
|
||||
scrollToBottomFrame = window.requestAnimationFrame(() => {
|
||||
scrollToBottomFrame = null;
|
||||
void scrollChatToBottom();
|
||||
});
|
||||
};
|
||||
|
||||
const normalizeBrowserInput = (value: string) => {
|
||||
const raw = (value || '').trim();
|
||||
if (!raw) return '';
|
||||
@@ -820,12 +1036,13 @@ const handleSend = async (textOrEvent?: string | Event) => {
|
||||
};
|
||||
|
||||
const validateLeaveForm = (form: LeaveRequestFormData) => {
|
||||
if (!form.applicantName.trim()) return '申请人不能为空。';
|
||||
if (!form.applicantName.trim()) return '请假人不能为空。';
|
||||
if (!form.employeeId.trim()) return '工号不能为空。';
|
||||
if (!form.leaveType.trim()) return '请选择假别。';
|
||||
if (!parseDateTime(form.startTime)) return '开始时间格式不正确。';
|
||||
if (!parseDateTime(form.endTime)) return '结束时间格式不正确。';
|
||||
if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '结束时间必须晚于开始时间。';
|
||||
if (!form.agentUid.trim()) return '请选择代理人。';
|
||||
if (!parseDateTime(form.startTime)) return '请选择正确的开始时间。';
|
||||
if (!parseDateTime(form.endTime)) return '请选择正确的结束时间。';
|
||||
if (calculateDurationHours(form.startTime, form.endTime) <= 0) return '时长必须大于0小时,请检查开始时间和结束时间。';
|
||||
return '';
|
||||
};
|
||||
|
||||
@@ -846,9 +1063,9 @@ const submitLeaveForm = (msg: any) => {
|
||||
|
||||
payload.confirmationGenerated = true;
|
||||
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
|
||||
messages.value.push({
|
||||
role: 'assistant',
|
||||
type: 'leave-confirmation',
|
||||
const confirmMsg = {
|
||||
role: 'assistant' as const,
|
||||
type: 'leave-confirmation' as const,
|
||||
content: '请确认以下请假信息,确认无误后再提交到 OA。',
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
@@ -857,7 +1074,12 @@ const submitLeaveForm = (msg: any) => {
|
||||
},
|
||||
local_id: newLocalMessageId('leave-confirm'),
|
||||
local_only: true,
|
||||
});
|
||||
};
|
||||
messages.value.push(confirmMsg);
|
||||
|
||||
// 保存更新后的表单消息和新的确认消息
|
||||
saveLocalMessageToBackend(msg);
|
||||
saveLocalMessageToBackend(confirmMsg);
|
||||
};
|
||||
|
||||
const editLeaveConfirmation = (msg: any, index: number) => {
|
||||
@@ -868,8 +1090,14 @@ const editLeaveConfirmation = (msg: any, index: number) => {
|
||||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.confirmationGenerated = false;
|
||||
saveLocalMessageToBackend(messages.value[sourceIndex]);
|
||||
}
|
||||
}
|
||||
|
||||
// 从后端删除对应的确认消息,或者不删除直接隐藏?
|
||||
// 暂时在前端移除,后端不需要立刻删除(如果没有删除接口),它在会话记录里可能残留。
|
||||
// 但是我们之前有 /api/chat/messages/local 吗?如果需要,也可以调一个删除接口。
|
||||
// 为了简单,我们只在前端切除。
|
||||
messages.value.splice(index, 1);
|
||||
};
|
||||
|
||||
@@ -887,29 +1115,65 @@ const confirmLeaveSubmission = async (msg: any) => {
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise((resolve) => window.setTimeout(resolve, 900));
|
||||
try {
|
||||
const res = await fetch('/api/user/leave-workflow/submit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload.form),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.error || 'OA 请假提交失败,请稍后重试。');
|
||||
}
|
||||
|
||||
const referenceNo = `OA-${Date.now().toString().slice(-8)}`;
|
||||
messages.value.push({
|
||||
role: 'assistant',
|
||||
type: 'leave-result',
|
||||
content: `请假单已生成,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。\n\n当前为前端演示提交流程,真实 OA 对接开发中。`,
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
success: true,
|
||||
referenceNo,
|
||||
submittedAt: formatDateTime(new Date()),
|
||||
},
|
||||
local_id: newLocalMessageId('leave-result'),
|
||||
local_only: true,
|
||||
});
|
||||
|
||||
payload.submitting = false;
|
||||
payload.confirmed = true;
|
||||
if (sourceIndex >= 0) {
|
||||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.submitting = false;
|
||||
const resultMsg = {
|
||||
role: 'assistant' as const,
|
||||
type: 'leave-result' as const,
|
||||
content: `请假单已提交到 OA,具体单据请到 ${LEAVE_RESULT_QUERY_URL} 查询。`,
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
success: true,
|
||||
referenceNo: data.request_id || '-',
|
||||
submittedAt: data.submitted_at || formatDateTime(new Date()),
|
||||
requestName: data.request_name || '',
|
||||
},
|
||||
local_id: newLocalMessageId('leave-result'),
|
||||
local_only: true,
|
||||
};
|
||||
messages.value.push(resultMsg);
|
||||
payload.confirmed = true;
|
||||
payload.submitting = false; // Add this line to immediately clear submitting state on success
|
||||
saveLocalMessageToBackend(msg);
|
||||
saveLocalMessageToBackend(resultMsg);
|
||||
} catch (error: any) {
|
||||
const errorMessage = error?.message || 'OA 请假提交失败,请稍后重试。';
|
||||
showMessageDialog('error', errorMessage);
|
||||
const resultMsg = {
|
||||
role: 'assistant' as const,
|
||||
type: 'leave-result' as const,
|
||||
content: `请假单提交失败:${errorMessage}`,
|
||||
payload: {
|
||||
formId: payload.formId,
|
||||
success: false,
|
||||
referenceNo: '-',
|
||||
submittedAt: formatDateTime(new Date()),
|
||||
errorMessage,
|
||||
},
|
||||
local_id: newLocalMessageId('leave-result'),
|
||||
local_only: true,
|
||||
};
|
||||
messages.value.push(resultMsg);
|
||||
saveLocalMessageToBackend(resultMsg);
|
||||
} finally {
|
||||
payload.submitting = false;
|
||||
if (sourceIndex >= 0) {
|
||||
const sourcePayload = getLeaveFormPayload(messages.value[sourceIndex]);
|
||||
if (sourcePayload) {
|
||||
sourcePayload.submitting = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1026,6 +1290,7 @@ onMounted(async () => {
|
||||
document.addEventListener('mousedown', handleDocumentPointerDown);
|
||||
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
|
||||
window.addEventListener('resize', syncViewportWidth);
|
||||
await syncCurrentUserProfile();
|
||||
await loadAgent();
|
||||
|
||||
await loadHistory();
|
||||
@@ -1036,6 +1301,7 @@ onMounted(async () => {
|
||||
}
|
||||
// Use config from config.ts instead of API
|
||||
showChatRating.value = config.workspace?.showChatRating ?? true;
|
||||
scheduleScrollChatToBottom();
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
@@ -1043,8 +1309,26 @@ onBeforeUnmount(() => {
|
||||
document.removeEventListener('touchstart', handleDocumentPointerDown);
|
||||
window.removeEventListener('resize', syncViewportWidth);
|
||||
stopBrowserResize();
|
||||
if (scrollToBottomFrame !== null) {
|
||||
window.cancelAnimationFrame(scrollToBottomFrame);
|
||||
scrollToBottomFrame = null;
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => ({
|
||||
messageCount: messages.value.length,
|
||||
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
|
||||
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
|
||||
isThinking: isThinking.value,
|
||||
conversationId: conversationId.value || '',
|
||||
}),
|
||||
() => {
|
||||
scheduleScrollChatToBottom();
|
||||
},
|
||||
{ deep: false },
|
||||
);
|
||||
|
||||
/**
|
||||
* 反馈相关状态
|
||||
* showChatRating:是否启用评分功能(后续可接入配置)
|
||||
@@ -1217,9 +1501,13 @@ const showChatRating = ref(false);
|
||||
<div class="flex min-h-0 flex-1">
|
||||
<div class="flex min-h-0 flex-1 flex-col">
|
||||
<main
|
||||
ref="chatScrollContainer"
|
||||
class="flex-1 p-3 md:p-8"
|
||||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'space-y-2 overflow-y-auto scrollbar-thin md:space-y-6'"
|
||||
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
|
||||
>
|
||||
<div
|
||||
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
|
||||
>
|
||||
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16">
|
||||
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
|
||||
AI
|
||||
@@ -1230,14 +1518,9 @@ const showChatRating = ref(false);
|
||||
<template v-for="(msg, index) in messages" :key="index">
|
||||
<div
|
||||
v-if="shouldRenderMessage(msg)"
|
||||
class="group mx-auto flex max-w-4xl gap-4 animate-slide-up mb-6"
|
||||
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
|
||||
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
|
||||
>
|
||||
<!-- AI Avatar -->
|
||||
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/20">
|
||||
<Sparkles class="h-4 w-4" />
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex flex-col"
|
||||
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
|
||||
@@ -1256,7 +1539,7 @@ const showChatRating = ref(false);
|
||||
<div v-if="msg.type === 'leave-form'" class="space-y-4">
|
||||
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">
|
||||
<template v-if="msg.content.includes('或登录OA系统直接申请')">
|
||||
已为你生成请假申请表,请直接在下方填写并提交。或 <a href="#" @click.prevent="openOALoginModal" class="text-brand-600 font-bold hover:underline">登录OA系统直接申请</a>
|
||||
已为你生成请假申请表,请直接在下方填写并提交。或 <a href="#" @click.prevent="openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">登录OA系统直接申请</a>
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ msg.content }}
|
||||
@@ -1264,9 +1547,9 @@ const showChatRating = ref(false);
|
||||
</div>
|
||||
<div v-if="getLeaveFormPayload(msg)" class="grid gap-4 md:grid-cols-2">
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">申请人</span>
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">填单人</span>
|
||||
<input
|
||||
v-model="getLeaveFormPayload(msg)!.form.applicantName"
|
||||
v-model="getLeaveFormPayload(msg)!.form.fillerName"
|
||||
type="text"
|
||||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-500 outline-none dark:border-slate-700 dark:bg-slate-950/60 dark:text-slate-400"
|
||||
disabled
|
||||
@@ -1282,7 +1565,7 @@ const showChatRating = ref(false);
|
||||
/>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">申请时间</span>
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">创建时间</span>
|
||||
<input
|
||||
:value="getLeaveFormPayload(msg)!.form.applyTime.replace('T', ' ')"
|
||||
type="text"
|
||||
@@ -1301,6 +1584,52 @@ const showChatRating = ref(false);
|
||||
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">请假人</span>
|
||||
<div class="relative">
|
||||
<input
|
||||
:value="getLeaveFormPayload(msg)!.form.applicantName ? `${getLeaveFormPayload(msg)!.form.applicantName} / ${getLeaveFormPayload(msg)!.form.employeeId}` : ''"
|
||||
type="text"
|
||||
placeholder="请选择请假人"
|
||||
readonly
|
||||
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
@click="openLeaveAgentDialog(msg, 'applicant')"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
@click="openLeaveAgentDialog(msg, 'applicant')"
|
||||
title="选择请假人"
|
||||
>
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">代理人</span>
|
||||
<div class="relative">
|
||||
<input
|
||||
:value="getLeaveAgentDisplayValue(getLeaveFormPayload(msg)!.form)"
|
||||
type="text"
|
||||
placeholder="请选择代理人"
|
||||
readonly
|
||||
class="w-full rounded-xl border border-slate-200 bg-white px-3 py-2 pr-11 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
@click="openLeaveAgentDialog(msg)"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-slate-400 transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
@click="openLeaveAgentDialog(msg)"
|
||||
title="选择代理人"
|
||||
>
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="space-y-1.5">
|
||||
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">开始时间</span>
|
||||
<input
|
||||
@@ -1337,8 +1666,8 @@ const showChatRating = ref(false);
|
||||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
>
|
||||
<option :value="false">否</option>
|
||||
<option :value="true">是</option>
|
||||
<option :value="1">否</option>
|
||||
<option :value="0">是</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-1.5 md:col-span-2">
|
||||
@@ -1348,8 +1677,8 @@ const showChatRating = ref(false);
|
||||
class="w-full rounded-xl border border-slate-200 px-3 py-2 text-sm text-slate-700 outline-none transition focus:border-blue-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||||
:disabled="getLeaveFormPayload(msg)!.submitting || getLeaveFormPayload(msg)!.confirmationGenerated"
|
||||
>
|
||||
<option :value="false">否</option>
|
||||
<option :value="true">是</option>
|
||||
<option :value="1">否</option>
|
||||
<option :value="0">是</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
@@ -1370,14 +1699,16 @@ const showChatRating = ref(false);
|
||||
<div class="text-sm font-medium text-slate-700 dark:text-slate-200">{{ msg.content }}</div>
|
||||
<div class="rounded-2xl border border-slate-200 bg-slate-50/90 p-4 dark:border-slate-700 dark:bg-slate-800/60">
|
||||
<div class="grid gap-3 text-sm md:grid-cols-2">
|
||||
<div><span class="text-slate-500 dark:text-slate-400">申请人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">申请时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">填单人:</span>{{ getLeaveConfirmationPayload(msg)!.form.fillerName || '暂无数据' }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">创建时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.applyTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">请假人:</span>{{ getLeaveConfirmationPayload(msg)!.form.applicantName }}({{ getLeaveConfirmationPayload(msg)!.form.employeeId }})</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">代理人:</span>{{ getLeaveAgentDisplayValue(getLeaveConfirmationPayload(msg)!.form) || '未选择' }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">假别:</span>{{ getLeaveTypeLabel(getLeaveConfirmationPayload(msg)!.form.leaveType) }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">时长:</span>{{ formatDurationLabel(getLeaveConfirmationPayload(msg)!.form.durationHours) }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">开始时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.startTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">结束时间:</span>{{ getLeaveConfirmationPayload(msg)!.form.endTime.replace('T', ' ') }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">是否外出:</span>{{ getLeaveConfirmationPayload(msg)!.form.isOutOfOffice ? '是' : '否' }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">是否为工伤:</span>{{ getLeaveConfirmationPayload(msg)!.form.isWorkInjury ? '是' : '否' }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">是否外出:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isOutOfOffice) }}</div>
|
||||
<div><span class="text-slate-500 dark:text-slate-400">是否为工伤:</span>{{ formatYesNoLabel(getLeaveConfirmationPayload(msg)!.form.isWorkInjury) }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-3">
|
||||
@@ -1413,6 +1744,7 @@ const showChatRating = ref(false);
|
||||
<div
|
||||
v-else
|
||||
class="chat-markdown prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 dark:prose-code:bg-slate-800 dark:prose-code:text-blue-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
|
||||
@click="handleChatMarkdownClick"
|
||||
v-html="renderMarkdown(msg.content)"
|
||||
></div>
|
||||
</div>
|
||||
@@ -1527,18 +1859,10 @@ const showChatRating = ref(false);
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- User Avatar -->
|
||||
<div v-if="msg.role === 'user'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-brand-600 text-white shadow-sm shadow-brand-500/20">
|
||||
<User class="h-4 w-4" />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl gap-4">
|
||||
<div class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 shadow-md shadow-brand-500/25">
|
||||
<Bot class="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<div v-if="shouldShowThinkingBubble" class="mx-auto flex w-full max-w-4xl justify-start">
|
||||
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-5 py-3 shadow-md dark:border-slate-700 dark:bg-slate-900/85">
|
||||
<div class="flex gap-1">
|
||||
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400"></span>
|
||||
@@ -1548,7 +1872,8 @@ const showChatRating = ref(false);
|
||||
<span class="text-sm font-medium text-slate-500 dark:text-slate-300">{{ $t('chat.thinking') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="messages.length > 0" class="h-6 md:h-8"></div>
|
||||
<div v-if="messages.length > 0" class="h-2 md:h-3"></div>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
|
||||
@@ -1736,48 +2061,84 @@ const showChatRating = ref(false);
|
||||
showGeneralFeedbackDialog = false;
|
||||
}"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="showOALoginModal"
|
||||
v-if="showLeaveAgentDialog"
|
||||
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
|
||||
@click.self="closeLeaveAgentDialog"
|
||||
>
|
||||
<div class="w-full max-w-sm rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-900">
|
||||
<div class="mb-5 flex items-center justify-between">
|
||||
<h3 class="text-lg font-bold text-slate-800 dark:text-slate-100">登录OA系统</h3>
|
||||
<button @click="showOALoginModal = false" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
|
||||
<div class="flex w-full max-w-2xl max-h-[80vh] flex-col rounded-2xl bg-white p-6 shadow-2xl dark:bg-slate-900">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-slate-800 dark:text-slate-100">选择{{ leaveUserSelectRole === 'agent' ? '代理人' : '请假人' }}</h3>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">已接入 OA 数据库视图查询。</p>
|
||||
</div>
|
||||
<button @click="closeLeaveAgentDialog" class="text-slate-400 hover:text-slate-600 dark:hover:text-slate-200">
|
||||
<X class="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-sm font-semibold text-slate-600 dark:text-slate-300">账号</label>
|
||||
<input
|
||||
v-model="oaLoginForm.username"
|
||||
type="text"
|
||||
placeholder="请输入账号"
|
||||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-100"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-sm font-semibold text-slate-600 dark:text-slate-300">密码</label>
|
||||
<input
|
||||
v-model="oaLoginForm.password"
|
||||
type="password"
|
||||
placeholder="请输入密码"
|
||||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 text-sm outline-none focus:border-brand-500 focus:ring-1 focus:ring-brand-500 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-100"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
@click="submitOALogin"
|
||||
class="mt-2 w-full rounded-xl bg-brand-600 py-2.5 text-sm font-semibold text-white transition-colors hover:bg-brand-500"
|
||||
>
|
||||
确认登录
|
||||
|
||||
<div class="mb-4 relative shrink-0">
|
||||
<input
|
||||
v-model="leaveAgentKeyword"
|
||||
@keydown.enter="handleAgentSearch"
|
||||
type="text"
|
||||
placeholder="输入姓名或工号搜索,按回车键查询"
|
||||
class="w-full rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 pr-10 text-sm outline-none transition focus:border-brand-400 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-100"
|
||||
/>
|
||||
<button @click="handleAgentSearch" class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-slate-400 hover:text-brand-600">
|
||||
<Search class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
|
||||
<div v-if="leaveAgentLoading && leaveAgentPage === 1" class="flex justify-center py-8">
|
||||
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
|
||||
</div>
|
||||
<div v-else-if="leaveAgentOptions.length === 0" class="py-8 text-center text-sm text-slate-400">
|
||||
暂无数据
|
||||
</div>
|
||||
<template v-else>
|
||||
<button
|
||||
v-for="option in leaveAgentOptions"
|
||||
:key="option.uid"
|
||||
type="button"
|
||||
class="flex w-full items-center justify-between rounded-2xl border border-slate-200 px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50 dark:border-slate-700 dark:hover:border-brand-500/40 dark:hover:bg-brand-500/10"
|
||||
@click="selectLeaveAgent(option)"
|
||||
>
|
||||
<div class="space-y-1">
|
||||
<div class="text-sm font-semibold text-slate-800 dark:text-slate-100">{{ option.name }}</div>
|
||||
<div class="text-xs text-slate-500 dark:text-slate-400">UID:{{ option.uid }}</div>
|
||||
</div>
|
||||
<div class="text-right text-xs text-slate-500 dark:text-slate-400">
|
||||
<div>工号:{{ option.employeeId }}</div>
|
||||
<div>姓名:{{ option.name }}</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div v-if="leaveAgentHasMore" class="flex items-center justify-center space-x-6 py-4">
|
||||
<button
|
||||
@click="loadAllAgents"
|
||||
:disabled="leaveAgentLoading"
|
||||
class="text-xs text-slate-500 hover:text-slate-700 disabled:opacity-50 dark:text-slate-400 dark:hover:text-slate-300"
|
||||
>
|
||||
加载全部
|
||||
</button>
|
||||
<button
|
||||
@click="loadMoreAgents"
|
||||
:disabled="leaveAgentLoading"
|
||||
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
|
||||
>
|
||||
{{ leaveAgentLoading ? '加载中...' : '加载更多' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="py-4 text-center text-xs text-slate-400">没有更多数据了</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
|
||||
</template>
|
||||
<style scoped>
|
||||
:deep(.chat-markdown details) {
|
||||
margin-top: 1rem;
|
||||
@@ -1812,4 +2173,50 @@ const showChatRating = ref(false);
|
||||
:deep(.chat-markdown details pre) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-action-trigger) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin: 0 0.2rem;
|
||||
padding: 0.1rem 0.6rem;
|
||||
border-radius: 9999px;
|
||||
border: 1px solid rgb(59 130 246 / 0.28);
|
||||
background: rgb(239 246 255);
|
||||
color: rgb(29 78 216);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-action-trigger:hover) {
|
||||
background: rgb(219 234 254);
|
||||
border-color: rgb(59 130 246 / 0.4);
|
||||
}
|
||||
|
||||
:deep(.chat-markdown .leave-intent-highlight) {
|
||||
display: inline-block;
|
||||
margin: 0 0.2rem;
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 0.5rem;
|
||||
background: rgb(254 249 195);
|
||||
color: rgb(161 98 7);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-action-trigger) {
|
||||
border-color: rgb(96 165 250 / 0.35);
|
||||
background: rgb(30 41 59);
|
||||
color: rgb(147 197 253);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
|
||||
background: rgb(30 64 175 / 0.25);
|
||||
}
|
||||
|
||||
:deep(.dark .chat-markdown .leave-intent-highlight) {
|
||||
background: rgb(113 63 18 / 0.45);
|
||||
color: rgb(253 224 71);
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,360 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { ArrowLeft, FolderPlus, Pencil, Play, RefreshCw, Settings, Trash2, Wrench, X } from 'lucide-vue-next';
|
||||
import DifyHealthDialog from '../components/kb/DifyHealthDialog.vue';
|
||||
import DifySettingsDialog from '../components/kb/DifySettingsDialog.vue';
|
||||
import {
|
||||
createKbGroup,
|
||||
deleteKbGroup,
|
||||
getKbGroupsSafe,
|
||||
getKbJobsSafe,
|
||||
runKbJob,
|
||||
updateKbGroup,
|
||||
type KbGroup,
|
||||
type KbJob,
|
||||
} from '../api/kb';
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const groups = ref<KbGroup[]>([]);
|
||||
const jobs = ref<KbJob[]>([]);
|
||||
const isSubmitting = ref(false);
|
||||
const isRefreshing = ref(false);
|
||||
const editingGroupId = ref<number | null>(null);
|
||||
const form = ref({
|
||||
name: '',
|
||||
description: '',
|
||||
});
|
||||
const feedback = ref('');
|
||||
const feedbackType = ref<'success' | 'error' | ''>('');
|
||||
const runningJobId = ref<number | string | null>(null);
|
||||
const settingsDialogOpen = ref(false);
|
||||
const healthDialogOpen = ref(false);
|
||||
|
||||
const formTitle = computed(() => editingGroupId.value ? '编辑知识库分组' : '新建知识库分组');
|
||||
const formDescription = computed(() => editingGroupId.value
|
||||
? '修改知识库分组名称和描述,保存后会立即刷新列表。'
|
||||
: '用于验证主平台里的知识库管理入口和基础接口壳。');
|
||||
const submitText = computed(() => {
|
||||
if (isSubmitting.value) return editingGroupId.value ? '保存中...' : '提交中...';
|
||||
return editingGroupId.value ? '保存修改' : '创建分组';
|
||||
});
|
||||
|
||||
const loadData = async () => {
|
||||
isRefreshing.value = true;
|
||||
const [groupsResult, jobsResult] = await Promise.all([getKbGroupsSafe(), getKbJobsSafe()]);
|
||||
if (groupsResult.ok) {
|
||||
groups.value = groupsResult.data;
|
||||
} else {
|
||||
feedback.value = groupsResult.error || '加载知识库分组失败';
|
||||
feedbackType.value = 'error';
|
||||
}
|
||||
if (jobsResult.ok) {
|
||||
jobs.value = jobsResult.data;
|
||||
} else {
|
||||
feedback.value = jobsResult.error || '加载任务列表失败';
|
||||
feedbackType.value = 'error';
|
||||
}
|
||||
isRefreshing.value = false;
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
editingGroupId.value = null;
|
||||
form.value = { name: '', description: '' };
|
||||
};
|
||||
|
||||
const handleCreateGroup = async () => {
|
||||
if (!form.value.name.trim()) {
|
||||
feedback.value = '请输入知识库分组名称';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
isSubmitting.value = true;
|
||||
const payload = {
|
||||
name: form.value.name.trim(),
|
||||
description: form.value.description.trim(),
|
||||
};
|
||||
const result = editingGroupId.value
|
||||
? await updateKbGroup(editingGroupId.value, payload)
|
||||
: await createKbGroup(payload);
|
||||
isSubmitting.value = false;
|
||||
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '创建失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = editingGroupId.value ? '知识库分组已更新' : '知识库分组创建成功';
|
||||
feedbackType.value = 'success';
|
||||
resetForm();
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleEditGroup = (group: KbGroup) => {
|
||||
editingGroupId.value = group.id;
|
||||
form.value = {
|
||||
name: group.name,
|
||||
description: group.description || '',
|
||||
};
|
||||
feedback.value = '';
|
||||
feedbackType.value = '';
|
||||
};
|
||||
|
||||
const handleDeleteGroup = async (group: KbGroup) => {
|
||||
const confirmed = window.confirm(`确认删除知识库分组「${group.name}」吗?`);
|
||||
if (!confirmed) return;
|
||||
|
||||
const result = await deleteKbGroup(group.id);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '删除失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
if (editingGroupId.value === group.id) {
|
||||
resetForm();
|
||||
}
|
||||
feedback.value = '知识库分组已删除';
|
||||
feedbackType.value = 'success';
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleRunJob = async (job: KbJob) => {
|
||||
runningJobId.value = job.id;
|
||||
const result = await runKbJob(job.id);
|
||||
runningJobId.value = null;
|
||||
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || '任务执行失败';
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = result.run_result || '任务已执行';
|
||||
feedbackType.value = 'success';
|
||||
await loadData();
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await loadData();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen bg-gray-50 dark:bg-slate-950 text-slate-800 dark:text-slate-200">
|
||||
<div class="mx-auto max-w-7xl px-4 py-6 md:px-6 lg:px-8">
|
||||
<div class="mb-6 flex flex-col gap-4 rounded-3xl border border-slate-200 bg-white p-6 shadow-sm md:flex-row md:items-center md:justify-between dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="flex items-start gap-4">
|
||||
<button
|
||||
@click="router.push('/admin')"
|
||||
class="rounded-2xl border border-slate-200 p-3 text-slate-500 transition-colors hover:bg-slate-50 hover:text-slate-900 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800 dark:hover:text-white"
|
||||
title="返回管理后台"
|
||||
>
|
||||
<ArrowLeft class="h-5 w-5" />
|
||||
</button>
|
||||
<div class="flex items-center gap-3">
|
||||
<div class="flex h-12 w-12 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
|
||||
<Settings class="h-6 w-6" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">知识库管理台</h1>
|
||||
<p class="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
第一阶段先承接分组、任务和 Dify 管理入口,后续再接入清洗链路。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
@click="loadData"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
刷新数据
|
||||
</button>
|
||||
<button
|
||||
@click="settingsDialogOpen = true"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
<Settings class="h-4 w-4" />
|
||||
Dify 设置
|
||||
</button>
|
||||
<button
|
||||
@click="healthDialogOpen = true"
|
||||
class="inline-flex items-center gap-2 rounded-2xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
<RefreshCw class="h-4 w-4" />
|
||||
健康检查
|
||||
</button>
|
||||
<button
|
||||
@click="router.push('/kb/workspace')"
|
||||
class="inline-flex items-center gap-2 rounded-2xl bg-brand-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-brand-700"
|
||||
>
|
||||
<Wrench class="h-4 w-4" />
|
||||
前往工作台
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 gap-6 xl:grid-cols-[420px_minmax(0,1fr)]">
|
||||
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="mb-5 flex items-center gap-3">
|
||||
<div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-brand-50 text-brand-600 dark:bg-brand-500/10">
|
||||
<FolderPlus class="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">{{ formTitle }}</h2>
|
||||
<p class="text-sm text-slate-500 dark:text-slate-400">{{ formDescription }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组名称</label>
|
||||
<input v-model="form.name" class="input-field" placeholder="例如:财务制度库" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-slate-600 dark:text-slate-300">分组描述</label>
|
||||
<textarea
|
||||
v-model="form.description"
|
||||
rows="4"
|
||||
class="input-field"
|
||||
placeholder="描述该知识库分组的业务范围或清洗目标"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
@click="handleCreateGroup"
|
||||
:disabled="isSubmitting"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl bg-brand-600 px-4 py-3 text-sm font-medium text-white transition-colors hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
>
|
||||
<FolderPlus class="h-4 w-4" />
|
||||
{{ submitText }}
|
||||
</button>
|
||||
<button
|
||||
v-if="editingGroupId"
|
||||
@click="resetForm"
|
||||
type="button"
|
||||
class="inline-flex w-full items-center justify-center gap-2 rounded-2xl border border-slate-200 px-4 py-3 text-sm font-medium text-slate-700 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
<X class="h-4 w-4" />
|
||||
取消编辑
|
||||
</button>
|
||||
<p
|
||||
v-if="feedback"
|
||||
class="text-sm"
|
||||
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600 dark:text-emerald-400'"
|
||||
>
|
||||
{{ feedback }}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="space-y-6">
|
||||
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">知识库分组概览</h2>
|
||||
<span class="text-xs text-slate-400">{{ isRefreshing ? '加载中...' : '`/api/kb/groups`' }}</span>
|
||||
</div>
|
||||
<div v-if="groups.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
|
||||
当前暂无分组,或知识库接口尚未联调完成。
|
||||
</div>
|
||||
<div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div
|
||||
v-for="group in groups"
|
||||
:key="group.id"
|
||||
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ group.name }}</div>
|
||||
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ group.description || '暂无描述' }}</div>
|
||||
</div>
|
||||
<div class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
||||
{{ group.document_count ?? 0 }} 文档
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="text-xs text-slate-400">
|
||||
更新时间:{{ group.updated_at || '--' }}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
@click="handleEditGroup(group)"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-slate-200 px-3 py-2 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
>
|
||||
<Pencil class="h-3.5 w-3.5" />
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
@click="handleDeleteGroup(group)"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 dark:border-rose-500/30 dark:text-rose-400 dark:hover:bg-rose-500/10"
|
||||
>
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100">任务队列占位</h2>
|
||||
<span class="text-xs text-slate-400">`/api/kb/jobs`</span>
|
||||
</div>
|
||||
<div v-if="jobs.length === 0" class="rounded-2xl border border-dashed border-slate-200 px-4 py-10 text-center text-sm text-slate-400 dark:border-slate-700">
|
||||
暂无任务。第二阶段会在这里接入清洗、同步和重试任务。
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="job in jobs"
|
||||
:key="job.id"
|
||||
class="rounded-2xl border border-slate-200 px-4 py-4 dark:border-slate-700"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold text-slate-900 dark:text-slate-100">{{ job.job_type }}</div>
|
||||
<div class="mt-1 text-sm text-slate-500 dark:text-slate-400">{{ job.created_at || '--' }}</div>
|
||||
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
|
||||
{{ job.message || '暂无任务说明' }}
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-slate-400">
|
||||
文档:{{ job.document_id ?? '--' }} · 版本:{{ job.document_version_id ?? '--' }} · 进度:{{ job.progress ?? 0 }}%
|
||||
</div>
|
||||
</div>
|
||||
<span class="rounded-full bg-slate-100 px-2.5 py-1 text-xs font-medium text-slate-600 dark:bg-slate-800 dark:text-slate-300">
|
||||
{{ job.status }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="mt-3 flex justify-end" v-if="['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'">
|
||||
<button
|
||||
@click="handleRunJob(job)"
|
||||
:disabled="runningJobId === job.id"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60 dark:border-brand-500/30 dark:text-brand-300 dark:hover:bg-brand-500/10"
|
||||
>
|
||||
<Play class="h-3.5 w-3.5" />
|
||||
{{ runningJobId === job.id ? '执行中...' : '执行任务' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DifySettingsDialog
|
||||
:open="settingsDialogOpen"
|
||||
@close="settingsDialogOpen = false"
|
||||
@saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }"
|
||||
@error="(message) => { feedback = message; feedbackType = 'error'; }"
|
||||
/>
|
||||
<DifyHealthDialog
|
||||
:open="healthDialogOpen"
|
||||
@close="healthDialogOpen = false"
|
||||
@error="(message) => { feedback = message; feedbackType = 'error'; }"
|
||||
/>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -24,7 +24,7 @@ import {
|
||||
const { t, locale } = useI18n();
|
||||
const { showMessageDialog } = useGlobalMessageDialog();
|
||||
const router = useRouter();
|
||||
const { setThemePreference } = useTheme();
|
||||
const { setThemePreference, appliedTheme } = useTheme();
|
||||
|
||||
interface ProfileForm {
|
||||
id: number;
|
||||
@@ -108,7 +108,11 @@ const fetchProfile = async () => {
|
||||
const data = await res.json();
|
||||
user.value = { ...user.value, ...data };
|
||||
if (data.language) locale.value = data.language;
|
||||
if (data.theme_preference) setThemePreference(data.theme_preference);
|
||||
if (data.theme_preference) {
|
||||
setThemePreference(data.theme_preference);
|
||||
} else {
|
||||
user.value.theme_preference = appliedTheme.value;
|
||||
}
|
||||
captureOriginalProfile();
|
||||
isEditing.value = false;
|
||||
} else {
|
||||
|
||||
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user