Merge branch 'dev' into order-delivery-reply

# Conflicts:
#	.env.shared
#	backend/app/api/chat.py
#	backend/app/core/config/settings.py
#	backend/app/models/user.py
#	backend/app/services/admin/permission_service.py
#	docs/demand.md
#	frontend/src/app/router/routes/workspace.routes.ts
#	frontend/src/features/admin/modules/users/components/UserFormModal.vue
#	frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts
#	frontend/src/features/admin/types/user.types.ts
#	frontend/src/features/auth/stores/auth.store.ts
#	frontend/src/features/user/views/UserProfilePage.vue
#	frontend/src/locales/en/admin.json
#	frontend/src/locales/en/errors.json
#	frontend/src/locales/th/admin.json
#	frontend/src/locales/th/errors.json
#	frontend/src/locales/zh-CN/admin.json
#	frontend/src/locales/zh-CN/errors.json
#	frontend/src/locales/zh-TW/admin.json
#	frontend/src/locales/zh-TW/errors.json
#	frontend/src/shared/utils/auth.ts
This commit is contained in:
HTEWJ\26070045 committed 2026-09-22 10:37:59 +08:00
commit 616034a4cd
541 files changed
+43805 -14767

No files matched your search

+18 -16
View File
@@ -135,27 +135,29 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
# RPA 目录(相对 backend/ 根目录)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# RPA 目录(相对 backend/ 根目录,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/freight_rpa/inventory/upload_triggers
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=data/freight_rpa/common/browser_profile
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 本地 RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py)
FREIGHT_RPA_WORKER_MOCK=false
# 本机无 Redis 时允许进程内存记录心跳;有 Redis 时优先写 Redis
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=false
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK=true
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 ---
# 设备维保助手后端工具调用密钥
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
+16 -13
View File
@@ -70,7 +70,7 @@ GUNICORN_WORKERS=20
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
# --- 5. 数据库与基础设施 ---
@@ -135,20 +135,23 @@ SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=false
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
# RPA 目录(正式环境:Ubuntu 挂载 Windows RPA 正式共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/freight_rpa/inventory/upload_triggers
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
+24 -4
View File
@@ -150,7 +150,7 @@ 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,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,order_delivery_reply_notify,training_overseas_thailand_guidelines
WECOM_FEEDBACK_NOTIFY_ENABLED=true
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
@@ -187,6 +187,26 @@ CONTRACT_PAYMENT_ERP_USERNAME=hxjm
CONTRACT_PAYMENT_ERP_PASSWORD=hxjm
ERP_TIMEOUT_SECONDS=30
TEXT2SQL_SCHEMA_PATH=
# 立账凭证销货放行单:E10 OpenAPI + ecology10(与 E9 OA_SQLSERVER_DATABASE=ecology 隔离)
# 开关/超时三环境一致;基址、corpId、应用密钥、SQL 主机与账号由 .env.local / .env.<env> / Jenkins 注入
OA_E10_SQLSERVER_DATABASE=ecology10
OA_E10_SQLSERVER_PORT=1433
OA_E10_SQLSERVER_ENCRYPT=no
OA_E10_SQLSERVER_TRUST_CERT=yes
OA_E10_SQLSERVER_TIMEOUT=10
OA_E10_TIMEOUT_SECONDS=30
OA_E10_TOKEN_REFRESH_SKEW_SECONDS=300
OA_E10_OPENAPI_BASE_URL=http://192.168.100.184:10600/papi/openapi
OA_E10_CORPID=8c47e679b2e3a415b0381089af1a2e58
OA_E10_APP_KEY=7a9c97b6a3f5525f1150985b006f96b8
OA_E10_APP_SECRET=474922f5e071f972c46f357aa8a41eda
# 需要换成OA
OA_E10_USERID=1251671276931039236
OA_E10_SQLSERVER_HOST=192.168.100.186
OA_E10_SQLSERVER_USERNAME=AI_Knowledge_Base_OA
OA_E10_SQLSERVER_PASSWORD=hoo-thai@123_AI_OA
# 驱动可留空,留空会按本机已装驱动自动选:ODBC Driver 18 for SQL Server → 17 → SQL Server
OA_E10_SQLSERVER_DRIVER=
# --- 8. 知识库与文件处理 ---
# Knowledge base runtime
@@ -270,7 +290,7 @@ SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
FREIGHT_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
# L7 验收完成前禁止开启通用解析与通用自动冻结。
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
@@ -300,9 +320,9 @@ SHIPPING_NOTICE_AUDIT_RETENTION_DAYS=1095
# 货代上传 RPA:默认关闭;具备 Worker/凭据/共享目录与隔离校验后再在环境文件显式设 true。
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
FREIGHT_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+23 -21
View File
@@ -70,7 +70,7 @@ GUNICORN_WORKERS=6
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push
WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,permission_batch_updated,task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,training_lean_video_push,training_overseas_thailand_guidelines
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
@@ -152,33 +152,35 @@ SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
FREIGHT_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS=900
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS=3
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS=30
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
FREIGHT_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
FREIGHT_RPA_WORKER_ALERT_USERNAMES=
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
FREIGHT_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享,统一 freight_rpa/{inventory,receipt,common} 三层布局)
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/drop
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/triggers
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/drop
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/receipt/triggers
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_queue
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/freight_rpa/inventory/upload_triggers
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/inventory/inventory_rpa_worker.py,可选)
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
# 本地 Mock RPA(scripts/freight_rpa/inventory/inventory_rpa_worker.py,可选)
# FREIGHT_RPA_WORKER_MOCK=true
# FREIGHT_RPA_WORKER_POLL_SECONDS=3
# FREIGHT_RPA_WORKER_SAMPLE_INVENTORY=
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
+1
View File
@@ -63,6 +63,7 @@ frontend/package-lock.json
*.swp
*.swo
.cursorrules
.zcode
# Runtime files
.run/
+1 -1
View File
@@ -163,7 +163,7 @@ docker compose logs -f hxops-backend
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ AI 平台、模型与内部工具 → ⑦ 企业系统集成 → ⑧ 知识库与文件处理 → ⑨ 业务模块 → ⑩ 运维、告警与维护工具;文件没有某类变量时直接省略该章节。
- **章节内组织**:先按业务域及子域聚合(如 Casdoor、MinIO、WeCom、HR、PLM、SRM、FAQ、Shipping Notice、Fixed Asset),不得把同一域拆散后做全局字母排序;同一域内按“开关/模式 → 地址 → 标识 → 凭据 → 路径 → 业务参数 → 超时/重试/并发 → 兼容/Mock”排列,同级变量再按字母排序。
- **数据库连接固定顺序**:`HOST → PORT → DATABASE/SID → USERNAME → PASSWORD → DRIVER → ENCRYPT/TRUST_CERT → TIMEOUT`;完整连接串(如 `DATABASE_URL`、`*_DSN`)置于该数据源首位。
- **RPA 命名空间(强制)**:货代发货通知 RPA 统一使用 `SHIPPING_NOTICE_RPA_*`。后端业务参数使用 `SHIPPING_NOTICE_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `SHIPPING_NOTICE_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `SHIPPING_NOTICE_RPA_WORKER_*`,平台凭据主密钥使用 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。禁止新增 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`;历史名称只能存在于兼容映射和迁移说明中。
- **RPA 命名空间(强制,2026-09-18 修订)**:货代 RPA(库存/收料/上传及后续新增 Worker)统一使用 `FREIGHT_RPA_*`。后端业务参数使用 `FREIGHT_RPA_<配置项>`,后端与 Windows Worker 的共享目录/标识使用 `FREIGHT_RPA_SHARED_*`,Windows Worker 自身运行参数使用 `FREIGHT_RPA_WORKER_*`,平台凭据主密钥使用 `FREIGHT_RPA_CREDENTIAL_KEY`。禁止新增 `SHIPPING_RPA_*` 或无 RPA 作用域的 `FREIGHT_*_DIR`。历史名称 `SHIPPING_NOTICE_RPA_*` 于 2026-09-18 未上线期一刀切废弃,**不设兼容层**;RPA 运行期数据统一存放于独立 `freight_rpa/` 根下,按 `inventory/`、`receipt/`、`common/` 分域(common 仅放跨 Worker 共享物,如 browser_profile)。
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
+5 -1
View File
@@ -103,12 +103,16 @@ def create_app(config_name='default'):
try:
from app.services.voucher_check.schedule_seed import (
ensure_default_voucher_check_schedule,
ensure_default_voucher_oa_sales_release_schedule,
ensure_default_voucher_po_print_schedule,
register_voucher_check_schedule_hooks,
)
register_voucher_check_schedule_hooks()
ensure_default_voucher_check_schedule()
ensure_default_voucher_po_print_schedule()
ensure_default_voucher_oa_sales_release_schedule()
except Exception as exc: # pragma: no cover - 表未就绪时容忍
logger.warning('Failed to ensure accounting-voucher-check schedule: %s', exc)
logger.warning('Failed to ensure accounting-voucher-check / po-print / oa-sales-release schedules: %s', exc)
try:
from app.services.contract_payment.schedule_seed import ensure_default_contract_payment_schedules
ensure_default_contract_payment_schedules()
+1 -1
View File
@@ -15,7 +15,7 @@ from app.core.auth.jwt import get_current_user
from app.core.errors import UnauthorizedError
from app.models import Agent, User, AgentGuide
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
# 定义 Blueprint,将在应用工厂中注册为 /api/agents
agents_bp = Blueprint('agents', __name__)
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -36,7 +36,7 @@ def get_chat_query_preview(chat_log_id: int):
if not sql:
raise ValidationError('query preview sql is missing')
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
total_count = payload.get('total_count')
try:
total_count = int(total_count) if total_count is not None else None
+4 -1
View File
@@ -39,6 +39,7 @@ def chat_completions():
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -87,7 +88,7 @@ def chat_completions():
role=getattr(user, 'role', None),
)
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
external_conversation_id = None
if conversation_id:
@@ -174,6 +175,7 @@ def chat_completions():
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
shipping_task_id=shipping_task_id,
kb_type=kb_type,
@@ -214,6 +216,7 @@ def chat_completions():
user_role=user_proxy.role,
adapter_hints=_build_chat_adapter_hints(
shipping_task_id=shipping_task_id,
shipping_batch_no=shipping_batch_no,
),
),
)
+6 -4
View File
@@ -10,19 +10,21 @@ from __future__ import annotations
from .shared import * # noqa: F403
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
"""
构建聊天入口分发给领域 adapter 的提示字典。
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
"""
task_id = str(shipping_task_id or '').strip()
if not task_id:
batch_no = str(shipping_batch_no or '').strip()
if not task_id and not batch_no:
return None
return {
'shipping_notice': {
'task_id': task_id or None,
'batch_no': batch_no or None,
}
}
@@ -35,7 +37,7 @@ def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy)
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
"""
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
+2 -2
View File
@@ -25,7 +25,7 @@ def get_oa_employees():
page = 1
page_size = 20
try:
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
result = OASQLServerService.search_employees(keyword, page, page_size)
return jsonify(result)
except Exception as e:
@@ -39,7 +39,7 @@ def resolve_oa_names():
sub_ids = request.args.get('subcompany_ids', '').strip()
result = {}
try:
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
if dept_ids:
for did in dept_ids.split(','):
did = did.strip()
+11 -3
View File
@@ -2,8 +2,8 @@
api/chat/sessions.py
用途:处理聊天会话、历史消息与本地结构化消息路由。
依赖:chat.shared、chat.core、ChatSession、ChatLog。
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
依赖:chat.shared、chat.core、ChatSession、ChatLog、_normalize_user_attachments。
逻辑:校验当前用户和 Agent 后读写会话及日志;用户附件快照写库前规范化,超限显式失败不落半截。
"""
from __future__ import annotations
@@ -246,7 +246,8 @@ def save_local_message():
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题;
user 角色 payload 含 user_attachments 时写库前调用 _normalize_user_attachments,超限抛 ValidationError。
"""
user = getattr(g, 'current_user', None)
agent = getattr(g, 'current_agent', None)
@@ -286,6 +287,13 @@ def save_local_message():
if user_query and _looks_like_review_auto_title(session.title or ''):
session.title = _session_title_from_text(user_query)
# [STEP] 用户附件快照写前规范化;超限由 _normalize_user_attachments 显式失败,禁止落半截
if role == 'user' and isinstance(payload, dict) and 'user_attachments' in payload:
payload = {
**payload,
'user_attachments': _normalize_user_attachments(payload.get('user_attachments')),
}
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
+19 -6
View File
@@ -24,9 +24,9 @@ from flask import Blueprint, request, Response, stream_with_context, jsonify, g,
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.core.config.settings import Config
from app.services.integration_api import IntegrationApiService
from app.services.integrations.integration_api import IntegrationApiService
from app.core.decorators import require_agent_permission
from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
@@ -43,7 +43,7 @@ from app.core.errors import (
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
# 用户消息附件白名单(迁移自 legacy app/api/chat.py;供 ChatLog payload 与历史接口复用)。
CHAT_USER_ATTACHMENT_LIMIT = 20
CHAT_USER_ATTACHMENT_LIMIT = 200
CHAT_USER_ATTACHMENT_MAX_SIZE = 10 * 1024 * 1024 * 1024
CHAT_USER_ATTACHMENT_TYPES = {'image', 'document', 'audio', 'video', 'custom'}
CHAT_USER_ATTACHMENT_SOURCES = {'local', 'remote', 'shipping_notice'}
@@ -53,18 +53,31 @@ def _normalize_user_attachments(value) -> list[dict]:
"""
校验并清洗用户消息附件快照,供 ChatLog payload 与历史接口复用。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举,不接收 URL、上传 ID 或资产编号。
核心逻辑:仅接受展示白名单字段;剥离路径、控制字符与未知枚举;
列表长度超过 CHAT_USER_ATTACHMENT_LIMIT 时显式失败,禁止静默截断。
Args:
value: 前端 user_attachments 原始值;必须为列表,最多处理 20 项。
value: 前端 user_attachments 原始值;必须为列表。
Returns:
可安全写入 JSON 的附件快照列表;非法项目被忽略。
Raises:
ValidationError: 列表长度超过上限(code=CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED)。
"""
if not isinstance(value, list):
return []
if len(value) > CHAT_USER_ATTACHMENT_LIMIT:
raise ValidationError(
f'User attachments exceed limit ({CHAT_USER_ATTACHMENT_LIMIT})',
code='CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED',
details={
'limit': CHAT_USER_ATTACHMENT_LIMIT,
'count': len(value),
},
)
normalized: list[dict] = []
for item in value[:CHAT_USER_ATTACHMENT_LIMIT]:
for item in value:
if not isinstance(item, dict):
continue
raw_name = str(item.get('name') or '')
+1 -1
View File
@@ -27,7 +27,7 @@ def upload_chat_file():
if not upload:
raise ValidationError('file is required')
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
from app.core.config.settings import Config
params = DifyService.get_app_parameters(agent, force_refresh=True)
+83 -29
View File
@@ -2,10 +2,10 @@
backend/app/api/contract_payment.py
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、Agent 授权、contract_payment 服务和通用 Job 队列。
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
鉴权:查询接口要求平台 admin 或持有 `agent_code=contract_payment` 的 Agent 授权;
同步/扫描/周汇总发送仅 `role=admin`。
"""
@@ -21,6 +21,7 @@ from app.core.response import ok
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import (
Agent,
ContractPaymentAlert,
ContractPaymentAlertBatch,
ContractPaymentAttachment,
@@ -41,6 +42,8 @@ from app.services.file_assets.service import read_asset_bytes
contract_payment_bp = Blueprint("contract_payment", __name__)
CONTRACT_PAYMENT_AGENT_CODE = "contract_payment"
def _attachment_parse_priority(attachment: ContractPaymentAttachment) -> tuple[int, int]:
"""
@@ -74,35 +77,45 @@ def _require_user():
return user
def _user_has_contract_payment_agent(user) -> bool:
"""
判断用户是否持有启用中的合同付款预警 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
"""
agent = Agent.query.filter_by(agent_code=CONTRACT_PAYMENT_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_contract_payment_access():
"""
确保当前用户已登录且具备合同付款预警访问权限。
核心逻辑:登录校验之后读取 `contract_payment.access`;admin 角色默认具备,
其他角色需在用户管理中显式授予。无权限时返回业务 403,而不是静默空数据。
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=contract_payment` Agent。
无权限时返回业务 403,而不是静默空数据。
Args:
无。当前请求身份由 JWT 上下文提供。
Returns:
已认证且具备合同付款预警访问权限的用户。
已认证且具备合同付款预警 Agent 授权(或 admin)的用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 已登录但没有 `contract_payment.access`。
ForbiddenError: 已登录但没有合同付款预警 Agent 授权。
"""
user = _require_user()
if not user.can_access_contract_payment():
raise ForbiddenError(
'Contract payment access required',
code='CONTRACT_PAYMENT.FORBIDDEN',
)
return user
if getattr(user, "role", None) == "admin" or _user_has_contract_payment_agent(user):
return user
raise ForbiddenError(
'Contract payment agent permission required',
code='CONTRACT_PAYMENT.FORBIDDEN',
)
def _require_contract_payment_admin():
"""
确保当前用户既有合同付款预警访问权,又是平台管理员。
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
核心逻辑:持有 Agent 的普通用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
Args:
@@ -195,19 +208,48 @@ def _serialize_contract(row: ContractPaymentContract) -> dict:
}
@contract_payment_bp.route("/contracts", methods=["GET"])
def list_contracts():
def _review_only_requested() -> bool:
"""
查询合同台账。
判断当前请求是否只要待确认合同。
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
Args:
无。筛选条件从 query string 读取。
无。读取 query string 的 review_only。
Returns:
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
值为 1 / true / yes 时为 True。
"""
return str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
def _scoped_contract_query(*, review_only: bool, parse_status: str = ""):
"""
按台账 / 待确认口径收窄合同查询。
核心逻辑:review_only 优先于 parse_status;二者都空时默认只看已解析台账。
Args:
review_only: 为 True 时只返回 needs_review。
parse_status: 精确解析状态;review_only 为 False 且为空时默认 parsed。
Returns:
已套上解析状态条件的合同查询。
"""
_require_contract_payment_access()
query = db.session.query(ContractPaymentContract)
if review_only:
return query.filter_by(parse_status="needs_review")
if parse_status:
return query.filter_by(parse_status=parse_status)
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
return query.filter_by(parse_status="parsed")
def _apply_contract_text_filters(query):
"""
叠关键词过滤。
核心逻辑:keyword 对合同号、流程号、采购单号、供应商、申请人做模糊 OR。
Args:
query: 已按解析状态收窄的合同查询。
Returns:
叠加文本过滤后的查询。
"""
keyword = str(request.args.get("keyword") or "").strip()
if keyword:
like = f"%{keyword}%"
@@ -216,16 +258,28 @@ def list_contracts():
| ContractPaymentContract.workflow_no.ilike(like)
| ContractPaymentContract.purchase_order_no.ilike(like)
| ContractPaymentContract.supplier_name.ilike(like)
| ContractPaymentContract.applicant_name.ilike(like)
)
return query
@contract_payment_bp.route("/contracts", methods=["GET"])
def list_contracts():
"""
查询合同台账。
核心逻辑:支持合同编号、流程编号、采购单号、供应商、申请人、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
Args:
无。筛选条件从 query string 读取。
Returns:
标准成功 envelope,data 包含 total、page、page_size、pages 和 items。
"""
_require_contract_payment_access()
review_only = _review_only_requested()
parse_status = str(request.args.get("parse_status") or "").strip()
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
if review_only:
query = query.filter_by(parse_status="needs_review")
elif parse_status:
query = query.filter_by(parse_status=parse_status)
else:
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
query = query.filter_by(parse_status="parsed")
query = _apply_contract_text_filters(
_scoped_contract_query(review_only=review_only, parse_status=parse_status)
)
focus = str(request.args.get("focus") or "").strip()
if focus:
if review_only:
@@ -262,7 +316,7 @@ def get_ledger_summary():
Args:
无。
Returns:
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
标准成功 envelope,含 due、overdue、active、due_this_month。
"""
_require_contract_payment_access()
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
+10 -21
View File
@@ -3,7 +3,7 @@ backend/app/api/file_check_tools.py
用途:文件检核 / 立账凭证检核 Chatflow 显式 HTTP Tool API(启动检核复用本蓝图)。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json。
逻辑:发起检核时可透传顶层 mode/invoice_no(或嵌套 run_options)写入 ScheduleRun.api_request_json;实际执行入队 FILE_CHECK_RUN,由 schedule worker 执行。
"""
from __future__ import annotations
@@ -17,6 +17,7 @@ from sqlalchemy import text
from app import db
from app.api.workspace_file_check import serialize_file_judgement
from app.jobs import JobType, enqueue
from app.core.errors import (
AppError,
ConflictError,
@@ -31,7 +32,7 @@ from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE, resolve_hx
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.scheduler_service import _generate_run_no
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
try:
@@ -543,28 +544,16 @@ def run_file_check():
db.session.commit()
_record_run_bind(run, data)
db.session.commit()
app = current_app._get_current_object()
run_id = run.id
task_id = task.id
def _background():
with app.app_context():
t = db.session.get(ScheduleTask, task_id)
r = db.session.get(ScheduleRun, run_id)
if not t or not r:
return
try:
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
except Exception as exc:
current_app.logger.error("[file-check-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
r = db.session.get(ScheduleRun, run_id)
if r and r.status == "running":
r.status = "failed"
r.error_message = str(exc)
r.finished_at = datetime.utcnow()
db.session.commit()
threading.Thread(target=_background, daemon=True, name=f"file-check-run-{run_id}").start()
enqueue(
JobType.FILE_CHECK_RUN,
{"task_id": task_id, "schedule_run_id": run_id},
domain="file_check",
business_ref=str(run_id),
message="等待执行文件检核",
)
db.session.refresh(run)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
+1 -1
View File
@@ -22,7 +22,7 @@ from app.core.errors import (
ValidationError,
raise_for_status,
)
from app.services.integration_api import IntegrationApiService
from app.services.integrations.integration_api import IntegrationApiService
integration_bp = Blueprint('integration', __name__)
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/knowledge_base.py
用途:知识库 API 兼容 shim(Wave 3 迁包过渡期)。
依赖:app.api.kb。
逻辑:旧 import 路径仍可用;新代码请用 app.api.kb。
"""
from app.api.kb import knowledge_base_bp
__all__ = ['knowledge_base_bp']
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/schedule_admin.py
用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。
依赖:app.api.schedule。
逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。
"""
from app.api.schedule import schedule_admin_bp
__all__ = ['schedule_admin_bp']
+14
View File
@@ -27,6 +27,7 @@ from app.services.training_config_service import get_published_config, list_trai
from app.services.lean_training_service import (
LEAN_TRAINING_TYPE,
create_or_update_weekly_task,
export_dashboard_excel,
get_current_weekly_task,
get_weekly_task_for_admin,
list_dashboard,
@@ -275,3 +276,16 @@ def get_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
return ok(list_dashboard(raw_task_id))
@training_admin_bp.route("/lean-training/dashboard/export", methods=["GET"])
def export_admin_lean_training_dashboard():
_require_lean_training_manager()
raw_task_id = request.args.get("task_id", type=int)
file_data, file_name = export_dashboard_excel(raw_task_id)
return send_file(
BytesIO(file_data),
as_attachment=True,
download_name=file_name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+1 -1
View File
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ValidationError
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
from . import auth as _compat
from .auth import auth_bp
+2 -2
View File
@@ -14,8 +14,8 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.integrations.wecom.crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
from app.core.auth.jwt import get_current_user as _auth_current_user, issue_local_access_token
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
from sqlalchemy import and_, or_, inspect, insert
+1 -1
View File
@@ -14,7 +14,7 @@ from flask import current_app, jsonify, request
from app import db
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
from app.services.integrations.wecom.crypto import decrypt_wecom_aes, extract_encrypt_field
from . import auth as _compat
from .auth import auth_bp
+3 -3
View File
@@ -13,7 +13,7 @@ from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaul
from app.services.feedback_notify import send_feedback_group_notification
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
from app.services.agent_registry.serialization import serialize_registry_fields
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
from app.services.integrations.wecom.notify import mark_wecom_message_opened, send_wecom_event_message
import re
import ast
from app.core.errors import (
@@ -108,7 +108,7 @@ def submit_leave_workflow():
if not form_data.get(key):
raise ValidationError(f'{label}不能为空。')
try:
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
from app.services.integrations.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)
@@ -358,7 +358,7 @@ def get_agent_details(id):
dify_parameters = None
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
try:
params = DifyService.get_app_parameters(agent)
+120 -4
View File
@@ -154,6 +154,21 @@ def _require_formal_notice(task: Any) -> ShippingNotice:
return task
def _require_editable_task(task: Any) -> Any:
"""订单编辑写接口的实体守卫:正式 Notice 或建单前 OT 均可。
核心逻辑:订单字段/行的编辑权限由服务层状态制闸门裁决
(Excel ready 硬冻结 + 活动 Attempt 忙碌锁 + Schema 反向锁),
与实体类型无关——通知准备阶段(Notice 未建)编辑履约字段是受支持场景。
"""
if not isinstance(task, (ShippingNotice, ShippingOrderTask)):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -199,6 +214,7 @@ def workspace_shipping_my_todos():
todo_category=str(request.args.get('todo_category') or '').strip() or None,
customer=str(request.args.get('customer') or '').strip() or None,
task_no=str(request.args.get('task_no') or '').strip() or None,
terminal_kind=str(request.args.get('terminal_kind') or '').strip() or None,
))
@@ -212,6 +228,67 @@ def workspace_shipping_my_todos_count():
return _ok(count_my_todos(user.id, is_admin=is_admin))
def _done_lines_report_params() -> dict[str, Any]:
"""解析明细报表共用筛选参数(客户/料号/发货通知日期范围),供查询与导出复用。"""
return {
'customer': str(request.args.get('customer') or '').strip() or None,
'part_number': str(request.args.get('part_number') or '').strip() or None,
'notice_date_from': str(request.args.get('notice_date_from') or '').strip() or None,
'notice_date_to': str(request.args.get('notice_date_to') or '').strip() or None,
}
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines', methods=['GET'])
def workspace_shipping_done_lines():
"""
分页列出已完成(已核验上传成功)通知的平铺明细行,供「通知完成」子视图报表。
核心逻辑:明细行跨 Notice 混排、不按 OT 聚合;支持 客户 / 料号 /
发货通知日期范围 筛选;行结构为标准 12 字段 + 溯源编号(task_no/business_no)。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import list_done_notice_lines
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
try:
page = int(request.args.get('page') or 1)
page_size = int(request.args.get('page_size') or 20)
except (TypeError, ValueError) as exc:
raise ValidationError('page and page_size must be integers') from exc
return _ok(list_done_notice_lines(
user.id,
is_admin=is_admin,
page=page,
page_size=page_size,
**_done_lines_report_params(),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/my-todos/done-lines/export', methods=['GET'])
def workspace_shipping_done_lines_export():
"""
导出当前筛选下的已完成通知明细 Excel。
核心逻辑:固定 12 列标准格式(客户/客户编号/订单日期/订单项次/料号/数量/
约定出货日期/客户PO/已用数量/open qty/订单单号/单价),OT 编号不落列;
已用数量 / open qty 无数据源留空。
"""
user = _require_user()
from app.services.shipping_notice.done_line_report import build_done_lines_xlsx
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
stream, filename = build_done_lines_xlsx(
user.id,
is_admin=is_admin,
**_done_lines_report_params(),
)
response = send_file(
stream, as_attachment=True, download_name=filename, mimetype=EXPORT_MIME_TYPE,
)
response.call_on_close(stream.close)
return response
def _batch_task_nos(data: dict) -> list[str]:
"""校验批量任务号,统一限制 100 条并去重,避免前端循环绕过服务端门禁。"""
raw_task_nos = data.get('task_nos')
@@ -481,6 +558,45 @@ def workspace_shipping_task_detail(task_no: str):
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-options', methods=['GET'])
def workspace_shipping_task_odm_options(task_no: str):
"""返回整单 ODM ID 候选与当前选择(工作台整单裁决路径,只读)。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import notice_odm_options
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok(notice_odm_options(task))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/odm-choice', methods=['POST'])
def workspace_set_shipping_task_odm_choice(task_no: str):
"""保存整单 ODM ID 用户选择;重复提交覆盖旧选择,成功后前端可重试生成 Excel。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.notice_odm_choice_service import set_notice_odm_choice
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
snapshot_line_id = int(data.get('snapshot_line_id') or 0)
except (TypeError, ValueError):
snapshot_line_id = 0
result = set_notice_odm_choice(
task,
snapshot_line_id=snapshot_line_id,
odm_id=str(data.get('odm_id') or ''),
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
def workspace_list_shipping_task_audit_timeline(task_no: str):
"""业务用户 Task 审计时间线(统一 ShippingAuditEvent,无敏感快照)。"""
@@ -559,7 +675,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
fields = data.get('fields')
if not isinstance(fields, dict) or not fields:
@@ -606,7 +722,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
@@ -695,7 +811,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
line = data.get('line')
if not isinstance(line, dict) or not line:
@@ -721,7 +837,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
task = _require_formal_notice(task)
task = _require_editable_task(task)
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get('line_index'))
+115 -13
View File
@@ -1,9 +1,10 @@
"""
backend/app/api/workspace/voucher_check.py
用途:工作台立账凭证检核查询与强制重检 API(任务列表 / 批次明细 / 企微发送记录)。
依赖:auth.jwt、response_utils envelope、voucher_check.query_service。
逻辑:对话与检核任务页共用;GET notifications 为企微发送记录;POST runs 仅 admin,以 force_all 入队周批排程。
用途:立账凭证检核查询、强制重检与通知配置 API(任务列表 / 最近一次检核 / 批次明细 / 企微发送记录 / 按类型接收人)。
依赖:auth.jwt、response_utils envelope、Agent 授权、voucher_check.query_service、notify_config_service。
逻辑:Chat Agent 与旧工作台查询共用;GET runs/latest 不跟筛选;GET notifications 为企微发送记录;
查询要求平台 admin 或持有 `agent_code=voucher_check` 的 Agent 授权;POST runs 与通知配置仅 admin。
"""
from __future__ import annotations
@@ -13,23 +14,88 @@ from flask import Blueprint, request
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.services.voucher_check import query_service
from app.models import Agent
from app.services.voucher_check import notify_config_service, query_service
workspace_voucher_check_bp = Blueprint("workspace_voucher_check", __name__)
VOUCHER_CHECK_AGENT_CODE = "voucher_check"
def _require_user():
"""
返回当前登录用户。
Returns:
已认证用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
"""
user = get_current_user()
if not user:
raise UnauthorizedError()
return user
def _require_admin():
"""工作台强制重检仅管理员可触发,鉴权方式与本蓝图 GET 一致。"""
def _user_has_voucher_check_agent(user) -> bool:
"""
判断用户是否持有启用中的立账凭证检核 Agent。
核心逻辑:按 agent_code 查找启用实例,再核对 user_agent_permissions;admin 不走此判断。
Args:
user: 已认证用户。
Returns:
已绑定启用中的 voucher_check Agent 时为 True。
"""
agent = Agent.query.filter_by(agent_code=VOUCHER_CHECK_AGENT_CODE, is_active=True).first()
return bool(agent is not None and agent in user.agents)
def _require_voucher_check_access():
"""
确保当前用户已登录且具备立账凭证检核访问权限。
核心逻辑:平台 admin 放行;普通用户必须被授予启用中的 `agent_code=voucher_check` Agent。
无权限时返回业务 403,而不是静默空数据。
Returns:
已认证且具备立账凭证 Agent 授权(或 admin)的用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 已登录但没有立账凭证 Agent 授权。
"""
user = _require_user()
if getattr(user, "role", None) == "admin" or _user_has_voucher_check_agent(user):
return user
raise ForbiddenError(
"Voucher check agent permission required",
code="VOUCHER_CHECK.FORBIDDEN",
)
def _require_admin():
"""
确保当前用户既有立账凭证访问权,又是平台管理员。
核心逻辑:持有 Agent 的普通用户可查检核任务与发送记录;强制重检与通知配置仅 `role=admin`。
Returns:
已认证的管理员用户。
Raises:
UnauthorizedError: 请求没有有效登录身份。
ForbiddenError: 无立账凭证访问权,或已授权但不是管理员。
"""
user = _require_voucher_check_access()
if getattr(user, "role", None) != "admin":
raise ForbiddenError("Admin privilege required")
raise ForbiddenError(
"Admin privilege required for voucher check jobs",
code="VOUCHER_CHECK.ADMIN_REQUIRED",
)
return user
@@ -37,9 +103,9 @@ def _require_admin():
def workspace_voucher_runs():
"""
分页查看检核任务列表。
核心逻辑:委托 query_service.list_runs,按资料所属期间/业务方/状态筛选。
核心逻辑:委托 query_service.list_runs;period 为 YYYY 或 YYYY-MM,可再按业务方/状态筛选。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_runs(
period=request.args.get("period"),
profile_code=request.args.get("profile_code"),
@@ -69,13 +135,23 @@ def workspace_voucher_force_run():
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/latest", methods=["GET"])
def workspace_voucher_latest_run():
"""
读取最近一次立账凭证检核批次(含排队/执行中)。
核心逻辑:委托 query_service.get_latest_run;不跟列表 period/status;无批次时 data 为 null。
"""
_require_voucher_check_access()
return ok(query_service.get_latest_run())
@workspace_voucher_check_bp.route("/accounting-voucher-check/runs/<int:run_id>/items", methods=["GET"])
def workspace_voucher_run_items(run_id: int):
"""
分页查看批次明细。
核心逻辑:委托 query_service.list_run_items,可按 result 过滤,并返回 by_file_type。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_run_items(
run_id=run_id,
result=request.args.get("result"),
@@ -88,10 +164,10 @@ def workspace_voucher_run_items(run_id: int):
@workspace_voucher_check_bp.route("/accounting-voucher-check/notifications", methods=["GET"])
def workspace_voucher_notifications():
"""
分页查看企微缺件汇总发送记录。
核心逻辑:委托 query_service.list_notifications,可按期间和发送状态筛选。
分页查看企微缺件通知发送记录。
核心逻辑:委托 query_service.list_notifications;period 为 YYYY 或 YYYY-MM,可再按发送状态筛选。
"""
_require_user()
_require_voucher_check_access()
data = query_service.list_notifications(
period=request.args.get("period"),
send_status=request.args.get("send_status"),
@@ -99,3 +175,29 @@ def workspace_voucher_notifications():
page_size=request.args.get("page_size", default=50, type=int) or 50,
)
return ok(data)
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["GET"])
def workspace_voucher_notify_config_get():
"""
读取按文件类型的企微接收人配置。
核心逻辑:仅 admin;规则来自销售 Profile,接收人来自独立配置表。
"""
_require_admin()
return ok(notify_config_service.get_notify_config(profile_code=request.args.get("profile_code")))
@workspace_voucher_check_bp.route("/accounting-voucher-check/notify-config", methods=["PUT"])
def workspace_voucher_notify_config_put():
"""
保存按文件类型的企微接收人。
核心逻辑:仅 admin;未知规则码丢弃;未绑企微的人可保存但发送时跳过。
"""
user = _require_admin()
payload = request.get_json(silent=True) or {}
data = notify_config_service.save_notify_config(
profile_code=payload.get("profile_code") or request.args.get("profile_code"),
recipients=payload.get("recipients"),
updated_by=getattr(user, "id", None),
)
return ok(data)
-10
View File
@@ -1,10 +0,0 @@
"""
backend/app/api/workspace_schedule.py
用途:工作台排程 API 兼容 shim(Wave 1 迁包)。
依赖:app.api.workspace.schedule。
逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。
"""
from app.api.workspace.schedule import workspace_schedule_bp
__all__ = ['workspace_schedule_bp']
@@ -1,10 +0,0 @@
"""
backend/app/api/workspace_shipping_notice.py
用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。
依赖:app.api.workspace.shipping_notice。
逻辑:旧 import 路径继续 re-export `workspace_shipping_notice_bp`;真实实现统一维护在 workspace 子包中,避免双份路由漂移。
"""
from app.api.workspace.shipping_notice import workspace_shipping_notice_bp
__all__ = ['workspace_shipping_notice_bp']
+83 -117
View File
@@ -8,7 +8,6 @@ backend/app/core/config/settings.py
旧路径 app.config 为兼容 shim。
"""
import os
import warnings
from pathlib import Path
from dotenv import dotenv_values
@@ -16,18 +15,6 @@ from dotenv import dotenv_values
_BACKEND_DIR = Path(__file__).resolve().parents[3]
_ROOT_DIR = _BACKEND_DIR.parent
_WARNED_LEGACY_RPA_ENV: set[str] = set()
_RPA_LEGACY_TO_CANONICAL = {
'SHIPPING_RPA_CREDENTIAL_KEY': 'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY',
'FREIGHT_INVENTORY_DROP_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR',
'FREIGHT_RPA_INVENTORY_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR',
'FREIGHT_UPLOAD_QUEUE_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR',
'FREIGHT_RPA_UPLOAD_TRIGGER_DIR': 'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR',
'FREIGHT_RPA_BROWSER_PROFILE_DIR': 'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR',
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR': 'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR',
'FREIGHT_RPA_MOCK': 'SHIPPING_NOTICE_RPA_WORKER_MOCK',
}
def _normalize_env_name(raw: str | None) -> str:
@@ -90,47 +77,15 @@ def _backend_path(env_key: str, *parts: str) -> str:
return resolve_backend_relative_path(os.getenv(env_key), default)
def _rpa_env(canonical_name: str, default: str | None = None) -> str | None:
def _rpa_data_path(env_key: str, *parts: str) -> str:
"""
读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。
解析 RPA 数据目录环境变量,未配置时回落到 `backend/data` 默认路径。
核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的
历史变量,并按进程对每个旧名称最多发出一次弃用警告。
核心逻辑:直接读取规范环境变量名(FREIGHT_RPA_*);历史
SHIPPING_NOTICE_RPA_* 前缀已于 2026-09-18 废弃,不提供别名兼容。
Args:
canonical_name: 统一后的规范环境变量名。
default: 新旧变量均未设置时返回的默认值。
Returns:
str | None: 环境变量值或默认值。
"""
value = os.getenv(canonical_name)
if value is not None:
return value
legacy_name = next(
(legacy for legacy, canonical in _RPA_LEGACY_TO_CANONICAL.items() if canonical == canonical_name),
None,
)
if legacy_name:
value = os.getenv(legacy_name)
if value is not None:
if legacy_name not in _WARNED_LEGACY_RPA_ENV:
warnings.warn(
f'{legacy_name} is deprecated; use {canonical_name}',
DeprecationWarning,
stacklevel=2,
)
_WARNED_LEGACY_RPA_ENV.add(legacy_name)
return value
return default
def _rpa_data_path(canonical_name: str, *parts: str) -> str:
"""
解析 RPA 数据目录,并兼容历史环境变量名称。
Args:
canonical_name: 统一后的 RPA 目录环境变量名。
env_key: 规范 RPA 目录环境变量名。
*parts: 未配置时相对 `backend/data` 的默认路径片段。
Returns:
@@ -139,7 +94,7 @@ def _rpa_data_path(canonical_name: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath('data', *parts)
return resolve_backend_relative_path(_rpa_env(canonical_name), default)
return resolve_backend_relative_path(os.getenv(env_key), default)
class Config:
@@ -310,9 +265,7 @@ class Config:
# 货代发货通知 Agent Tool API
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# RPA Profile 凭据字段的 Fernet 主密钥;只允许由环境变量提供,禁止持久化到数据库。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = _rpa_env('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY')
# 兼容仍从 Flask config 读取旧属性的扩展;新代码禁止继续使用该属性。
SHIPPING_RPA_CREDENTIAL_KEY = SHIPPING_NOTICE_RPA_CREDENTIAL_KEY
FREIGHT_RPA_CREDENTIAL_KEY = os.getenv('FREIGHT_RPA_CREDENTIAL_KEY')
# 文件检核 Chatflow Tool API
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
@@ -425,46 +378,46 @@ class Config:
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS') or '900'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS') or '90'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS', '').strip().lower()
in {'1', 'true', 'yes', 'on'}
if os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
if os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS')
else _normalize_env_name(os.getenv('ENV_NAME')) in {'test', 'prod'}
)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = (
os.getenv('FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID = os.getenv('SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID', '').strip()
SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME = (
os.getenv('SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
FREIGHT_RPA_SHARED_SCOPE_ID = os.getenv('FREIGHT_RPA_SHARED_SCOPE_ID', '').strip()
FREIGHT_RPA_SHARED_SENTINEL_NAME = (
os.getenv('FREIGHT_RPA_SHARED_SENTINEL_NAME', '.hxops_rpa_shared_mount').strip()
or '.hxops_rpa_shared_mount'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_ENABLED = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES', ''
FREIGHT_RPA_WORKER_ALERT_USERNAMES = os.getenv(
'FREIGHT_RPA_WORKER_ALERT_USERNAMES', ''
).strip()
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN = (
os.getenv('FREIGHT_RPA_WORKER_ALERT_FALLBACK_ADMIN', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS = int(
os.getenv('FREIGHT_RPA_WORKER_ALERT_SEND_LOCK_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
@@ -481,9 +434,9 @@ class Config:
)
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('FREIGHT_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
@@ -496,39 +449,32 @@ class Config:
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop'
# RPA 运行期数据目录统一为 `freight_rpa/{inventory,receipt,common}` 三层布局(与 env/ps1 三侧一致)。
FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR', 'freight_rpa', 'inventory', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'freight_rpa', 'inventory', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_drop'
FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR', 'freight_rpa', 'receipt', 'drop'
)
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'shipping_notice', 'freight_receipt_rpa', 'receipt_triggers'
FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', 'freight_rpa', 'receipt', 'triggers'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR', 'shipping_notice', 'freight_rpa', 'upload_queue'
FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR', 'freight_rpa', 'inventory', 'upload_queue'
)
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'upload_triggers'
FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR = _rpa_data_path(
'FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR', 'freight_rpa', 'inventory', 'upload_triggers'
)
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR', 'shipping_notice', 'freight_rpa', 'browser_profile'
FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR = _rpa_data_path(
'FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR', 'freight_rpa', 'common', 'browser_profile'
)
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', 'freight_rpa', 'inventory_archives'
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
'FREIGHT_RPA_INVENTORY_ARCHIVE_DIR', 'freight_rpa', 'inventory', 'archives'
)
SHIPPING_NOTICE_RPA_WORKER_MOCK = _rpa_env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false')
# 旧 Flask config 属性仅用于过渡期测试和外部扩展兼容。
FREIGHT_INVENTORY_DROP_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
FREIGHT_UPLOAD_QUEUE_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR
FREIGHT_RPA_BROWSER_PROFILE_DIR = SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR
FREIGHT_RPA_INVENTORY_ARCHIVE_DIR = SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR
FREIGHT_RPA_MOCK = SHIPPING_NOTICE_RPA_WORKER_MOCK
FREIGHT_RPA_WORKER_MOCK = os.getenv('FREIGHT_RPA_WORKER_MOCK', 'false')
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
@@ -552,11 +498,13 @@ class Config:
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', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 27=员工培训)。
# 注意:默认值必须指向 content_profile=training 的培训 agent;历史默认 16 实为「通用入口」,
# 会导致卡片落地非培训 agent、前端精益页签深链不消费([FIX] 2026-09-11)。
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '27'))
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder,order_delivery_reply_notify,training_overseas_thailand_guidelines')
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>)。
# 缺省 0 = 不显式指定,由后端按 handler_config.content_profile='training' 动态解析各环境的培训 Agent
# (测试/正式环境 Agent ID 不同,动态解析保证卡片均可定位「员工培训-精益管理」);
# 仅当某环境需要固定指向特定 Agent 时才配置此项。历史默认 27 曾在部分环境错指「通用入口」导致深链失效
# ([FIX] 2026-09-18 改为动态解析,27 仅保留为解析失败时的兼容兜底)。
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '0'))
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
@@ -684,6 +632,24 @@ class Config:
VOUCHER_CHECK_DMS_LIBRARY_ID = os.getenv('VOUCHER_CHECK_DMS_LIBRARY_ID', '').strip()
VOUCHER_CHECK_DMS_ROOT_FOLDER_ID = os.getenv('VOUCHER_CHECK_DMS_ROOT_FOLDER_ID', '').strip()
# 立账凭证销货放行单:E10 OpenAPI + ecology10(密码仅 env;DATABASE 禁止回退 E9 ecology)
OA_E10_OPENAPI_BASE_URL = os.getenv('OA_E10_OPENAPI_BASE_URL', '').strip().rstrip('/')
OA_E10_CORPID = os.getenv('OA_E10_CORPID', '').strip()
OA_E10_APP_KEY = os.getenv('OA_E10_APP_KEY', '').strip()
OA_E10_APP_SECRET = os.getenv('OA_E10_APP_SECRET', '')
OA_E10_USERID = os.getenv('OA_E10_USERID', '').strip()
OA_E10_TIMEOUT_SECONDS = int(os.getenv('OA_E10_TIMEOUT_SECONDS', '30') or '30')
OA_E10_TOKEN_REFRESH_SKEW_SECONDS = int(os.getenv('OA_E10_TOKEN_REFRESH_SKEW_SECONDS', '300') or '300')
OA_E10_SQLSERVER_HOST = os.getenv('OA_E10_SQLSERVER_HOST', '').strip()
OA_E10_SQLSERVER_PORT = os.getenv('OA_E10_SQLSERVER_PORT', '').strip()
OA_E10_SQLSERVER_DATABASE = os.getenv('OA_E10_SQLSERVER_DATABASE', 'ecology10').strip() or 'ecology10'
OA_E10_SQLSERVER_USERNAME = os.getenv('OA_E10_SQLSERVER_USERNAME', '').strip()
OA_E10_SQLSERVER_PASSWORD = os.getenv('OA_E10_SQLSERVER_PASSWORD', '')
OA_E10_SQLSERVER_DRIVER = os.getenv('OA_E10_SQLSERVER_DRIVER', '').strip()
OA_E10_SQLSERVER_ENCRYPT = os.getenv('OA_E10_SQLSERVER_ENCRYPT', '').strip()
OA_E10_SQLSERVER_TRUST_CERT = os.getenv('OA_E10_SQLSERVER_TRUST_CERT', '').strip()
OA_E10_SQLSERVER_TIMEOUT = os.getenv('OA_E10_SQLSERVER_TIMEOUT', '').strip()
# MinIO 配置
MINIO_ENDPOINT = os.getenv('MINIO_ENDPOINT', '127.0.0.1:9000')
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
@@ -794,8 +760,8 @@ class DevelopmentConfig(Config):
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL')
ORDER_DOCUMENT_PROFILE_PREVIEW_ALLOW_MEMORY_FALLBACK = True
# 本机常无 Redis:不强制 Redis,允许进程内存兜底心跳(单进程 run.py 可用)
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# XFA 拆分确认 JTI:仅单进程 development 允许内存消费;test/prod 多 Worker 必须 Redis
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
@@ -816,8 +782,8 @@ class TestingConfig(Config):
FIXED_ASSETS_SYNC_ENABLED = False
FIXED_ASSETS_EXPORT_TO_DOCS = False
ENV_NAME = 'dev'
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS = False
FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK = True
# pytest 单进程:允许内存 JTI;生产语义由 ProductionConfig 关闭
XFA_SPLIT_PREVIEW_TOKEN_ALLOW_MEMORY_JTI = True
+51
View File
@@ -0,0 +1,51 @@
"""
backend/app/core/http_context.py
用途:把 Flask request 读取收口在 core,避免 services 直接依赖 flask.request。
依赖:flask.has_request_context / request(仅本模块)。
逻辑:API 与 service 需要 Host、Header、客户端 IP 时调用本模块;无请求上下文时返回空值。
"""
from __future__ import annotations
def has_http_request() -> bool:
"""
当前是否处于 HTTP 请求上下文。
返回:
有请求上下文时 True,Worker / CLI 时 False。
"""
from flask import has_request_context
return bool(has_request_context())
def header(name: str, default: str = "") -> str:
"""
读取请求头;无请求上下文时返回 default。
参数:
name: Header 名。
default: 缺省值。
"""
if not has_http_request():
return default
from flask import request
return str(request.headers.get(name) or default)
def host_url() -> str:
"""返回当前请求 host_url(无尾斜杠);无请求时返回空字符串。"""
if not has_http_request():
return ""
from flask import request
return str(request.host_url or "").rstrip("/")
def remote_addr() -> str:
"""返回 request.remote_addr;无请求时返回空字符串。"""
if not has_http_request():
return ""
from flask import request
return str(request.remote_addr or "").strip()
+31 -4
View File
@@ -2,17 +2,44 @@
backend/app/jobs/handlers/file_check_run.py
用途:文件检核异步执行 handler。
逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。
依赖:schedule.scheduler_service.run_task_now、jobs.queue.finish_job。
逻辑:schedule worker 领取 FILE_CHECK_RUN 后,按 payload 中的 task_id / schedule_run_id 执行已创建的 ScheduleRun。
"""
from __future__ import annotations
from app import db
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.scheduler_service import run_task_now
@register_handler(JobType.FILE_CHECK_RUN)
def run_file_check(ctx: JobContext, payload: dict) -> None:
"""执行异步文件检核。"""
ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload)
raise NotImplementedError('file_check_run handler pending Wave 4')
"""
执行已入队的文件检核 ScheduleRun。
核心逻辑:读取 task/run → 调用 run_task_now(与原 API 后台线程同一入口)→ finish_job。
参数:
ctx: Worker 上下文。
payload: 必须包含 task_id 与 schedule_run_id;可选 job_id。
异常:
RuntimeError: payload 缺失或任务/运行记录不存在。
"""
task_id = int(payload.get("task_id") or 0)
run_id = int(payload.get("schedule_run_id") or 0)
job_id = int(payload.get("job_id") or 0)
if not task_id or not run_id:
raise RuntimeError("task_id and schedule_run_id are required")
task = db.session.get(ScheduleTask, task_id)
run = db.session.get(ScheduleRun, run_id)
if not task or not run:
raise RuntimeError(f"file-check task/run not found task_id={task_id} run_id={run_id}")
ctx.logger.info("file_check_run start job_id=%s task_id=%s run_id=%s", job_id, task_id, run_id)
run_task_now(task, trigger_type="dify_chatflow", triggered_by_user_id=None, run=run)
if job_id:
finish_job(job_id, result={"task_id": task_id, "schedule_run_id": run_id}, message="文件检核执行完成")
@@ -4,10 +4,15 @@ backend/app/jobs/handlers/shipping_order_extraction.py
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)、
order_extraction_has_extractable_ready_work(收口自交接判断)。
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
收口时用 DB 实况判断:有 extractable ready work 则 layout_ready_continue 自交接;
仅 layouts_pending 且无 ready work 时以 partial_units_done 回到 waiting_layout;
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
两处续抽须同事务先 finish(commit=False) 再 enqueue(唯一索引含 running,
否则会撞 uq_jobs_shipping_order_extraction_active_ref);continue_from_running
仅对 queued 去重,避免复用已结束 Job;
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
@@ -46,6 +51,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
begin_input_freeze,
complete_input_freeze,
mark_order_extraction_persistence_started,
order_extraction_has_extractable_ready_work,
order_extraction_layout_prerequisite_issues,
order_extraction_layouts_pending,
order_extraction_ready_document_ids,
@@ -662,6 +668,62 @@ def _process_unit_with_retries(*, run, unit, job, owned_attempt: int) -> list[di
return None
def _handoff_continue_order_extraction(
*,
job: Job,
run: ShippingOrderProcessingRun,
owned_attempt: int,
result: dict[str, Any],
message: str,
enqueue_message: str,
phase: str,
) -> bool:
"""
同事务自交接:当前 running Job → success,再 INSERT 续抽 queued Job。
核心逻辑:finish_job(commit=False) 释放
uq_jobs_shipping_order_extraction_active_ref 槽位后,再
_enqueue_ready_order_extraction_job(continue_from_running=True);
写入 continue_job_id / Run.current_job_id 后一次 commit。
禁止先 enqueue 再 finish(running 仍占唯一索引会 UniqueViolation)。
Args:
job: 当前 running 的抽取 Job。
run: 对应 ProcessingRun。
owned_attempt: Worker 领取代次,传给 finish_job 围栏。
result: 写入旧 Job.result_json 的业务结果(本函数会补 continue_job_id)。
message: 旧 Job 收口说明。
enqueue_message: 新 Job 初始 message。
phase: 交接后 Run.phase(queued / waiting_layout)。
Returns:
True 表示已成功收口并入队;False 表示 finish 未生效(代次失效),调用方应停止。
"""
# [STEP 1] 先释放 active 唯一槽,勿在 running 时 INSERT 后继
if not finish_job(
job.id,
result=result,
message=message,
owned_attempt=owned_attempt,
commit=False,
):
return False
# [STEP 2] 同事务入队续抽;仅对 queued 去重,避免复用已 success 的本 Job
continue_job_id = _enqueue_ready_order_extraction_job(
run,
message=enqueue_message,
continue_from_running=True,
)
result['continue_job_id'] = int(continue_job_id)
run.current_job_id = int(continue_job_id)
run.phase = phase
finished = db.session.get(Job, int(job.id))
if finished is not None:
finished.result_json = dict(result)
db.session.commit()
return True
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
"""
@@ -1158,8 +1220,30 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
)
raise
# [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。
if layout_blocked_in_wave or order_extraction_layouts_pending(run):
# [STEP] 收口前用 DB 实况判断版面就绪:有可抽 ready work 则自交接续抽,
# 覆盖「Job 中途 layout 变 ready」与「开工快照过期跳过」;勿仅信 layout_blocked_in_wave。
has_ready_work = order_extraction_has_extractable_ready_work(run)
layouts_pending = order_extraction_layouts_pending(run)
if has_ready_work:
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'waiting_layout': bool(layouts_pending),
'waiting_continue': True,
'handoff_status': 'layout_ready_continue',
'merged_unit_count': len(pending_merge_unit_ids),
'ready_document_ids': sorted(ready_document_ids),
},
message='附件版面已就绪,已排队继续识别剩余附件',
enqueue_message='附件版面已就绪,继续识别剩余附件',
phase='waiting_layout' if layouts_pending else 'queued',
)
return
if layouts_pending:
# 仅仍有 layout pending、无可抽 ready work:回到 waiting_layout,靠 layout 完成回调唤醒。
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
@@ -1196,14 +1280,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
job_id=job.id,
commit=False,
)
continue_job_id = _enqueue_ready_order_extraction_job(
run, message='运行时预算已用尽,继续识别剩余附件',
)
run.current_job_id = continue_job_id
run.phase = 'waiting_layout'
db.session.commit()
finish_job(
job.id,
_handoff_continue_order_extraction(
job=job,
run=run,
owned_attempt=owned_attempt,
result={
'run_no': run.run_no,
'budget_stopped': True,
@@ -1213,10 +1293,10 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
'pending_unit_count': sum(
1 for unit in units if str(unit.status or '') == 'pending'
),
'continue_job_id': int(continue_job_id),
},
message='运行时预算已用尽,已排队继续识别剩余附件',
owned_attempt=owned_attempt,
enqueue_message='运行时预算已用尽,继续识别剩余附件',
phase='waiting_layout',
)
return
orders = persisted_orders + merged_orders
@@ -2,17 +2,38 @@
backend/app/jobs/handlers/wecom_directory_sync.py
用途:企微通讯录同步 handler。
逻辑:Wave 4 包装 wecom_directory_sync 服务。
依赖:wecom_directory_sync.sync_wecom_userids_from_directory、jobs.queue.finish_job。
逻辑:schedule worker 领取后按 payload.apply / department_id 执行通讯录回填。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.queue import finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.integrations.wecom.directory_sync import sync_wecom_userids_from_directory
@register_handler(JobType.WECOM_DIRECTORY_SYNC)
def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None:
"""同步企微通讯录到本地用户/部门。"""
ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload)
raise NotImplementedError('wecom_directory_sync handler pending Wave 4')
"""
从企微通讯录同步 users.wecom_userid。
核心逻辑:委托 sync_wecom_userids_from_directory;conflicts 时抛错由 Job 层标记失败。
参数:
ctx: Worker 上下文。
payload: apply(bool)、department_id(可选 int)、job_id(可选)。
"""
apply = bool(payload.get("apply"))
raw_dept = payload.get("department_id")
department_id = int(raw_dept) if raw_dept not in (None, "") else None
job_id = int(payload.get("job_id") or 0)
ctx.logger.info(
"wecom_directory_sync start job_id=%s apply=%s department_id=%s",
job_id,
apply,
department_id,
)
summary = sync_wecom_userids_from_directory(apply=apply, department_id=department_id)
if job_id:
finish_job(job_id, result=summary, message="企微通讯录同步完成")
+15 -1
View File
@@ -6,6 +6,7 @@ backend/app/jobs/queue.py
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
finish_job(commit=False) 可供与续抽 enqueue 同事务提交;
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
@@ -791,10 +792,22 @@ def finish_job(
result: dict[str, Any] | None = None,
message: str | None = None,
owned_attempt: int | None = None,
commit: bool = True,
) -> bool:
"""
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
核心逻辑:status/attempts 条件 UPDATE;commit=False 时不提交,供调用方与
续抽 enqueue 等同事务提交(避免 shipping_order_extraction 唯一索引仍被
本 Job running 占用时无法 INSERT 后继)。
Args:
job: Job 实例或主键。
result: 写入 result_json 的业务结果。
message: 收口说明。
owned_attempt: 非空时要求 Job.attempts 匹配,防止代次错收口。
commit: False 时仅执行 UPDATE,由调用方统一 commit。
Returns:
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
"""
@@ -819,7 +832,8 @@ def finish_job(
)
)
rowcount = int(db.session.execute(stmt).rowcount or 0)
db.session.commit()
if commit:
db.session.commit()
cached = db.session.get(Job, job_id)
if cached is not None:
db.session.expire(cached)
+7
View File
@@ -149,6 +149,13 @@ def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
)
if job:
return _normalize_generic_job(job)
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
job = claim_next_job(
domain=None,
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
)
if job:
return _normalize_generic_job(job)
return None
+1 -1
View File
@@ -81,7 +81,7 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
}),
'contract': frozenset({'procurement_contract_review', 'contract_payment_sync', 'contract_payment_alert', 'contract_payment_alert_weekly'}),
'schedule': frozenset({'schedule_run'}),
'schedule': frozenset({'schedule_run', 'file_check_run', 'wecom_directory_sync'}),
'transfer': frozenset({
'in_transit_transfer_precheck', 'in_transit_transfer_run', 'in_transit_transfer_item',
}),
+2
View File
@@ -221,6 +221,7 @@ from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgen
from app.models.voucher_check import (
VoucherCheckFileResult,
VoucherCheckNotification,
VoucherCheckNotifyConfig,
VoucherCheckProfile,
VoucherCheckRun,
VoucherCheckSubject,
@@ -420,6 +421,7 @@ __all__ = [
'VoucherCheckSubject',
'VoucherCheckFileResult',
'VoucherCheckNotification',
'VoucherCheckNotifyConfig',
'ContractPaymentContract',
'ContractPaymentAttachment',
'ContractPaymentNode',
+2
View File
@@ -45,6 +45,8 @@ class ShippingCustomer(Base):
index=True,
)
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
# 客户可用的 ODM ID 清单;为空表示不限定。生成发货 Excel 时用于收敛库存命中行。
odm_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -126,6 +126,8 @@ class ShippingNoticeLineInventoryMatch(Base):
onupdate=datetime.utcnow,
nullable=False,
)
# 整单 ODM ID 用户选择;写在当前匹配事实行上,随重匹配轮次自然失效。
chosen_odm_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
# T6: 行级实际源证据(决策 E1 硬约束)——用于幂等保护与跨源匹配审计。
matched_file_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
matched_row_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
@@ -29,7 +29,7 @@ class ShippingReceiptReportConfig(Base):
inventory_source_id: Mapped[int] = mapped_column(
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
@@ -40,10 +40,7 @@ class ShippingReceiptReportConfig(Base):
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
warehouse_ids_json: Mapped[list[str]] = mapped_column(
JSON, default=list, server_default=text("'[]'"), nullable=False,
)
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
+2 -6
View File
@@ -109,7 +109,7 @@ class User(Base):
返回当前用户的有效功能权限。
用途:统一为前端展示、登录态注入与后端业务校验提供同一份权限结果。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训、合同付款等业务权限硬编码在多个模块。
核心逻辑:先按角色生成默认权限,再用用户显式配置覆盖,避免把培训等业务权限硬编码在多个模块。
输出约束:仅返回布尔型权限键,缺失项自动回退到角色默认值。
"""
defaults = self._role_default_feature_permissions()
@@ -127,7 +127,7 @@ class User(Base):
保存用户显式配置的功能权限覆盖项。
用途:给管理后台用户编辑表单落库权限配置。
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。
核心逻辑:只持久化与角色默认值不同的权限,既保留“admin/hr 角色默认可见”的现有语义,也支持前端手动关闭或给普通用户单独授予。合同付款预警改走 Agent 授权,不再占用功能权限键。
参数约束:permissions 必须为 dict 或 None;未知键会被忽略。
"""
defaults = self._role_default_feature_permissions()
@@ -149,10 +149,6 @@ class User(Base):
"""判断当前用户是否可使用培训 HR 管理面板与接口。"""
return self.has_feature_permission('training_hr_manage')
def can_access_contract_payment(self) -> bool:
"""判断当前用户是否可查看合同付款预警工作台并触发同步/扫描。"""
return self.has_feature_permission('contract_payment.access')
def set_password(self, password: str) -> None:
"""设置密码哈希。"""
self.password_hash = generate_password_hash(password)
+27 -4
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/voucher_check.py
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知)。
用途:立账凭证检核 ORM(Profile / 批次 / 主体 / 单文件结果 / 企微通知 / 按类型接收人)。
依赖:models.base.Base、schedule_runs。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;工作台与查询服务只读这些表。
逻辑:引擎写入 profiles/runs/subjects/file_results/notifications;通知配置表供管理员维护文件类型接收人。
"""
from __future__ import annotations
@@ -17,6 +17,7 @@ from sqlalchemy import (
DateTime,
ForeignKey,
Index,
Integer,
JSON,
String,
Text,
@@ -158,13 +159,35 @@ class VoucherCheckFileResult(Base):
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
class VoucherCheckNotifyConfig(Base):
"""按业务方保存文件类型 → 接收人;换人不改 Profile 版本。"""
__tablename__ = "voucher_check_notify_configs"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
profile_code: Mapped[str] = mapped_column(String(32), nullable=False, unique=True)
recipients_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
updated_by: Mapped[Optional[int]] = mapped_column(
Integer,
ForeignKey("users.id", ondelete="SET NULL"),
nullable=True,
)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(
DateTime,
default=datetime.utcnow,
onupdate=datetime.utcnow,
nullable=False,
)
class VoucherCheckNotification(Base):
"""一个检核批次对应一条企微汇总通知审计。"""
"""一个检核批次对应一条企微缺件通知审计(可含多人分信摘要)。"""
__tablename__ = "voucher_check_notifications"
__table_args__ = (Index("ix_voucher_check_notifications_status", "send_status"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True)
run_id: Mapped[int] = mapped_column(
BigInteger,
ForeignKey("voucher_check_runs.id", ondelete="CASCADE"),
+1 -1
View File
@@ -27,7 +27,7 @@ from app.services.admin.training_exam_pdf_service import parse_training_question
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
from app.services.agent_registry.catalog_loader import get_dify_required_providers
from app.services.agent_registry.serialization import serialize_agent_for_admin
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
def serialize_agent(agent: Agent) -> dict:
+1 -1
View File
@@ -14,7 +14,7 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import AgentGuide
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
GUIDE_USAGE_GENERAL = 'general'
@@ -11,8 +11,8 @@ from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import Agent, User
from app.services.wecom_notify import send_wecom_event_message
from app.models import Agent, PermissionRequest, User
from app.services.integrations.wecom.notify import send_wecom_event_message
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
@@ -37,6 +37,47 @@ from app.services.shipping_notice.customer_normalization import (
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
_ODM_ID_MAX_ITEMS = 100
_ODM_ID_MAX_LENGTH = 64
def _normalize_odm_ids(value: Any) -> list[str] | None:
"""
规范化客户 ODM ID 清单:逐项 trim、去空、去重(保持原顺序)。
Args:
value: 前端提交的清单(字符串列表);None 表示未提交,空列表表示清空。
Returns:
规范化后的清单;None 仅当输入为 None。
Raises:
ValidationError: 条目超长或清单超量。
"""
if value is None:
return None
if not isinstance(value, list):
raise ValidationError(
'ODM ID list must be an array of strings',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
normalized: list[str] = []
for item in value:
text = str(item or '').strip()
if not text:
continue
if len(text) > _ODM_ID_MAX_LENGTH:
raise ValidationError(
'ODM ID is too long',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
details={'odm_id': text},
)
if text not in normalized:
normalized.append(text)
if len(normalized) > _ODM_ID_MAX_ITEMS:
raise ValidationError(
'Too many ODM IDs',
code='SHIPPING.CUSTOMER_ODM_IDS_INVALID',
)
return normalized
def _record_lifecycle_event(
@@ -142,6 +183,7 @@ def serialize_customer(
'status': record.status,
'merged_into_customer_id': record.merged_into_customer_id,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
'created_by_id': record.created_by_id,
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
@@ -318,6 +360,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
short_code=short_code,
status=status,
remark=clean_text(data.get('remark')) or None,
odm_ids=_normalize_odm_ids(data.get('odm_ids')) if 'odm_ids' in data else None,
created_by_id=actor_id,
updated_by_id=actor_id,
)
@@ -385,11 +428,13 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
'short_code': record.short_code,
'status': record.status,
'remark': record.remark,
'odm_ids': list(record.odm_ids or []) if record.odm_ids is not None else None,
}
next_name = before['standard_name']
next_short_code = before['short_code']
next_status = before['status']
next_remark = before['remark']
next_odm_ids = before['odm_ids']
if 'standard_name' in data:
name = clean_text(data.get('standard_name'))
if not name:
@@ -404,11 +449,14 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
if 'remark' in data:
next_remark = clean_text(data.get('remark')) or None
if 'odm_ids' in data:
next_odm_ids = _normalize_odm_ids(data.get('odm_ids'))
after = {
'standard_name': next_name,
'short_code': next_short_code,
'status': next_status,
'remark': next_remark,
'odm_ids': next_odm_ids,
}
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
if changes:
@@ -418,6 +466,7 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
record.short_code = next_short_code
record.status = next_status
record.remark = next_remark
record.odm_ids = next_odm_ids
record.updated_by_id = actor_id
_record_lifecycle_event(
record,
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
return dict(value)
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
value = data.get(field, [])
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
result: list[str] = []
for item in value:
normalized = item.strip()
if normalized and normalized not in result:
result.append(normalized)
return result
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
value = data.get('login_config_json', {})
@@ -269,19 +256,18 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
return {
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
'id': config.id, 'inventory_source_id': config.inventory_source_id,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
'config_version': config.config_version,
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
}
def _validate_receipt_report_config(
source: ShippingInventorySource, data: dict[str, Any],
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
enabled = _bool(data, 'enabled', True)
) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
try:
parameters = _validate_query_parameters(data)
except ValidationError as exc:
@@ -289,19 +275,22 @@ def _validate_receipt_report_config(
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
raw_path = _json_object(data, 'report_path_json')
if source.connector_type == 'dbs':
try:
path = _validate_report_path('dbs', raw_path)
except ValidationError as exc:
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
if enabled and not raw_warehouses:
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
return enabled, path, parameters, raw_warehouses
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
if len(warehouse_conditions) != 1 or not any(warehouse_values):
raise ValidationError(
'DBS receipt report requires exactly one Warehouse query condition with values',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return path, parameters
if source.connector_type == 'crane':
if raw_warehouses:
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
if parameters:
@@ -309,7 +298,7 @@ def _validate_receipt_report_config(
'Crane receipt report does not support query parameters',
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
)
return enabled, {'report_name': 'Inbound Details'}, [], []
return {'report_name': 'Inbound Details'}, []
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
@@ -327,7 +316,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
path, parameters = _validate_receipt_report_config(source, data)
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
before = _receipt_report_config_payload(config) if config else None
is_new = config is None
@@ -337,10 +326,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
db.session.add(config)
else:
config.config_version += 1
config.enabled = enabled
config.report_path_json = path
config.query_parameters_json = parameters
config.warehouse_ids_json = warehouses
config.updated_by = actor_id
db.session.flush()
after = _receipt_report_config_payload(config)
@@ -20,7 +20,7 @@ from app.core.errors import NotFoundError, ValidationError
from app.models import AgentGuide, KbDocumentVersion
from app.services.admin.guide_service import GUIDE_USAGE_TRAINING_EXAM_PDF
from app.services.kb.storage import resolve_storage_path
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_pdf, ocr
@@ -21,7 +21,7 @@ from app.core.config.env_persistence import persist_env_settings
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import Agent, LoginAudit, User, WecomNotifyAudit
from app.services.auth import wecom_auth_service
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
def serialize_debug_match_user(user: User) -> dict:
@@ -12,5 +12,7 @@ from __future__ import annotations
RUNTIME_HANDLER_BINDINGS: dict[str, str] = {
'shipping_notice': 'shipping_notice',
'file_check': 'file_check',
'contract_payment': 'contract_payment',
'voucher_check': 'voucher_check',
'in_transit_transfer': 'in_transit_transfer',
}
@@ -129,6 +129,37 @@ agent_types:
file_upload: true
human_confirm: false
handler_config_schema: {}
contract_payment:
label: 合同付款预警
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- ContractPaymentContract
- ContractPaymentAlert
- ContractPaymentAlertBatch
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
voucher_check:
label: 立账凭证
conversation_mode_default: task_chat
runtime_provider_default: builtin
models:
- VoucherCheckRun
- VoucherCheckNotification
required_fields: []
default_capabilities:
streaming: false
file_upload: false
task_progress: false
forced_capabilities:
file_upload: false
handler_config_schema: {}
in_transit_transfer:
label: 在途仓自动调拨
conversation_mode_default: task_chat
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/bootstrap.py
用途:应用启动时加载 HANDLER_REGISTRY。
依赖:handlers.shipping_notice 等领域 handler 模块。
依赖:handlers.shipping_notice、handlers.contract_payment、handlers.voucher_check 等领域 handler 模块。
逻辑:create_app 在 load_context_adapters 之后调用 load_handlers()。
"""
@@ -29,12 +29,16 @@ def load_handlers() -> None:
import importlib
import app.services.agent_registry.handlers.contract_payment as contract_payment_mod
import app.services.agent_registry.handlers.file_check as file_check_mod
import app.services.agent_registry.handlers.in_transit_transfer as in_transit_transfer_mod
import app.services.agent_registry.handlers.shipping_notice as shipping_mod
import app.services.agent_registry.handlers.voucher_check as voucher_check_mod
importlib.reload(file_check_mod)
importlib.reload(shipping_mod)
importlib.reload(contract_payment_mod)
importlib.reload(voucher_check_mod)
importlib.reload(in_transit_transfer_mod)
logger.info('Agent handlers loaded: %s', sorted(HANDLER_REGISTRY.keys()))
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/contract_payment.py
用途:合同付款预警 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染台账 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('contract_payment')
class ContractPaymentHandler(AgentHandler):
"""
合同付款预警业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入合同摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;台账由独立 HTTP API 加载。"""
return None
@@ -0,0 +1,31 @@
"""
backend/app/services/agent_registry/handlers/voucher_check.py
用途:立账凭证检核 builtin Handler。第一期不走对话 completions,只满足 Catalog 对 builtin 必须声明 runtime_handler 的校验。
依赖:agent_registry.handlers.base / registry。
逻辑:Chat 主区渲染检核任务 / 企微发送记录 Tab,不调用 Dify;prepare_stream 原样返回上下文,供后续 hybrid 接入预留。
"""
from __future__ import annotations
from typing import Any
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
@register_handler('voucher_check')
class VoucherCheckHandler(AgentHandler):
"""
立账凭证检核业务 Handler。
核心逻辑:第一期隐藏输入框,不进入聊天流;保留钩子以便第二期改 hybrid 后注入批次摘要。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
"""聊天流开始前原样返回上下文;第一期前端不会发起 completions。"""
return ctx
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
"""第一期无领域 UI State;检核列表由独立 HTTP API 加载。"""
return None
@@ -15,7 +15,7 @@ from app.services.chat.executors.base import (
ChatStreamContext,
build_dify_inputs_for_context,
)
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
class DifyChatExecutor(ChatExecutor):
@@ -16,13 +16,13 @@ from app.services.chat.intent_route_registry import (
def _match(ctx: ChatIntentRouteContext) -> bool:
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.supports(ctx.query, ctx.agent)
def _stream(ctx: ChatIntentRouteContext):
from app.services.plm_oracle import PLMOracleService
from app.services.integrations.plm.oracle import PLMOracleService
return PLMOracleService.stream_chat(
ctx.query,
@@ -27,7 +27,7 @@ def _match(ctx: ChatIntentRouteContext) -> bool:
def _stream(ctx: ChatIntentRouteContext):
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
return Text2SQLService.stream_chat(
ctx.query,
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
@@ -29,7 +29,7 @@ from app.models import (
ContractPaymentNode,
User,
)
from app.services.wecom_notify import (
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
@@ -53,7 +53,7 @@ def fetch_paid_records(purchase_order_nos: Iterable[str]) -> dict[str, list[ErpP
return {}
try:
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
except ImportError:
current_app.logger.warning("合同付款预警:Oracle 驱动不可用,按未付款处理")
return {}
@@ -1,9 +1,9 @@
"""
backend/app/services/contract_payment/ledger_focus.py
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
用途:合同台账汇总卡口径——即将到期、逾期未付、进行中、本月应付,均按合同计数。
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
逻辑:由 list/summary API 调用;即将到期/逾期/进行中互斥,本月应付可与这三项重叠。行级「待补充」不进汇总卡。
"""
from __future__ import annotations
@@ -20,12 +20,12 @@ from app.models import ContractPaymentContract, ContractPaymentNode
LEDGER_FOCUS_DUE = "due"
LEDGER_FOCUS_OVERDUE = "overdue"
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
LEDGER_FOCUS_ACTIVE = "active"
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
LEDGER_FOCUS_VALUES = {
LEDGER_FOCUS_DUE,
LEDGER_FOCUS_OVERDUE,
LEDGER_FOCUS_NEEDS_COMPLETION,
LEDGER_FOCUS_ACTIVE,
LEDGER_FOCUS_DUE_THIS_MONTH,
}
_NEAR_DUE_DAYS = 7
@@ -68,7 +68,7 @@ def classify_ledger_status(
"""
按合同聚合出台账状态,与列表「状态」列一致。
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
核心逻辑:非激活或待确认 → 待补充(仅行状态,不进汇总卡);无进行中节点则按是否已付分为已完成/待补充;
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
Args:
contract_status: 合同主状态。
@@ -80,16 +80,16 @@ def classify_ledger_status(
"""
node_list = list(nodes)
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
if not node_list:
return LEDGER_FOCUS_NEEDS_COMPLETION
return "needs_completion"
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
if not active:
has_paid = any(
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
for node in node_list
)
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
return "completed" if has_paid else "needs_completion"
refs = [
ref
for node in active
@@ -99,7 +99,7 @@ def classify_ledger_status(
return LEDGER_FOCUS_OVERDUE
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
return LEDGER_FOCUS_DUE
return "active"
return LEDGER_FOCUS_ACTIVE
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
@@ -138,7 +138,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
"""
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。进行中为未到期且未逾期的未付合同;本月应付可与即将到期、逾期或进行中重叠。
Args:
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
@@ -154,7 +154,7 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets: dict[str, set[int]] = {
LEDGER_FOCUS_DUE: set(),
LEDGER_FOCUS_OVERDUE: set(),
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
LEDGER_FOCUS_ACTIVE: set(),
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
}
if not contracts:
@@ -180,8 +180,8 @@ def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict
buckets[LEDGER_FOCUS_DUE].add(row.id)
elif status == LEDGER_FOCUS_OVERDUE:
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
elif status == LEDGER_FOCUS_ACTIVE:
buckets[LEDGER_FOCUS_ACTIVE].add(row.id)
if has_unpaid_due_this_month(nodes, as_of):
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
return buckets
@@ -195,7 +195,7 @@ def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[
session: 当前请求的 SQLAlchemy 会话。
today: 可选业务日。
Returns:
due / overdue / needs_completion / due_this_month 的计数。
due / overdue / active / due_this_month 的计数。
"""
buckets = collect_ledger_focus(session=session, today=today)
return {key: len(ids) for key, ids in buckets.items()}
@@ -16,7 +16,7 @@ from typing import Any
from flask import current_app
from app.services.oa_sqlserver import OASQLServerService
from app.services.integrations.oa.sqlserver import OASQLServerService
# [STEP] 仅允许字母数字下划线作为 SQL 标识符,表名/字段来自配置,禁止拼接任意字符串。
_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -14,8 +14,8 @@ from flask import current_app
from app import db
from app.models import KbDifySyncRecord, QuickQuestion
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
from app.services.integrations.dify import DifyService
from app.services.integrations.integration_api import IntegrationApiService
STALE_REASON_KB_UPDATED = 'kb_document_updated'
STALE_REASON_KB_DELETED = 'kb_document_deleted'
+1 -1
View File
@@ -12,7 +12,7 @@ from typing import Any
import requests
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
VALID_FILE_CHECK_RESULTS = {"合格", "不合格", "人工判定"}
@@ -284,7 +284,7 @@ ORDER BY faj.faj02
def _fetch_snapshot_rows(cls, timeout_seconds: int) -> list[dict[str, str]]:
"""从 ERP Oracle 拉取固定资产全量快照。"""
import oracledb
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
username, password, dsn = cls._oracle_credentials()
Text2SQLService._init_oracle_client(oracledb)
@@ -729,7 +729,7 @@ INSERT INTO fixed_assets (
user_context: dict[str, Any] | None = None,
) -> tuple[str, list[str], dict[str, Any]]:
"""根据用户问句生成本地快照过滤条件。"""
from app.services.text2sql import Text2SQLService
from app.services.integrations.text2sql import Text2SQLService
clauses: list[str] = []
params: list[str] = []
+13 -11
View File
@@ -2,12 +2,14 @@
backend/app/services/hxops_tool_api.py
用途:解析 HXOPS 两类对外基地址——Dify Tool API(服务端)与用户浏览器访问(下载链等)。
依赖:Flask current_app / request。
依赖:Flask current_app、core.http_context。
逻辑:Dify/RPA 调 Tool API 走 resolve_HXOPS_TOOLS_API_BASE;用户可见下载链走 resolve_hxops_user_facing_base_url。
"""
from __future__ import annotations
from flask import current_app, has_request_context, request
from flask import current_app
from app.core.http_context import has_http_request, host_url
def _resolve_config(config: dict | None = None) -> dict:
@@ -25,11 +27,11 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
核心逻辑:仅读 HXOPS_TOOLS_API_BASE(常为内网 IP),与浏览器下载链、PUBLIC_BASE_URL 分离。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 request.host_url。
request_host: 可选请求 host_url;缺省且在请求上下文中时取 host_url()。
Returns:
返回:
无尾斜杠的根地址,如 http://192.168.100.192:8890。
"""
cfg = _resolve_config(config)
@@ -39,8 +41,8 @@ def resolve_HXOPS_TOOLS_API_BASE(*, config: dict | None = None, request_host: st
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
if host is None and has_http_request():
host = host_url()
return host or ""
@@ -50,10 +52,10 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
核心逻辑:仅读 HXOPS_PUBLIC_BASE_URL / WECOM_PUBLIC_BASE_URL,不复用 Tool API 内网地址或通知地址。
Args:
参数:
config: 可选配置字典;缺省时读 current_app.config。
Returns:
返回:
无尾斜杠的根地址,如 https://ai.example.com。
"""
cfg = _resolve_config(config)
@@ -63,7 +65,7 @@ def resolve_hxops_user_facing_base_url(*, config: dict | None = None) -> str:
if configured:
return configured
if has_request_context():
return request.host_url.rstrip("/")
if has_http_request():
return host_url()
return resolve_HXOPS_TOOLS_API_BASE(config=cfg)
@@ -1,19 +1,20 @@
"""在途调拨依赖装配(Dependencies)。
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
依赖:file_preparation / erp_adapter / precheck_service / models。
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
"""
from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
from app.services.in_transit_transfer.precheck_service import (
RouteMapping,
RouteNotResolvedError,
@@ -21,28 +22,6 @@ from app.services.in_transit_transfer.precheck_service import (
TransferDeps,
)
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
class ReceiptRowsNotFrozenError(AppError):
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
def __init__(self, message: str = "receipt file row contract not frozen"):
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
class ShippingReceiptFileRepository:
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
"""
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
raise ReceiptRowsNotFrozenError(
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
)
class DefaultRouteResolver:
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
@@ -86,7 +65,7 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
def get_transfer_dependencies() -> TransferDeps:
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
if _override is not None:
return _override
return TransferDeps(
@@ -98,21 +77,19 @@ def get_transfer_dependencies() -> TransferDeps:
class _DefaultRpaTrigger:
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
"""
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
from flask import current_app
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
trigger_dir = str(
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
).strip()
if not trigger_dir:
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
return {
"ok": bool(outcome.get("ok")),
"callback_id": outcome.get("callback_id"),
"error_code": outcome.get("error_code"),
"error_message": outcome.get("error_message"),
}
@@ -6,7 +6,9 @@
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
movement_contract、openpyxl。
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
file_parser 完成。
"""
from __future__ import annotations
@@ -31,14 +33,14 @@ class ShippingReceiptFileRepository:
source_code: 来源实例编码。
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
Returns:
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
return None
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None or config.parsing_profile_id is None:
return None
profile = config.parsing_profile
@@ -85,7 +87,8 @@ def _extract_movement_rows(
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
"""
from openpyxl import load_workbook
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
@@ -112,7 +115,15 @@ def _extract_movement_rows(
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
sheet_title = str(ws.title or '').strip()
return [
{"sheet": sheet_title, "row_no": header_idx + 2 + offset,
**_map_header_row(headers, row, header_to_code)}
for offset, row in enumerate(data_rows)
]
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
@@ -37,6 +37,7 @@ from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
from app.services.in_transit_transfer.file_parser import (
ParsedReceiptRow,
ReceiptFileSchemaError,
parse_movement_rows,
parse_receipt_rows,
)
from app.services.in_transit_transfer.file_preparation import (
@@ -188,7 +189,9 @@ def run_precheck(
"file_version": ready_file.file_version,
"checksum": ready_file.checksum,
}
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
# 真实仓库(movement_file_repository)产出 movement 领域字段行
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
source_items = _precheck_invoices(
invoices=invoices,
@@ -9,7 +9,7 @@
from __future__ import annotations
from datetime import datetime
from datetime import datetime, timedelta
from app import db
from app.models import TransferSourceJob
@@ -55,3 +55,33 @@ def advance_source_job_from_receipt_callback(
job.finished_at = datetime.utcnow()
db.session.flush()
return job
def recover_stale_waiting_source_jobs() -> int:
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
Returns:
本次回收的任务数。
"""
from flask import current_app
try:
timeout = max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
timeout = 900
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
stale = (
TransferSourceJob.query
.filter(TransferSourceJob.status == _WAITING_RPA_CALLBACK, TransferSourceJob.updated_at < cutoff)
.all()
)
for job in stale:
job.status = _FAILED
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
job.error_message = f'receipt rpa callback not received within {timeout}s'
job.finished_at = datetime.utcnow()
if stale:
db.session.commit()
return len(stale)
@@ -2,10 +2,11 @@
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
写 trigger writer 可注入替身(测试)。
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
"""
from __future__ import annotations
@@ -23,27 +24,29 @@ def _build_trigger_unit(
) -> dict[str, Any]:
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
raise RuntimeError(f'source not enabled: {source_code}')
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
if config is None:
raise RuntimeError(f'receipt config missing: {source_code}')
profile = source.rpa_profile
if profile is None or not profile.enabled:
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses else None
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
snapshot = {
'config_id': config.id, 'config_version': config.config_version,
'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {},
'query_parameters_json': config.query_parameters_json or [],
'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return {
'unit_run_id': 0,
'inventory_source_id': source.id,
'callback_id': f'receipt:{uuid.uuid4().hex}',
'source_code': source.source_code,
'connector_type': source.connector_type,
@@ -71,7 +74,7 @@ def trigger_receipt_rpa(
reason: str = 'transfer_retry_receipt',
writer: RouteTriggerWriter | None = None,
) -> dict[str, Any]:
"""触发一次来源收料 RPA 抓取。
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
Args:
source_code: 来源实例编码。
@@ -83,13 +86,33 @@ def trigger_receipt_rpa(
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
"""
try:
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
except RuntimeError as exc:
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
from app import db
from app.models import ShippingReceiptRpaUnitRun
unit = ShippingReceiptRpaUnitRun(
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
inventory_source_id=unit_payload['inventory_source_id'],
source_code=unit_payload['source_code'],
connector_type=unit_payload['connector_type'],
warehouse_id=unit_payload.get('warehouse_id'),
callback_id=unit_payload['callback_id'],
status='awaiting_rpa',
config_snapshot_json=dict(unit_payload['config_snapshot']),
)
db.session.add(unit)
db.session.flush()
unit_payload['unit_run_id'] = unit.id
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
writer_fn = writer or write_receipt_export_batch_trigger
path = writer_fn(run_no, [unit], payload={
path = writer_fn(run_no, [unit_payload], payload={
'schema_version': 'shipping_receipt_rpa.v1',
'action': 'receipt_export_batch',
'source_code': source_code,
@@ -97,5 +120,13 @@ def trigger_receipt_rpa(
'reason': reason,
})
if not path:
unit.status = 'failed'
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
unit.error_message = 'receipt trigger directory unavailable'
db.session.commit()
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
unit.trigger_snapshot_json = unit_payload
db.session.commit()
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
-514
View File
@@ -1,514 +0,0 @@
"""
backend/app/services/integration_api.py
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask request/current_app、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import requests
from flask import current_app, has_app_context, has_request_context, request
from app.core.config.settings import Config
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _request_origin_url() -> str:
if not has_request_context():
return ""
forwarded_proto = (request.headers.get("X-Forwarded-Proto") or "").split(",")[0].strip()
forwarded_host = (request.headers.get("X-Forwarded-Host") or "").split(",")[0].strip()
if forwarded_proto and forwarded_host:
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
origin = str(request.headers.get("Origin") or "").strip().rstrip("/")
if origin:
return origin
referer = str(request.headers.get("Referer") or "").strip()
if referer:
parsed = urlparse(referer)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return request.host_url.rstrip("/")
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
return None
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id or not row.get("found"):
return None
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
return None
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
return key, normalized
@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 = ""
# For server-side lookups, always prefer the explicitly configured
# integration service endpoint when present. Falling back to the current
# request host would incorrectly call this backend itself.
if configured:
return configured
if mode != "external":
request_origin = IntegrationApiService._request_origin_url()
if request_origin:
return request_origin
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))
@staticmethod
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
exp_str = payload.get("download_url_expires_at")
if exp_str:
try:
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
except Exception:
pass
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
source_url = payload.get("source_download_url") or ""
if "token=" in source_url:
try:
import base64
import json
from urllib.parse import urlparse, parse_qs
import time
qs = parse_qs(urlparse(source_url).query)
if 'token' in qs:
token = qs['token'][0]
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300:
return False # 已过期或即将过期
except Exception:
pass
return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
normalized_dataset_id = str(dataset_id or '').strip()
normalized_remote_document_id = str(remote_document_id or '').strip()
if not normalized_dataset_id or not normalized_remote_document_id:
return None
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.dataset_id == normalized_dataset_id,
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_request_context():
base_url = request.host_url.rstrip('/')
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': normalized_dataset_id,
'remote_document_id': normalized_remote_document_id,
'version_id': version.id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
return None
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
cached = IntegrationApiService._cache.get(cache_key)
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
params = {
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code == 200:
payload = resp.json()
if isinstance(payload, dict):
IntegrationApiService._cache[cache_key] = payload
return payload
elif has_app_context():
current_app.logger.info(
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
resp.status_code,
)
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
batch_url = f"{base_url}/api/integration/dify-files/resolve"
batch_headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
batch_body = {
"items": [
{
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
]
}
try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code == 200:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
if key == cache_key:
return normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# Last fallback: query Dify document API directly and request a signed download URL.
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
"""
Batch resolve source files by (dataset_id, remote_document_id).
Returns a mapping keyed by (dataset_id, remote_document_id).
"""
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
if not items:
return results
unresolved: List[Dict[str, str]] = []
seen = set()
for item in items:
dataset_id = str(item.get("dataset_id") or "").strip()
remote_document_id = str(item.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in seen:
continue
seen.add(key)
cached = IntegrationApiService._cache.get(key)
if cached and IntegrationApiService._is_cache_valid(cached):
results[key] = cached
else:
unresolved.append({
"dataset_id": dataset_id,
"remote_document_id": remote_document_id,
})
if not unresolved:
return results
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return results
url = f"{base_url}/api/integration/dify-files/resolve"
headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
body = {"items": unresolved}
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if has_app_context():
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
else:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup or local DB for unresolved items
for item in unresolved:
dataset_id = item["dataset_id"]
remote_document_id = item["remote_document_id"]
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in results:
continue
# Check if single lookup was not called already (if it was, it might be cached)
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results
@@ -2,16 +2,17 @@
backend/app/services/integration_tool_auth.py
用途:Dify / 集成方 HTTP Tool API 共用鉴权(Bearer 或 X-Integration-Key)。
依赖:Flask current_app、core.errors。
依赖:Flask current_app、core.errors、core.http_context。
逻辑:file-check / accounting-voucher-check 等 Tool Blueprint before_request 调用;
密钥优先 FILE_CHECK_TOOL_API_KEY,回退 INTEGRATION_API_KEY。
"""
from __future__ import annotations
from flask import current_app, request
from flask import current_app
from app.core.errors import ServiceUnavailableError, UnauthorizedError
from app.core.http_context import header
def require_integration_tool_auth() -> None:
@@ -19,7 +20,7 @@ def require_integration_tool_auth() -> None:
校验 Tool API 访问权限。
核心逻辑:Authorization Bearer 与 X-Integration-Key 二选一,值须与配置密钥完全一致。
Raises:
异常:
ServiceUnavailableError: 服务端未配置密钥。
UnauthorizedError: 缺少或错误的凭证。
"""
@@ -34,9 +35,9 @@ def require_integration_tool_auth() -> None:
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
bearer = header("Authorization").strip()
api_token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
integration_key = header("X-Integration-Key").strip()
if configured in {api_token, integration_key}:
return
if not api_token and not integration_key:
File diff suppressed because it is too large. Load diff
@@ -1,8 +1,514 @@
"""
backend/app/services/integrations/integration_api.py
用途:知识库源文件反查等集成 API 适配。
用途:解析 Dify dataset/document 对应的源文件下载链接(本地 KB 映射 + Dify 签名 URL 兜底)。
依赖:Flask current_app、core.http_context、requests、Kb* 模型。
逻辑:chat.resolve_source_file / 预览代理调用本服务;本地无可读文件时回退 Dify download。
"""
from app.services import integration_api # noqa: F401
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse
__all__ = ['integration_api']
import requests
from flask import current_app, has_app_context
from app.core.config.settings import Config
from app.core.http_context import has_http_request, header, host_url
class IntegrationApiService:
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
@staticmethod
def _request_origin_url() -> str:
if not has_http_request():
return ""
forwarded_proto = header("X-Forwarded-Proto").split(",")[0].strip()
forwarded_host = header("X-Forwarded-Host").split(",")[0].strip()
if forwarded_proto and forwarded_host:
return f"{forwarded_proto}://{forwarded_host}".rstrip("/")
origin = header("Origin").strip().rstrip("/")
if origin:
return origin
referer = header("Referer").strip()
if referer:
parsed = urlparse(referer)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return host_url()
@staticmethod
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
"""
if not dataset_id or not remote_document_id:
return None
try:
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
except Exception:
return None
try:
service = KbDifySyncService()
if not service.base_url or not service.api_key:
return None
document_payload = service.get_document(
dataset_id=str(dataset_id),
document_id=str(remote_document_id),
)
if not isinstance(document_payload, dict):
return None
download_resp = requests.get(
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
headers=service._headers(),
timeout=(5, 15),
)
if download_resp.status_code != 200:
if has_app_context():
current_app.logger.info(
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
download_resp.status_code,
)
return None
download_payload = download_resp.json() if download_resp.content else {}
source_url = str((download_payload or {}).get("url") or "").strip()
if not source_url:
return None
upload_info = (
((document_payload.get("data_source_info") or {}).get("upload_file"))
if isinstance(document_payload.get("data_source_info"), dict)
else {}
) or {}
source_filename = str(
upload_info.get("name")
or document_payload.get("name")
or ""
).strip() or None
source_ext = str(
upload_info.get("extension")
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
).strip().lower() or None
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
return {
"source_download_url": source_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": expires_at,
"version_id": None,
"document_id": remote_document_id,
}
except Exception as e:
if has_app_context():
current_app.logger.warning(
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
dataset_id,
remote_document_id,
e,
)
return None
@staticmethod
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
if not isinstance(row, dict):
return None
req = row.get("request") if isinstance(row.get("request"), dict) else {}
dataset_id = str(req.get("dataset_id") or "").strip()
remote_document_id = str(req.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id or not row.get("found"):
return None
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
source_url = doc.get("source_download_url")
if not source_url:
return None
normalized = {
"source_download_url": source_url,
"source_filename": doc.get("source_filename"),
"source_ext": doc.get("source_ext"),
"download_url_expires_at": doc.get("download_url_expires_at"),
"version_id": doc.get("version_id"),
"document_id": doc.get("document_id"),
}
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
return key, normalized
@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 = ""
# 服务端查询优先使用显式配置的集成服务地址;
# 回退到当前请求 host 会错误地打到本后端自身。
if configured:
return configured
if mode != "external":
request_origin = IntegrationApiService._request_origin_url()
if request_origin:
return request_origin
if public_base:
return public_base
if has_http_request():
return host_url()
return configured
@staticmethod
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
return (str(dataset_id), str(remote_document_id))
@staticmethod
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
exp_str = payload.get("download_url_expires_at")
if exp_str:
try:
return datetime.fromisoformat(exp_str) > datetime.now().astimezone()
except Exception:
pass
# 如果没有明确的过期时间,尝试解析 url 里的 JWT token 检查
source_url = payload.get("source_download_url") or ""
if "token=" in source_url:
try:
import base64
import json
from urllib.parse import urlparse, parse_qs
import time
qs = parse_qs(urlparse(source_url).query)
if 'token' in qs:
token = qs['token'][0]
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300:
return False # 已过期或即将过期
except Exception:
pass
return True
@staticmethod
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
"""
从本地 KbDifySyncRecord 反查可预览下载链接。
核心逻辑:优先返回磁盘上存在的源文件;缺失时回退清洗 Markdown;
两者皆无则返回 None,让上层继续走 Dify 签名下载兜底。
"""
if not has_app_context():
return None
from pathlib import Path
from app import db
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
normalized_dataset_id = str(dataset_id or '').strip()
normalized_remote_document_id = str(remote_document_id or '').strip()
if not normalized_dataset_id or not normalized_remote_document_id:
return None
record = (
db.session.query(KbDifySyncRecord)
.join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id)
.join(KbDocument, KbDocument.id == KbDocumentVersion.document_id)
.filter(
KbDocument.is_deleted.is_(False),
KbDifySyncRecord.dataset_id == normalized_dataset_id,
KbDifySyncRecord.remote_document_id == normalized_remote_document_id,
)
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
.first()
)
if not record or not record.document_version or not record.document_version.document:
return None
version = record.document_version
document = version.document
def _existing(path_value: str | None):
if not path_value:
return None
raw = Path(str(path_value))
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
candidate = (raw if raw.is_absolute() else (root / raw)).resolve()
try:
candidate.relative_to(root)
except ValueError:
return None
if candidate.exists() and candidate.is_file():
return candidate
return None
source_path = _existing(version.source_file_path)
markdown_path = _existing(version.cleaned_file_path) or _existing(version.cleaned_preview_path)
if source_path is None and markdown_path is None:
current_app.logger.info(
'[integration-lookup] local mapping found but no readable file document_id=%s version_id=%s',
document.id,
version.id,
)
return None
base_url = IntegrationApiService._request_origin_url()
if not base_url:
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
if explicit:
base_url = explicit
elif has_http_request():
base_url = host_url()
else:
base_url = ''
import time
import jwt
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not secret:
secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip()
exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens
payload = {
'dataset_id': normalized_dataset_id,
'remote_document_id': normalized_remote_document_id,
'version_id': version.id,
'exp': exp
}
token = jwt.encode(payload, secret, algorithm='HS256')
if source_path is not None:
kind = 'source'
source_filename = version.source_file_name
source_ext = version.source_file_ext
else:
kind = 'md'
stem = Path(str(version.source_file_name or document.title or f'document-{document.id}')).stem
source_filename = f'{stem}.md'
source_ext = 'md'
source_download_url = (
f'{base_url}/api/integration/files/{document.id}/download'
f'?kind={kind}&version_id={version.id}&token={token}'
)
return {
"source_download_url": source_download_url,
"source_filename": source_filename,
"source_ext": source_ext,
"download_url_expires_at": None,
"version_id": version.id,
"document_id": document.id,
}
@staticmethod
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
if not dataset_id or not remote_document_id:
return None
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
cached = IntegrationApiService._cache.get(cache_key)
if cached and IntegrationApiService._is_cache_valid(cached):
return cached
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
url = f"{base_url}/api/integration/dify-file"
headers = {"X-Integration-Key": api_key}
params = {
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
try:
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
if resp.status_code == 200:
payload = resp.json()
if isinstance(payload, dict):
IntegrationApiService._cache[cache_key] = payload
return payload
elif has_app_context():
current_app.logger.info(
"Integration API single lookup missed, falling back to batch resolve: dataset_id=%s remote_document_id=%s status=%s",
dataset_id,
remote_document_id,
resp.status_code,
)
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API lookup failed: {e}")
batch_url = f"{base_url}/api/integration/dify-files/resolve"
batch_headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
batch_body = {
"items": [
{
"dataset_id": str(dataset_id),
"remote_document_id": str(remote_document_id),
}
]
}
try:
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
if resp.status_code == 200:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
if key == cache_key:
return normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
# Fallback to local database if remote integration API fails or misses
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[cache_key] = local_result
return local_result
# 最终兜底:直接查 Dify 文档 API 并请求签名下载 URL。
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
if dify_result:
IntegrationApiService._cache[cache_key] = dify_result
return dify_result
return None
@staticmethod
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
"""
Batch resolve source files by (dataset_id, remote_document_id).
Returns a mapping keyed by (dataset_id, remote_document_id).
"""
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
if not items:
return results
unresolved: List[Dict[str, str]] = []
seen = set()
for item in items:
dataset_id = str(item.get("dataset_id") or "").strip()
remote_document_id = str(item.get("remote_document_id") or "").strip()
if not dataset_id or not remote_document_id:
continue
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in seen:
continue
seen.add(key)
cached = IntegrationApiService._cache.get(key)
if cached and IntegrationApiService._is_cache_valid(cached):
results[key] = cached
else:
unresolved.append({
"dataset_id": dataset_id,
"remote_document_id": remote_document_id,
})
if not unresolved:
return results
base_url = IntegrationApiService.get_base_url()
api_key = IntegrationApiService.get_api_key()
if not base_url or not api_key:
return results
url = f"{base_url}/api/integration/dify-files/resolve"
headers = {
"X-Integration-Key": api_key,
"Content-Type": "application/json",
}
body = {"items": unresolved}
try:
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
if resp.status_code != 200:
if has_app_context():
current_app.logger.warning(
"Integration API batch lookup failed: status=%s", resp.status_code
)
else:
payload = resp.json()
data = payload.get("data") if isinstance(payload, dict) else None
if isinstance(data, list):
for row in data:
if not isinstance(row, dict):
continue
normalized_row = IntegrationApiService._normalize_batch_row(row)
if not normalized_row:
continue
key, normalized = normalized_row
IntegrationApiService._cache[key] = normalized
results[key] = normalized
except Exception as e:
if has_app_context():
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
# Fallback to single lookup or local DB for unresolved items
for item in unresolved:
dataset_id = item["dataset_id"]
remote_document_id = item["remote_document_id"]
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
if key in results:
continue
# Check if single lookup was not called already (if it was, it might be cached)
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
if local_result:
IntegrationApiService._cache[key] = local_result
results[key] = local_result
continue
# As a last resort, try remote single lookup if batch missed it
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if payload:
results[key] = payload
return results
+137 -3
View File
@@ -1,8 +1,142 @@
"""
backend/app/services/integrations/minio.py
用途:MinIO 对象存储适配。
用途:MinIO 对象存储适配(Agent 指南等文件上传/下载)。
依赖:minio SDK、app.core.config.settings。
逻辑:初始化客户端与 bucket;供 admin/agents、培训指南等模块读写对象。
"""
from app.services import minio_service # noqa: F401
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.core.config.settings import config, ACTIVE_ENV_NAME
__all__ = ['minio_service']
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
返回同源的指南文件代理地址。
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
读取对象的原始字节内容。
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
"""
local_path = os.path.join('data/agent-guides', object_name)
if os.path.exists(local_path):
with open(local_path, 'rb') as file_obj:
return file_obj.read()
response = self.client.get_object(self.bucket_name, object_name)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
@@ -1,2 +1,446 @@
"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。"""
from app.services import oa_leave_workflow # noqa: F401
"""
backend/app/services/integrations/oa/leave_workflow.py
用途:OA 请假流程 SOAP 适配(创建/查询请假单)。
依赖:requests、SOAP XML、OA WorkflowService、integrations.oa.sqlserver。
逻辑:由 HR 请假聊天意图或相关服务调用;组装 WorkflowRequestInfo 并提交 OA。
"""
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'
# 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,
}
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@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'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@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)
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
@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'])
cls._set_field(request_info, 'sqrgh', 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'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
cls._set_field(request_info, 'dlrgh', 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)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
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)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
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),
}
@@ -1,2 +1,258 @@
"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。"""
from app.services import oa_sqlserver # noqa: F401
"""
backend/app/services/integrations/oa/sqlserver.py
用途:封装 OA SQL Server 的员工检索与组织信息查询,供请假代理人/申请人选择等场景复用。
依赖:pyodbc、OA ecology 视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
逻辑:只读 SQL 查询返回 OA 用户与组织字段;对 OA 多语言包装串在服务层清洗为可展示中文。
"""
import os
import re
import pyodbc
from flask import current_app
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
)
class OASQLServerService:
@staticmethod
def _normalize_oa_text(value) -> str:
"""
清洗 OA 多语言包装字段。
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
Args:
value: 来自 OA SQL Server 的原始字段值。
Returns:
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
"""
text = str(value or "").strip()
if not text:
return ""
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
if not matched:
return text
simplified, english, traditional = (
segment.strip().strip("`").strip()
for segment in matched.groups()
)
return simplified or english or traditional or text
@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()
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = 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};"
)
if driver != "SQL Server":
conn_str += (
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, jobtitle, departmentid, subcompanyid1,
departmentname, subcompanyname, jobtitlename
FROM (
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename,
ROW_NUMBER() OVER(ORDER BY v.id) as rn
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
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) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
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 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE v.workcode = ? AND v.lastname = ?
ORDER BY v.id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
if not row:
return None
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_department_name(cls, department_id: str) -> str:
if not department_id or not department_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
[department_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_subcompany_name(cls, subcompany_id: str) -> str:
if not subcompany_id or not subcompany_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
[subcompany_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
if not jobtitle_id or not jobtitle_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()
finally:
connection.close()
@@ -1,2 +1,473 @@
"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。"""
from app.services import oa_wecom_sync # noqa: F401
"""
backend/app/services/integrations/oa/wecom_sync.py
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
依赖:OASQLServerService、SQLAlchemy db、User 模型。
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import User
from app.services.integrations.oa.sqlserver import OASQLServerService
_PREVIEW_LIMIT = 20
_OA_VIEW = 'userInfo_view'
_OA_IN_BATCH_SIZE = 500
def _clean_str(value) -> str | None:
"""
规范化字符串;空值返回 None。
@param value: 任意输入
Returns:
去首尾空白后的字符串,或 None
"""
if value is None:
return None
text = str(value).strip()
return text or None
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
"""
加载本地含有效工号的用户列表。
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
Returns:
(User, employee_id) 元组列表
"""
rows: list[tuple[User, str]] = []
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
employee_id = _clean_str(user.employee_id)
if not employee_id:
continue
rows.append((user, employee_id))
return rows
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
"""
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
@param workcodes: 本地 users.employee_id 列表
Returns:
每项含 workcode、wecom_userid、name
Raises:
RuntimeError: ODBC 连接或查询失败
"""
unique_codes: list[str] = []
seen: set[str] = set()
for code in workcodes:
cleaned = _clean_str(code)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
unique_codes.append(cleaned)
if not unique_codes:
return []
connection = OASQLServerService._connect()
cursor = connection.cursor()
rows: list[dict[str, str | None]] = []
try:
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
placeholders = ','.join('?' for _ in batch)
cursor.execute(
f"""
SELECT id, workcode, lastname
FROM userInfo_view
WHERE workcode IN ({placeholders})
AND id IS NOT NULL
""",
batch,
)
for row in cursor.fetchall():
workcode = _clean_str(row.workcode)
wecom_userid = _clean_str(row.id)
if not workcode or not wecom_userid:
continue
rows.append(
{
'workcode': workcode,
'wecom_userid': wecom_userid,
'name': _clean_str(row.lastname),
}
)
return rows
finally:
try:
cursor.close()
finally:
connection.close()
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
"""
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
Returns:
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
Raises:
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
"""
local_users = _load_local_users_with_employee_id()
workcodes = [employee_id for _, employee_id in local_users]
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
'department_ids': [],
'local_candidates': len(local_users),
'wecom_users': 0,
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
oa_by_workcode: dict[str, dict[str, str | None]] = {}
duplicate_workcodes: set[str] = set()
for row in oa_rows:
workcode = row['workcode']
if not workcode:
continue
if workcode in oa_by_workcode:
duplicate_workcodes.add(workcode)
summary['conflicts'].append(
{
'employee_id': workcode,
'username': '',
'new_wecom_userid': row['wecom_userid'],
'reason': 'duplicate_workcode_in_oa',
}
)
continue
oa_by_workcode[workcode] = row
summary['wecom_users'] = len(oa_by_workcode)
for local_user, employee_id in local_users:
if employee_id in duplicate_workcodes:
continue
oa_row = oa_by_workcode.get(employee_id)
if not oa_row:
summary['local_missing'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{
'employee_id': employee_id,
'username': local_user.username,
}
)
continue
wecom_userid = oa_row['wecom_userid']
name = oa_row.get('name')
if not wecom_userid:
summary['wecom_without_employee_id'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': name,
}
)
if apply:
local_user.wecom_userid = wecom_userid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
+381 -2
View File
@@ -1,2 +1,381 @@
"""PLM Oracle 流式查询适配(Wave 4 自 plm_oracle.py 迁入)。"""
from app.services import plm_oracle # noqa: F401
"""
backend/app/services/integrations/plm/oracle.py
用途:PLM Oracle 物料/SOP 查询与流式聊天快路径。
依赖:Flask current_app、Text2SQLService、ChatLog 模型。
逻辑:聊天意图路由命中 PLM 时调用;查询 Oracle 并格式化为 SSE 结果。
"""
import json
import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
from app import db
from app.models import ChatLog
from app.services.integrations.text2sql import Text2SQLService
class PLMOracleService:
_MAX_RESULT_ROWS = 50
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
re.IGNORECASE,
)
_RELATIONAL_SQL = """
select *
from bi_file endb
where endb.revisionguid in (
select bb.revisionguid
from (
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v,
StructureObject_0 str,
document_0 doc,
bi_file b
where v.name in ('RelatedDoc')
and str.viewfk = v.guid
and str.end2$master = doc.masterfk
and doc.latestrevision like '%m%'
and b.revisionguid = doc.guid
) bb,
item_0 i
where bb.end1 = i.guid
and i.id = :item_id
and i.latestrevision like '%m%'
)
and endb.lastaccesstime is not null
"""
_FILENAME_SQL = """
select *
from bi_file
where upper(name) like :name_pattern
and lastaccesstime is not null
order by lastaccesstime desc nulls last
"""
@classmethod
def supports(cls, query: str, agent) -> bool:
_ = agent
return bool(cls.extract_material_no(query))
@classmethod
def extract_material_no(cls, query: str) -> str | None:
text = str(query or "").strip().upper()
if not text:
return None
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
if explicit:
return explicit.group(1).strip().upper()
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
if direct_match:
return direct_match.group(0).upper()
for match in cls._MATERIAL_PATTERN.finditer(text):
candidate = match.group(0).upper()
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
return candidate
return None
@staticmethod
def _get_connect_kwargs() -> dict:
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
kwargs = {
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
}
if dsn:
kwargs["dsn"] = dsn
return kwargs
import oracledb
if service_name:
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
else:
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
return kwargs
@classmethod
def _connect(cls):
try:
import oracledb
except ImportError as exc:
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
Text2SQLService._init_oracle_client(oracledb)
return oracledb.connect(**cls._get_connect_kwargs())
@classmethod
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
try:
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
if rows:
return columns, rows, "relational"
except Exception as exc:
if current_app:
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
columns, rows = cls._execute_query(
cls._FILENAME_SQL,
name_pattern=f"{material_no.upper()}%",
)
return columns, rows, "filename_fallback"
@staticmethod
def _format_datetime(value) -> str:
if value is None:
return "-"
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return str(value)
@staticmethod
def _format_size(value) -> str:
if value in (None, ""):
return "-"
try:
size = int(value)
except (TypeError, ValueError):
return str(value)
if size < 1024:
return f"{size} B"
if size < 1024 * 1024:
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
@classmethod
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
for value in (storage_id, file_path, file_id):
text = str(value or "").strip()
if not text:
continue
parts.append(text.replace("/", "\\").strip("\\"))
return "\\".join(part for part in parts if part)
@classmethod
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
def raw(column_name: str):
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return None
value = row[idx]
return None if value in (None, "") else value
file_name = str(raw("NAME") or "").strip()
if not file_name:
return "-"
storage_id = raw("STORAGEID")
file_path = raw("FILEPATH")
file_id = str(raw("ID") or "").strip()
if not storage_id or file_path is None or not file_id:
return escape(file_name)
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
return f'<a href="{preview_href}">{escape(file_name)}</a>'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
@classmethod
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return "-"
value = row[idx]
if value in (None, ""):
return "-"
upper_name = column_name.upper()
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if upper_name == "FILESIZE":
return cls._format_size(value)
if upper_name == "NAME":
return cls._render_file_name(row, index_map)
return str(value)
@classmethod
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
parts = [f"记录 {row_no}"]
for column_name in cls._SUMMARY_COLUMNS:
if column_name.upper() not in index_map:
continue
rendered = cls._render_column_value(row, column_name, index_map)
label = {
"NAME": "文件名",
"EXTENTIONNAME": "扩展名",
"FILETYPE": "文件类型",
"FILESIZE": "文件大小",
"RELATIVEPATH": "相对路径",
"LASTACCESSTIME": "最后访问时间",
}.get(column_name.upper(), column_name)
if column_name.upper() == "NAME":
parts.append(f"{label}: {rendered}")
else:
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
return " | ".join(parts)
@classmethod
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
rows_html = []
for column_name in columns:
rendered_value = cls._render_column_value(row, column_name, index_map)
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
rows_html.append(
"<tr>"
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
"</tr>"
)
summary_html = cls._build_record_summary(row, index_map, row_no)
return (
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
"<div style=\"margin-top:10px;overflow:auto;\">"
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
"<thead><tr>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
"</tr></thead>"
f"<tbody>{''.join(rows_html)}</tbody>"
"</table>"
"</div>"
"</details>"
)
@classmethod
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
if not rows:
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
overflow = len(rows) > cls._MAX_RESULT_ROWS
visible_rows = rows[: cls._MAX_RESULT_ROWS]
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
lines = [
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
+ ("(仅展示前 50 条)" if overflow else "。"),
"",
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
]
for idx, row in enumerate(visible_rows, start=1):
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
if overflow:
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
return "\n".join(lines)
@classmethod
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
start_time = time.time()
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
material_no = cls.extract_material_no(query)
try:
if not material_no:
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
columns, rows, query_mode = cls._query_files(material_no)
answer = cls._build_answer(material_no, columns, rows)
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
payload={
"material_no": material_no,
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
"query_mode": query_mode,
},
)
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 PLM chat: %s", exc)
db.session.rollback()
end_data = {
"event": "message_end",
"answer": answer,
"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("[plm-oracle] stream_chat failed query=%s", query)
error_data = {
"event": "error",
"message": str(exc) or "PLM 查询失败",
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
File diff suppressed because it is too large. Load diff
@@ -1,2 +1,97 @@
"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。"""
from app.services import wecom_crypto # noqa: F401
"""
backend/app/services/integrations/wecom/crypto.py
用途:企业微信回调加解密工具(兼容 WXBizMsgCrypt 布局)。
依赖:pycryptodome AES。
逻辑:user/auth 企微回调验签、解密 Encrypt 字段时调用。
"""
from __future__ import annotations
import base64
import hashlib
import random
import struct
from typing import Optional
from Crypto.Cipher import AES
def sha1_hex(parts: list[str]) -> str:
merged = ''.join(sorted([str(p) for p in parts if p is not None]))
return hashlib.sha1(merged.encode('utf-8')).hexdigest()
def _pkcs7_pad(data: bytes, block_size: int = 32) -> bytes:
pad_len = block_size - (len(data) % block_size)
return data + bytes([pad_len] * pad_len)
def _pkcs7_unpad(data: bytes) -> bytes:
if not data:
return data
pad_len = data[-1]
if pad_len < 1 or pad_len > 32:
raise ValueError('invalid pkcs7 padding')
if data[-pad_len:] != bytes([pad_len] * pad_len):
raise ValueError('invalid pkcs7 padding tail')
return data[:-pad_len]
def _aes_key_from_encoding_key(encoding_aes_key_b64: str) -> bytes:
raw = (encoding_aes_key_b64 or '').strip()
key = base64.b64decode(raw + '=')
if len(key) != 32:
raise ValueError('EncodingAESKey must decode to 32 bytes')
return key
def encrypt_wecom_aes(plain_text: str, encoding_aes_key_b64: str, corp_id: str) -> str:
"""
Encrypt plain text to base64 ciphertext (for tests / optional outbound use).
"""
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
random_bytes = bytes(random.randint(0, 255) for _ in range(16))
msg_bytes = plain_text.encode('utf-8')
pack = (
random_bytes
+ struct.pack('>I', len(msg_bytes))
+ msg_bytes
+ corp_id.encode('utf-8')
)
padded = _pkcs7_pad(pack, 32)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(padded)
return base64.b64encode(encrypted).decode('ascii')
def decrypt_wecom_aes(cipher_b64: str, encoding_aes_key_b64: str, corp_id: str) -> str:
aes_key = _aes_key_from_encoding_key(encoding_aes_key_b64)
iv = aes_key[:16]
cipher_bytes = base64.b64decode(cipher_b64)
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
plain_padded = cipher.decrypt(cipher_bytes)
plain = _pkcs7_unpad(plain_padded)
content = plain[16:]
if len(content) < 4:
raise ValueError('decrypted payload too short')
xml_len = struct.unpack('>I', content[:4])[0]
xml_bytes = content[4:4 + xml_len]
tail = content[4 + xml_len:]
if tail.decode('utf-8', errors='strict') != corp_id:
raise ValueError('corp_id mismatch after decrypt')
return xml_bytes.decode('utf-8')
def extract_encrypt_field(xml_body: str) -> Optional[str]:
if not xml_body:
return None
import re
m = re.search(r'<Encrypt><!\[CDATA\[(.*?)\]\]></Encrypt>', xml_body, re.DOTALL)
if m:
return m.group(1).strip()
m2 = re.search(r'<Encrypt>(.*?)</Encrypt>', xml_body, re.DOTALL)
if m2:
return m2.group(1).strip()
return None
@@ -1,2 +1,244 @@
"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。"""
from app.services import wecom_directory_sync # noqa: F401
"""
backend/app/services/integrations/wecom/directory_sync.py
用途:从企业微信通讯录拉取成员,按工号回填本地 users.wecom_userid。
依赖:Flask current_app、SQLAlchemy db、wecom.notify._get_access_token、User 模型。
逻辑:供 admin API 与 scripts/sync_wecom_userid_by_employee_id.py 共用;支持 dry-run 与 apply。
"""
from __future__ import annotations
from typing import Any
import requests
from flask import current_app
from app import db
from app.models import User
from app.services.integrations.wecom.notify import _get_access_token
_PREVIEW_LIMIT = 20
def _clean_str(value) -> str | None:
"""裁剪字符串类取值;空串视为 None。"""
if value is None:
return None
text = str(value).strip()
return text or None
def _extract_wecom_extattr_value(wecom_user: dict, key: str) -> str | None:
"""
从企微成员 extattr.attrs 中读取指定扩展字段。
@param wecom_user: user/list 返回的成员 dict
@param key: 扩展属性名
Returns:
字段文本或 None
"""
extattr = wecom_user.get('extattr') or {}
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
if not isinstance(attrs, list):
return None
for attr in attrs:
if not isinstance(attr, dict):
continue
if _clean_str(attr.get('name')) != key:
continue
raw = attr.get('value')
if isinstance(raw, dict):
raw = raw.get('text') or raw.get('web') or raw.get('value')
return _clean_str(raw)
return None
def extract_employee_id_from_wecom_user(wecom_user: dict, employee_id_source: str) -> str | None:
"""
按 WECOM_EMPLOYEE_ID_SOURCE 从企微成员解析工号。
核心逻辑:userid / extattr:xxx / 其它字段名,与 user.py _extract_wecom_identity 对齐。
"""
userid = _clean_str(wecom_user.get('userid'))
source = _clean_str(employee_id_source) or 'userid'
if source == 'userid':
return userid
if source.startswith('extattr:'):
return _extract_wecom_extattr_value(wecom_user, source.split(':', 1)[1])
return _clean_str(wecom_user.get(source))
def fetch_wecom_departments(access_token: str) -> list[dict[str, Any]]:
"""
拉取企业微信部门列表。
Raises:
RuntimeError: API 失败
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/department/list',
params={'access_token': access_token},
timeout=15,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'department/list failed: {data}')
departments = data.get('department') or []
if not isinstance(departments, list):
return []
return [item for item in departments if isinstance(item, dict)]
def fetch_wecom_users_in_department(access_token: str, department_id: int) -> list[dict[str, Any]]:
"""
拉取指定部门(含子部门)成员简要列表。
@param department_id: 企微部门 ID
Returns:
user/list 返回的 userlist
"""
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/user/list',
params={
'access_token': access_token,
'department_id': department_id,
'fetch_child': 1,
},
timeout=30,
)
data = resp.json() or {}
if data.get('errcode') != 0:
raise RuntimeError(f'user/list failed department_id={department_id}: {data}')
userlist = data.get('userlist') or []
if not isinstance(userlist, list):
return []
return [item for item in userlist if isinstance(item, dict)]
def collect_wecom_users(access_token: str, department_ids: list[int]) -> dict[str, dict[str, Any]]:
"""
汇总多个部门成员,按 wecom_userid 去重。
Returns:
key=userid, value=成员 dict
"""
merged: dict[str, dict[str, Any]] = {}
for dept_id in department_ids:
for user in fetch_wecom_users_in_department(access_token, dept_id):
userid = _clean_str(user.get('userid'))
if userid:
merged[userid] = user
return merged
def sync_wecom_userids_from_directory(*, apply: bool, department_id: int | None = None) -> dict[str, Any]:
"""
执行工号 → wecom_userid 同步。
核心逻辑:拉企微成员 → 解析 employee_id → 匹配本地 User → dry-run 或写 wecom_userid/wecom_unionid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
@param department_id: 指定根部门 ID;None 时使用全部部门
Returns:
统计摘要 dict(含 conflicts、pending_updates 预览)
"""
if not current_app.config.get('WECOM_CORP_ID') or not current_app.config.get('WECOM_SECRET'):
raise RuntimeError('WECOM_CORP_ID / WECOM_SECRET is not configured')
employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid'
token = _get_access_token()
if department_id is not None:
department_ids = [department_id]
else:
departments = fetch_wecom_departments(token)
department_ids = [int(item.get('id')) for item in departments if item.get('id') is not None]
if not department_ids:
department_ids = [1]
wecom_users = collect_wecom_users(token, department_ids)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': employee_id_source,
'department_ids': department_ids,
'wecom_users': len(wecom_users),
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
for wecom_user in wecom_users.values():
wecom_userid = _clean_str(wecom_user.get('userid'))
wecom_unionid = _clean_str(wecom_user.get('unionid'))
employee_id = extract_employee_id_from_wecom_user(wecom_user, employee_id_source)
if not employee_id:
summary['wecom_without_employee_id'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{'wecom_userid': wecom_userid, 'name': _clean_str(wecom_user.get('name'))}
)
continue
local_user = db.session.query(User).filter(User.employee_id == employee_id).first()
if not local_user:
summary['local_missing'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': _clean_str(wecom_user.get('name')),
}
)
if apply:
local_user.wecom_userid = wecom_userid
if wecom_unionid:
local_user.wecom_unionid = wecom_unionid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
@@ -1,2 +1,264 @@
"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。"""
from app.services import wecom_notify # noqa: F401
"""
backend/app/services/integrations/wecom/notify.py
用途:企业微信消息通知适配(文本卡片、文件、事件消息)。
依赖:requests、Flask current_app、User / WecomNotifyAudit 模型。
逻辑:排程完成、权限申请、培训提醒等业务事件调用本模块发送企微消息并写审计。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from io import BytesIO
from urllib.parse import urlencode, urlparse, parse_qsl, urlunparse
import uuid
import requests
from flask import current_app
from app import db
from app.models import User, WecomNotifyAudit
_TOKEN_CACHE = {
'token': None,
'expires_at': None,
}
def _get_enabled_events() -> set[str]:
raw = current_app.config.get('WECOM_NOTIFY_EVENTS', '')
if isinstance(raw, str):
return {x.strip() for x in raw.split(',') if x.strip()}
if isinstance(raw, (list, tuple, set)):
return {str(x).strip() for x in raw if str(x).strip()}
return set()
def _get_notify_base_url() -> str:
"""
解析企微 textcard 跳转基地址(用户点击入口,须为浏览器可访问的 HTTPS 公网域名)。
核心逻辑:优先 WECOM_PUBLIC_BASE_URL,其次 HXOPS_PUBLIC_BASE_URL;
WECOM_NOTIFY_BASE_URL 仅作历史内网/端口兼容兜底。
Returns:
去掉尾斜杠的基地址;均未配置时返回空字符串。
"""
for key in ('WECOM_PUBLIC_BASE_URL', 'HXOPS_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
raw = current_app.config.get(key)
if isinstance(raw, str) and raw.strip():
return raw.strip().rstrip('/')
return ''
def _build_jump_url(path: str, trace_id: str, params: dict | None = None) -> str:
base = _get_notify_base_url()
if not base:
return ''
base = base.rstrip('/')
if not path.startswith('/'):
path = f'/{path}'
merged = {'wecom_trace': trace_id}
if params:
merged.update({k: v for k, v in params.items() if v is not None})
return f'{base}{path}?{urlencode(merged)}'
def _get_access_token() -> str:
now = datetime.utcnow()
token = _TOKEN_CACHE.get('token')
expires_at = _TOKEN_CACHE.get('expires_at')
if token and expires_at and now < expires_at:
return token
corp_id = current_app.config.get('WECOM_CORP_ID')
secret = current_app.config.get('WECOM_SECRET')
resp = requests.get(
'https://qyapi.weixin.qq.com/cgi-bin/gettoken',
params={'corpid': corp_id, 'corpsecret': secret},
timeout=8,
)
data = resp.json()
if data.get('errcode') != 0 or not data.get('access_token'):
raise RuntimeError(f"Failed to fetch WeCom token: {data}")
_TOKEN_CACHE['token'] = data['access_token']
_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60))
return data['access_token']
def _create_audit(
event_type: str,
user: User,
title: str,
content: str,
trace_id: str,
) -> WecomNotifyAudit:
audit = WecomNotifyAudit(
event_type=event_type,
status='failed',
trace_id=trace_id,
user_id=user.id if user else None,
username=user.username if user else None,
wecom_userid=user.wecom_userid if user else None,
title=title,
content=content,
)
db.session.add(audit)
return audit
def upload_wecom_temp_media(file_data: bytes, filename: str) -> str:
token = _get_access_token()
url = (
f'https://qyapi.weixin.qq.com/cgi-bin/media/upload'
f'?access_token={token}&type=file'
)
resp = requests.post(
url,
files={'media': (filename, BytesIO(file_data), 'application/octet-stream')},
timeout=30,
)
data = resp.json()
if data.get('errcode', 0) != 0 or not data.get('media_id'):
raise RuntimeError(f"WeCom media upload failed: {data}")
return data['media_id']
def send_wecom_file_message(wecom_userid: str, media_id: str) -> dict:
token = _get_access_token()
payload = {
'touser': wecom_userid,
'msgtype': 'file',
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
'file': {'media_id': media_id},
'safe': 0,
}
resp = requests.post(
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
params={'access_token': token},
json=payload,
timeout=8,
)
return resp.json()
def send_wecom_textcard_message(
wecom_userid: str,
title: str,
description: str,
jump_url: str,
) -> dict:
token = _get_access_token()
payload = {
'touser': wecom_userid,
'msgtype': 'textcard',
'agentid': int(current_app.config.get('WECOM_AGENT_ID')),
'textcard': {
'title': title[:120],
'description': (description or '')[:1024],
'url': jump_url or _get_notify_base_url() or 'https://work.weixin.qq.com',
'btntxt': '查看详情',
},
'safe': 0,
}
resp = requests.post(
'https://qyapi.weixin.qq.com/cgi-bin/message/send',
params={'access_token': token},
json=payload,
timeout=8,
)
return resp.json()
def _append_query_param(url: str, key: str, value: str) -> str:
"""
向 URL 追加单个 query 参数,保留已有参数。
@param url: 原始 URL
@param key: 参数名
@param value: 参数值
Returns:
追加参数后的 URL
"""
parsed = urlparse(url)
pairs = parse_qsl(parsed.query, keep_blank_values=True)
pairs.append((key, value))
return urlunparse(parsed._replace(query=urlencode(pairs)))
def send_wecom_event_message(
*,
event_type: str,
user: User,
title: str,
content: str,
jump_path: str = '/workspace',
jump_params: dict | None = None,
jump_url: str | None = None,
wecom_userid: str | None = None,
) -> dict:
"""
发送企微事件 textcard;可选 jump_url 覆盖默认跳转(如密码重置外链)。
核心逻辑:默认使用 `user.wecom_userid`;合同付款第二、三轮可传入 OA HrmResource.id
作为 wecom_userid,因为该 id 同时是企业微信 userid。
Args:
event_type: 通知事件开关名。
user: 审计关联的系统用户,可为收件人在 HXOPS 中的映射账号。
title: 卡片标题。
content: 卡片正文。
jump_path: 站内跳转路径。
jump_params: 跳转查询参数。
jump_url: 若传入则覆盖默认拼接的跳转地址。
wecom_userid: 可选,显式指定企微 touser;空则回退 user.wecom_userid。
Returns:
含 ok / trace_id 的发送结果字典。
"""
trace_id = uuid.uuid4().hex
audit = _create_audit(event_type, user, title, content, trace_id)
target_userid = str(wecom_userid or (user.wecom_userid if user else "") or "").strip()
if target_userid:
audit.wecom_userid = target_userid
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
audit.error_code = 'NOTIFY_DISABLED'
audit.error_message = 'WECOM_NOTIFY_ENABLED=false'
return {'ok': False, 'trace_id': trace_id, 'reason': 'notify_disabled'}
if event_type not in _get_enabled_events():
audit.error_code = 'EVENT_DISABLED'
audit.error_message = f'event {event_type} disabled'
return {'ok': False, 'trace_id': trace_id, 'reason': 'event_disabled'}
if not target_userid:
audit.error_code = 'WECOM_USER_UNBOUND'
audit.error_message = 'user has no wecom_userid'
return {'ok': False, 'trace_id': trace_id, 'reason': 'user_unbound'}
try:
if jump_url:
final_jump_url = _append_query_param(jump_url, 'wecom_trace', trace_id)
else:
final_jump_url = _build_jump_url(jump_path, trace_id, jump_params)
audit.jump_url = final_jump_url
data = send_wecom_textcard_message(target_userid, title, content, final_jump_url)
if data.get('errcode') == 0:
audit.status = 'sent'
return {'ok': True, 'trace_id': trace_id}
audit.error_code = str(data.get('errcode'))
audit.error_message = str(data.get('errmsg', 'unknown error'))[:255]
return {'ok': False, 'trace_id': trace_id, 'reason': 'send_failed', 'raw': data}
except Exception as exc:
audit.error_code = 'EXCEPTION'
audit.error_message = str(exc)[:255]
return {'ok': False, 'trace_id': trace_id, 'reason': 'exception'}
def mark_wecom_message_opened(trace_id: str) -> bool:
if not trace_id:
return False
row = db.session.query(WecomNotifyAudit).filter_by(trace_id=trace_id).first()
if not row:
return False
if not row.opened_at:
row.opened_at = datetime.utcnow()
return True
@@ -4,9 +4,11 @@ backend/app/services/lean_training_push_service.py
用途:按"每周任务数量"分批推送精益培训视频给受训对象并发送企微通知,记录每轮推送日志;
同时承担"每周自动滚动创建当周任务"与"推送成功后立即提醒已延期人员"两项周任务规则。
依赖:LeanTrainingWeeklyTask/LeanTrainingVideoPushLog/LeanTrainingReminder/User、lean_training_service(受训对象/当周边界)、lean_training_reminder_service(企微发送模板/延期提醒)、wecom_notify。
逻辑:以 task.pushed_video_count 为游标,按视频冻结顺序每次取 weekly_count 个视频;员工端展示已推送前缀;
逻辑:以 task.pushed_video_count 为游标,每次从游标向后取 weekly_count 个"未被任何任务推送过"的视频(跨任务
按已推送前缀并集去重,推过的视频绝不重复推);员工端展示已推送前缀;
企微 event_key 按"批次区间"幂等防止重复打扰;每轮执行写入 lean_training_video_push_logs 便于管理端查看失败明细;
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置,无需人工维护),再对各任务推进一批推送。
排程入口每周一 09:00 先自动滚动创建当周任务(复制最近一期配置并自动追加配置新增视频,无需人工维护;
视频库全部推完且无新增视频时暂停滚动、不创建内容重复的新一期),再对各任务推进一批推送。
"""
from __future__ import annotations
@@ -22,7 +24,12 @@ from app.services.lean_training_reminder_service import (
notify_overdue_users_after_push,
send_initial_target_notifications,
)
from app.services.lean_training_service import _current_week_bounds, target_user_ids_for_task
from app.services.lean_training_service import (
_already_pushed_resource_ids,
_config_video_resource_ids,
_current_week_bounds,
target_user_ids_for_task,
)
from app.services.schedule.timezone_util import utc_now_naive
VIDEO_PUSH_EVENT_TYPE = "training_lean_video_push"
@@ -41,7 +48,12 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
- 模板仅从"严格早于当周"的最近一期已发布任务选取:任务周已支持管理员指定任意自然周,
必须排除未来周任务,避免其(更大游标/不同配置)污染当周滚动进度;
- 模板复制视频冻结列表、每周推送数量与受训对象;推送游标继承模板进度,
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完。
保证"推过的视频不重复推",跨周按视频列表顺序连续推进直至全部推完;
- 配置中新增上传、尚未冻结进模板列表的视频按上传时间倒序自动追加到列表末尾:
HR 事后手动勾选补推的进度经游标继承持续生效,每周自动计划从断点继续向后推;
追加只发生在末尾,已推送前缀与游标不变,推过的视频绝不重复推;
- 视频库已全部推完且配置无新增视频时**暂停滚动**:不再创建内容重复的新一期任务
(对应"全部视频推送完成后暂停,不再重复推送"规则);新视频上传后下周一自动恢复创建。
"""
week_start, due_at = _current_week_bounds(now)
week_key = week_start.isoformat()
@@ -55,15 +67,40 @@ def ensure_current_week_task(*, now: datetime | None = None) -> LeanTrainingWeek
).scalars().first()
if not template:
return None
# [RULE] 视频库已全部推完且配置无新增视频时暂停滚动:不再创建内容重复的新一期任务。
# 若继续创建,新一期只会继承同一份已推完的清单,学员端每期显示完全相同的视频、
# 也无可推送的新内容(对应"全部视频推送完成后暂停,不再重复推送"规则);
# 配置上传新视频后,下周一滚动自动恢复创建并只推新视频。
template_video_ids = list(template.video_resource_ids or [])
if template.pushed_video_count >= len(template_video_ids):
template_frozen_ids = {int(resource_id) for resource_id in template_video_ids}
has_new_config_videos = any(
resource.id not in template_frozen_ids
for resource in _config_video_resource_ids(template.config)
)
if not has_new_config_videos:
return None
# [STEP 1] 复制最近一期配置滚动创建当周任务(视频列表沿用冻结顺序,游标继承已推送进度避免重复推送)
video_resource_ids = template_video_ids
# [RULE] 自动追加配置新增视频(上传时间倒序、只追加到末尾):前缀与游标保持对齐,断点续推不重推
frozen_ids = {int(resource_id) for resource_id in video_resource_ids}
video_resource_ids.extend(
resource.id
for resource in sorted(
_config_video_resource_ids(template.config),
key=lambda resource: resource.created_at or datetime.min,
reverse=True,
)
if resource.id not in frozen_ids
)
task = LeanTrainingWeeklyTask(
config_id=template.config_id,
week_key=week_key,
created_by_id=template.created_by_id,
weekly_count=template.weekly_count,
pushed_video_count=template.pushed_video_count,
pushed_video_count=min(template.pushed_video_count, len(video_resource_ids)),
due_at=due_at,
video_resource_ids=list(template.video_resource_ids or []),
video_resource_ids=video_resource_ids,
target_roles=list(template.target_roles or []),
target_user_ids=list(template.target_user_ids or []),
status="published",
@@ -128,18 +165,36 @@ def push_lean_training_videos(
Returns:
含 status(completed=无待推视频/partial/failed/sent)、batch、counts 与日志字段的 dict。
业务约束:企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中。
业务约束:
- 企微发送失败不影响游标前进(员工端已可见视频),失败明细仅记录在日志中;
- 跨任务绝对去重:已被其它周任务推送过的视频不进入本批(游标越过),待推区间全部重复时
游标直接推进到末尾并返回 completed,不发送企微。
"""
task = db.session.get(LeanTrainingWeeklyTask, task_id)
if not task or task.status != "published":
raise ValueError("Lean training weekly task not found")
current = now or utc_now_naive()
# [STEP 1] 计算本批视频:按选择顺序从游标起取 weekly_count 个;无待推视频时视为全部推送完
batch = pending_video_ids(task)[: task.weekly_count]
if not batch:
# [STEP 1] 计算本批视频:按选择顺序从游标向后扫描,取满 weekly_count 个"未被任何任务推送过"的新视频;
# 已被其它任务推送过的视频仅越过(游标同步越过),绝不重复进入批次;无新视频可推时不发企微
candidates = pending_video_ids(task)
if not candidates:
return {"status": "completed", "message": "all videos pushed", "pushed_count": 0}
start_index = task.pushed_video_count
event_key = f"video-push-{start_index}-{start_index + len(batch)}"
already_pushed = _already_pushed_resource_ids(exclude_task_id=task.id)
batch: list[int] = []
consumed = 0
for resource_id in candidates:
if len(batch) >= task.weekly_count:
break
consumed += 1
if int(resource_id) not in already_pushed:
batch.append(resource_id)
if not batch:
# [RULE] 待推区间已全部被其它任务推送过:游标推进到末尾即视为全部推完,不重复推送、不重复打扰
task.pushed_video_count = start_index + consumed
db.session.commit()
return {"status": "completed", "message": "all pending videos already pushed", "pushed_count": 0}
event_key = f"video-push-{start_index}-{start_index + consumed}"
# [STEP 2] 面向全体在职受训对象发送企微通知;event_key 按批次区间幂等,同批重推不重复打扰
recipients = db.session.execute(
select(User).where(User.id.in_(target_user_ids_for_task(task)), User.status == "active")
@@ -159,8 +214,8 @@ def push_lean_training_videos(
counts[result] = counts.get(result, 0) + 1
if result == "failed" and recipient.id not in {line.split(":")[0] for line in failure_details}:
failure_details.append(f"{recipient.id}:{recipient.real_name or recipient.username}")
# [STEP 3] 游标前进(企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + len(batch)
# [STEP 3] 游标前进(越过跳过的重复视频与本批新视频;企微失败不回退,员工端已可见该批视频),并落盘本轮推送日志
task.pushed_video_count = start_index + consumed
status = "sent" if counts["failed"] == 0 else ("failed" if counts["sent"] == 0 and counts["skipped"] == 0 else "partial")
log = LeanTrainingVideoPushLog(
weekly_task_id=task.id,
@@ -11,14 +11,16 @@ from __future__ import annotations
import uuid
from datetime import datetime, timezone
from flask import current_app
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from app.extensions import db
from app.models import LeanTrainingCompletion, LeanTrainingReminder, LeanTrainingWeeklyTask, User
from app.services.lean_training_service import target_user_ids_for_task
from app.services.wecom_notify import send_wecom_event_message
from app.services.lean_training_service import (
resolve_lean_training_jump_agent_id,
target_user_ids_for_task,
)
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
@@ -52,10 +54,11 @@ def _send_reminder(
db.session.flush()
except IntegrityError:
return "skipped"
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(默认 agent 27,content_profile=training),
# [STEP] 企微卡片跳转地址:动态解析各环境「员工培训」聊天页(content_profile=training),
# 由前端 TrainingWorkspacePanel 消费 training_type=lean_management 自动展开精益页签;
# agent id 走配置(app_settings/env 覆盖),便于多环境调整,避免硬编码。
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 27)
# 支持 WECOM_LEAN_TRAINING_JUMP_AGENT_ID 显式覆盖,动态解析失败回退历史默认 27([FIX] 2026-09-18
# 历史固定默认 27 在部分环境实为其它 Agent,导致卡片落地后无法定位精益模块)。
jump_agent_id = resolve_lean_training_jump_agent_id()
result = send_wecom_event_message(
event_type=event_type,
user=recipient,
+157 -8
View File
@@ -10,24 +10,72 @@ backend/app/services/lean_training_service.py
from __future__ import annotations
from datetime import date, datetime, time, timedelta, timezone
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from sqlalchemy import func, or_, select
from app.core.errors import NotFoundError, ValidationError
from app.extensions import db
from app.models import (
Agent,
LeanTrainingCompletion,
LeanTrainingWeeklyTask,
TrainingConfig,
TrainingConfigResource,
User,
)
from app.services.minio_service import minio_service
from app.services.integrations.minio import minio_service
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, to_utc_naive, utc_now_naive
LEAN_TRAINING_TYPE = "lean_management"
MIN_SUMMARY_LENGTH = 50
# 精益提醒/推送企微卡片跳转 Agent 的历史默认值;仅当动态解析失败(系统内无培训 Agent)时兜底
LEGACY_LEAN_JUMP_AGENT_ID = 27
def resolve_lean_training_jump_agent_id() -> int:
"""
解析精益提醒/推送企微卡片落地聊天页的「员工培训」Agent ID。
用途:卡片须跳 /chat/<培训agent>?training_type=lean_management,由前端 TrainingWorkspacePanel
自动展开精益页签;前端仅在目标 Agent 是培训 Agent 时才消费深链参数,
因此 Agent ID 指错环境会导致卡片落地后无法定位精益模块。
核心逻辑:各环境培训 Agent ID 不同,禁止依赖固定值——优先取 WECOM_LEAN_TRAINING_JUMP_AGENT_ID
显式配置覆盖,否则在启用 Agent 中按 handler_config.content_profile='training' 动态解析;
均不可用时回退历史默认 27 保持兼容。
Returns:
培训 Agent ID。
"""
from flask import current_app
override = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 0)
if override > 0:
return override
agents = db.session.execute(
select(Agent).where(Agent.is_active.is_(True)).order_by(Agent.sort_order, Agent.id)
).scalars().all()
for agent in agents:
handler_config = agent.handler_config if isinstance(agent.handler_config, dict) else {}
if str(handler_config.get("content_profile") or "").strip() == "training":
return int(agent.id)
return LEGACY_LEAN_JUMP_AGENT_ID
def _format_dashboard_datetime(value: str | None) -> str:
"""将看板 ISO 时间统一为页面展示的年月日时分格式。"""
text = str(value or "").strip()
return text[:16].replace("T", " ") if text else ""
def _dashboard_status_label(status: str | None) -> str:
"""将看板状态转换为页面一致的中文文案。"""
return {
"completed": "已完成",
"overdue": "已延期",
"in_progress": "进行中",
}.get(str(status or ""), str(status or ""))
def _get_lean_config() -> TrainingConfig:
@@ -69,6 +117,22 @@ def week_index_for_task(task: LeanTrainingWeeklyTask) -> int:
return int(earlier_count) + 1
def _config_video_resource_ids(config: TrainingConfig) -> list[TrainingConfigResource]:
"""
返回精益配置下全部"视频型"学习资源(agent_guide 且文件类型为 video)。
用途:冻结列表自动填充与每周自动滚动追加新增视频共用同一判定,避免两处视频口径漂移。
Args:
config: 已发布的精益培训配置(需含 resources 关系)。
Returns:
视频资源列表(顺序由调用方排序)。
"""
return [
resource for resource in config.resources
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
]
def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
"""
校验周任务绑定的视频资源并返回冻结顺序列表。
@@ -83,10 +147,7 @@ def _normalize_video_ids(value: Any, config: TrainingConfig) -> list[int]:
- 未选择时自动按资源上传时间倒序冻结全部视频(对应"发布周任务按上传时间倒序推送"规则);
- 推过的视频不能重复推:由推送游标(pushed_video_count)保证,直至全部视频推完。
"""
video_resources = [
resource for resource in config.resources
if resource.resource_type == "agent_guide" and resource.agent_guide and str(resource.agent_guide.file_type or "").lower().startswith("video")
]
video_resources = _config_video_resource_ids(config)
# [RULE] 管理端未显式勾选视频时,按上传时间倒序自动冻结全部视频,满足"直至全部上传视频推送完"
if not isinstance(value, list) or len(value) == 0:
if value is not None and not isinstance(value, list):
@@ -195,6 +256,48 @@ def serialize_weekly_task(task: LeanTrainingWeeklyTask, *, learner_view: bool =
}
def _already_pushed_resource_ids(*, exclude_task_id: int | None = None) -> set[int]:
"""
汇总全部已发布周任务中"实际已推送过员工"的视频资源 ID(各任务推送前缀的并集)。
用途:作为跨任务去重基线,保证"推过的视频绝对不能重复推"——新建任务继承游标与推送分批都以此集合为准。
Args:
exclude_task_id: 需要排除的任务 ID(对已存在任务推进批次时排除自身,自身前缀已由游标表达)。
Returns:
已推送视频资源 ID 集合。
"""
tasks = db.session.execute(
select(LeanTrainingWeeklyTask).where(LeanTrainingWeeklyTask.status == "published")
).scalars().all()
pushed: set[int] = set()
for task in tasks:
if exclude_task_id is not None and task.id == exclude_task_id:
continue
pushed.update(int(resource_id) for resource_id in list(task.video_resource_ids or [])[: task.pushed_video_count])
return pushed
def _inherited_pushed_video_count(video_ids: list[int]) -> int:
"""
计算手动新建周任务应继承的推送游标:新视频列表的"最长已推送前缀"长度。
用途:修复 HR 手动新建下一期任务时游标从 0 重推首批的问题——必须从上一任务断点续推。
核心逻辑:以已推送前缀并集为基线,从头统计新列表中有多少个视频已被推送过;
列表与上一期一致时精确继承断点;自动填充顺序因新上传视频变化时也能正确定位到首个未推送视频。
Args:
video_ids: 新任务冻结的视频资源 ID 顺序列表。
Returns:
继承后的推送游标(0 <= 游标 <= len(video_ids))。
"""
already_pushed = _already_pushed_resource_ids()
inherited = 0
for resource_id in video_ids:
if int(resource_id) not in already_pushed:
break
inherited += 1
return inherited
def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str, Any]:
"""
创建或更新精益视频周任务,并由 HR 冻结视频列表、每周推送数量与受训对象。
@@ -204,7 +307,9 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
- 截止时间支持修改:显式传 due_at 按所选时刻落库,缺省为所选周周日 23:59:59;
不得早于所选周周一 00:00(Asia/Shanghai),避免任务创建即处于"已延期"的明显配置错误;
- 修改后【发布周任务】/【立即新增任务补推】均作用于所选周任务(发布仅首次自动推首批);
- 同周重复提交为更新(游标不回退),新周提交为新建。
- 同周重复提交为更新(游标不回退),新周提交为新建;
- 新建任务的推送游标从历史已推送进度继承(新列表的最长已推送前缀),推过的视频绝不从 0 重推,
后续批次自动从上一任务断点继续向后推进。
"""
config = _get_lean_config()
shanghai_tz = resolve_schedule_tzinfo("Asia/Shanghai")
@@ -247,8 +352,12 @@ def create_or_update_weekly_task(data: dict[str, Any], user_id: int) -> dict[str
task = existing or LeanTrainingWeeklyTask(config_id=config.id, week_key=week_start.isoformat(), created_by_id=user_id, weekly_count=1, pushed_video_count=0)
task.due_at = due_at
task.video_resource_ids = video_ids
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
if existing:
# [STEP] 视频列表可能被追加,推送游标不能超出列表长度,否则下一轮无视频可推
task.pushed_video_count = min(task.pushed_video_count, len(video_ids))
else:
# [RULE] 手动新建周任务继承历史推送进度:推过的视频绝不从 0 重推,从上一任务断点续推
task.pushed_video_count = _inherited_pushed_video_count(video_ids)
task.weekly_count = weekly_count
task.target_roles = target_roles
task.target_user_ids = target_user_ids
@@ -441,3 +550,43 @@ def list_dashboard(task_id: int | None) -> dict[str, Any]:
row = serialize_completion(item, task, user) if item else {"user_id": user.id, "employee_id": user.employee_id, "name": user.real_name or user.username, "department": user.department, "videos": _task_video_rows(task, None), "summary_text": None, "status": "overdue" if utc_now_naive() > task.due_at else "in_progress", "completed_at": None}
(completed if row["status"] == "completed" else incomplete).append(row)
return {"task": serialize_weekly_task(task), "completed": completed, "incomplete": incomplete, "periods": periods}
def export_dashboard_excel(task_id: int | None) -> tuple[bytes, str]:
"""导出指定精益培训期次的完整看板数据。
Args:
task_id: 指定周任务 ID;为空时按看板规则导出最新一期。
Returns:
Excel 二进制内容与下载文件名;无可导出任务时抛出 NotFoundError。
"""
dashboard = list_dashboard(task_id)
task = dashboard["task"]
if not task:
raise NotFoundError("Lean training weekly task not found")
workbook = Workbook()
worksheet = workbook.active
worksheet.title = "lean_training"
worksheet.append(["期号", "培训周次", "截止时间", "工号", "姓名", "部门", "视频名称", "观看时间", "状态", "学习感悟", "完成时间"])
rows = [*dashboard["completed"], *dashboard["incomplete"]]
for row in rows:
videos = row.get("videos") or []
worksheet.append([
task.get("week_index") or "",
task.get("week_key") or "",
_format_dashboard_datetime(task.get("due_at")),
row.get("employee_id") or "",
row.get("name") or "",
row.get("department") or "",
"\n".join(str(video.get("name") or "") for video in videos),
"\n".join(_format_dashboard_datetime(video.get("watched_at")) for video in videos),
_dashboard_status_label(row.get("status")),
row.get("summary_text") or "",
_format_dashboard_datetime(row.get("completed_at")),
])
buffer = BytesIO()
workbook.save(buffer)
filename = f"lean_training_dashboard_{task['week_key']}.xlsx"
return buffer.getvalue(), filename
-135
View File
@@ -1,135 +0,0 @@
import os
import uuid
from typing import BinaryIO
from minio import Minio
from minio.error import S3Error
from werkzeug.utils import secure_filename
from app.core.config.settings import config, ACTIVE_ENV_NAME
cfg = config[ACTIVE_ENV_NAME]
class MinioService:
def __init__(self):
self.client = Minio(
cfg.MINIO_ENDPOINT,
access_key=cfg.MINIO_ACCESS_KEY,
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
try:
if not self.client.bucket_exists(self.bucket_name):
self.client.make_bucket(self.bucket_name)
# Set bucket policy to public read
policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"AWS": ["*"]},
"Action": ["s3:GetObject"],
"Resource": [f"arn:aws:s3:::{self.bucket_name}/*"]
}
]
}
import json
self.client.set_bucket_policy(self.bucket_name, json.dumps(policy))
except Exception as e:
# log or print error
print(f"MinIO bucket error (or not reachable): {e}")
def upload_file(self, file_stream: BinaryIO, filename: str, content_type: str, file_size: int) -> str:
"""
Uploads a file to MinIO and returns the generated object name.
"""
# If MinIO is not running, we could fallback to local storage or raise clear error
try:
self._ensure_bucket_exists()
except Exception:
pass
ext = os.path.splitext(filename)[1]
unique_filename = f"{uuid.uuid4().hex}{ext}"
try:
self.client.put_object(
bucket_name=self.bucket_name,
object_name=unique_filename,
data=file_stream,
length=file_size,
content_type=content_type
)
except Exception as e:
# For development, if minio is down, let's mock it so UI can continue
print(f"Warning: Minio upload failed ({e}). Fallback to local storage.")
# fallback to local storage
os.makedirs('data/agent-guides', exist_ok=True)
local_path = os.path.join('data/agent-guides', unique_filename)
file_stream.seek(0)
with open(local_path, 'wb') as f:
f.write(file_stream.read())
return unique_filename
def get_public_url(self, object_name: str) -> str:
"""
返回同源的指南文件代理地址。
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
读取对象的原始字节内容。
用途:给后台解析 PDF、图片等资料时复用统一文件读取入口,避免业务层自己判断本地回退还是 MinIO。
参数约束:object_name 必须是已存储的对象名,不接受外部 URL。
"""
local_path = os.path.join('data/agent-guides', object_name)
if os.path.exists(local_path):
with open(local_path, 'rb') as file_obj:
return file_obj.read()
response = self.client.get_object(self.bucket_name, object_name)
try:
return response.read()
finally:
response.close()
response.release_conn()
def delete_file(self, object_name: str):
try:
self.client.remove_object(self.bucket_name, object_name)
except S3Error as e:
print(f"Error deleting file from MinIO: {e}")
minio_service = MinioService()
-439
View File
@@ -1,439 +0,0 @@
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'
# 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,
}
max_retries = 3
last_exc = None
for attempt in range(1, max_retries + 1):
try:
response = requests.post(
cls._get_service_url(),
data=payload,
headers=headers,
timeout=cls._request_timeout(),
)
response.raise_for_status()
return ET.fromstring(response.text)
except requests.RequestException as exc:
last_exc = exc
status_code = getattr(getattr(exc, 'response', None), 'status_code', None)
retryable = status_code in (502, 503, 504) if status_code else True
if retryable and attempt < max_retries:
import time
wait = attempt * 2
current_app.logger.warning(
'[oa-leave] SOAP request failed (attempt %d/%d, status=%s), retrying in %ds: %s',
attempt, max_retries, status_code, wait, exc,
)
time.sleep(wait)
continue
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败:{exc}') from exc
except ET.ParseError as exc:
raise OALeaveWorkflowError('OA WorkflowService 返回了无法解析的 XML。') from exc
raise OALeaveWorkflowError(f'OA WorkflowService 请求失败(重试{max_retries}次后仍出错):{last_exc}') from last_exc
@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'],
'jobtitle': matched.get('jobtitle', ''),
'jobtitleName': matched.get('jobtitleName', ''),
'departmentid': matched.get('departmentid', ''),
'departmentName': matched.get('departmentName', ''),
'subcompanyid1': matched.get('subcompanyid1', ''),
'subcompanyName': matched.get('subcompanyName', ''),
}
@staticmethod
def _pick_browser_field_value(*values: Any) -> str:
for value in values:
text = ('' if value is None else str(value)).strip()
if text:
return text
return ''
@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)
field_html_type = (field.findtext('wf:fieldHtmlType', default='', namespaces=NS) or '').strip()
if field_html_type == '3':
filed_html_node = field.find('wf:filedHtmlShow', NS)
if filed_html_node is not None:
filed_html_node.text = str(show_value)
for tag in ['edit', 'view']:
node = field.find(f'wf:{tag}', NS)
if node is not None:
node.text = 'true'
else:
node = ET.SubElement(field, f'{{{WORKFLOW_NS}}}{tag}')
node.text = 'true'
@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'])
cls._set_field(request_info, 'sqrgh', 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'])
filler_jobtitle = cls._pick_browser_field_value(filler.get('jobtitle'), form_data.get('fillerJobTitle'))
filler_jobtitle_name = cls._pick_browser_field_value(filler.get('jobtitleName'))
filler_department = cls._pick_browser_field_value(filler.get('departmentid'), form_data.get('fillerDepartmentId'))
filler_department_name = cls._pick_browser_field_value(filler.get('departmentName'))
filler_subcompany = cls._pick_browser_field_value(filler.get('subcompanyid1'), form_data.get('fillerSubCompanyId1'))
filler_subcompany_name = cls._pick_browser_field_value(filler.get('subcompanyName'))
applicant_jobtitle = cls._pick_browser_field_value(applicant.get('jobtitle'), form_data.get('applicantJobTitle'))
applicant_jobtitle_name = cls._pick_browser_field_value(applicant.get('jobtitleName'))
applicant_department = cls._pick_browser_field_value(applicant.get('departmentid'), form_data.get('applicantDepartmentId'))
applicant_department_name = cls._pick_browser_field_value(applicant.get('departmentName'))
applicant_subcompany = cls._pick_browser_field_value(applicant.get('subcompanyid1'), form_data.get('applicantSubCompanyId1'))
applicant_subcompany_name = cls._pick_browser_field_value(applicant.get('subcompanyName'))
try:
from app.services.oa_sqlserver import OASQLServerService
if filler_jobtitle and not filler_jobtitle_name:
filler_jobtitle_name = OASQLServerService.get_jobtitle_name(filler_jobtitle)
if filler_department and not filler_department_name:
filler_department_name = OASQLServerService.get_department_name(filler_department)
if filler_subcompany and not filler_subcompany_name:
filler_subcompany_name = OASQLServerService.get_subcompany_name(filler_subcompany)
if applicant_jobtitle and not applicant_jobtitle_name:
applicant_jobtitle_name = OASQLServerService.get_jobtitle_name(applicant_jobtitle)
if applicant_department and not applicant_department_name:
applicant_department_name = OASQLServerService.get_department_name(applicant_department)
if applicant_subcompany and not applicant_subcompany_name:
applicant_subcompany_name = OASQLServerService.get_subcompany_name(applicant_subcompany)
except Exception:
pass
cls._set_field(request_info, 'tdrzw', value=filler_jobtitle, show_value=filler_jobtitle_name or filler_jobtitle or '暂无')
cls._set_field(request_info, 'tdrbm', value=filler_department, show_value=filler_department_name or filler_department or '暂无')
cls._set_field(request_info, 'tdrgs', value=filler_subcompany, show_value=filler_subcompany_name or filler_subcompany or '暂无')
cls._set_field(request_info, 'sqrzw', value=applicant_jobtitle, show_value=applicant_jobtitle_name or applicant_jobtitle or '暂无')
cls._set_field(request_info, 'sqrbm', value=applicant_department, show_value=applicant_department_name or applicant_department or '暂无')
cls._set_field(request_info, 'sqrgs', value=applicant_subcompany, show_value=applicant_subcompany_name or applicant_subcompany or '暂无')
current_app.logger.info(
'[oa-leave] field values: tdrzw=%s/%s tdrbm=%s/%s tdrgs=%s/%s sqrzw=%s/%s sqrbm=%s/%s sqrgs=%s/%s',
filler_jobtitle, filler_jobtitle_name or filler_jobtitle or '暂无',
filler_department, filler_department_name or filler_department or '暂无',
filler_subcompany, filler_subcompany_name or filler_subcompany or '暂无',
applicant_jobtitle, applicant_jobtitle_name or applicant_jobtitle or '暂无',
applicant_department, applicant_department_name or applicant_department or '暂无',
applicant_subcompany, applicant_subcompany_name or applicant_subcompany or '暂无',
)
cls._set_field(request_info, 'dlrgh', 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)
log_fields = ['tdrzw', 'tdrbm', 'tdrgs', 'sqrzw', 'sqrbm', 'sqrgs', 'qjsc', 'tdrgh', 'sqrgh']
for fn in log_fields:
f = cls._find_field(request_info, fn)
if f is not None:
fv = f.findtext('wf:fieldValue', default='', namespaces=NS)
fsv = f.findtext('wf:fieldShowValue', default='', namespaces=NS)
fe = f.findtext('wf:edit', default='(removed)', namespaces=NS)
current_app.logger.info('[oa-leave] PUSH field %s: value=%s showValue=%s edit=%s', fn, fv, fsv, fe)
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)
current_app.logger.info('[oa-leave] OA response request_id=%s', request_id)
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),
}
-258
View File
@@ -1,258 +0,0 @@
"""
backend/app/services/oa_sqlserver.py
用途:封装 OA SQL Server 的员工检索与组织信息查询能力,供请假代理人/申请人选择等场景复用。
依赖:pyodbc、OA ecology 数据库视图 userInfo_view / HrmDepartment / HrmSubCompany / HrmJobTitles。
逻辑:通过只读 SQL 查询返回 OA 用户与组织字段;对于 OA 中夹带的多语言包装串,统一在服务层清洗成可直接展示的中文文本。
"""
import os
import re
import pyodbc
from flask import current_app
_OA_MULTILINGUAL_WRAPPER_PATTERN = re.compile(
r"~`~`7\s*(.*?)\s*~`8\s*(.*?)\s*~`9\s*(.*?)\s*~`~"
)
class OASQLServerService:
@staticmethod
def _normalize_oa_text(value) -> str:
"""
清洗 OA 多语言包装字段。
AI 触发时机:当 OA 视图返回的姓名、部门、分部、职务等字段中夹带
`~`~`7 中文 ~`8 English ~`9 繁中 ~`~` 这类原始包装串时,需统一提取
可直接给用户展示的文本,避免在代理人选择弹窗中看到乱码样式的标记串。
Args:
value: 来自 OA SQL Server 的原始字段值。
Returns:
优先返回简体中文,其次英文、繁中;若未命中包装规则,则返回原始去空白文本。
"""
text = str(value or "").strip()
if not text:
return ""
matched = _OA_MULTILINGUAL_WRAPPER_PATTERN.search(text)
if not matched:
return text
simplified, english, traditional = (
segment.strip().strip("`").strip()
for segment in matched.groups()
)
return simplified or english or traditional or text
@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()
available_drivers = pyodbc.drivers()
if driver not in available_drivers:
driver = 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};"
)
if driver != "SQL Server":
conn_str += (
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, jobtitle, departmentid, subcompanyid1,
departmentname, subcompanyname, jobtitlename
FROM (
SELECT v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename,
ROW_NUMBER() OVER(ORDER BY v.id) as rn
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
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) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
})
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 v.id, v.workcode, v.lastname, v.jobtitle, v.departmentid, v.subcompanyid1,
d.departmentname, s.subcompanyname, j.jobtitlename
FROM userInfo_view v
LEFT JOIN HrmDepartment d ON v.departmentid = d.id
LEFT JOIN HrmSubCompany s ON v.subcompanyid1 = s.id
LEFT JOIN HrmJobTitles j ON v.jobtitle = j.id
WHERE v.workcode = ? AND v.lastname = ?
ORDER BY v.id
"""
cursor.execute(query_sql, [normalized_employee_id, normalized_name])
row = cursor.fetchone()
if not row:
return None
return {
"uid": str(row.id) if row.id is not None else "",
"employeeId": str(row.workcode) if row.workcode is not None else "",
"name": cls._normalize_oa_text(row.lastname),
"jobtitle": cls._normalize_oa_text(row.jobtitle),
"departmentid": str(row.departmentid) if row.departmentid is not None else "",
"subcompanyid1": str(row.subcompanyid1) if row.subcompanyid1 is not None else "",
"departmentName": cls._normalize_oa_text(row.departmentname),
"subcompanyName": cls._normalize_oa_text(row.subcompanyname),
"jobtitleName": cls._normalize_oa_text(row.jobtitlename),
}
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_department_name(cls, department_id: str) -> str:
if not department_id or not department_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 departmentname FROM HrmDepartment WHERE id = ?",
[department_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.departmentname) if row and row.departmentname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_subcompany_name(cls, subcompany_id: str) -> str:
if not subcompany_id or not subcompany_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 subcompanyname FROM HrmSubCompany WHERE id = ?",
[subcompany_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.subcompanyname) if row and row.subcompanyname else ""
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def get_jobtitle_name(cls, jobtitle_id: str) -> str:
if not jobtitle_id or not jobtitle_id.strip():
return ""
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(
"SELECT TOP 1 jobtitlename FROM HrmJobTitles WHERE id = ?",
[jobtitle_id.strip()],
)
row = cursor.fetchone()
return cls._normalize_oa_text(row.jobtitlename) if row and row.jobtitlename else ""
finally:
try:
cursor.close()
finally:
connection.close()
-240
View File
@@ -1,240 +0,0 @@
"""
backend/app/services/oa_wecom_sync.py
用途:从 OA SQL Server userInfo_view 按本地工号回填 users.wecom_userid。
依赖:OASQLServerService、SQLAlchemy db、User 模型。
逻辑:先查本地有 employee_id 的用户,再按工号 IN 查询 OA;供 admin 绑定管理预览/写入。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import User
from app.services.oa_sqlserver import OASQLServerService
_PREVIEW_LIMIT = 20
_OA_VIEW = 'userInfo_view'
_OA_IN_BATCH_SIZE = 500
def _clean_str(value) -> str | None:
"""
规范化字符串;空值返回 None。
@param value: 任意输入
Returns:
去首尾空白后的字符串,或 None
"""
if value is None:
return None
text = str(value).strip()
return text or None
def _load_local_users_with_employee_id() -> list[tuple[User, str]]:
"""
加载本地含有效工号的用户列表。
核心逻辑:查询 employee_id 非空记录,trim 后过滤空串。
Returns:
(User, employee_id) 元组列表
"""
rows: list[tuple[User, str]] = []
for user in db.session.query(User).filter(User.employee_id.isnot(None)).all():
employee_id = _clean_str(user.employee_id)
if not employee_id:
continue
rows.append((user, employee_id))
return rows
def fetch_oa_wecom_bindings_for_workcodes(workcodes: list[str]) -> list[dict[str, str | None]]:
"""
按工号批量查询 OA userInfo_view 中的企微 userid 映射。
核心逻辑:工号去重后分批 IN 查询,避免全表扫描。
@param workcodes: 本地 users.employee_id 列表
Returns:
每项含 workcode、wecom_userid、name
Raises:
RuntimeError: ODBC 连接或查询失败
"""
unique_codes: list[str] = []
seen: set[str] = set()
for code in workcodes:
cleaned = _clean_str(code)
if not cleaned or cleaned in seen:
continue
seen.add(cleaned)
unique_codes.append(cleaned)
if not unique_codes:
return []
connection = OASQLServerService._connect()
cursor = connection.cursor()
rows: list[dict[str, str | None]] = []
try:
for offset in range(0, len(unique_codes), _OA_IN_BATCH_SIZE):
batch = unique_codes[offset : offset + _OA_IN_BATCH_SIZE]
placeholders = ','.join('?' for _ in batch)
cursor.execute(
f"""
SELECT id, workcode, lastname
FROM userInfo_view
WHERE workcode IN ({placeholders})
AND id IS NOT NULL
""",
batch,
)
for row in cursor.fetchall():
workcode = _clean_str(row.workcode)
wecom_userid = _clean_str(row.id)
if not workcode or not wecom_userid:
continue
rows.append(
{
'workcode': workcode,
'wecom_userid': wecom_userid,
'name': _clean_str(row.lastname),
}
)
return rows
finally:
try:
cursor.close()
finally:
connection.close()
def sync_wecom_userids_from_oa(*, apply: bool) -> dict[str, Any]:
"""
执行 OA 工号 → wecom_userid 同步(本地用户驱动)。
核心逻辑:读本地工号 → 按 IN 查 OA → 匹配并 dry-run 或写入 wecom_userid。
@param apply: True 时提交数据库;存在 conflicts 时不写入
Returns:
统计摘要 dict(结构与企微通讯录同步兼容,便于前端复用)
Raises:
RuntimeError: OA 未配置、连接失败或 apply 时存在冲突
"""
local_users = _load_local_users_with_employee_id()
workcodes = [employee_id for _, employee_id in local_users]
oa_rows = fetch_oa_wecom_bindings_for_workcodes(workcodes)
summary: dict[str, Any] = {
'apply': apply,
'employee_id_source': f'oa:{_OA_VIEW}.workcode',
'department_ids': [],
'local_candidates': len(local_users),
'wecom_users': 0,
'wecom_without_employee_id': 0,
'local_matched': 0,
'would_update': 0,
'updated': 0,
'already_bound': 0,
'local_missing': 0,
'conflicts': [],
'missing_samples': [],
'pending_updates': [],
}
oa_by_workcode: dict[str, dict[str, str | None]] = {}
duplicate_workcodes: set[str] = set()
for row in oa_rows:
workcode = row['workcode']
if not workcode:
continue
if workcode in oa_by_workcode:
duplicate_workcodes.add(workcode)
summary['conflicts'].append(
{
'employee_id': workcode,
'username': '',
'new_wecom_userid': row['wecom_userid'],
'reason': 'duplicate_workcode_in_oa',
}
)
continue
oa_by_workcode[workcode] = row
summary['wecom_users'] = len(oa_by_workcode)
for local_user, employee_id in local_users:
if employee_id in duplicate_workcodes:
continue
oa_row = oa_by_workcode.get(employee_id)
if not oa_row:
summary['local_missing'] += 1
if len(summary['missing_samples']) < _PREVIEW_LIMIT:
summary['missing_samples'].append(
{
'employee_id': employee_id,
'username': local_user.username,
}
)
continue
wecom_userid = oa_row['wecom_userid']
name = oa_row.get('name')
if not wecom_userid:
summary['wecom_without_employee_id'] += 1
continue
summary['local_matched'] += 1
if local_user.wecom_userid == wecom_userid:
summary['already_bound'] += 1
continue
conflict = None
if local_user.wecom_userid and local_user.wecom_userid != wecom_userid:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'old_wecom_userid': local_user.wecom_userid,
'new_wecom_userid': wecom_userid,
}
else:
occupied = (
db.session.query(User)
.filter(User.wecom_userid == wecom_userid, User.id != local_user.id)
.first()
)
if occupied:
conflict = {
'employee_id': employee_id,
'username': local_user.username,
'new_wecom_userid': wecom_userid,
'occupied_by_user_id': occupied.id,
'occupied_by_username': occupied.username,
}
if conflict:
summary['conflicts'].append(conflict)
continue
summary['would_update'] += 1
if len(summary['pending_updates']) < _PREVIEW_LIMIT:
summary['pending_updates'].append(
{
'employee_id': employee_id,
'username': local_user.username,
'wecom_userid': wecom_userid,
'name': name,
}
)
if apply:
local_user.wecom_userid = wecom_userid
summary['updated'] += 1
if summary['conflicts'] and apply:
db.session.rollback()
raise RuntimeError('Conflicts detected; resolve manually before apply')
if apply and summary['updated'] > 0:
db.session.commit()
elif apply:
db.session.rollback()
return summary
@@ -31,7 +31,7 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名;与 settings.WECOM_NOTIFY_EVENTS 默认值条目一致(同 contract_payment_warning 命名风格)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
@@ -29,7 +29,7 @@ from app.models.order_delivery_reply import (
OrderDeliveryErpLine,
OrderDeliveryLineState,
)
from app.services.wecom_notify import send_wecom_event_message
from app.services.integrations.wecom.notify import send_wecom_event_message
# 企微事件开关名:与行级通知共用同一事件(WECOM_NOTIFY_EVENTS 已包含,无需新增配置)。
WECOM_EVENT_TYPE = "order_delivery_reply_notify"
-374
View File
@@ -1,374 +0,0 @@
import json
import os
import re
import time
from datetime import datetime
from html import escape
from urllib.parse import quote
from flask import current_app
from app import db
from app.models import ChatLog
from app.services.text2sql import Text2SQLService
class PLMOracleService:
_MAX_RESULT_ROWS = 50
_PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
_SUMMARY_COLUMNS = ("NAME", "EXTENTIONNAME", "FILETYPE", "FILESIZE", "RELATIVEPATH", "LASTACCESSTIME")
_MATERIAL_PATTERN = re.compile(r"\b[A-Z0-9]+(?:-[A-Z0-9]+)+\b", re.IGNORECASE)
_EXPLICIT_LABEL_PATTERN = re.compile(
r"(?:料号|料號|物料料号|物料料號|物料编号|物料編號|part\s*(?:no|number)?)\s*[::]?\s*([A-Z0-9][A-Z0-9._-]{5,})",
re.IGNORECASE,
)
_RELATIONAL_SQL = """
select *
from bi_file endb
where endb.revisionguid in (
select bb.revisionguid
from (
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00016_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v, NT_00064_0 str, NT_00018_0 cad, bi_file b
where v.name in ('ITEM-CAD2D$', 'ITEM-CAD3D$')
and str.viewfk = v.guid
and str.end2$master = cad.masterfk
and cad.latestrevision like '%m%'
and b.revisionguid = cad.guid
union
select v.end1, b.*
from viewobject_0 v,
StructureObject_0 str,
document_0 doc,
bi_file b
where v.name in ('RelatedDoc')
and str.viewfk = v.guid
and str.end2$master = doc.masterfk
and doc.latestrevision like '%m%'
and b.revisionguid = doc.guid
) bb,
item_0 i
where bb.end1 = i.guid
and i.id = :item_id
and i.latestrevision like '%m%'
)
and endb.lastaccesstime is not null
"""
_FILENAME_SQL = """
select *
from bi_file
where upper(name) like :name_pattern
and lastaccesstime is not null
order by lastaccesstime desc nulls last
"""
@classmethod
def supports(cls, query: str, agent) -> bool:
_ = agent
return bool(cls.extract_material_no(query))
@classmethod
def extract_material_no(cls, query: str) -> str | None:
text = str(query or "").strip().upper()
if not text:
return None
explicit = cls._EXPLICIT_LABEL_PATTERN.search(text)
if explicit:
return explicit.group(1).strip().upper()
direct_match = cls._MATERIAL_PATTERN.fullmatch(text)
if direct_match:
return direct_match.group(0).upper()
for match in cls._MATERIAL_PATTERN.finditer(text):
candidate = match.group(0).upper()
if any(ch.isalpha() for ch in candidate) and any(ch.isdigit() for ch in candidate):
return candidate
return None
@staticmethod
def _get_connect_kwargs() -> dict:
dsn = (os.getenv("PLM_ORACLE_DSN") or "").strip()
host = (os.getenv("PLM_ORACLE_HOST") or "192.168.0.11").strip()
port = int((os.getenv("PLM_ORACLE_PORT") or "1521").strip())
service_name = (os.getenv("PLM_ORACLE_SERVICE_NAME") or "").strip()
sid = (os.getenv("PLM_ORACLE_SID") or "orcl").strip()
kwargs = {
"user": (os.getenv("PLM_ORACLE_USERNAME") or "PLM").strip(),
"password": (os.getenv("PLM_ORACLE_PASSWORD") or "PLM").strip(),
}
if dsn:
kwargs["dsn"] = dsn
return kwargs
import oracledb
if service_name:
kwargs["dsn"] = oracledb.makedsn(host, port, service_name=service_name)
else:
kwargs["dsn"] = oracledb.makedsn(host, port, sid=sid)
return kwargs
@classmethod
def _connect(cls):
try:
import oracledb
except ImportError as exc:
raise RuntimeError("oracledb 未安装,无法连接 PLM Oracle") from exc
oracle_client_dir = Text2SQLService._get_oracle_client_dir()
Text2SQLService._prepare_oracle_runtime_env(oracle_client_dir)
Text2SQLService._init_oracle_client(oracledb)
return oracledb.connect(**cls._get_connect_kwargs())
@classmethod
def _execute_query(cls, sql: str, **params) -> tuple[list[str], list[tuple]]:
connection = cls._connect()
cursor = connection.cursor()
try:
cursor.execute(sql, params)
columns = [col[0] for col in cursor.description] if cursor.description else []
rows = cursor.fetchmany(cls._MAX_RESULT_ROWS + 1)
return columns, rows
finally:
try:
cursor.close()
finally:
connection.close()
@classmethod
def _query_files(cls, material_no: str) -> tuple[list[str], list[tuple], str]:
try:
columns, rows = cls._execute_query(cls._RELATIONAL_SQL, item_id=material_no)
if rows:
return columns, rows, "relational"
except Exception as exc:
if current_app:
current_app.logger.warning("[plm-oracle] relational query failed for %s: %s", material_no, exc)
columns, rows = cls._execute_query(
cls._FILENAME_SQL,
name_pattern=f"{material_no.upper()}%",
)
return columns, rows, "filename_fallback"
@staticmethod
def _format_datetime(value) -> str:
if value is None:
return "-"
if isinstance(value, datetime):
return value.strftime("%Y-%m-%d %H:%M:%S")
return str(value)
@staticmethod
def _format_size(value) -> str:
if value in (None, ""):
return "-"
try:
size = int(value)
except (TypeError, ValueError):
return str(value)
if size < 1024:
return f"{size} B"
if size < 1024 * 1024:
return f"{size / 1024:.1f} KB"
return f"{size / 1024 / 1024:.2f} MB"
@classmethod
def _build_plm_share_path(cls, storage_id, file_path, file_id: str) -> str:
parts = [cls._PLM_PREVIEW_SHARE_ROOT.rstrip("\\/")]
for value in (storage_id, file_path, file_id):
text = str(value or "").strip()
if not text:
continue
parts.append(text.replace("/", "\\").strip("\\"))
return "\\".join(part for part in parts if part)
@classmethod
def _render_file_name(cls, row: tuple, index_map: dict[str, int]) -> str:
def raw(column_name: str):
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return None
value = row[idx]
return None if value in (None, "") else value
file_name = str(raw("NAME") or "").strip()
if not file_name:
return "-"
storage_id = raw("STORAGEID")
file_path = raw("FILEPATH")
file_id = str(raw("ID") or "").strip()
if not storage_id or file_path is None or not file_id:
return escape(file_name)
share_path = cls._build_plm_share_path(storage_id, file_path, file_id)
preview_href = f"#plm-preview?name={quote(file_name, safe='')}&url={quote(share_path, safe='')}"
return f'<a href="{preview_href}">{escape(file_name)}</a>'
@staticmethod
def _escape_markdown_cell(value: str) -> str:
return str(value).replace("|", r"\|").replace("\r", " ").replace("\n", "<br>")
@staticmethod
def _escape_html_text(value) -> str:
return escape(str(value), quote=True).replace("\r", " ").replace("\n", "<br>")
@classmethod
def _render_column_value(cls, row: tuple, column_name: str, index_map: dict[str, int]) -> str:
idx = index_map.get(column_name.upper())
if idx is None or idx >= len(row):
return "-"
value = row[idx]
if value in (None, ""):
return "-"
upper_name = column_name.upper()
if upper_name in {"CREATETIME", "LASTACCESSTIME"}:
return cls._format_datetime(value)
if upper_name == "FILESIZE":
return cls._format_size(value)
if upper_name == "NAME":
return cls._render_file_name(row, index_map)
return str(value)
@classmethod
def _build_record_summary(cls, row: tuple, index_map: dict[str, int], row_no: int) -> str:
parts = [f"记录 {row_no}"]
for column_name in cls._SUMMARY_COLUMNS:
if column_name.upper() not in index_map:
continue
rendered = cls._render_column_value(row, column_name, index_map)
label = {
"NAME": "文件名",
"EXTENTIONNAME": "扩展名",
"FILETYPE": "文件类型",
"FILESIZE": "文件大小",
"RELATIVEPATH": "相对路径",
"LASTACCESSTIME": "最后访问时间",
}.get(column_name.upper(), column_name)
if column_name.upper() == "NAME":
parts.append(f"{label}: {rendered}")
else:
parts.append(f"{label}: {cls._escape_html_text(rendered)}")
return " | ".join(parts)
@classmethod
def _build_record_detail_html(cls, row: tuple, columns: list[str], index_map: dict[str, int], row_no: int) -> str:
rows_html = []
for column_name in columns:
rendered_value = cls._render_column_value(row, column_name, index_map)
safe_value = rendered_value if column_name.upper() == "NAME" else cls._escape_html_text(rendered_value)
rows_html.append(
"<tr>"
f"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f8fafc;white-space:nowrap;\">{cls._escape_html_text(column_name)}</th>"
f"<td style=\"padding:6px 10px;border:1px solid #d1d5db;word-break:break-all;\">{safe_value}</td>"
"</tr>"
)
summary_html = cls._build_record_summary(row, index_map, row_no)
return (
"<details style=\"margin:12px 0;border:1px solid #e5e7eb;border-radius:8px;padding:8px 12px;background:#ffffff;\">"
f"<summary style=\"cursor:pointer;font-weight:600;\">{summary_html}</summary>"
"<div style=\"margin-top:10px;overflow:auto;\">"
"<table style=\"width:100%;border-collapse:collapse;font-size:13px;\">"
"<thead><tr>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;width:220px;\">字段</th>"
"<th style=\"padding:6px 10px;text-align:left;border:1px solid #d1d5db;background:#f1f5f9;\">值</th>"
"</tr></thead>"
f"<tbody>{''.join(rows_html)}</tbody>"
"</table>"
"</div>"
"</details>"
)
@classmethod
def _build_answer(cls, material_no: str, columns: list[str], rows: list[tuple]) -> str:
if not rows:
return f"已在 PLM 中查询料号 `{material_no}`,未找到符合条件的相关资料。"
overflow = len(rows) > cls._MAX_RESULT_ROWS
visible_rows = rows[: cls._MAX_RESULT_ROWS]
index_map = {name.upper(): idx for idx, name in enumerate(columns)}
lines = [
f"已在 PLM 中查询到料号 `{material_no}` 的相关资料,共返回 {len(visible_rows)} 条记录"
+ ("(仅展示前 50 条)" if overflow else "。"),
"",
"以下结果支持点击单条记录展开,展开后按数据库原始字段顺序展示完整数据:",
]
for idx, row in enumerate(visible_rows, start=1):
lines.extend(["", cls._build_record_detail_html(row, columns, index_map, idx)])
if overflow:
lines.extend(["", "如需查看更多结果,请进一步限定料号或资料范围。"])
return "\n".join(lines)
@classmethod
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
start_time = time.time()
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
material_no = cls.extract_material_no(query)
try:
if not material_no:
raise RuntimeError("未识别到有效料号,请输入类似 F3-A12M290000019 的料号。")
yield f"data: {json.dumps({'event': 'message', 'answer': f'已识别料号 `{material_no}`,正在查询 PLM 资料,请稍候...\\n'}, ensure_ascii=False)}\n\n"
columns, rows, query_mode = cls._query_files(material_no)
answer = cls._build_answer(material_no, columns, rows)
latency = int((time.time() - start_time) * 1000)
chat_log_id = None
try:
chat_log = ChatLog(
user_id=user.id,
agent_id=agent.id,
conversation_id=final_conversation_id,
session_id=session_id,
query=query,
answer=answer,
tokens_used=0,
latency=latency,
payload={
"material_no": material_no,
"row_count": min(len(rows), cls._MAX_RESULT_ROWS),
"query_mode": query_mode,
},
)
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 PLM chat: %s", exc)
db.session.rollback()
end_data = {
"event": "message_end",
"answer": answer,
"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("[plm-oracle] stream_chat failed query=%s", query)
error_data = {
"event": "error",
"message": str(exc) or "PLM 查询失败",
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(error_data, ensure_ascii=False)}\n\n"
@@ -18,7 +18,7 @@ from flask import current_app
from app import db
from app.core.config.settings import Config
from app.models import Agent
from app.services.dify import DifyService
from app.services.integrations.dify import DifyService
MAX_FINDINGS = 20
@@ -79,7 +79,7 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
def _receipt_timeout_seconds() -> int:
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
try:
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
return max(60, int(current_app.config.get('FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
except (TypeError, ValueError):
return 900
@@ -7,7 +7,7 @@ from typing import Any
from app import db
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
@@ -28,7 +28,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
wanted = _wanted_source_codes(task)
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
).filter(ShippingInventorySource.enabled.is_(True)).all()
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
@@ -37,7 +37,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
callback_id = f'receipt:{uuid.uuid4().hex}'
snapshot = {
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
}
return ShippingReceiptRpaUnitRun(
@@ -78,7 +78,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
units: list[ShippingReceiptRpaUnitRun] = []
for source, config in _eligible_sources(task):
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
for warehouse_id in warehouses:
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
unit.schedule_run_id = run.id
Loaded 100 of 541 files, more files were not shown because too many files have changed in this diff. Show more