Merge branch 'dev0914' into runny0914
This commit is contained in:
commit
453d910364
300 files changed
+20048
-12165
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
|
||||
+23
-3
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 管理机制注入。
|
||||
|
||||
|
||||
@@ -103,14 +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 / po-print schedules: %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()
|
||||
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -87,7 +87,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:
|
||||
|
||||
@@ -35,7 +35,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)
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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__)
|
||||
|
||||
|
||||
|
||||
@@ -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']
|
||||
@@ -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,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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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():
|
||||
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
|
||||
@@ -660,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:
|
||||
@@ -707,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'))
|
||||
@@ -796,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:
|
||||
@@ -822,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'))
|
||||
|
||||
@@ -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']
|
||||
@@ -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'
|
||||
@@ -679,6 +625,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')
|
||||
@@ -789,8 +753,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
|
||||
|
||||
@@ -810,8 +774,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
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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="文件检核执行完成")
|
||||
@@ -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="企微通讯录同步完成")
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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',
|
||||
}),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -21,7 +21,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:
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, PermissionRequest, User
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
|
||||
_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'}
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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 {}
|
||||
|
||||
@@ -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
@@ -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'
|
||||
|
||||
@@ -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] = []
|
||||
|
||||
@@ -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}
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -20,7 +20,7 @@ from app.services.lean_training_service import (
|
||||
resolve_lean_training_jump_agent_id,
|
||||
target_user_ids_for_task,
|
||||
)
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
from app.services.integrations.wecom.notify import send_wecom_event_message
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo, utc_now_naive
|
||||
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ from app.models import (
|
||||
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"
|
||||
|
||||
@@ -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()
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -57,7 +57,7 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
|
||||
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 [{
|
||||
'label': source.display_name or source.source_code, 'value': source.source_code,
|
||||
'description': f'{source.connector_type} · 收料已配置',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/schedule/job_registry.py
|
||||
|
||||
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、job_params。
|
||||
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、voucher_po_print_job、voucher_oa_sales_release_job、job_params。
|
||||
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
|
||||
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
|
||||
"""
|
||||
@@ -140,12 +140,17 @@ def _register_builtin_platform_jobs() -> None:
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
)
|
||||
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
|
||||
from app.services.schedule.voucher_oa_sales_release_job import run_voucher_oa_sales_release_schedule
|
||||
from app.services.schedule.voucher_po_print_job import run_voucher_po_print_schedule
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
)
|
||||
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_PO_PRINT_JOB_PARAMS
|
||||
from app.services.voucher_check.config import (
|
||||
DEFAULT_JOB_PARAMS,
|
||||
DEFAULT_OA_SALES_RELEASE_JOB_PARAMS,
|
||||
DEFAULT_PO_PRINT_JOB_PARAMS,
|
||||
)
|
||||
from app.services.schedule.contract_payment_job import (
|
||||
run_contract_payment_alert_schedule,
|
||||
run_contract_payment_sync_schedule,
|
||||
@@ -430,6 +435,43 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults=dict(DEFAULT_PO_PRINT_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="accounting-voucher-oa-sales-release",
|
||||
label="立账凭证销货放行单拉取",
|
||||
label_key="admin.schedule.form.platformJobAccountingVoucherOaSalesRelease",
|
||||
handler=run_voucher_oa_sales_release_schedule,
|
||||
description="每周二 05:30 从 E10 筛上月已归档销货放行单,下载表单 PDF 并上传到「销货单」;早于 06:00 检核周批。",
|
||||
description_key="admin.schedule.form.accountingVoucherOaSalesReleaseHint",
|
||||
category="finance",
|
||||
params_schema=(
|
||||
{
|
||||
"key": "scope_code",
|
||||
"type": "select",
|
||||
"label": "账套",
|
||||
"label_key": "admin.schedule.form.voucherCheckScope",
|
||||
"required": True,
|
||||
"default": "HXJM",
|
||||
"options": [{"value": "HXJM", "label": "HXJM"}],
|
||||
},
|
||||
{
|
||||
"key": "profile_code",
|
||||
"type": "text",
|
||||
"label": "业务方 Profile",
|
||||
"label_key": "admin.schedule.form.voucherCheckProfile",
|
||||
"required": True,
|
||||
"default": "sales",
|
||||
},
|
||||
{
|
||||
"key": "notify_failure_enabled",
|
||||
"type": "boolean",
|
||||
"label": "失败告警",
|
||||
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
|
||||
"required": False,
|
||||
"default": True,
|
||||
},
|
||||
),
|
||||
defaults=dict(DEFAULT_OA_SALES_RELEASE_JOB_PARAMS),
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="in-transit-receipt-file",
|
||||
label="在途收料文件抓取",
|
||||
|
||||
@@ -371,6 +371,14 @@ def prepare_schedule_queue() -> int:
|
||||
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
|
||||
_worker_initialized = True
|
||||
|
||||
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
|
||||
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||||
|
||||
transfer_stale = recover_stale_waiting_source_jobs()
|
||||
if transfer_stale:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||
|
||||
|
||||
@@ -149,7 +149,7 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
||||
核心逻辑:若 response_summary_json.domain_notification_managed=true(如立账凭证检核),
|
||||
则跳过以免与领域缺件/失败告警重复。
|
||||
"""
|
||||
from app.services.wecom_notify import (
|
||||
from app.services.integrations.wecom.notify import (
|
||||
upload_wecom_temp_media,
|
||||
send_wecom_file_message,
|
||||
send_wecom_textcard_message,
|
||||
|
||||
@@ -39,14 +39,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
|
||||
def get_inventory_archive_dir() -> str:
|
||||
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
|
||||
archive_dir = Path(
|
||||
current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR")
|
||||
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
|
||||
if current_app
|
||||
else ""
|
||||
)
|
||||
if not str(archive_dir):
|
||||
from app.core.config.settings import Config
|
||||
|
||||
archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR)
|
||||
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(archive_dir)
|
||||
|
||||
@@ -251,7 +251,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
|
||||
"""
|
||||
校验归档 ZIP 路径是否安全可下载。
|
||||
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
|
||||
"""
|
||||
resolved = zip_path.resolve()
|
||||
if resolved.suffix.lower() != ".zip":
|
||||
@@ -272,7 +272,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
|
||||
|
||||
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
|
||||
且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
|
||||
Returns:
|
||||
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
|
||||
|
||||
@@ -19,7 +19,10 @@ from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import AWAITING_RPA_CALLBACK_STATUS
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
RPA_WORKER_OFFLINE_MESSAGE,
|
||||
assert_inventory_rpa_worker_ready,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
@@ -121,6 +124,8 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
|
||||
run_no = run.run_no or f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}"
|
||||
try:
|
||||
# 写 trigger 前强制就绪检查:worker 离线立即 failed,不进入 awaiting_rpa_callback。
|
||||
assert_inventory_rpa_worker_ready()
|
||||
trigger_path = write_inventory_export_batch_trigger(
|
||||
run_no,
|
||||
sources,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
"""
|
||||
backend/app/services/schedule/voucher_oa_sales_release_job.py
|
||||
|
||||
用途:立账凭证销货放行单拉取 platform_job 薄封装。
|
||||
依赖:voucher_check.oa_sales_release_runner。
|
||||
逻辑:job_registry 注册 accounting-voucher-oa-sales-release 后由 schedule worker 调用;早于检核周批。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.voucher_check.oa_sales_release_runner import (
|
||||
ScheduleExecuteResult,
|
||||
run_oa_sales_release_batch,
|
||||
)
|
||||
|
||||
|
||||
def run_voucher_oa_sales_release_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行立账凭证销货放行单拉取排程。
|
||||
核心逻辑:委托 oa_sales_release_runner;默认周二 05:30,检核周批 06:00 只扫目录。
|
||||
"""
|
||||
return run_oa_sales_release_batch(task, run)
|
||||
@@ -26,17 +26,17 @@ def _fernet() -> Fernet:
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
"""
|
||||
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
|
||||
key = str(current_app.config.get('FREIGHT_RPA_CREDENTIAL_KEY') or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is not configured',
|
||||
'FREIGHT_RPA_CREDENTIAL_KEY is not configured',
|
||||
code='SHIPPING.RPA_CREDENTIAL_KEY_MISSING',
|
||||
)
|
||||
try:
|
||||
return Fernet(key.encode('ascii'))
|
||||
except (ValueError, UnicodeEncodeError) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_RPA_CREDENTIAL_KEY is invalid',
|
||||
'FREIGHT_RPA_CREDENTIAL_KEY is invalid',
|
||||
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
|
||||
) from exc
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
services/shipping_notice/effective_order_view.py
|
||||
|
||||
用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
|
||||
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
|
||||
ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
|
||||
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
|
||||
对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
|
||||
后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
def _owner_task(task: Any) -> Any:
|
||||
"""与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id:
|
||||
return db.session.get(ShippingOrderTask, order_task_id)
|
||||
return task
|
||||
|
||||
|
||||
def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""
|
||||
返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。
|
||||
|
||||
核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
|
||||
field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
|
||||
行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 或 ShippingOrderTask。
|
||||
Returns:
|
||||
(header dict[field_id, value], lines list[dict[field_id, value]])。
|
||||
"""
|
||||
header, lines = order_field_id_values(task)
|
||||
owner = _owner_task(task)
|
||||
current_id = getattr(owner, 'current_order_extraction_id', None)
|
||||
if current_id is None:
|
||||
return header, lines
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
header = dict(header)
|
||||
lines = [dict(row) for row in lines]
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
|
||||
# [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
|
||||
# 因此单头值始终以当前 Extraction 的已接受值为准。
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
header[str(item.field_id)] = item.value_json
|
||||
# [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
|
||||
if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
|
||||
position_by_line_id = {
|
||||
int(row.id): int(row.position)
|
||||
for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
|
||||
}
|
||||
overlay_by_index: dict[int, dict[str, Any]] = {}
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
continue
|
||||
index = position_by_line_id.get(int(item.line_id))
|
||||
if index is None:
|
||||
continue
|
||||
overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
|
||||
for index, row in enumerate(lines):
|
||||
row.update(overlay_by_index.get(index, {}))
|
||||
return header, lines
|
||||
|
||||
|
||||
def _coerce_qty(value: Any) -> Decimal | None:
|
||||
"""把字段值安全转为数量;空/非法值返回 None。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。
|
||||
|
||||
核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
|
||||
required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
|
||||
缺少规则映射时对应键为 None(由消费方回退冻结列)。
|
||||
|
||||
Args:
|
||||
owner: 已冻结订单的 ShippingOrderTask。
|
||||
Returns:
|
||||
{snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
|
||||
Raises:
|
||||
ValueError: 任务没有冻结快照。
|
||||
"""
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于通知行物化的冻结订单快照')
|
||||
_header, lines = effective_order_field_values(owner)
|
||||
required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
|
||||
required_ids = required_ids if isinstance(required_ids, dict) else {}
|
||||
part_fid = str(required_ids.get('part_number') or '')
|
||||
rsv_fid = str(required_ids.get('reservation_id') or '')
|
||||
qty_fid = str(required_ids.get('qty') or '')
|
||||
facts: dict[int, dict[str, Any]] = {}
|
||||
for line_orm, values in zip(snapshot.lines, lines, strict=True):
|
||||
facts[int(line_orm.id)] = {
|
||||
'part_number': values.get(part_fid) if part_fid else None,
|
||||
'reservation_id': values.get(rsv_fid) if rsv_fid else None,
|
||||
'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
|
||||
'field_values': dict(values),
|
||||
}
|
||||
return facts
|
||||
@@ -142,7 +142,10 @@ def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。
|
||||
|
||||
库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。
|
||||
"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
|
||||
@@ -779,7 +782,8 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
header_values, all_line_values = effective_order_field_values(task)
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
@@ -814,6 +818,26 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
# [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存,
|
||||
# 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。
|
||||
closed_snapshot_line_ids = set()
|
||||
if source_notice.id is not None:
|
||||
closed_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
closed_snapshot_line_ids = {
|
||||
int(snapshot.lines[int(decision.line_index)].id)
|
||||
for decision in closed_rows
|
||||
if decision.line_index is not None
|
||||
and 0 <= int(decision.line_index) < len(snapshot.lines)
|
||||
}
|
||||
selected_snapshot_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
|
||||
@@ -824,6 +848,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
source_notice,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
closed_snapshot_line_ids=closed_snapshot_line_ids,
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/fulfillment_audit.py
|
||||
|
||||
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError、db.session。
|
||||
依赖:audit_service.append_shipping_audit_event、Flask g.request_id、core.http_context、AppError、db.session。
|
||||
逻辑:由 candidate / decision / fulfillment_workflow / workspace 读取与导出 / Workflow 写路径调用;
|
||||
默认 strict=True;审计写入包在 SAVEPOINT 内,失败不污染外层业务事务;
|
||||
strict=False 时仅记日志(门禁路径用,禁止审计打断匹配等业务结果);
|
||||
@@ -37,10 +37,11 @@ def _client_request_context() -> tuple[str | None, str | None]:
|
||||
核心逻辑:优先 X-Forwarded-For 首段;无请求上下文时返回 (None, None)。
|
||||
"""
|
||||
try:
|
||||
from flask import request
|
||||
forwarded = str(request.headers.get('X-Forwarded-For') or '').split(',')[0].strip()
|
||||
ip = forwarded or str(request.remote_addr or '').strip() or None
|
||||
ua = str(request.headers.get('User-Agent') or '').strip() or None
|
||||
from app.core.http_context import header, remote_addr
|
||||
|
||||
forwarded = header('X-Forwarded-For').split(',')[0].strip()
|
||||
ip = forwarded or remote_addr() or None
|
||||
ua = header('User-Agent').strip() or None
|
||||
return ip, ua
|
||||
except RuntimeError:
|
||||
return None, None
|
||||
|
||||
@@ -420,7 +420,7 @@ def _auto_upload_enabled() -> bool:
|
||||
def _rpa_upload_timeout_seconds() -> int:
|
||||
"""货代上传 RPA 等待回调超时秒数。"""
|
||||
try:
|
||||
return max(int(current_app.config.get('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
|
||||
return max(int(current_app.config.get('FREIGHT_RPA_UPLOAD_TIMEOUT_SECONDS') or 30), 1)
|
||||
except (TypeError, ValueError):
|
||||
return 30
|
||||
|
||||
@@ -718,12 +718,47 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
}
|
||||
|
||||
|
||||
def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
"""读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。
|
||||
|
||||
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
|
||||
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
if task.id is None:
|
||||
return set()
|
||||
if not getattr(task, 'order_snapshot_id', None):
|
||||
return set()
|
||||
decisions = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
from app.models import ShippingOrderSnapshot
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if snapshot is None:
|
||||
return set()
|
||||
return {
|
||||
int(snapshot.lines[int(row.line_index)].id)
|
||||
for row in decisions
|
||||
if row.line_index is not None
|
||||
and 0 <= int(row.line_index) < len(snapshot.lines)
|
||||
}
|
||||
|
||||
|
||||
def match_completed(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
|
||||
|
||||
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
|
||||
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
|
||||
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
|
||||
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
|
||||
"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
@@ -738,17 +773,23 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if getattr(task, 'order_snapshot_id', None) else None
|
||||
)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []}
|
||||
closed_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
|
||||
if not expected_line_ids:
|
||||
# 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
|
||||
return False
|
||||
current_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in rows
|
||||
if getattr(row, 'snapshot_line_id', None) is not None
|
||||
}
|
||||
# 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if expected_line_ids and current_line_ids != expected_line_ids:
|
||||
} - closed_ids
|
||||
# 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if current_line_ids != expected_line_ids:
|
||||
return False
|
||||
released_ids = _released_snapshot_line_ids_for_task(task)
|
||||
for row in rows:
|
||||
if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
|
||||
continue
|
||||
result = str(row.match_result or '').strip()
|
||||
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
|
||||
if result == 'matched' and shortage <= 0:
|
||||
@@ -823,6 +864,7 @@ def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
return set()
|
||||
@@ -1344,6 +1386,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
|
||||
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
|
||||
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
|
||||
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
|
||||
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
|
||||
"""
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
@@ -1353,6 +1397,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
if not rows:
|
||||
return 'unfulfillable', []
|
||||
released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task)
|
||||
closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
has_ok = False
|
||||
has_block = False
|
||||
shortages: list[dict[str, Any]] = []
|
||||
@@ -1378,7 +1423,12 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
|
||||
shortage = _line_shortage_qty(shortage_qty)
|
||||
released = entry['snapshot_line_id'] in released_snapshot_line_ids
|
||||
if match_result == 'matched' and shortage <= 0:
|
||||
closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
|
||||
if closed:
|
||||
# [BE-结案-豁免] 结案行不再是履约要求:不阻断、不进缺货列表,
|
||||
# 但也不计入满足(非可履约内容);全结案 ⇒ 无可履约内容 ⇒ unfulfillable。
|
||||
entry['line_status'] = 'closed'
|
||||
elif match_result == 'matched' and shortage <= 0:
|
||||
entry['line_status'] = 'ok'
|
||||
has_ok = True
|
||||
elif released and shortage > 0:
|
||||
@@ -1390,21 +1440,25 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
has_block = True
|
||||
shortages.append(entry)
|
||||
line_results.append(entry)
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'),
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
# 结案行既不计满足也不阻断:无 ok 且无 block(如全结案)时无可履约内容 ⇒ unfulfillable,
|
||||
# 与 match_completed 的整单口径保持一致,避免 Gate 同步误判满足后空转编排。
|
||||
if has_block and has_ok:
|
||||
status = 'partial'
|
||||
elif has_block:
|
||||
status = 'unfulfillable'
|
||||
else:
|
||||
elif has_ok:
|
||||
status = 'fulfillable'
|
||||
else:
|
||||
status = 'unfulfillable'
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': status,
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
return status, shortages
|
||||
|
||||
|
||||
@@ -1615,7 +1669,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if lang:
|
||||
inv_payload["lang"] = lang
|
||||
return ensure_inventory(inv_payload)
|
||||
_order_header_values, order_field_lines = order_field_id_values(task)
|
||||
# [STEP 2] 兜底匹配基线读取有效视图(冻结快照 + 冻结后人工修正):
|
||||
# 匹配身份键(料号/预约等字段值)必须与展示值(__required_qty/__display_part_number)
|
||||
# 同源,否则出现"按冻结料号匹配、却展示有效料号"的混合投影。
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
_order_header_values, order_field_lines = effective_order_field_values(task)
|
||||
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
|
||||
for index, order_line in enumerate(order_field_lines):
|
||||
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
|
||||
@@ -2039,6 +2097,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
_verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
available_line_ids = set()
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/i18n.py
|
||||
|
||||
用途:维护发货通知链路的多语言文案与语言解析工具。
|
||||
依赖:Flask request 上下文、模块内 `_MESSAGES` 文案字典。
|
||||
依赖:core.http_context、模块内 `_MESSAGES` 文案字典。
|
||||
逻辑:由 parse_summary、field_alignment_summary、workflow 提示文案等上游模块调用本文件输出用户可读消息。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import has_request_context, request
|
||||
from app.core.http_context import has_http_request, header
|
||||
|
||||
SUPPORTED_LANGS = ("zh", "en", "th")
|
||||
|
||||
@@ -422,11 +422,11 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str:
|
||||
if val:
|
||||
return normalize_lang(val)
|
||||
|
||||
if has_request_context():
|
||||
hdr = str(request.headers.get("X-Lang") or "").strip()
|
||||
if has_http_request():
|
||||
hdr = header("X-Lang").strip()
|
||||
if hdr:
|
||||
return normalize_lang(hdr)
|
||||
accept = str(request.headers.get("Accept-Language") or "").strip()
|
||||
accept = header("Accept-Language").strip()
|
||||
if accept:
|
||||
return normalize_lang(accept.split(",")[0].strip())
|
||||
return "zh"
|
||||
|
||||
@@ -219,7 +219,7 @@ def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
|
||||
同一 RPA Profile 的批量站点由 Windows Worker 串行执行。每个站点沿用单站
|
||||
等待窗口会让排在后面的站点尚未被领取就超时,因此同组按站点数量线性扩展。
|
||||
"""
|
||||
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
timeout = max(1, int(current_app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS']))
|
||||
runs = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
@@ -357,7 +357,7 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
|
||||
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
# FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
raw_file_path = str(payload.get('file_path') or '').strip()
|
||||
path: Path | None = None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
|
||||
@@ -56,11 +56,11 @@ def callback_quarantine_dir() -> Path | None:
|
||||
|
||||
|
||||
def callback_cleanup_max_attempts() -> int:
|
||||
"""cleanup job 最大重试次数(SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
|
||||
"""cleanup job 最大重试次数(FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS)。"""
|
||||
try:
|
||||
return max(
|
||||
1,
|
||||
int(current_app.config.get("SHIPPING_NOTICE_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
|
||||
int(current_app.config.get("FREIGHT_RPA_CALLBACK_CLEANUP_MAX_ATTEMPTS") or _DEFAULT_MAX_CLEANUP_ATTEMPTS),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return _DEFAULT_MAX_CLEANUP_ATTEMPTS
|
||||
|
||||
@@ -508,6 +508,26 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
|
||||
return out
|
||||
|
||||
|
||||
def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dict[str, Any]]:
|
||||
"""按 line_index 索引当前匹配事实(Case 履约投影专用)。
|
||||
|
||||
核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
|
||||
_line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
|
||||
"""
|
||||
if task_id is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
int(row.line_index): serialize_match_fact(row)
|
||||
for row in rows
|
||||
if row.line_index is not None
|
||||
}
|
||||
|
||||
|
||||
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
|
||||
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
|
||||
facts = list(load_current_match_facts_by_task(task_id).values())
|
||||
|
||||
@@ -21,6 +21,7 @@ def replace_notice_lines_from_snapshot(
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
snapshot_line_ids: set[int] | None = None,
|
||||
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
|
||||
line_overrides: dict[int, dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
@@ -29,6 +30,10 @@ def replace_notice_lines_from_snapshot(
|
||||
notice_id: shipping_notices.id。
|
||||
snapshot: 已 flush 且带 lines 的 Snapshot。
|
||||
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
|
||||
inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
|
||||
line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
|
||||
按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
|
||||
缺失或 None 时回退冻结快照值。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
@@ -44,6 +49,7 @@ def replace_notice_lines_from_snapshot(
|
||||
continue
|
||||
notice_position += 1
|
||||
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
|
||||
override = (line_overrides or {}).get(int(line.id)) or {}
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
@@ -51,13 +57,17 @@ def replace_notice_lines_from_snapshot(
|
||||
position=notice_position - 1,
|
||||
# 发货通知项次按当前通知单重新从 1 编排。
|
||||
line_no=notice_position,
|
||||
part_number=getattr(line, 'part_number', None),
|
||||
reservation_id=getattr(line, 'reservation_id', None),
|
||||
required_qty=getattr(line, 'qty', None),
|
||||
part_number=override.get('part_number')
|
||||
if override.get('part_number') is not None else getattr(line, 'part_number', None),
|
||||
reservation_id=override.get('reservation_id')
|
||||
if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
|
||||
required_qty=override.get('qty')
|
||||
if override.get('qty') is not None else getattr(line, 'qty', None),
|
||||
inventory_source_code=inventory_facts.get('inventory_source_code'),
|
||||
inventory_file_id=inventory_facts.get('inventory_file_id'),
|
||||
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
|
||||
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
|
||||
field_values_json=dict(override['field_values'])
|
||||
if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
|
||||
依赖:冻结履约策略、export.order_field_id_values、ShippingNotice。
|
||||
依赖:冻结履约策略、effective_order_view.effective_order_field_values、ShippingNotice。
|
||||
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
"""
|
||||
|
||||
@@ -12,7 +12,8 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingNotice
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
|
||||
_PURPOSE_BY_CAPABILITY = {
|
||||
@@ -47,9 +48,9 @@ def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | No
|
||||
|
||||
|
||||
def task_line_purpose_values(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
|
||||
"""按订单行位置返回用途键值,值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)。"""
|
||||
purpose_ids = task_line_purpose_field_ids(task, required=required)
|
||||
_header, lines = order_field_id_values(task)
|
||||
_header, lines = effective_order_field_values(task)
|
||||
return [
|
||||
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
|
||||
for line in lines
|
||||
|
||||
@@ -426,12 +426,20 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
|
||||
]
|
||||
|
||||
|
||||
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
|
||||
def _sync_confirmed_task_fulfillment_gates(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_id: int,
|
||||
trigger: str = 'inventory_shortage_released',
|
||||
) -> None:
|
||||
"""
|
||||
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
|
||||
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
|
||||
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
|
||||
|
||||
Args:
|
||||
trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。
|
||||
"""
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
if task_id is None:
|
||||
@@ -469,7 +477,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
submit_auto_progress(
|
||||
task=task,
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
operator_id=actor_id,
|
||||
commit=False,
|
||||
)
|
||||
@@ -480,7 +488,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(task.task_no),
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
@@ -763,7 +771,6 @@ def project_review_case_line_decisions(
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
line_auto_fulfill_enabled,
|
||||
load_current_match_facts_by_task,
|
||||
project_line_inventory_view,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
@@ -810,7 +817,11 @@ def project_review_case_line_decisions(
|
||||
'status': 'resolving',
|
||||
'source': 'inventory_source_clue',
|
||||
}
|
||||
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
|
||||
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
load_current_match_facts_by_line_index,
|
||||
)
|
||||
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
|
||||
labels = dict(source_labels or {})
|
||||
if not labels:
|
||||
draft = getattr(case, 'current_draft', None)
|
||||
@@ -835,7 +846,12 @@ def project_review_case_line_decisions(
|
||||
decision = by_key.get(key)
|
||||
# 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留
|
||||
# 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。
|
||||
fact = match_facts.get(key)
|
||||
# [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
|
||||
line_index = draft_line.get('_line_index')
|
||||
fact = (
|
||||
match_facts_by_line.get(int(line_index))
|
||||
if line_index is not None else None
|
||||
)
|
||||
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
|
||||
fulfill_proj = dict(proj)
|
||||
if isinstance(fact, dict):
|
||||
@@ -1083,7 +1099,7 @@ def decide_review_line_fulfillment(
|
||||
case_no: Case 编号。
|
||||
draft_line_id: 草稿行键。
|
||||
decision_code: 决定码。
|
||||
reason: 关闭/重开/短缺放行必填原因。
|
||||
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
||||
expected_draft_version: 可选草稿乐观锁。
|
||||
actor_is_admin: 是否管理员(重开授权)。
|
||||
@@ -1098,7 +1114,9 @@ def decide_review_line_fulfillment(
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_INVALID',
|
||||
details={'decision_code': code},
|
||||
)
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN, DECISION_RELEASE_SHORTAGE} and not str(reason or '').strip():
|
||||
# [BE-放行免因] 短缺放行不强制原因:人工放行事实已由审计链完整记录
|
||||
# (操作人 + 时间 + 决定快照 release_field_values);结案/重开仍要求原因。
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN} and not str(reason or '').strip():
|
||||
raise ValidationError(
|
||||
'Reason is required',
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_REASON_REQUIRED',
|
||||
@@ -1239,8 +1257,13 @@ def decide_review_line_fulfillment(
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
|
||||
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
|
||||
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=case,
|
||||
actor_id=int(user_id),
|
||||
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, ShippingOrderReviewCase, ShippingOrderReviewSuggestion
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
|
||||
@@ -914,14 +914,12 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'snapshot_after_ref',
|
||||
'path_id_hash',
|
||||
'revision_no',
|
||||
# 独立收料报表配置快照:路径、受控条件与仓库清单均不含 selector、凭据或日期筛选。
|
||||
# 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。
|
||||
'inventory_source_id',
|
||||
'connector_type',
|
||||
'enabled',
|
||||
'config_version',
|
||||
'report_path_json',
|
||||
'query_parameters_json',
|
||||
'warehouse_ids_json',
|
||||
'file_id',
|
||||
'recipient_user_id',
|
||||
'message_type',
|
||||
|
||||
@@ -1468,8 +1468,8 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为
|
||||
shipping_processing_status(与 shipping_processing_projection 同源),
|
||||
并注入 shipping_processing_stage / progress_version / order_task_no;
|
||||
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
|
||||
供任务中心「进入订单处理」深链。
|
||||
另附带 review_run_no / review_case_no / owner_agent_id / conversation_id(经 OT.extraction_run
|
||||
与 OT 反查确认 Case),供任务中心「进入订单处理」深链。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 或 ShippingOrderTask。
|
||||
@@ -1517,6 +1517,19 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
data['conversation_id'] = cid
|
||||
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
|
||||
data['owner_agent_id'] = int(run.owner_agent_id)
|
||||
# [STEP 3] 注入确认 Case 号:工作台以 case_no 绑定工作项,OT 直链缺失该字段时
|
||||
# 选法 2 不会拉 Case,任务详情身份链断裂、五阶段页签全锁(2026-09-17 工作台直链修复)。
|
||||
# confirmed_task_id 唯一约束保证 OT→Case 至多一条,点查代价可忽略。
|
||||
if order_task is not None and not str(data.get('review_case_no') or '').strip():
|
||||
confirmed_case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(confirmed_task_id=int(order_task.id))
|
||||
.first()
|
||||
)
|
||||
if confirmed_case is not None:
|
||||
case_no = str(confirmed_case.case_no or '').strip()
|
||||
if case_no:
|
||||
data['review_case_no'] = case_no
|
||||
|
||||
|
||||
def _enrich_task_center_fields(
|
||||
|
||||
Loaded 100 of 300 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user