feat(shipping-notice): 新增临时库存管理功能,支持创建会话、获取分析结果及字段映射建议
This commit is contained in:
1 parent
46eb63f5bb
commit
e9bdd81f1a
320 files changed
+28361
-10487
No files matched your search
@@ -3,24 +3,31 @@
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
|
||||
# --- 1. 环境与应用标识 ---
|
||||
ENV_NAME=dev
|
||||
FLASK_ENV=development
|
||||
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=sync
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
AUTH_LOGIN_MODE=password
|
||||
# --- 3. 公共地址与网络入口 ---
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
|
||||
# --- 4. 安全、认证与身份源 ---
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_LOGIN_MODE=password
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=http://192.168.100.192:8870
|
||||
# 以下为 hxops-dev 应用在 Casdoor 控制台里的 Client ID / Secret(勿与 prod 混用)
|
||||
@@ -32,18 +39,14 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom(Name=wecom,与 prod 共用同一 Provider 即可)
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=sync
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=10
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
||||
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
||||
@@ -53,67 +56,61 @@ MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||
MINIO_SECURE=false
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# --- 6. AI 平台、模型与内部工具 ---
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(相对 backend/ 根目录)
|
||||
FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
|
||||
FREIGHT_RPA_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
|
||||
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
# RPA 目录(相对 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
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
|
||||
FREIGHT_RPA_MOCK=false
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
|
||||
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -3,24 +3,31 @@
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
|
||||
# --- 1. 环境与应用标识 ---
|
||||
ENV_NAME=prod
|
||||
FLASK_ENV=production
|
||||
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# --- 3. 公共地址与网络入口 ---
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.230:8891
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 4. 安全、认证与身份源 ---
|
||||
# AUTH_LOGIN_MODE=casdoor
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
AUTH_LOGIN_MODE=password
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=http://ai.well-trust.com:8870
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.230:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=https://auth.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
@@ -34,23 +41,14 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段(截图即为 wecom);Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.230:8891
|
||||
DIFY_API_BASE=http://192.168.100.230:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=20
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
DATABASE_URL=postgresql://postgres:difyai123456@192.168.100.230:5432/hxops_db
|
||||
ORACLE_CLIENT_MOUNT_DIR=/data/ai-platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
MINIO_ENDPOINT=host.docker.internal:9000
|
||||
@@ -60,37 +58,44 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
|
||||
|
||||
# --- 6. AI 平台、模型与内部工具 ---
|
||||
DIFY_API_BASE=http://192.168.100.230:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
# RoHS / 货代 / 设备维保等 Dify Tool API 基地址(Dify 服务端内网调用,无尾斜杠)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
|
||||
# 浏览器可访问根地址(Excel 下载等用户可见链接,应为域名,无尾斜杠)
|
||||
HXOPS_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
# --- 7. 企业系统集成 ---
|
||||
WECOM_PUBLIC_BASE_URL=https://ai.well-trust.com
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ai.well-trust.com:8890/
|
||||
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 货代库存 RPA(正式环境:Ubuntu 挂载 Windows RPA 正式共享)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
# 货代发货通知 Agent(RPA 回调共用;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=FZs8NJ4tC7krtLqKsm4AAHBRtwP0BXcscajnl_f62aBWpfFA6Mo24w6Br1fiPueh
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-prod-data/inventory_drop
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/inventory_triggers
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-prod-data/upload_queue
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-prod-data/upload_triggers
|
||||
# 固资履历共享盘(Linux 正式环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-prod
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
+74
-74
@@ -1,11 +1,38 @@
|
||||
# Shared environment variables for all environments (dev/test/prod)
|
||||
# Keep only values that are truly identical across all environments.
|
||||
|
||||
# --- 1. 环境与应用标识 ---
|
||||
# Runtime selector fallback (actual deployment still sets ENV_NAME explicitly)
|
||||
ENV_NAME=dev
|
||||
# Common runtime defaults
|
||||
FLASK_APP=run.py
|
||||
|
||||
# --- 3. 公共地址与网络入口 ---
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# --- 4. 安全、认证与身份源 ---
|
||||
SECRET_KEY=hxops-dify
|
||||
AUTH_JWT_REQUIRED=true
|
||||
# 是否保留本地密码登录/本地TWT兼容
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
# Common auth defaults
|
||||
AUTH_LEGACY_HEADER_ENABLED=true
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
|
||||
MINIO_KB_IMAGE_BUCKET=image-hosting-service
|
||||
MINIO_AGENT_GUIDES_BUCKET=agent-guides
|
||||
|
||||
# --- 6. AI 平台、模型与内部工具 ---
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
# 知识库管理(后续需要修改此地址)
|
||||
# 查「Dify 文档对应原始源文件下载地址」时,要连的那台 Integration API 的根 URL
|
||||
INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
@@ -13,41 +40,17 @@ INTEGRATION_API_BASE=http://192.168.100.230:8891
|
||||
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致
|
||||
FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
# 硅基流动相关
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
|
||||
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
|
||||
|
||||
SECRET_KEY=hxops-dify
|
||||
|
||||
# Knowledge base runtime
|
||||
# KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
KB_WORKER_CONCURRENCY=3
|
||||
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
|
||||
EDKB_SOFFICE=/usr/bin/soffice
|
||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
|
||||
# chat回答的评分与评论
|
||||
FEEDBACK_ENABLED=true
|
||||
|
||||
# Common auth defaults
|
||||
AUTH_LEGACY_HEADER_ENABLED=true
|
||||
AUTH_JWT_REQUIRED=true
|
||||
|
||||
# 是否保留本地密码登录/本地TWT兼容
|
||||
AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=true
|
||||
AUTH_ALLOW_LOCAL_JWT=true
|
||||
AUTH_LOCAL_JWT_ISSUER=hxops-backend
|
||||
AUTH_LOCAL_JWT_AUDIENCE=hxops-frontend
|
||||
AUTH_LOCAL_JWT_EXPIRES_HOURS=12
|
||||
|
||||
# --- 7. 企业系统集成 ---
|
||||
# WeCom
|
||||
WECOM_ENABLED=true
|
||||
WECOM_CORP_ID=ww1ada6c11b684783e
|
||||
@@ -75,29 +78,6 @@ WECOM_FEEDBACK_NOTIFY_ENABLED=true
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL=http://ai.well-trust.com:8881
|
||||
# 企业微信群机器人 webhook,按环境写入 .env.<env> 或部署平台变量;不要提交真实 URL。
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK=https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=bdb65cf6-e537-44b2-a10b-d826b15f4498
|
||||
|
||||
|
||||
# Common integration defaults
|
||||
INTEGRATION_API_MODE=local
|
||||
DIFY_API_BASE=https://api.dify.ai/v1
|
||||
# HXOPS Tool API 对外基地址(RoHS / 货代等 Dify Chatflow 服务端调用;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_TOOLS_API_BASE=
|
||||
# HXOPS 浏览器可访问根地址(Excel 签名下载等用户可见链接;无尾斜杠;各环境 .env.* 覆盖)
|
||||
HXOPS_PUBLIC_BASE_URL=
|
||||
|
||||
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
|
||||
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
|
||||
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
|
||||
MINIO_KB_IMAGE_BUCKET=image-hosting-service
|
||||
MINIO_AGENT_GUIDES_BUCKET=agent-guides
|
||||
|
||||
# 硅基流动相关
|
||||
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
|
||||
GJL_API_BASE=https://api.siliconflow.cn/v1
|
||||
GJL_MODEL=deepseek-ai/DeepSeek-V3
|
||||
# 硅基流动 ASR:FunAudioLLM/SenseVoiceSmall 或 TeleAI/TeleSpeechASR
|
||||
ASR_MODEL=FunAudioLLM/SenseVoiceSmall
|
||||
|
||||
# HR SQL Server Configuration
|
||||
HR_SQLSERVER_HOST=192.168.100.191
|
||||
HR_SQLSERVER_PORT=1433
|
||||
@@ -108,14 +88,12 @@ HR_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
HR_SQLSERVER_ENCRYPT=no
|
||||
HR_SQLSERVER_TRUST_CERT=yes
|
||||
HR_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# PLM Oracle
|
||||
PLM_ORACLE_HOST=192.168.0.11
|
||||
PLM_ORACLE_PORT=1521
|
||||
PLM_ORACLE_SID=orcl
|
||||
PLM_ORACLE_USERNAME=PLM
|
||||
PLM_ORACLE_PASSWORD=PLM
|
||||
|
||||
# SRM SQL Server Configuration
|
||||
SRM_SQLSERVER_HOST=192.168.55.106
|
||||
SRM_SQLSERVER_PORT=1433
|
||||
@@ -126,23 +104,33 @@ SRM_SQLSERVER_DRIVER=ODBC Driver 18 for SQL Server
|
||||
SRM_SQLSERVER_ENCRYPT=no
|
||||
SRM_SQLSERVER_TRUST_CERT=yes
|
||||
SRM_SQLSERVER_TIMEOUT=10
|
||||
|
||||
# ERP
|
||||
ERP_DB_DSN=192.168.8.24:1521/topprod
|
||||
TEXT2SQL_SCHEMA_PATH=
|
||||
|
||||
# 固资履历共享盘
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# --- 8. 知识库与文件处理 ---
|
||||
# Knowledge base runtime
|
||||
# KB_STORAGE_ROOT=backend/data/kb
|
||||
KB_TASK_EXECUTION_MODE=worker
|
||||
KB_WORKER_POLL_SECONDS=2
|
||||
KB_WORKER_CONCURRENCY=3
|
||||
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
|
||||
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
|
||||
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
|
||||
EDKB_SOFFICE=/usr/bin/soffice
|
||||
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
|
||||
EDKB_SOFFICE_TIMEOUT_SEC=600
|
||||
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
|
||||
EDKB_WORD_TIMEOUT_SEC=300
|
||||
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
|
||||
EDKB_FILE_TIMEOUT_SEC=300
|
||||
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
|
||||
EDKB_WORD_FILE_TIMEOUT_SEC=420
|
||||
|
||||
# 固资图片文档库
|
||||
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# chat回答的评分与评论
|
||||
FEEDBACK_ENABLED=true
|
||||
# 热点 FAQ 离线聚合(ChatLog -> PostgreSQL faq_hot_candidates 表)
|
||||
# 管理端「常用问题 > 热点发现」刷新聚合时读取以下配置
|
||||
FAQ_HOT_ENABLED=true # 是否启用热点聚合(false 时刷新/CLI 直接跳过)
|
||||
@@ -158,13 +146,25 @@ FAQ_HOT_ANSWER_SIMILARITY=0.95 # (聚类已关闭)答案聚类相
|
||||
FAQ_HOT_ANSWER_DOMINANCE=0.6 # (聚类已关闭)最大答案簇占比下限,恢复聚类时生效
|
||||
FAQ_HOT_GOOD_SCORE=4 # 选代表答案时「好评」反馈分阈值(≥此分优先)
|
||||
FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈分阈值(≤此分排除)
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
FREIGHT_RPA_MOCK=false
|
||||
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=false
|
||||
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
|
||||
# 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。
|
||||
# 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。
|
||||
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
|
||||
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
|
||||
# RPA Profile Fernet master key; inject through Jenkins/Secret/system environment, never commit a real value.
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
|
||||
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
|
||||
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
|
||||
SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
# 固资履历共享盘
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
# 固资图片文档库
|
||||
FIXED_ASSET_IMAGE_BASE_URL=http://192.168.8.158:8071/Web/#/login
|
||||
FIXED_ASSET_IMAGE_USERNAME=26040006
|
||||
FIXED_ASSET_IMAGE_PASSWORD=26040006
|
||||
FIXED_ASSET_IMAGE_LIBRARY_ID=8d61bd96-ff2d-489b-86fc-ca0b8c6bbcf8
|
||||
FIXED_ASSET_IMAGE_FOLDER_ID=3aea6c19-d9ac-40fa-ab16-9cb06c0db3e3
|
||||
@@ -3,24 +3,30 @@
|
||||
# Environment-specific variables stay in .env.dev/.env.test/.env.prod
|
||||
# - .env.dev / .env.test / .env.prod for deployment environments
|
||||
# =============================================================================
|
||||
|
||||
# --- 1. 环境与应用标识 ---
|
||||
ENV_NAME=test
|
||||
FLASK_ENV=test
|
||||
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
|
||||
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
# --- 2. 应用运行与进程 ---
|
||||
TASK_EXECUTION_MODE=rq
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# --- 3. 公共地址与网络入口 ---
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
# --- 4. 安全、认证与身份源 ---
|
||||
# 如果需要用户密码登录,修改该值为password
|
||||
#AUTH_LOGIN_MODE=casdoor
|
||||
|
||||
AUTH_LOGIN_MODE=casdoor
|
||||
# 是否启用 JWT 认证
|
||||
AUTH_JWT_REQUIRED=true
|
||||
AUTH_JWT_ISSUER=http://ait.well-trust.com:8872
|
||||
AUTH_JWT_AUDIENCE=758be5fcba2df784fdb4
|
||||
AUTH_JWT_JWKS_URL=http://192.168.100.192:8870/.well-known/jwks
|
||||
|
||||
# Casdoor
|
||||
CASDOOR_BASE_URL=https://autht.well-trust.com
|
||||
# 与 Casdoor 里 Application「hxops-prod」(或你当前生产应用)的 Client ID 一致
|
||||
@@ -34,24 +40,14 @@ CASDOOR_SCOPE=openid profile email
|
||||
CASDOOR_ORGANIZATION=organization_HX
|
||||
# Casdoor Providers → wecom:Name 字段;Organization=organization_HX,Sub type=Internal,Scope=snsapi_userinfo
|
||||
CASDOOR_WECOM_PROVIDER_HINT=wecom
|
||||
|
||||
# 知识库 Dify 对接
|
||||
PUBLIC_BASE_URL=http://192.168.100.192:8891
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
DEFAULT_ADMIN_USERNAME=admin
|
||||
DEFAULT_ADMIN_PASSWORD=admin123456
|
||||
TASK_EXECUTION_MODE=rq
|
||||
|
||||
# Gunicorn配置
|
||||
GUNICORN_WORKERS=6
|
||||
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
HXOPS_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
|
||||
# --- 5. 数据库与基础设施 ---
|
||||
DATABASE_URL=postgresql://postgres:8je2olWwHj28fCfVTgRWmankoTQORjqyBn6iIK3dG2q10vAq@192.168.100.192:5432/hxops_testing
|
||||
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
|
||||
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_23_26
|
||||
LD_LIBRARY_PATH=/app/oracle_client/instantclient_23_26:/app/oracle_client
|
||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
|
||||
@@ -62,51 +58,56 @@ MINIO_SECURE=false
|
||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||
|
||||
# --- 6. AI 平台、模型与内部工具 ---
|
||||
DIFY_API_BASE=http://192.168.100.192:8882/v1
|
||||
DIFY_API_KEY=dataset-7xxs1P1QnqBmkEAjGhXLjmwF
|
||||
# 货代发货通知 Agent(见 docs/features/shipping-notice/technical.md §1.2;Tool 基地址见 HXOPS_TOOLS_API_BASE)
|
||||
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
|
||||
HXOPS_TOOLS_API_BASE=http://192.168.100.192:8890
|
||||
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
|
||||
HXOPS_TOOLS_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
# --- 7. 企业系统集成 ---
|
||||
WECOM_PUBLIC_BASE_URL=https://ait.well-trust.com
|
||||
# 企业微信通知配置(如果不使用企业微信通知,留空即可)
|
||||
# WECOM_NOTIFY_BASE_URL:历史内网/端口地址,仅作兼容;textcard 跳转优先 WECOM_PUBLIC_BASE_URL
|
||||
WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
||||
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
# --- 9. 业务模块 ---
|
||||
|
||||
# 自动推进(auto_progress)
|
||||
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED=true
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true
|
||||
SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
|
||||
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
|
||||
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
|
||||
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
FREIGHT_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
FREIGHT_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
|
||||
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
|
||||
# 文件存储(相对 backend/ 根目录)
|
||||
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
|
||||
# 解析与文本上限
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
|
||||
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
|
||||
# 字段对齐确认(生产建议 true;测试可设 false)
|
||||
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
|
||||
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
|
||||
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
|
||||
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
|
||||
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
|
||||
# 两者皆无则告警只写日志、不会发企微
|
||||
@@ -114,29 +115,26 @@ SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
|
||||
# 企微发送中短锁秒数(发送失败过期后可重试,默认 120)
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS=120
|
||||
|
||||
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS=21600
|
||||
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx
|
||||
# RPA 目录(测试环境:Ubuntu 挂载 Windows RPA 测试共享)
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory_drop
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
|
||||
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
|
||||
# 发货 Excel 模板(可选)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# SHIPPING_NOTICE_RPA_WORKER_MOCK=true
|
||||
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
|
||||
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
|
||||
# 固资履历共享盘(Linux 测试环境请优先挂载到本地目录,再通过 LOCAL_ROOT 访问)
|
||||
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
|
||||
FIXED_ASSET_HISTORY_LOCAL_ROOT=/mnt/hxops-fixed-asset-history-test
|
||||
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
|
||||
FIXED_ASSET_HISTORY_SHARE_PASSWORD=7A1XQ5Nv
|
||||
|
||||
# AWS 库存列映射(可选 JSON 字符串)
|
||||
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
|
||||
|
||||
# Dify Chatflow(seed_shipping_notice_agents.py)
|
||||
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
|
||||
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
|
||||
|
||||
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
|
||||
# FREIGHT_RPA_MOCK=true
|
||||
# FREIGHT_RPA_POLL_SECONDS=3
|
||||
# FREIGHT_RPA_SAMPLE_INVENTORY=
|
||||
|
||||
|
||||
# --- 10. 运维、告警与维护工具 ---
|
||||
# 设备维保助手后端工具调用密钥
|
||||
MAINTENANCE_TOOL_API_KEY=kgea7gvqxL79tZPD6aZSe3H1FrqUCkh_QFZeaSZ4KEFR-fJVNT5lKAVEVJCJhsWu
|
||||
@@ -157,6 +157,16 @@ docker compose logs -f hxops-backend
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
### 8.1 环境变量文件与排序规则
|
||||
|
||||
- **文件职责**:`.env.shared` 仅放 dev/test/prod 完全一致的共享项;`.env.dev`、`.env.test`、`.env.prod` 仅放环境差异项;`.env.local` 仅放开发者个人覆盖项且不得提交。高优先级文件只写需要覆盖的变量,不完整复制低优先级文件。
|
||||
- **文件内章节顺序**:① 环境与应用标识 → ② 应用运行与进程 → ③ 公共地址与网络入口 → ④ 安全、认证与身份源 → ⑤ 数据库与基础设施 → ⑥ 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`;历史名称只能存在于兼容映射和迁移说明中。
|
||||
- **跨环境一致性**:`.env.dev`、`.env.test`、`.env.prod` 使用相同章节骨架;同名变量保持相同相对位置,便于审查差异;新增变量时同步检查所有适用环境文件和上述权威文档。
|
||||
- **调整红线**:重排环境变量时只能移动“注释 + 完整赋值行”,禁止修改变量名或值,禁止删除变量、注释或示例;真实密码、密钥、Token、Webhook 与生产连接信息必须由系统环境变量、Jenkins/CI 或 Secret 管理机制注入。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
---
|
||||
|
||||
@@ -20,5 +20,7 @@ import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_inventory # noqa: F401
|
||||
import app.api.admin.shipping_order_schema # noqa: F401
|
||||
|
||||
__all__ = ['admin_bp']
|
||||
@@ -15,14 +15,17 @@ from flask import g, jsonify, request, send_file
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.admin import shipping_customer_import_service, shipping_customer_service
|
||||
from app.services.admin import (
|
||||
shipping_customer_import_service,
|
||||
shipping_customer_lifecycle_service,
|
||||
shipping_customer_merge_service,
|
||||
shipping_customer_service,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import (
|
||||
get_shadow_quality_report,
|
||||
label_shadow_resolution,
|
||||
)
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
backfill_historical_task_customer,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
)
|
||||
@@ -55,6 +58,77 @@ def get_shipping_customer(customer_id: int):
|
||||
return jsonify(shipping_customer_service.get_customer(customer_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/lifecycle-impact', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_lifecycle_impact(customer_id: int):
|
||||
"""预览永久删除的阻断引用与可级联识别证据,不执行删除。"""
|
||||
return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_impact(customer_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/lifecycle-timeline', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_lifecycle_timeline(customer_id: int):
|
||||
"""查询客户创建、变更、证据、归并和删除相关的治理时间线。"""
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Invalid timeline limit') from exc
|
||||
return jsonify(shipping_customer_lifecycle_service.get_customer_lifecycle_timeline(customer_id, limit=limit))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/governance-quality', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_governance_quality():
|
||||
"""查询客户识别质量、自动确认门禁和生命周期治理汇总。"""
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Invalid report limit') from exc
|
||||
return jsonify(shipping_customer_lifecycle_service.get_customer_governance_quality(limit=limit))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_customer(customer_id: int):
|
||||
"""受控永久删除无生命周期引用的误建客户,必须二次确认简码和原因。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return jsonify(shipping_customer_lifecycle_service.delete_customer(
|
||||
customer_id,
|
||||
confirmation_short_code=data.get('confirmation_short_code'),
|
||||
reason=data.get('reason'),
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/merge-impact', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_customer_merge_impact(customer_id: int):
|
||||
"""预览将源客户归并到目标客户时保留的历史引用和可迁移配置。"""
|
||||
try:
|
||||
target_customer_id = int(request.args.get('target_customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc
|
||||
return jsonify(shipping_customer_merge_service.get_customer_merge_impact(customer_id, target_customer_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/merge', methods=['POST'])
|
||||
@require_admin
|
||||
def merge_shipping_customer(customer_id: int):
|
||||
"""受控归并重复客户;历史业务与审计不迁移,仅归并未来配置。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
target_customer_id = int(data.get('target_customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Target customer id is required', code='SHIPPING.CUSTOMER_MERGE_TARGET_REQUIRED') from exc
|
||||
return jsonify(shipping_customer_merge_service.merge_customer(
|
||||
customer_id,
|
||||
target_customer_id=target_customer_id,
|
||||
confirmation_short_code=data.get('confirmation_short_code'),
|
||||
reason=data.get('reason'),
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer():
|
||||
@@ -77,7 +151,12 @@ def update_shipping_customer(customer_id: int):
|
||||
@require_admin
|
||||
def deactivate_shipping_customer(customer_id: int):
|
||||
"""停用标准客户并保留历史引用。"""
|
||||
return jsonify(shipping_customer_service.deactivate_customer(customer_id, actor_id=_actor_id()))
|
||||
data = request.get_json(silent=True) or {}
|
||||
return jsonify(shipping_customer_service.deactivate_customer(
|
||||
customer_id,
|
||||
reason=data.get('reason'),
|
||||
actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/identifiers', methods=['POST'])
|
||||
@@ -102,6 +181,33 @@ def update_shipping_customer_identifier(identifier_id: int):
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/external-refs', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_external_ref(customer_id: int):
|
||||
"""维护来源系统客户编码,供 Bill-to 精确匹配。"""
|
||||
return jsonify(shipping_customer_service.create_external_ref(
|
||||
customer_id, request.get_json(silent=True) or {},
|
||||
)), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/<int:customer_id>/sites', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_site(customer_id: int):
|
||||
"""新增客户送货站点,供 Ship-to 匹配。"""
|
||||
return jsonify(shipping_customer_service.create_site(
|
||||
customer_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
)), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customer-sites/<int:site_id>/identifiers', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_customer_site_identifier(site_id: int):
|
||||
"""新增站点名称别名、地址或外部 Ship-to Code。"""
|
||||
return jsonify(shipping_customer_service.create_site_identifier(
|
||||
site_id, request.get_json(silent=True) or {},
|
||||
)), 201
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/import-template', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_customer_import_template():
|
||||
@@ -183,25 +289,6 @@ def get_shipping_customer_shadow_report():
|
||||
return jsonify(report)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/historical-task-backfill', methods=['POST'])
|
||||
@require_admin
|
||||
def backfill_shipping_historical_task_customer():
|
||||
"""管理员为历史无业务单任务确认客户;默认不生成历史业务编号。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_no = str(data.get('task_no') or '').strip().upper()
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Customer id is required') from exc
|
||||
task = ShippingTask.query.filter_by(task_no=task_no).first()
|
||||
if task is None:
|
||||
raise ValidationError('Historical task not found', code='SHIPPING.HISTORICAL_TASK_NOT_FOUND')
|
||||
try:
|
||||
return jsonify(backfill_historical_task_customer(task, customer_id=customer_id, actor_id=_actor_id()))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.HISTORICAL_BACKFILL_INVALID') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-customers/numbered-task-correction', methods=['POST'])
|
||||
@require_admin
|
||||
def correct_shipping_numbered_task_customer():
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""
|
||||
api/admin/shipping_inventory.py
|
||||
|
||||
用途:提供库存源、RPA Profile、路由规则及外部系统映射的管理 API。
|
||||
依赖:admin blueprint、require_admin、shipping_inventory_service。
|
||||
逻辑:路由只处理鉴权和 JSON 参数,业务校验、凭据加密及事务由服务层完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from flask import g, request, send_file
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ConflictError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import shipping_inventory_service
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice import inventory_field_catalog
|
||||
from app.services.shipping_notice import inventory_structure_analysis
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""取得 require_admin 已写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_excel_templates():
|
||||
"""列出版本化发货 Excel 模板。"""
|
||||
return _ok(excel_template.list_templates())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template():
|
||||
"""上传 xlsx 并创建模板草稿版本。"""
|
||||
try:
|
||||
definition = json.loads(request.form.get('definition') or '{}')
|
||||
except json.JSONDecodeError as exc:
|
||||
from app.core.errors import ValidationError
|
||||
raise ValidationError('definition must be valid JSON', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
|
||||
data = {
|
||||
'template_code': request.form.get('template_code'),
|
||||
'display_name': request.form.get('display_name'),
|
||||
'definition': definition,
|
||||
}
|
||||
return _ok(excel_template.create_draft(request.files.get('file'), data, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_excel_template(template_id: int):
|
||||
"""更新 Excel 模板草稿定义。"""
|
||||
return _ok(excel_template.update_draft(template_id, request.get_json(silent=True) or {}))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/layout', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_excel_template_layout(template_id: int):
|
||||
"""读取已保存模板的工作表和栏位,编辑时无需重新上传 Excel。"""
|
||||
return _ok(excel_template.get_layout(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/new-version', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_excel_template_version(template_id: int):
|
||||
"""复制现有模板文件和映射定义,创建新的草稿版本。"""
|
||||
return _ok(excel_template.create_draft_from_existing(template_id, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_excel_template(template_id: int):
|
||||
"""校验工作簿和字段映射后发布模板。"""
|
||||
return _ok(excel_template.publish(template_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_excel_template(template_id: int):
|
||||
"""退役没有启用库存源引用的模板。"""
|
||||
return _ok(excel_template.retire(template_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/excel-templates/<int:template_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_excel_template(template_id: int):
|
||||
"""删除从未发布且未使用的模板草稿。"""
|
||||
excel_template.delete_draft(template_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_rpa_profiles():
|
||||
"""列出脱敏后的 RPA Profile 配置。"""
|
||||
return _ok(shipping_inventory_service.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_rpa_profile():
|
||||
"""创建 RPA Profile;明文凭据仅在本次请求内用于加密。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_rpa_profile(profile_id: int):
|
||||
"""更新 RPA Profile;未提交密码字段时保留既有密文。"""
|
||||
return _ok(shipping_inventory_service.save_profile(request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/rpa-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_rpa_profile(profile_id: int):
|
||||
"""删除没有库存源引用的错误连接配置。"""
|
||||
shipping_inventory_service.delete_profile(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_sources():
|
||||
"""列出库存业务来源。"""
|
||||
return _ok(shipping_inventory_service.list_sources())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_source():
|
||||
"""保存停用的库存站点基础配置;正式启用由独立接口控制。"""
|
||||
return _ok(shipping_inventory_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), allow_enable_transition=False,
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_source(source_id: int):
|
||||
"""更新库存站点业务配置;不能借由普通保存绕过启用门禁。"""
|
||||
return _ok(shipping_inventory_service.save_source(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), source_id=source_id,
|
||||
allow_enable_transition=False,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/activate', methods=['POST'])
|
||||
@require_admin
|
||||
def activate_shipping_inventory_source(source_id: int):
|
||||
"""仅在库存站点完成测试与必需绑定后启用正式运行。"""
|
||||
return _ok(shipping_inventory_service.activate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/deactivate', methods=['POST'])
|
||||
@require_admin
|
||||
def deactivate_shipping_inventory_source(source_id: int):
|
||||
"""停用库存站点而不删除已有配置和运行审计。"""
|
||||
return _ok(shipping_inventory_service.deactivate_source(source_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_source(source_id: int):
|
||||
"""删除无运行/路由引用的错误库存源。"""
|
||||
shipping_inventory_service.delete_source(source_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export', methods=['POST'])
|
||||
@require_admin
|
||||
def start_shipping_inventory_configuration_test(source_id: int):
|
||||
"""为停用库存站点发起异步测试导出,不产生生产库存快照。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
|
||||
"""读取库存站点测试导出的异步执行状态与结构识别结果。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return _ok(inventory_configuration_test.get_test_run(source_id, run_no))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>/confirm-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def confirm_shipping_inventory_configuration_test_profile(source_id: int, run_no: str):
|
||||
"""确认测试结果采用的解析方案,并更新仍停用的库存站点绑定。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_configuration_test.confirm_test_profile(
|
||||
source_id, run_no, int(payload.get('profile_id') or 0), actor_id=_actor_id(),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/snapshots', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_snapshots():
|
||||
"""列出库存快照的管理端只读记录。"""
|
||||
return _ok(shipping_inventory_service.list_snapshots())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/snapshots/<int:snapshot_id>/download', methods=['GET'])
|
||||
@require_admin
|
||||
def download_shipping_inventory_snapshot(snapshot_id: int):
|
||||
"""下载管理员选定的已托管库存快照,不向前端暴露服务器存储路径。"""
|
||||
path, filename = shipping_inventory_service.get_snapshot_download(snapshot_id)
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/export-records', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_export_records():
|
||||
"""列出 RPA 导出结果;失败后应修复配置并重新创建运行。"""
|
||||
return _ok(shipping_inventory_service.list_export_records())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_rules():
|
||||
"""列出库存源路由规则及条件。"""
|
||||
return _ok(shipping_inventory_service.list_rules())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_routing_fields():
|
||||
"""返回已发布订单字段与受控系统事实;未发布时保留页面可加载的空目录。"""
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'order_schema_published': published,
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_fields():
|
||||
"""列出库存统一业务字段;管理工作区可查看已停用字段。"""
|
||||
return _ok(inventory_field_catalog.list_fields(include_retired=request.args.get('include_retired') == 'true'))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_field():
|
||||
"""创建可由 DBS、Crane 等多个库存解析方案复用的扩展业务字段。"""
|
||||
return _ok(inventory_field_catalog.create_field(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_field(field_id: int):
|
||||
"""更新库存业务字段的名称、说明、格式和展示顺序。"""
|
||||
return _ok(inventory_field_catalog.update_field(field_id, request.get_json(silent=True) or {}, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_field(field_id: int):
|
||||
"""停用无引用的扩展库存字段,核心字段始终由服务层保护。"""
|
||||
return _ok(inventory_field_catalog.retire_field(field_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-fields/<int:field_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_field(field_id: int):
|
||||
"""删除未被配置引用的扩展库存字段。"""
|
||||
inventory_field_catalog.delete_field(field_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/configuration-catalog', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_configuration_catalog():
|
||||
"""返回 Profile、模板和路由编辑器共用的后端受控字段目录。"""
|
||||
from app.services.shipping_notice.excel_template import (
|
||||
ALLOWED_FORMATTERS,
|
||||
ALLOWED_ROW_MODES,
|
||||
ALLOWED_SOURCE_KINDS,
|
||||
ALLOWED_SYSTEM_FACTS,
|
||||
)
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
|
||||
try:
|
||||
contract = order_schema_service.get_published_contract()
|
||||
order_fields = contract['fields']
|
||||
published = True
|
||||
except ConflictError as exc:
|
||||
if not isinstance(exc, ConflictError) or exc.code != 'SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED':
|
||||
raise
|
||||
order_fields = []
|
||||
published = False
|
||||
return _ok({
|
||||
'order_fields': order_fields,
|
||||
'order_schema_published': published,
|
||||
'routing_system_facts': sorted(ALLOWED_SYSTEM_FACT_KEYS),
|
||||
'inventory_fields': inventory_field_catalog.list_fields(),
|
||||
'template_system_facts': sorted(ALLOWED_SYSTEM_FACTS),
|
||||
'template_source_kinds': sorted(ALLOWED_SOURCE_KINDS),
|
||||
'template_row_modes': sorted(ALLOWED_ROW_MODES),
|
||||
'template_formatters': sorted(ALLOWED_FORMATTERS),
|
||||
})
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_parsing_profiles():
|
||||
"""列出可复用库存解析 Profile 版本。"""
|
||||
return _ok(inventory_parsing_profile.list_profiles())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_profile():
|
||||
"""创建库存解析 Profile 草稿。"""
|
||||
return _ok(inventory_parsing_profile.save_draft(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""更新库存解析 Profile 草稿。"""
|
||||
return _ok(inventory_parsing_profile.save_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), profile_id=profile_id,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""发布库存解析 Profile。"""
|
||||
return _ok(inventory_parsing_profile.publish(profile_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""退役无库存源引用的已发布解析 Profile。"""
|
||||
return _ok(inventory_parsing_profile.retire(profile_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_parsing_profile(profile_id: int):
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
inventory_parsing_profile.delete_draft(profile_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_structure_analysis():
|
||||
"""上传库存样本并返回后端分析出的工作表、表头、栏位和建议。"""
|
||||
return _ok(inventory_structure_analysis.create_sample_upload(
|
||||
request.files.get('file'), actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_inventory_structure_analysis(analysis_id: int):
|
||||
"""读取库存样本结构分析结果,供管理端继续配置解析方案。"""
|
||||
return _ok(inventory_structure_analysis.get_analysis(analysis_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_parsing_draft_from_analysis(analysis_id: int):
|
||||
"""使用确认后的真实表头和匹配键创建库存文件解析方案草稿。"""
|
||||
return _ok(inventory_structure_analysis.create_profile_draft(
|
||||
analysis_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/inventory-structure-analyses/<int:analysis_id>/adopt-profile', methods=['POST'])
|
||||
@require_admin
|
||||
def adopt_shipping_inventory_parsing_profile(analysis_id: int):
|
||||
"""确认复用推荐的已发布库存文件解析方案,不修改库存站点绑定。"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
return _ok(inventory_structure_analysis.adopt_published_profile(
|
||||
analysis_id, int(payload.get('profile_id') or 0),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-inventory-sessions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_confirmed_shipping_temporary_inventory_sessions():
|
||||
"""列出已通过质量校验、可供管理员沉淀为解析方案草稿的对话临时库存会话。"""
|
||||
from app.services.shipping_notice import inventory_temporary_session
|
||||
|
||||
return _ok(inventory_temporary_session.list_confirmed_temporary_inventory_sessions())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/temporary-inventory-sessions/<string:session_no>/create-profile-draft', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_parsing_draft_from_temporary_inventory_session(session_no: str):
|
||||
"""管理员将已确认临时会话锁定映射复制为解析方案草稿;发布仍走既有门禁。"""
|
||||
from app.services.shipping_notice import inventory_temporary_session
|
||||
|
||||
return _ok(inventory_temporary_session.create_parsing_profile_draft_from_temporary_session(
|
||||
session_no, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_rule():
|
||||
"""创建草稿路由规则。"""
|
||||
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_rule(rule_id: int):
|
||||
"""更新草稿规则;已发布规则由服务层拒绝原地修改。"""
|
||||
return _ok(shipping_inventory_service.save_rule(request.get_json(silent=True) or {}, actor_id=_actor_id(), rule_id=rule_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_inventory_rule(rule_id: int):
|
||||
"""发布草稿规则并写入不可变定义快照。"""
|
||||
return _ok(shipping_inventory_service.publish_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_inventory_rule(rule_id: int):
|
||||
"""归档已发布规则,保留其审计版本但停止新路由使用。"""
|
||||
return _ok(shipping_inventory_service.retire_rule(rule_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/routing-rules/<int:rule_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_rule(rule_id: int):
|
||||
"""删除从未发布的草稿规则。"""
|
||||
shipping_inventory_service.delete_draft_rule(rule_id)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_inventory_external_mappings():
|
||||
"""列出库存源到外部系统仓库映射。"""
|
||||
return _ok(shipping_inventory_service.list_external_mappings())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_inventory_external_mapping():
|
||||
"""创建精确或 Source 默认外部系统映射。"""
|
||||
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""更新外部系统映射,不参与任何调拨动作。"""
|
||||
return _ok(shipping_inventory_service.save_external_mapping(request.get_json(silent=True) or {}, actor_id=_actor_id(), mapping_id=mapping_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/external-mappings/<int:mapping_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_inventory_external_mapping(mapping_id: int):
|
||||
"""删除错误的外部系统仓库映射。"""
|
||||
shipping_inventory_service.delete_external_mapping(mapping_id)
|
||||
return '', 204
|
||||
@@ -0,0 +1,193 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_schema.py
|
||||
|
||||
用途:提供唯一货代订单 Schema、字段目录和版本发布的管理 API。
|
||||
依赖:admin blueprint、require_admin、order_schema.service。
|
||||
逻辑:路由只读取参数和管理员身份;字段校验、不可变性与事务由领域服务完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.order_schema import service
|
||||
|
||||
|
||||
def _actor_id() -> int | None:
|
||||
"""读取 require_admin 写入请求上下文的管理员 ID。"""
|
||||
return getattr(getattr(g, 'current_user', None), 'id', None)
|
||||
|
||||
|
||||
def _ok(data, *, status: int = 200):
|
||||
"""按平台统一 envelope 返回管理 API 成功结果。"""
|
||||
return ok(data, request_id=getattr(g, 'request_id', None), status=status)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema():
|
||||
"""读取订单 Schema 管理状态和受控字段能力目录。"""
|
||||
return _ok(service.get_state())
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema', methods=['POST'])
|
||||
@require_admin
|
||||
def initialize_shipping_order_schema():
|
||||
"""初始化全局唯一订单 Schema。"""
|
||||
return _ok(service.initialize_schema(request.get_json(silent=True) or {}, actor_id=_actor_id()), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_order_field():
|
||||
"""创建稳定订单字段身份。"""
|
||||
return _ok(service.save_field(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields/<field_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_order_field(field_id: str):
|
||||
"""更新尚未发布的字段 code/scope/type;发布后服务层限制身份变更。"""
|
||||
return _ok(service.save_field(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), field_id=field_id,
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields/<field_id>/retire', methods=['POST'])
|
||||
@require_admin
|
||||
def retire_shipping_order_field(field_id: str):
|
||||
"""退役订单字段,保留历史发布版本中的不可变定义。"""
|
||||
return _ok(service.retire_field(
|
||||
field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/fields/<field_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_order_field(field_id: str):
|
||||
"""按字段是否存在历史引用自动物理删除或归档,并同步移出当前草稿。"""
|
||||
return _ok(service.delete_field(
|
||||
field_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions', methods=['POST'])
|
||||
@require_admin
|
||||
def create_shipping_order_schema_version():
|
||||
"""创建下一订单 Schema 草稿,可复制已有版本。"""
|
||||
return _ok(service.create_draft(
|
||||
request.get_json(silent=True) or {}, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
), status=201)
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_versions():
|
||||
"""分页读取订单 Schema 全部版本概要,供历史抽屉按需加载。"""
|
||||
try:
|
||||
page = int(request.args.get('page', '1'))
|
||||
page_size = int(request.args.get('page_size', '20'))
|
||||
version_number = request.args.get('version_number')
|
||||
parsed_version_number = int(version_number) if version_number is not None else None
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError('page must be an integer') from exc
|
||||
return _ok(service.list_versions(
|
||||
page=page, page_size=page_size, version_number=parsed_version_number,
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version(version_id: int):
|
||||
"""读取一个版本的完整只读快照,供历史查看和后续版本比较使用。"""
|
||||
return _ok(service.get_version_detail(version_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/diff', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version_diff(version_id: int):
|
||||
"""返回两个版本之间由服务端计算的字段级语义差异。"""
|
||||
try:
|
||||
against_version_id = int(request.args['against_version_id'])
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise service.ValidationError(
|
||||
'against_version_id is required', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
) from exc
|
||||
return _ok(service.get_version_diff(version_id, against_version_id=against_version_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/audit-events', methods=['GET'])
|
||||
@require_admin
|
||||
def list_shipping_order_schema_audit_events():
|
||||
"""分页读取订单 Schema 的只读配置审计时间线。"""
|
||||
try:
|
||||
page = int(request.args.get('page', '1'))
|
||||
page_size = int(request.args.get('page_size', '20'))
|
||||
version_id = request.args.get('version_id')
|
||||
parsed_version_id = int(version_id) if version_id is not None else None
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError('page must be an integer') from exc
|
||||
return _ok(service.list_audit_events(page=page, page_size=page_size, version_id=parsed_version_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/usage', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_version_usage(version_id: int):
|
||||
"""分页返回实际使用该版本的订单解析及状态汇总。"""
|
||||
try:
|
||||
page = int(request.args.get('page', '1'))
|
||||
page_size = int(request.args.get('page_size', '20'))
|
||||
except ValueError as exc:
|
||||
raise service.ValidationError('page must be an integer') from exc
|
||||
return _ok(service.get_version_usage(version_id, page=page, page_size=page_size))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/order-extractions/<int:extraction_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_schema_extraction_audit(extraction_id: int):
|
||||
"""读取一次订单解析的完整只读审计详情与证据链。"""
|
||||
return _ok(service.get_extraction_audit(extraction_id))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['PUT'])
|
||||
@require_admin
|
||||
def update_shipping_order_schema_version(version_id: int):
|
||||
"""整体替换草稿字段配置。"""
|
||||
return _ok(service.save_draft(
|
||||
version_id, request.get_json(silent=True) or {}, actor_id=_actor_id(),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_shipping_order_schema_version(version_id: int):
|
||||
"""删除错误草稿,已发布和退役版本由服务层保护。"""
|
||||
service.delete_draft(
|
||||
version_id, actor_id=_actor_id(), request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return '', 204
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/versions/<int:version_id>/publish', methods=['POST'])
|
||||
@require_admin
|
||||
def publish_shipping_order_schema_version(version_id: int):
|
||||
"""发布草稿并自动退役上一当前版本。"""
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _ok(service.publish(
|
||||
version_id, actor_id=_actor_id(), expected_lock_version=data.get('expected_lock_version'),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-order-schema/published-contract', methods=['GET'])
|
||||
@require_admin
|
||||
def get_published_shipping_order_contract():
|
||||
"""读取当前发布的精简字段契约,供配置验证和 Dify 文档维护使用。"""
|
||||
return _ok(service.get_published_contract())
|
||||
+14
-2
@@ -142,6 +142,8 @@ def _build_chat_adapter_hints(
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
shipping_temporary_inventory_asset_no: str | None = None,
|
||||
shipping_temporary_inventory_session_no: str | None = None,
|
||||
) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
@@ -152,14 +154,18 @@ def _build_chat_adapter_hints(
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
|
||||
if not task_id and not batch_no and not intake_nos:
|
||||
temporary_asset_no = str(shipping_temporary_inventory_asset_no or '').strip().upper()
|
||||
temporary_session_no = str(shipping_temporary_inventory_session_no or '').strip().upper()
|
||||
if not task_id and not batch_no and not intake_nos and not temporary_asset_no and not temporary_session_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
'intake_nos': intake_nos,
|
||||
'capability': 'order_extraction' if intake_nos else None,
|
||||
'capability': 'temporary_inventory' if temporary_asset_no else ('order_extraction' if intake_nos else None),
|
||||
'temporary_inventory_asset_no': temporary_asset_no or None,
|
||||
'temporary_inventory_session_no': temporary_session_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1385,6 +1391,8 @@ def chat_completions():
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
shipping_temporary_inventory_asset_no = str(data.get('shipping_temporary_inventory_asset_no') or '').strip().upper()
|
||||
shipping_temporary_inventory_session_no = str(data.get('shipping_temporary_inventory_session_no') or '').strip().upper()
|
||||
raw_shipping_intakes = data.get('shipping_intake_nos')
|
||||
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
|
||||
raise ValidationError('shipping_intake_nos must be a list')
|
||||
@@ -1532,6 +1540,8 @@ def chat_completions():
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
@@ -1575,6 +1585,8 @@ def chat_completions():
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -157,6 +157,42 @@ def tool_submit_order_extraction():
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_order_extraction(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
def tool_create_temporary_inventory_session():
|
||||
"""
|
||||
创建对话上传库存候选会话。
|
||||
【AI 触发时机】:用户明确说明 .xls、.xlsx 或 .csv 附件是库存文件时,在临时库存固定分支调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.create_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_temporary_inventory_session', methods=['POST'])
|
||||
def tool_get_temporary_inventory_session():
|
||||
"""
|
||||
读取临时库存候选的脱敏分析结果。
|
||||
【AI 触发时机】:创建临时会话后,需要决定采用已有方案还是请求映射建议时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_temporary_inventory_session(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_temporary_inventory_mapping_suggestion', methods=['POST'])
|
||||
def tool_submit_temporary_inventory_mapping_suggestion():
|
||||
"""
|
||||
保存临时库存字段映射建议。
|
||||
【AI 触发时机】:仅在临时库存 LLM 节点返回真实表头到库存字段目录的候选后调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_temporary_inventory_mapping_suggestion(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/confirm_temporary_inventory_use', methods=['POST'])
|
||||
def tool_confirm_temporary_inventory_use():
|
||||
"""
|
||||
确认本次对话临时库存文件的使用。
|
||||
【AI 触发时机】:仅在用户明确确认当前文件和方案后调用,禁止模型自行确认。
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
@@ -215,40 +251,6 @@ def tool_remove_notice_line():
|
||||
"""
|
||||
return jsonify(shipping_tools.remove_notice_line(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
|
||||
def tool_parse_inventory():
|
||||
"""
|
||||
解析库存内容。
|
||||
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.parse_inventory(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
|
||||
def tool_upload_inventory_file():
|
||||
"""
|
||||
服务器侧接收库存 Excel 并解析。
|
||||
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
|
||||
"""
|
||||
task_id = str(request.form.get('task_id') or request.args.get('task_id') or '').strip()
|
||||
upload = request.files.get('file')
|
||||
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
|
||||
def tool_get_inventory_schema_preview():
|
||||
"""
|
||||
获取库存表头预览。
|
||||
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
|
||||
def tool_apply_inventory_mapping():
|
||||
"""
|
||||
应用库存字段映射。
|
||||
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
|
||||
def tool_ensure_inventory():
|
||||
"""
|
||||
@@ -391,6 +393,14 @@ def rpa_inventory_batch_ready():
|
||||
"""RPA 批量库存导出回调:按 Warehouse 写入库存快照。"""
|
||||
return jsonify(shipping_tools.rpa_report_inventory_batch(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
|
||||
def rpa_inventory_configuration_test_ready():
|
||||
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
|
||||
from app.services.shipping_notice import inventory_configuration_test
|
||||
|
||||
return jsonify({'status': 'ok', 'data': inventory_configuration_test.report_test_export(_payload())})
|
||||
|
||||
@shipping_notice_bp.route('/tasks/<task_no>/repair-inventory-attachment', methods=['POST'])
|
||||
def repair_task_inventory_attachment(task_no: str):
|
||||
"""
|
||||
|
||||
@@ -15,13 +15,12 @@ from app import db
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
|
||||
from app.core.response import ok
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.models import ShippingBatch, ShippingNoticeIntake, ShippingOrderExtraction, ShippingTask
|
||||
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_CHAIN_FALLBACK,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
MAP_JSON,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
from app.services.shipping_notice.query_service import (
|
||||
@@ -44,6 +43,7 @@ from app.services.shipping_notice.customer_identity_gate import (
|
||||
confirm_task_customer,
|
||||
list_customer_options,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
|
||||
|
||||
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
|
||||
|
||||
@@ -84,6 +84,23 @@ def workspace_shipping_batches():
|
||||
return jsonify(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(
|
||||
user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos,
|
||||
)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-customers', methods=['GET'])
|
||||
def workspace_shipping_customers():
|
||||
"""列出可供当前业务用户确认的启用标准客户。"""
|
||||
@@ -115,6 +132,47 @@ def workspace_confirm_shipping_customer(task_no: str):
|
||||
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
|
||||
return jsonify(serialize_task_detail(updated))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-order-extractions/<int:extraction_id>/customer-matches/<role>/confirm',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
"""确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。"""
|
||||
user = _require_user()
|
||||
extraction = (
|
||||
db.session.query(ShippingOrderExtraction)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingOrderExtraction.intake_id)
|
||||
.filter(
|
||||
ShippingOrderExtraction.id == extraction_id,
|
||||
ShippingNoticeIntake.user_id == user.id,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
if extraction is None:
|
||||
raise NotFoundError(
|
||||
'Order extraction not found',
|
||||
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
|
||||
)
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
site_id = int(data['site_id']) if data.get('site_id') is not None else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.ORDER_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
result = confirm_order_customer_match(
|
||||
extraction.id,
|
||||
role=role,
|
||||
customer_id=customer_id,
|
||||
site_id=site_id,
|
||||
actor_id=user.id,
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照。"""
|
||||
@@ -385,17 +443,6 @@ def workspace_retry_shipping_task(task_no: str):
|
||||
payload['comment'] = comment
|
||||
return jsonify(shipping_tools.retry_task(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/upload-inventory', methods=['POST'])
|
||||
def workspace_upload_shipping_inventory(task_no: str):
|
||||
"""用户态上传库存 Excel,并在服务端完成解析。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
upload = request.files.get('file')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/confirm-inventory-source', methods=['POST'])
|
||||
def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
"""确认当前任务的库存 RPA 来源,并继续触发库存导出。"""
|
||||
@@ -414,22 +461,6 @@ def workspace_confirm_shipping_inventory_source(task_no: str):
|
||||
'_trusted_user_id': user.id,
|
||||
}))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/apply-inventory-mapping', methods=['POST'])
|
||||
def workspace_apply_inventory_mapping(task_no: str):
|
||||
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
data = request.get_json(silent=True) or {}
|
||||
map_json = data.get(MAP_JSON)
|
||||
if not isinstance(map_json, dict) or not map_json:
|
||||
raise ValidationError(f'{MAP_JSON} is required')
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
|
||||
return jsonify(shipping_tools.apply_inventory_mapping(payload))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/submit-decision', methods=['POST'])
|
||||
def workspace_submit_shipping_decision(task_no: str):
|
||||
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
|
||||
|
||||
@@ -6,6 +6,7 @@ backend/app/core/config/settings.py
|
||||
逻辑:create_app 通过 config[config_name] 加载;旧路径 app.config 为兼容 shim。
|
||||
"""
|
||||
import os
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import dotenv_values
|
||||
@@ -13,6 +14,18 @@ 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:
|
||||
@@ -75,6 +88,58 @@ 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:
|
||||
"""
|
||||
读取 Shipping Notice RPA 配置,并在迁移期兼容历史环境变量名。
|
||||
|
||||
核心逻辑:优先读取 `SHIPPING_NOTICE_RPA_*`;仅在新变量缺失时读取映射的
|
||||
历史变量,并按进程对每个旧名称最多发出一次弃用警告。
|
||||
|
||||
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 目录环境变量名。
|
||||
*parts: 未配置时相对 `backend/data` 的默认路径片段。
|
||||
|
||||
Returns:
|
||||
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)
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
SECRET_KEY = os.getenv('SECRET_KEY')
|
||||
@@ -127,6 +192,10 @@ 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
|
||||
|
||||
# 文件检核 Chatflow Tool API
|
||||
FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY')
|
||||
@@ -161,6 +230,13 @@ class Config:
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED', 'false').lower() == 'true'
|
||||
)
|
||||
# 自动确认必须同时满足人工标注样本量和准确率门禁,避免仅凭开关放大解析误识别。
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES = int(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES') or '20'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY = float(
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY') or '0.98'
|
||||
)
|
||||
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
|
||||
)
|
||||
@@ -221,9 +297,6 @@ class Config:
|
||||
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG = _backend_path(
|
||||
'SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG', 'config', 'shipping_inventory_sources.yaml'
|
||||
)
|
||||
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS = int(
|
||||
os.getenv('SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS') or '24'
|
||||
)
|
||||
@@ -242,27 +315,33 @@ class Config:
|
||||
).strip().lower()
|
||||
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
|
||||
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
|
||||
FREIGHT_INVENTORY_DROP_DIR = _data_path(
|
||||
"FREIGHT_INVENTORY_DROP_DIR", "shipping_notice", "freight_rpa", "inventory_drop"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR', 'shipping_notice', 'freight_rpa', 'inventory_drop'
|
||||
)
|
||||
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "shipping_notice", "freight_rpa", "inventory_triggers"
|
||||
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR', 'shipping_notice', 'freight_rpa', 'inventory_triggers'
|
||||
)
|
||||
FREIGHT_UPLOAD_QUEUE_DIR = _data_path(
|
||||
"FREIGHT_UPLOAD_QUEUE_DIR", "shipping_notice", "freight_rpa", "upload_queue"
|
||||
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_UPLOAD_TRIGGER_DIR = _data_path(
|
||||
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "shipping_notice", "freight_rpa", "upload_triggers"
|
||||
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_BROWSER_PROFILE_DIR = _data_path(
|
||||
"FREIGHT_RPA_BROWSER_PROFILE_DIR", "shipping_notice", "freight_rpa", "browser_profile"
|
||||
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_INVENTORY_ARCHIVE_DIR = _data_path(
|
||||
"FREIGHT_RPA_INVENTORY_ARCHIVE_DIR", "shipping_notice", "freight_rpa", "inventory_archives"
|
||||
)
|
||||
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
|
||||
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
|
||||
SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR = _rpa_data_path(
|
||||
'SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR', 'shipping_notice', '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
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.models.file_asset import FileAsset
|
||||
from app.models.shipping import (
|
||||
ShippingBatch,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventoryMapping,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
@@ -29,15 +28,45 @@ from app.models.shipping import (
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict, ShippingTaskLine
|
||||
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule,
|
||||
ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRuleVersion,
|
||||
ShippingInventorySource,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingRpaProfile,
|
||||
)
|
||||
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
|
||||
from app.models.shipping_customer import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
)
|
||||
from app.models.shipping_customer_import import ShippingCustomerImportBatch, ShippingCustomerImportRow
|
||||
from app.models.shipping_customer_resolution import ShippingCustomerShadowResolution
|
||||
from app.models.shipping_customer_resolution import ShippingCustomerShadowMatch, ShippingCustomerShadowResolution
|
||||
from app.models.training import TrainingRecord
|
||||
from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig
|
||||
from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit
|
||||
@@ -78,18 +107,45 @@ __all__ = [
|
||||
'ShippingTask',
|
||||
'ShippingTaskLine',
|
||||
'ShippingTaskFieldConflict',
|
||||
'ShippingOrderSchema',
|
||||
'ShippingOrderSchemaVersion',
|
||||
'ShippingOrderSchemaAuditEvent',
|
||||
'ShippingOrderField',
|
||||
'ShippingOrderExtraction',
|
||||
'ShippingOrderLine',
|
||||
'ShippingOrderFieldObservation',
|
||||
'ShippingOrderFieldDecision',
|
||||
'ShippingOrderFieldValue',
|
||||
'ShippingOrderCustomerMatch',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
'ShippingCustomerExternalRef',
|
||||
'ShippingCustomerLifecycleEvent',
|
||||
'ShippingCustomerMerge',
|
||||
'ShippingCustomerSite',
|
||||
'ShippingCustomerSiteIdentifier',
|
||||
'ShippingCustomerImportBatch',
|
||||
'ShippingCustomerImportRow',
|
||||
'ShippingCase',
|
||||
'ShippingBusinessSequence',
|
||||
'ShippingCustomerShadowResolution',
|
||||
'ShippingCustomerShadowMatch',
|
||||
'ShippingTaskEvent',
|
||||
'ShippingInventoryFile',
|
||||
'ShippingTaskInventoryLink',
|
||||
'ShippingInventoryMapping',
|
||||
'ShippingRpaProfile',
|
||||
'ShippingInventorySource',
|
||||
'ShippingInventoryField',
|
||||
'ShippingInventoryStructureAnalysis',
|
||||
'ShippingInventoryRoutingRule',
|
||||
'ShippingInventoryRoutingRuleCondition',
|
||||
'ShippingInventoryRoutingRuleVersion',
|
||||
'ShippingInventoryExternalMapping',
|
||||
'ShippingInventoryConfigurationTestRun',
|
||||
'ShippingInventoryParsingProfile',
|
||||
'ShippingTemporaryInventorySession',
|
||||
'ShippingExcelTemplate',
|
||||
'ShippingExportArtifact',
|
||||
'ShippingNoticeIntake',
|
||||
'ShippingNoticeDocument',
|
||||
'ShippingNoticeCandidate',
|
||||
|
||||
@@ -67,7 +67,6 @@ class ShippingBatch(Base):
|
||||
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
tasks: Mapped[List['ShippingTask']] = relationship(
|
||||
'ShippingTask',
|
||||
back_populates='batch',
|
||||
@@ -85,7 +84,6 @@ class ShippingTask(Base):
|
||||
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
|
||||
Index('ix_shipping_tasks_upload_status', 'upload_status'),
|
||||
Index('ix_shipping_tasks_inventory_source_code', 'inventory_source_code'),
|
||||
Index('ix_shipping_tasks_inventory_site_id', 'inventory_site_id'),
|
||||
Index('ix_shipping_tasks_inventory_source_status', 'inventory_source_status'),
|
||||
Index('ix_shipping_tasks_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
|
||||
Index('ix_shipping_tasks_inventory_rpa_consumed_run_no', 'inventory_rpa_consumed_run_no'),
|
||||
@@ -160,7 +158,6 @@ class ShippingTask(Base):
|
||||
warehouse_hint: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
inventory_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_connector_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
inventory_source_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
inventory_source_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
@@ -186,6 +183,15 @@ class ShippingTask(Base):
|
||||
server_default=text("'pending'"),
|
||||
nullable=False,
|
||||
)
|
||||
current_order_extraction_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey(
|
||||
'shipping_order_extractions.id',
|
||||
name='fk_shipping_tasks_current_order_extraction_id',
|
||||
use_alter=True,
|
||||
),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
|
||||
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
|
||||
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -215,7 +221,6 @@ class ShippingTask(Base):
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
batch: Mapped[Optional['ShippingBatch']] = relationship(
|
||||
'ShippingBatch',
|
||||
back_populates='tasks',
|
||||
@@ -273,25 +278,38 @@ class ShippingInventoryFile(Base):
|
||||
'exported_at',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_inventory_files_source_site_wh',
|
||||
'ix_shipping_inventory_files_source_warehouse',
|
||||
'source_code',
|
||||
'site_id',
|
||||
'warehouse_id',
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inventory_files_rpa_identity_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
'site_id',
|
||||
'warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND site_id IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NOT NULL"
|
||||
),
|
||||
),
|
||||
# 动态多仓文件没有单一 Warehouse;按 RPA run + Source 保证回调重放幂等。
|
||||
Index(
|
||||
'uq_shipping_inventory_files_rpa_dynamic_source_ready',
|
||||
'rpa_run_no',
|
||||
'source_code',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"snapshot_status = 'ready' AND rpa_run_no IS NOT NULL "
|
||||
"AND source_code IS NOT NULL AND warehouse_id IS NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -311,7 +329,6 @@ class ShippingInventoryFile(Base):
|
||||
share_mode: Mapped[str] = mapped_column(String(32), default='task_only')
|
||||
warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
warehouse_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
source_config_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
|
||||
source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
|
||||
@@ -344,7 +361,6 @@ class ShippingTaskInventoryLink(Base):
|
||||
'ix_shipping_task_inventory_links_task_source',
|
||||
'task_id',
|
||||
'matched_source_code',
|
||||
'matched_site_id',
|
||||
),
|
||||
)
|
||||
|
||||
@@ -357,7 +373,6 @@ class ShippingTaskInventoryLink(Base):
|
||||
link_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_source_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
matched_site_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
@@ -442,8 +457,6 @@ class ShippingNoticeIntake(Base):
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ShippingNoticeDocument(Base):
|
||||
"""
|
||||
发货通知文档单元:邮件正文或单个附件(阶段二)。
|
||||
@@ -493,8 +506,6 @@ class ShippingNoticeDocument(Base):
|
||||
order_extraction_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ShippingNoticeCandidate(Base):
|
||||
"""
|
||||
订单候选:一封邮件中识别出的独立发货通知(阶段二,尚未创建 Task)。
|
||||
@@ -572,22 +583,3 @@ class ShippingNoticeCandidate(Base):
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ShippingInventoryMapping(Base):
|
||||
"""客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_mappings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
|
||||
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
||||
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, index=True)
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import date, datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy import Boolean, CheckConstraint, Date, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
@@ -39,6 +39,11 @@ class ShippingCustomer(Base):
|
||||
standard_name: Mapped[str] = mapped_column(String(200), nullable=False, index=True)
|
||||
short_code: Mapped[str] = mapped_column(String(6), nullable=False, unique=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
merged_into_customer_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_customers.id'),
|
||||
nullable=True,
|
||||
index=True,
|
||||
)
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -51,6 +56,21 @@ class ShippingCustomer(Base):
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer')
|
||||
merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship(
|
||||
'ShippingCustomer',
|
||||
remote_side='ShippingCustomer.id',
|
||||
back_populates='merged_source_customers',
|
||||
)
|
||||
external_refs: Mapped[List['ShippingCustomerExternalRef']] = relationship(
|
||||
'ShippingCustomerExternalRef', back_populates='customer', cascade='all, delete-orphan',
|
||||
)
|
||||
sites: Mapped[List['ShippingCustomerSite']] = relationship(
|
||||
'ShippingCustomerSite', back_populates='customer', cascade='all, delete-orphan',
|
||||
)
|
||||
merged_source_customers: Mapped[List['ShippingCustomer']] = relationship(
|
||||
'ShippingCustomer',
|
||||
back_populates='merged_into_customer',
|
||||
)
|
||||
|
||||
|
||||
class ShippingCustomerIdentifier(Base):
|
||||
@@ -108,7 +128,65 @@ class ShippingCustomerExternalRef(Base):
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer')
|
||||
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='external_refs')
|
||||
|
||||
|
||||
class ShippingCustomerSite(Base):
|
||||
"""标准客户下的送货/收货站点;Ship-to 匹配指向站点而不是复制一条账款客户。"""
|
||||
|
||||
__tablename__ = 'shipping_customer_sites'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('customer_id', 'site_code', name='uq_shipping_customer_sites_customer_code'),
|
||||
Index('ix_shipping_customer_sites_status_name', 'status', 'site_name'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False, index=True)
|
||||
site_name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
site_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
address: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
city: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
country: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active')
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
customer: Mapped['ShippingCustomer'] = relationship('ShippingCustomer', back_populates='sites')
|
||||
identifiers: Mapped[List['ShippingCustomerSiteIdentifier']] = relationship(
|
||||
'ShippingCustomerSiteIdentifier', back_populates='site', cascade='all, delete-orphan',
|
||||
)
|
||||
|
||||
|
||||
class ShippingCustomerSiteIdentifier(Base):
|
||||
"""送货站点的名称、外部站点编码或地址别名,用于 Ship-to 确定性匹配。"""
|
||||
|
||||
__tablename__ = 'shipping_customer_site_identifiers'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'site_id', 'identifier_type', 'source_system', 'normalized_value',
|
||||
name='uq_shipping_customer_site_identifiers_value',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_customer_site_identifiers_lookup',
|
||||
'identifier_type', 'source_system', 'normalized_value', 'status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
site_id: Mapped[int] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=False, index=True)
|
||||
identifier_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
source_system: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
raw_value: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
normalized_value: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='approved', server_default='approved')
|
||||
remark: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers')
|
||||
|
||||
|
||||
class ShippingCase(Base):
|
||||
@@ -174,3 +252,45 @@ class ShippingBusinessSequence(Base):
|
||||
current_value: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
|
||||
class ShippingCustomerLifecycleEvent(Base):
|
||||
"""客户生命周期审计;只保存客户快照,不能反向阻断受控删除。"""
|
||||
|
||||
__tablename__ = 'shipping_customer_lifecycle_events'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_customer_lifecycle_events_customer_created', 'customer_id_snapshot', 'created_at'),
|
||||
Index('ix_shipping_customer_lifecycle_events_event_created', 'event_type', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
customer_id_snapshot: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
|
||||
|
||||
class ShippingCustomerMerge(Base):
|
||||
"""客户身份归并审计;仅存快照,不给历史审计链增加客户外键依赖。"""
|
||||
|
||||
__tablename__ = 'shipping_customer_merges'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('source_customer_id_snapshot', name='uq_shipping_customer_merges_source_snapshot'),
|
||||
Index('ix_shipping_customer_merges_target_created', 'target_customer_id_snapshot', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
source_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
source_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
target_customer_id_snapshot: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
target_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
target_short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
detail_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
@@ -9,10 +9,10 @@ backend/app/models/shipping_customer_resolution.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, JSON, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy import CheckConstraint, Float, ForeignKey, Index, Integer, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
@@ -52,3 +52,40 @@ class ShippingCustomerShadowResolution(Base):
|
||||
labeled_at: Mapped[Optional[datetime]] = mapped_column(nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
matches: Mapped[List['ShippingCustomerShadowMatch']] = relationship(
|
||||
'ShippingCustomerShadowMatch',
|
||||
back_populates='resolution',
|
||||
cascade='all, delete-orphan',
|
||||
order_by='ShippingCustomerShadowMatch.match_rank',
|
||||
)
|
||||
|
||||
|
||||
class ShippingCustomerShadowMatch(Base):
|
||||
"""影子识别候选的规范化关联,供删除资格与合并可靠反查。"""
|
||||
|
||||
__tablename__ = 'shipping_customer_shadow_matches'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('resolution_id', 'customer_id', name='uq_shipping_customer_shadow_matches_resolution_customer'),
|
||||
Index('ix_shipping_customer_shadow_matches_customer', 'customer_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
resolution_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_customer_shadow_resolutions.id', ondelete='CASCADE'),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
customer_id: Mapped[int] = mapped_column(ForeignKey('shipping_customers.id'), nullable=False)
|
||||
match_rank: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
score: Mapped[float] = mapped_column(Float, nullable=False)
|
||||
standard_name_snapshot: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
short_code_snapshot: Mapped[str] = mapped_column(String(6), nullable=False)
|
||||
reasons_json: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
resolution: Mapped['ShippingCustomerShadowResolution'] = relationship(
|
||||
'ShippingCustomerShadowResolution',
|
||||
back_populates='matches',
|
||||
)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
models/shipping_excel_template.py
|
||||
|
||||
用途:定义版本化发货 Excel 模板及不可变任务导出产物。
|
||||
依赖:models.base.Base、库存源、订单 Schema、发货任务与库存快照模型。
|
||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingExcelTemplate(Base):
|
||||
"""可跨库存源复用的发货 Excel 模板版本。"""
|
||||
|
||||
__tablename__ = 'shipping_excel_templates'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('template_code', 'version', name='uq_shipping_excel_templates_code_version'),
|
||||
Index('ix_shipping_excel_templates_status', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
template_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
|
||||
storage_provider: Mapped[str] = mapped_column(String(32), nullable=False, default='minio', server_default='minio')
|
||||
storage_bucket: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
original_filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
definition_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='excel_template')
|
||||
|
||||
|
||||
class ShippingExportArtifact(Base):
|
||||
"""一次任务导出的不可变产物及生成输入快照。"""
|
||||
|
||||
__tablename__ = 'shipping_export_artifacts'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('artifact_no', name='uq_shipping_export_artifacts_no'),
|
||||
Index('ix_shipping_export_artifacts_task_created', 'task_id', 'created_at'),
|
||||
Index('ix_shipping_export_artifacts_batch_created', 'batch_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
artifact_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False, index=True)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True)
|
||||
template_id: Mapped[int] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=False)
|
||||
order_schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
order_extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id'), nullable=False)
|
||||
inventory_parsing_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=False)
|
||||
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True)
|
||||
input_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='ready', server_default='ready')
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
template: Mapped[ShippingExcelTemplate] = relationship()
|
||||
task: Mapped['ShippingTask'] = relationship()
|
||||
@@ -0,0 +1,317 @@
|
||||
"""
|
||||
models/shipping_inventory_config.py
|
||||
|
||||
用途:定义货代库存源、RPA Profile、通用路由规则及外部系统仓库映射主数据。
|
||||
依赖:models.base.Base、SQLAlchemy ORM;凭据密文由 shipping_notice.credential_crypto 读写。
|
||||
逻辑:库存运行链路以 ShippingInventorySource.source_code 为业务主键;RPA Profile 仅提供登录连接配置,
|
||||
外部系统映射仅供后端内部复用,不承载调拨决策。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingInventoryField(Base):
|
||||
"""用户维护的库存业务字段目录;程序仅依据字段 ID 和业务用途运行。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_fields'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('field_code', name='uq_shipping_inventory_fields_code'),
|
||||
UniqueConstraint('display_name', name='uq_shipping_inventory_fields_display_name'),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_inventory_fields_status'),
|
||||
CheckConstraint("value_type IN ('text', 'integer', 'decimal', 'date')", name='ck_shipping_inventory_fields_value_type'),
|
||||
CheckConstraint(
|
||||
"usage_type IN ('match_identity', 'inventory_quantity', 'warehouse_identity', 'general')",
|
||||
name='ck_shipping_inventory_fields_usage_type',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
# Internal stable code supports runtime contracts; it is deliberately not exposed in the business UI.
|
||||
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='text', server_default='text')
|
||||
usage_type: Mapped[str] = mapped_column(String(32), nullable=False, default='general', server_default='general')
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, default=100, server_default='100')
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingRpaProfile(Base):
|
||||
"""货代库存登录连接配置;凭据字段始终保存密文。"""
|
||||
|
||||
__tablename__ = 'shipping_rpa_profiles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_code', name='uq_shipping_rpa_profiles_profile_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_rpa_profiles_connector_type'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
login_url: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
username_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
password_ciphertext: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
login_config_json: Mapped[dict[str, Any]] = mapped_column(
|
||||
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='rpa_profile')
|
||||
|
||||
|
||||
class ShippingInventorySource(Base):
|
||||
"""库存业务来源;固定仓或库存行动态解析 Warehouse。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_sources'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('source_code', name='uq_shipping_inventory_sources_source_code'),
|
||||
CheckConstraint("connector_type IN ('dbs', 'crane')", name='ck_shipping_inventory_sources_connector_type'),
|
||||
CheckConstraint(
|
||||
"(warehouse_resolution_mode = 'fixed' AND fixed_warehouse_id IS NOT NULL) "
|
||||
"OR (warehouse_resolution_mode = 'inventory_match' AND fixed_warehouse_id IS NULL)",
|
||||
name='ck_shipping_inventory_sources_warehouse_mode',
|
||||
),
|
||||
CheckConstraint(
|
||||
"enabled = false OR (parsing_profile_id IS NOT NULL AND excel_template_id IS NOT NULL)",
|
||||
name='ck_shipping_inventory_sources_enabled_bindings',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
connector_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
rpa_profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_rpa_profiles.id'), nullable=False, index=True)
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True)
|
||||
excel_template_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_excel_templates.id'), nullable=True, index=True)
|
||||
warehouse_resolution_mode: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
fixed_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 业务报表定义属于 Source;Driver 的 selector、等待与下载实现不进入数据库配置。
|
||||
report_path_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, server_default=text("'{}'"), nullable=False)
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
|
||||
match_aliases_json: Mapped[list[str]] = mapped_column(JSON, default=list, server_default=text("'[]'"), nullable=False)
|
||||
snapshot_ttl_seconds: Mapped[int] = mapped_column(Integer, default=86400, server_default=text('86400'), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
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)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
rpa_profile: Mapped[ShippingRpaProfile] = relationship(back_populates='sources')
|
||||
parsing_profile: Mapped[Optional['ShippingInventoryParsingProfile']] = relationship(back_populates='sources')
|
||||
excel_template: Mapped[Optional['ShippingExcelTemplate']] = relationship(back_populates='sources')
|
||||
external_mappings: Mapped[list['ShippingInventoryExternalMapping']] = relationship(
|
||||
back_populates='inventory_source', cascade='all, delete-orphan'
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryParsingProfile(Base):
|
||||
"""可跨库存源复用的库存文件结构与订单匹配配置。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_parsing_profiles'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('profile_code', 'version', name='uq_inventory_parsing_profiles_code_version'),
|
||||
Index('ix_inv_parse_profile_exact_fp', 'exact_structure_fingerprint'),
|
||||
Index('ix_inv_parse_profile_compat_fp', 'compatibility_fingerprint'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default=text('1'))
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
|
||||
file_format: Mapped[str] = mapped_column(String(16), nullable=False, default='xlsx', server_default='xlsx')
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
structure_definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
|
||||
|
||||
|
||||
class ShippingInventoryStructureAnalysis(Base):
|
||||
"""库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_structure_analyses'
|
||||
__table_args__ = (
|
||||
Index('ix_inv_structure_analysis_file_hash', 'file_checksum'),
|
||||
Index('ix_inv_structure_analysis_created', 'created_at'),
|
||||
Index('ix_inv_structure_analysis_exact_fp', 'exact_structure_fingerprint'),
|
||||
Index('ix_inv_structure_analysis_compat_fp', 'compatibility_fingerprint'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload')
|
||||
source_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
storage_path: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
file_format: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready')
|
||||
structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
match_result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryConfigurationTestRun(Base):
|
||||
"""库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_configuration_test_runs'
|
||||
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
|
||||
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRule(Base):
|
||||
"""可版本化的库存源路由决策表;仅产出受控 Source 候选。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rules'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('rule_code', 'version', name='uq_shipping_inventory_routing_rules_code_version'),
|
||||
CheckConstraint("scope IN ('task', 'line')", name='ck_shipping_inventory_routing_rules_scope'),
|
||||
CheckConstraint("match_mode IN ('all', 'any')", name='ck_shipping_inventory_routing_rules_match_mode'),
|
||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_inventory_routing_rules_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
rule_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
rule_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
scope: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
priority: Mapped[int] = mapped_column(Integer, default=0, server_default=text('0'), nullable=False)
|
||||
match_mode: Mapped[str] = mapped_column(String(16), default='all', server_default=text("'all'"), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), default='draft', server_default=text("'draft'"), nullable=False)
|
||||
action_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
action_payload_json: Mapped[dict[str, Any]] = mapped_column(JSON, default=dict, nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
effective_from: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
effective_to: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
conditions: Mapped[list['ShippingInventoryRoutingRuleCondition']] = relationship(
|
||||
back_populates='rule', cascade='all, delete-orphan', order_by='ShippingInventoryRoutingRuleCondition.sequence'
|
||||
)
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRuleCondition(Base):
|
||||
"""库存源路由条件;订单字段引用稳定 field_id,系统事实使用受控 key。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rule_conditions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('rule_id', 'sequence', name='uq_shipping_inventory_routing_rule_conditions_sequence'),
|
||||
CheckConstraint(
|
||||
"(source_kind = 'order_field' AND order_field_id IS NOT NULL AND system_fact_key IS NULL) OR "
|
||||
"(source_kind = 'system_fact' AND order_field_id IS NULL AND system_fact_key IS NOT NULL)",
|
||||
name='ck_inventory_routing_condition_source',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
||||
condition_group: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
source_kind: Mapped[str] = mapped_column(String(16), nullable=False, default='order_field')
|
||||
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
||||
system_fact_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
operator: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
expected_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
sequence: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
rule: Mapped[ShippingInventoryRoutingRule] = relationship(back_populates='conditions')
|
||||
|
||||
|
||||
class ShippingInventoryRoutingRuleVersion(Base):
|
||||
"""已发布路由规则的不可变定义快照,供任务审计回放使用。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_routing_rule_versions'
|
||||
__table_args__ = (UniqueConstraint('rule_id', 'version', name='uq_shipping_inventory_routing_rule_versions_rule_version'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
rule_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_routing_rules.id'), nullable=False, index=True)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
"""货代库存身份到外部系统仓库的单向映射;不承载调拨规则。"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
__table_args__ = (
|
||||
Index(
|
||||
'uq_shipping_inventory_external_mappings_source_default_enabled',
|
||||
'inventory_source_id',
|
||||
unique=True,
|
||||
postgresql_where=text('freight_warehouse_id IS NULL AND enabled = true'),
|
||||
sqlite_where=text('freight_warehouse_id IS NULL AND enabled = 1'),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_inventory_external_mappings_source_warehouse_enabled',
|
||||
'inventory_source_id',
|
||||
'freight_warehouse_id',
|
||||
unique=True,
|
||||
postgresql_where=text('freight_warehouse_id IS NOT NULL AND enabled = true'),
|
||||
sqlite_where=text('freight_warehouse_id IS NOT NULL AND enabled = 1'),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
|
||||
freight_warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_system_code: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
external_organization_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_site_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
external_warehouse_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
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)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
inventory_source: Mapped[ShippingInventorySource] = relationship(back_populates='external_mappings')
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_customer_match.py
|
||||
|
||||
用途:保存订单解析中账款客户、送货客户与货代客户主数据的角色化匹配结果。
|
||||
依赖:ShippingOrderExtraction、ShippingCustomer、users。
|
||||
逻辑:动态订单字段保留原文客户名称;本表按角色保存候选、确认客户及名称/简称快照,供复核和导出读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderCustomerMatch(Base):
|
||||
"""一次订单解析中的角色化客户匹配;每个解析记录的每种客户角色仅保留一条当前结果。"""
|
||||
|
||||
__tablename__ = 'shipping_order_customer_matches'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('extraction_id', 'role', name='uq_shipping_order_customer_matches_extraction_role'),
|
||||
CheckConstraint("role IN ('bill_to', 'ship_to')", name='ck_shipping_order_customer_matches_role'),
|
||||
CheckConstraint(
|
||||
"status IN ('unmatched', 'unique_candidate', 'ambiguous', 'confirmed')",
|
||||
name='ck_shipping_order_customer_matches_status',
|
||||
),
|
||||
Index('ix_shipping_order_customer_matches_customer_role', 'customer_id', 'role'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False, index=True,
|
||||
)
|
||||
role: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
raw_name: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
normalized_name: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
source_system: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='unmatched', server_default='unmatched')
|
||||
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True)
|
||||
site_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customer_sites.id'), nullable=True)
|
||||
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
|
||||
candidates_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
resolution_method: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
confirmed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
|
||||
extraction = relationship('ShippingOrderExtraction')
|
||||
customer = relationship('ShippingCustomer')
|
||||
site = relationship('ShippingCustomerSite')
|
||||
@@ -0,0 +1,311 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_schema.py
|
||||
|
||||
用途:定义货代订单唯一 Schema、不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
|
||||
逻辑:草稿和发布版本统一保存完整 JSON 定义;写操作追加审计事件;解析链锁定发布版本并保存裁决结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Date,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
JSON,
|
||||
Numeric,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
def _uuid() -> str:
|
||||
"""生成跨 PostgreSQL/SQLite 通用的 UUID 字符串主键。"""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
class ShippingOrderSchema(Base):
|
||||
"""全局唯一货代订单 Schema;当前业务只允许一个逻辑 Schema。"""
|
||||
|
||||
__tablename__ = 'shipping_order_schemas'
|
||||
__table_args__ = (
|
||||
CheckConstraint("schema_code = 'SHIPPING_ORDER'", name='ck_shipping_order_schemas_single_code'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_code: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
fields: Mapped[list['ShippingOrderField']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderField.field_code'
|
||||
)
|
||||
versions: Mapped[list['ShippingOrderSchemaVersion']] = relationship(
|
||||
back_populates='schema', cascade='all, delete-orphan', order_by='ShippingOrderSchemaVersion.version'
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderField(Base):
|
||||
"""订单字段稳定身份;下游使用 field_id,版本快照冻结当时的名称和规则。"""
|
||||
|
||||
__tablename__ = 'shipping_order_fields'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'),
|
||||
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
|
||||
CheckConstraint(
|
||||
"value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')",
|
||||
name='ck_shipping_order_fields_value_type',
|
||||
),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_order_fields_status'),
|
||||
Index('ix_shipping_order_fields_schema_scope', 'schema_id', 'scope'),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
scope: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='fields')
|
||||
|
||||
|
||||
class ShippingOrderSchemaVersion(Base):
|
||||
"""订单 Schema 版本;草稿与发布版本统一以完整 definition_json 为配置真相。"""
|
||||
|
||||
__tablename__ = 'shipping_order_schema_versions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schema_id', 'version', name='uq_shipping_order_schema_versions_schema_version'),
|
||||
CheckConstraint("status IN ('draft', 'published', 'retired')", name='ck_shipping_order_schema_versions_status'),
|
||||
Index(
|
||||
'uq_shipping_order_schema_one_published',
|
||||
'schema_id',
|
||||
unique=True,
|
||||
postgresql_where=text("status = 'published'"),
|
||||
sqlite_where=text("status = 'published'"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='draft', server_default='draft')
|
||||
definition_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
|
||||
change_note: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
source_version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id'), nullable=True
|
||||
)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
retired_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
schema: Mapped['ShippingOrderSchema'] = relationship(back_populates='versions')
|
||||
source_version: Mapped[Optional['ShippingOrderSchemaVersion']] = relationship(
|
||||
remote_side='ShippingOrderSchemaVersion.id', foreign_keys=[source_version_id]
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderSchemaAuditEvent(Base):
|
||||
"""订单 Schema 配置的追加式审计事件;保存操作前后快照且不提供修改入口。"""
|
||||
|
||||
__tablename__ = 'shipping_order_schema_audit_events'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"event_type IN ('draft_created', 'draft_saved', 'published', 'draft_deleted', 'cloned', "
|
||||
"'field_saved', 'field_retired', 'field_deleted')",
|
||||
name='ck_shipping_order_schema_audit_event_type',
|
||||
),
|
||||
Index('ix_shipping_order_schema_audit_version_created', 'version_id', 'created_at'),
|
||||
Index('ix_shipping_order_schema_audit_schema_created', 'schema_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
schema_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schemas.id'), nullable=False)
|
||||
version_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id', ondelete='SET NULL'), nullable=True
|
||||
)
|
||||
event_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
before_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
after_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
change_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
class ShippingOrderExtraction(Base):
|
||||
"""一次订单解析审计;锁定 Schema 和输入快照,承载 LLM 原始结果及最终状态。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extractions'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_order_extractions_task_created', 'task_id', 'created_at'),
|
||||
Index('ix_shipping_order_extractions_intake_created', 'intake_id', 'created_at'),
|
||||
# Version history pages aggregate and paginate the runtime records that used a Schema snapshot.
|
||||
Index('ix_shipping_order_extractions_schema_version_created', 'schema_version_id', 'created_at'),
|
||||
CheckConstraint(
|
||||
"status IN ('created', 'extracting', 'needs_review', 'accepted', 'failed', 'superseded')",
|
||||
name='ck_shipping_order_extractions_status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
input_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created', server_default='created')
|
||||
raw_llm_output_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
normalized_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
validation_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
schema_version: Mapped['ShippingOrderSchemaVersion'] = relationship()
|
||||
lines: Mapped[list['ShippingOrderLine']] = relationship(
|
||||
back_populates='extraction', cascade='all, delete-orphan', order_by='ShippingOrderLine.position'
|
||||
)
|
||||
observations: Mapped[list['ShippingOrderFieldObservation']] = relationship(
|
||||
back_populates='extraction', cascade='all, delete-orphan'
|
||||
)
|
||||
decisions: Mapped[list['ShippingOrderFieldDecision']] = relationship(
|
||||
back_populates='extraction', cascade='all, delete-orphan'
|
||||
)
|
||||
values: Mapped[list['ShippingOrderFieldValue']] = relationship(
|
||||
back_populates='extraction', cascade='all, delete-orphan'
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderLine(Base):
|
||||
"""动态订单解析中的行身份;业务值全部位于 FieldValue。"""
|
||||
|
||||
__tablename__ = 'shipping_order_lines'
|
||||
__table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines')
|
||||
|
||||
|
||||
class ShippingOrderFieldObservation(Base):
|
||||
"""某字段来自某 Document/解析器的原始观察及可回查证据。"""
|
||||
|
||||
__tablename__ = 'shipping_order_field_observations'
|
||||
__table_args__ = (Index('ix_shipping_order_observations_extraction_field', 'extraction_id', 'field_id'),)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
source_document_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_documents.id'), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
extractor: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
raw_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
normalized_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
evidence_quote: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
confidence: Mapped[Optional[Decimal]] = mapped_column(Numeric(5, 4), nullable=True)
|
||||
evidence_verified: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='observations')
|
||||
|
||||
|
||||
class ShippingOrderFieldDecision(Base):
|
||||
"""后端对字段观察集合的最终裁决;下游只能消费 accepted 决定。"""
|
||||
|
||||
__tablename__ = 'shipping_order_field_decisions'
|
||||
__table_args__ = (
|
||||
Index(
|
||||
'uq_shipping_order_decisions_header_field', 'extraction_id', 'field_id', unique=True,
|
||||
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_order_decisions_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
|
||||
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
|
||||
),
|
||||
CheckConstraint(
|
||||
"decision_status IN ('accepted', 'corroborated', 'needs_review', 'blocked', 'missing')",
|
||||
name='ck_shipping_order_decisions_status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
decision_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
selected_observation_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_field_observations.id'), nullable=True
|
||||
)
|
||||
supporting_observation_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
|
||||
resolved_value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
reason_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
decided_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='decisions')
|
||||
|
||||
|
||||
class ShippingOrderFieldValue(Base):
|
||||
"""已接受订单字段的类型化查询投影,供路由、匹配和 Excel 模板稳定引用。"""
|
||||
|
||||
__tablename__ = 'shipping_order_field_values'
|
||||
__table_args__ = (
|
||||
Index(
|
||||
'uq_shipping_order_field_values_header_field', 'extraction_id', 'field_id', unique=True,
|
||||
postgresql_where=text('line_id IS NULL'), sqlite_where=text('line_id IS NULL'),
|
||||
),
|
||||
Index(
|
||||
'uq_shipping_order_field_values_line_field', 'extraction_id', 'line_id', 'field_id', unique=True,
|
||||
postgresql_where=text('line_id IS NOT NULL'), sqlite_where=text('line_id IS NOT NULL'),
|
||||
),
|
||||
Index('ix_shipping_order_field_values_field_text', 'field_id', 'value_text'),
|
||||
Index('ix_shipping_order_field_values_field_decimal', 'field_id', 'value_decimal'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
|
||||
line_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_lines.id', ondelete='CASCADE'), nullable=True)
|
||||
field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
value_text: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
value_decimal: Mapped[Optional[Decimal]] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
value_integer: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
value_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
value_boolean: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
||||
value_json: Mapped[Any] = mapped_column(JSON, nullable=True)
|
||||
decision_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_field_decisions.id'), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='values')
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
models/shipping_temporary_inventory.py
|
||||
|
||||
用途:定义对话上传库存文件的临时会话,隔离其分析、确认与后续批次使用过程。
|
||||
依赖:Base、FileAsset、ChatSession、ShippingBatch/ShippingTask、库存结构分析记录。
|
||||
逻辑:Dify Tool 与工作台均先创建本会话,再由后端对受控文件资产进行结构初检;
|
||||
本表不代表库存站点配置,也不代表生产库存快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingTemporaryInventorySession(Base):
|
||||
"""对话上传库存候选文件的短生命周期会话;禁止直接成为生产库存来源。"""
|
||||
|
||||
__tablename__ = 'shipping_temporary_inventory_sessions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('session_no', name='uq_shipping_temporary_inventory_sessions_no'),
|
||||
Index('ix_shipping_temp_inventory_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_temp_inventory_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_temp_inventory_asset', 'asset_id'),
|
||||
Index('ix_shipping_temp_inventory_status_expires', 'status', 'expires_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
session_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
asset_id: Mapped[int] = mapped_column(ForeignKey('file_assets.id'), nullable=False, index=True)
|
||||
analysis_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
|
||||
)
|
||||
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), nullable=True, index=True)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True, index=True)
|
||||
declared_intent: Mapped[str] = mapped_column(String(32), nullable=False, default='inventory_candidate')
|
||||
file_classification_status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='created')
|
||||
classification_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
candidate_source_ids_json: Mapped[list[int]] = mapped_column(JSON, nullable=False, default=list)
|
||||
result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -15,6 +15,8 @@ from . import (
|
||||
permission_service,
|
||||
report_service,
|
||||
shipping_customer_import_service,
|
||||
shipping_customer_lifecycle_service,
|
||||
shipping_customer_merge_service,
|
||||
shipping_customer_service,
|
||||
user_service,
|
||||
wecom_admin_service,
|
||||
@@ -31,6 +33,8 @@ __all__ = [
|
||||
'permission_service',
|
||||
'report_service',
|
||||
'shipping_customer_import_service',
|
||||
'shipping_customer_lifecycle_service',
|
||||
'shipping_customer_merge_service',
|
||||
'shipping_customer_service',
|
||||
'user_service',
|
||||
'wecom_admin_service',
|
||||
|
||||
@@ -497,8 +497,11 @@ def decide_import_row(row_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
target_id = int(target_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Target customer is required', code='SHIPPING.CUSTOMER_IMPORT_TARGET_REQUIRED') from exc
|
||||
if db.session.get(ShippingCustomer, target_id) is None:
|
||||
target = db.session.get(ShippingCustomer, target_id)
|
||||
if target is None:
|
||||
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if target.status != 'active':
|
||||
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
|
||||
else:
|
||||
target_id = None
|
||||
row.decision_action = action
|
||||
@@ -586,6 +589,8 @@ def publish_import_batch(batch_id: int, *, actor_id: int | None) -> dict[str, An
|
||||
target = db.session.get(ShippingCustomer, row.target_customer_id)
|
||||
if target is None:
|
||||
raise NotFoundError('Target customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if target.status != 'active':
|
||||
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
|
||||
if action == 'update':
|
||||
target.standard_name = data['standard_name']
|
||||
target.short_code = data['short_code']
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
services/admin/shipping_customer_lifecycle_service.py
|
||||
|
||||
用途:统一计算货代客户生命周期影响和永久删除资格。
|
||||
依赖:客户、业务单、流水、导入、影子识别模型及统一 AppError。
|
||||
逻辑:所有删除入口先调用本服务;业务和识别审计引用均阻断删除,识别证据仅作为可级联配置数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerImportRow,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerSite,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
)
|
||||
|
||||
|
||||
def _legacy_shadow_json_match_count(customer_id: int, *, matched_resolution_ids: set[int]) -> int:
|
||||
"""统计规范化迁移前 JSON 中仍未映射的候选,防止现存审计记录漏算。"""
|
||||
count = 0
|
||||
rows = db.session.query(
|
||||
ShippingCustomerShadowResolution.id,
|
||||
ShippingCustomerShadowResolution.candidate_matches_json,
|
||||
).all()
|
||||
for resolution_id, matches in rows:
|
||||
if int(resolution_id) in matched_resolution_ids:
|
||||
continue
|
||||
for item in matches or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
if int(item.get('customer_id')) == customer_id:
|
||||
count += 1
|
||||
break
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return count
|
||||
|
||||
|
||||
def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, Any]:
|
||||
"""按已锁定或已读取的客户对象统计删除资格,保证各删除入口使用同一口径。"""
|
||||
matched_resolution_ids = {
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingCustomerShadowMatch.resolution_id)
|
||||
.filter_by(customer_id=customer.id)
|
||||
.all()
|
||||
}
|
||||
shadow_normalized = len(matched_resolution_ids)
|
||||
blockers = {
|
||||
'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(),
|
||||
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
|
||||
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
|
||||
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
|
||||
'import_target_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(target_customer_id=customer.id).count(),
|
||||
'import_result_rows': db.session.query(ShippingCustomerImportRow.id).filter_by(result_customer_id=customer.id).count(),
|
||||
'shadow_top_candidates': db.session.query(ShippingCustomerShadowResolution.id).filter_by(top_customer_id=customer.id).count(),
|
||||
'shadow_manual_labels': db.session.query(ShippingCustomerShadowResolution.id).filter_by(manual_customer_id=customer.id).count(),
|
||||
'shadow_candidate_matches': shadow_normalized + _legacy_shadow_json_match_count(
|
||||
customer.id,
|
||||
matched_resolution_ids=matched_resolution_ids,
|
||||
),
|
||||
'merged_source_customers': db.session.query(ShippingCustomer.id).filter_by(
|
||||
merged_into_customer_id=customer.id,
|
||||
).count(),
|
||||
'merged_into_customer': int(customer.merged_into_customer_id is not None),
|
||||
}
|
||||
return {
|
||||
'customer': {
|
||||
'id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'status': customer.status,
|
||||
},
|
||||
'can_delete': not any(blockers.values()),
|
||||
'blockers': blockers,
|
||||
'cascade': {
|
||||
'identifiers': db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=customer.id).count(),
|
||||
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=customer.id).count(),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_customer_lifecycle_impact(customer_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
返回客户永久删除前必须检查的全部引用和可级联配置数据。
|
||||
|
||||
Args:
|
||||
customer_id: 标准客户主键。
|
||||
Returns:
|
||||
客户快照、can_delete、阻断引用计数和可级联识别证据数。
|
||||
"""
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
|
||||
return _build_customer_lifecycle_impact(customer)
|
||||
|
||||
|
||||
def get_customer_lifecycle_timeline(customer_id: int, *, limit: int = 100) -> dict[str, Any]:
|
||||
"""返回客户关键治理操作的倒序时间线,事件只含快照而不依赖客户外键。"""
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
rows = (
|
||||
db.session.query(ShippingCustomerLifecycleEvent)
|
||||
.filter_by(customer_id_snapshot=customer_id)
|
||||
.order_by(ShippingCustomerLifecycleEvent.id.desc())
|
||||
.limit(max(1, min(int(limit), 500)))
|
||||
.all()
|
||||
)
|
||||
if customer is None and not rows:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
# 受控删除后主表已不存在;以最近生命周期快照继续提供审计回放。
|
||||
customer_snapshot = _build_customer_lifecycle_impact(customer)['customer'] if customer is not None else {
|
||||
'id': customer_id,
|
||||
'standard_name': rows[0].customer_name_snapshot,
|
||||
'short_code': rows[0].customer_short_code_snapshot,
|
||||
'status': 'deleted',
|
||||
}
|
||||
return {
|
||||
'customer': customer_snapshot,
|
||||
'items': [{
|
||||
'id': row.id,
|
||||
'event_type': row.event_type,
|
||||
'actor_id': row.actor_id,
|
||||
'reason': row.reason,
|
||||
'detail': row.detail_json or {},
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
} for row in rows],
|
||||
}
|
||||
|
||||
|
||||
def get_customer_governance_quality(*, limit: int = 100) -> dict[str, Any]:
|
||||
"""汇总影子识别、自动确认门禁和生命周期事件,供管理端持续治理。"""
|
||||
from app.services.shipping_notice.customer_shadow_resolution import get_shadow_quality_report
|
||||
from app.services.shipping_notice.customer_auto_resolution import get_auto_resolution_metrics
|
||||
|
||||
report = get_shadow_quality_report(limit=limit)
|
||||
report['auto_resolution'] = get_auto_resolution_metrics()
|
||||
event_counts = dict(
|
||||
db.session.query(ShippingCustomerLifecycleEvent.event_type, db.func.count())
|
||||
.group_by(ShippingCustomerLifecycleEvent.event_type)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
'shadow_quality': report,
|
||||
'lifecycle_event_counts': event_counts,
|
||||
}
|
||||
|
||||
|
||||
def delete_customer(
|
||||
customer_id: int,
|
||||
*,
|
||||
confirmation_short_code: object,
|
||||
reason: object,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
受控永久删除未进入任何业务或审计链的误建客户。
|
||||
|
||||
Args:
|
||||
customer_id: 待删除的标准客户主键。
|
||||
confirmation_short_code: 管理员二次输入的客户简码,忽略首尾空格并按大写比对。
|
||||
reason: 必填删除原因,写入不可反向引用客户的生命周期审计。
|
||||
actor_id: 当前管理员主键。
|
||||
Returns:
|
||||
已删除客户的快照、级联删除证据数与审计事件主键。
|
||||
Raises:
|
||||
ValidationError: 删除原因或二次确认简码不合法。
|
||||
ConflictError: 锁定后发现存在任一阻断引用。
|
||||
NotFoundError: 客户不存在。
|
||||
"""
|
||||
confirmed_code = str(confirmation_short_code or '').strip().upper()
|
||||
delete_reason = str(reason or '').strip()
|
||||
if not delete_reason:
|
||||
raise ValidationError(
|
||||
'Customer deletion reason is required',
|
||||
code='SHIPPING.CUSTOMER_DELETE_REASON_REQUIRED',
|
||||
details={'field': 'reason'},
|
||||
)
|
||||
|
||||
try:
|
||||
# 锁住客户行后再统计引用,避免预检与提交之间出现可删除的错误判断。
|
||||
customer = db.session.execute(
|
||||
select(ShippingCustomer)
|
||||
.where(ShippingCustomer.id == customer_id)
|
||||
.with_for_update()
|
||||
).scalar_one_or_none()
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if confirmed_code != customer.short_code:
|
||||
raise ValidationError(
|
||||
'Customer deletion confirmation short code is invalid',
|
||||
code='SHIPPING.CUSTOMER_DELETE_CONFIRMATION_INVALID',
|
||||
details={'field': 'confirmation_short_code'},
|
||||
)
|
||||
|
||||
impact = _build_customer_lifecycle_impact(customer)
|
||||
if not impact['can_delete']:
|
||||
raise ConflictError(
|
||||
'Customer deletion is blocked by lifecycle references',
|
||||
code='SHIPPING.CUSTOMER_DELETE_BLOCKED',
|
||||
details={'blockers': impact['blockers']},
|
||||
)
|
||||
|
||||
event = ShippingCustomerLifecycleEvent(
|
||||
event_type='deleted',
|
||||
customer_id_snapshot=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
actor_id=actor_id,
|
||||
reason=delete_reason,
|
||||
detail_json={
|
||||
'cascade': impact['cascade'],
|
||||
},
|
||||
)
|
||||
customer_snapshot = impact['customer']
|
||||
db.session.add(event)
|
||||
db.session.flush()
|
||||
db.session.delete(customer)
|
||||
db.session.commit()
|
||||
return {
|
||||
'deleted_customer': customer_snapshot,
|
||||
'cascade': impact['cascade'],
|
||||
'lifecycle_event_id': event.id,
|
||||
}
|
||||
except (ConflictError, NotFoundError, ValidationError):
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
services/admin/shipping_customer_merge_service.py
|
||||
|
||||
用途:执行货代标准客户的受控身份归并。
|
||||
依赖:客户、识别证据、外部来源键、生命周期审计与统一业务异常。
|
||||
逻辑:历史业务、编号、导入和影子审计保持指向源客户;仅将未来识别配置归并至目标客户。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerSite,
|
||||
)
|
||||
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
|
||||
|
||||
|
||||
def _load_customers_for_merge(source_customer_id: int, target_customer_id: int) -> tuple[ShippingCustomer, ShippingCustomer]:
|
||||
"""按主键固定顺序锁住源和目标客户,避免两个反向合并请求产生死锁。"""
|
||||
if source_customer_id == target_customer_id:
|
||||
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
|
||||
ids = sorted({int(source_customer_id), int(target_customer_id)})
|
||||
records = db.session.execute(
|
||||
select(ShippingCustomer)
|
||||
.where(ShippingCustomer.id.in_(ids))
|
||||
.order_by(ShippingCustomer.id.asc())
|
||||
.with_for_update()
|
||||
).scalars().all()
|
||||
by_id = {int(record.id): record for record in records}
|
||||
source = by_id.get(int(source_customer_id))
|
||||
target = by_id.get(int(target_customer_id))
|
||||
if source is None or target is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
return source, target
|
||||
|
||||
|
||||
def _assert_merge_allowed(source: ShippingCustomer, target: ShippingCustomer) -> None:
|
||||
"""校验合并两端均处于可操作状态,禁止链式或循环归并。"""
|
||||
if source.status == 'merged' or source.merged_into_customer_id is not None:
|
||||
raise ConflictError('Source customer has already been merged', code='SHIPPING.CUSTOMER_MERGE_SOURCE_ALREADY_MERGED')
|
||||
if target.status != 'active' or target.merged_into_customer_id is not None:
|
||||
raise ValidationError('Target customer must be active', code='SHIPPING.CUSTOMER_MERGE_TARGET_INVALID')
|
||||
|
||||
|
||||
def get_customer_merge_impact(source_customer_id: int, target_customer_id: int) -> dict[str, Any]:
|
||||
"""预览归并的历史保留引用与可迁移配置,不执行任何数据修改。"""
|
||||
if source_customer_id == target_customer_id:
|
||||
raise ValidationError('Source and target customer must differ', code='SHIPPING.CUSTOMER_MERGE_SAME_CUSTOMER')
|
||||
source = db.session.get(ShippingCustomer, source_customer_id)
|
||||
target = db.session.get(ShippingCustomer, target_customer_id)
|
||||
if source is None or target is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
_assert_merge_allowed(source, target)
|
||||
target_identifiers = {
|
||||
(item.identifier_type, item.normalized_value)
|
||||
for item in db.session.query(ShippingCustomerIdentifier)
|
||||
.filter_by(customer_id=target.id)
|
||||
.all()
|
||||
}
|
||||
source_identifiers = db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all()
|
||||
duplicate_identifiers = sum(
|
||||
(item.identifier_type, item.normalized_value) in target_identifiers
|
||||
for item in source_identifiers
|
||||
)
|
||||
return {
|
||||
'source': {
|
||||
'id': source.id,
|
||||
'standard_name': source.standard_name,
|
||||
'short_code': source.short_code,
|
||||
'status': source.status,
|
||||
},
|
||||
'target': {
|
||||
'id': target.id,
|
||||
'standard_name': target.standard_name,
|
||||
'short_code': target.short_code,
|
||||
'status': target.status,
|
||||
},
|
||||
'historical_references': get_customer_lifecycle_impact(source.id)['blockers'],
|
||||
'migrate': {
|
||||
'identifiers': len(source_identifiers) - duplicate_identifiers,
|
||||
'duplicate_identifiers': duplicate_identifiers,
|
||||
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=source.id).count(),
|
||||
'sites': db.session.query(ShippingCustomerSite.id).filter_by(customer_id=source.id).count(),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def merge_customer(
|
||||
source_customer_id: int,
|
||||
*,
|
||||
target_customer_id: int,
|
||||
confirmation_short_code: object,
|
||||
reason: object,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
原子归并重复客户,不改写历史业务号及其引用。
|
||||
|
||||
Args:
|
||||
source_customer_id: 待归并的源客户。
|
||||
target_customer_id: 承接未来识别配置的启用目标客户。
|
||||
confirmation_short_code: 必须匹配源客户当前简码。
|
||||
reason: 必填合并原因。
|
||||
actor_id: 当前管理员主键。
|
||||
Returns:
|
||||
源/目标快照、迁移统计与合并审计主键。
|
||||
"""
|
||||
merge_reason = str(reason or '').strip()
|
||||
confirmation = str(confirmation_short_code or '').strip().upper()
|
||||
if not merge_reason:
|
||||
raise ValidationError('Customer merge reason is required', code='SHIPPING.CUSTOMER_MERGE_REASON_REQUIRED')
|
||||
try:
|
||||
source, target = _load_customers_for_merge(source_customer_id, target_customer_id)
|
||||
_assert_merge_allowed(source, target)
|
||||
if confirmation != source.short_code:
|
||||
raise ValidationError(
|
||||
'Customer merge confirmation short code is invalid',
|
||||
code='SHIPPING.CUSTOMER_MERGE_CONFIRMATION_INVALID',
|
||||
details={'field': 'confirmation_short_code'},
|
||||
)
|
||||
|
||||
impact = get_customer_merge_impact(source.id, target.id)
|
||||
target_identifier_keys = {
|
||||
(item.identifier_type, item.normalized_value)
|
||||
for item in db.session.query(ShippingCustomerIdentifier)
|
||||
.filter_by(customer_id=target.id)
|
||||
.all()
|
||||
}
|
||||
moved_identifiers = 0
|
||||
duplicates: list[ShippingCustomerIdentifier] = []
|
||||
identifiers_to_move: list[ShippingCustomerIdentifier] = []
|
||||
for identifier in db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source.id).all():
|
||||
key = (identifier.identifier_type, identifier.normalized_value)
|
||||
if key in target_identifier_keys:
|
||||
duplicates.append(identifier)
|
||||
else:
|
||||
identifiers_to_move.append(identifier)
|
||||
target_identifier_keys.add(key)
|
||||
# 先实际删除与目标重复的证据,再更新其余证据的外键,避免唯一约束瞬时冲突。
|
||||
for identifier in duplicates:
|
||||
db.session.delete(identifier)
|
||||
db.session.flush()
|
||||
for identifier in identifiers_to_move:
|
||||
identifier.customer_id = target.id
|
||||
moved_identifiers += 1
|
||||
removed_duplicate_identifiers = len(duplicates)
|
||||
|
||||
external_refs = db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=source.id).all()
|
||||
for external_ref in external_refs:
|
||||
external_ref.customer_id = target.id
|
||||
|
||||
target_site_codes = {
|
||||
item.site_code for item in db.session.query(ShippingCustomerSite).filter_by(customer_id=target.id).all()
|
||||
}
|
||||
source_sites = db.session.query(ShippingCustomerSite).filter_by(customer_id=source.id).all()
|
||||
duplicate_site_codes = sorted({item.site_code for item in source_sites if item.site_code in target_site_codes})
|
||||
if duplicate_site_codes:
|
||||
raise ConflictError(
|
||||
'Customer sites conflict during merge',
|
||||
code='SHIPPING.CUSTOMER_MERGE_SITE_CONFLICT',
|
||||
details={'site_codes': duplicate_site_codes},
|
||||
)
|
||||
for site in source_sites:
|
||||
site.customer_id = target.id
|
||||
|
||||
source_snapshot = impact['source']
|
||||
target_snapshot = impact['target']
|
||||
merge = ShippingCustomerMerge(
|
||||
source_customer_id_snapshot=source.id,
|
||||
source_name_snapshot=source.standard_name,
|
||||
source_short_code_snapshot=source.short_code,
|
||||
target_customer_id_snapshot=target.id,
|
||||
target_name_snapshot=target.standard_name,
|
||||
target_short_code_snapshot=target.short_code,
|
||||
actor_id=actor_id,
|
||||
reason=merge_reason,
|
||||
detail_json={
|
||||
'historical_references': impact['historical_references'],
|
||||
'migrate': {
|
||||
'identifiers': moved_identifiers,
|
||||
'duplicate_identifiers': removed_duplicate_identifiers,
|
||||
'external_references': len(external_refs),
|
||||
'sites': len(source_sites),
|
||||
},
|
||||
},
|
||||
)
|
||||
source.status = 'merged'
|
||||
source.merged_into_customer_id = target.id
|
||||
source.updated_by_id = actor_id
|
||||
db.session.add_all([
|
||||
merge,
|
||||
ShippingCustomerLifecycleEvent(
|
||||
event_type='merged_source', customer_id_snapshot=source.id,
|
||||
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
|
||||
actor_id=actor_id, reason=merge_reason,
|
||||
detail_json={'target': target_snapshot},
|
||||
),
|
||||
ShippingCustomerLifecycleEvent(
|
||||
event_type='merged_target', customer_id_snapshot=target.id,
|
||||
customer_name_snapshot=target.standard_name, customer_short_code_snapshot=target.short_code,
|
||||
actor_id=actor_id, reason=merge_reason,
|
||||
detail_json={'source': source_snapshot},
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
return {
|
||||
'source': source_snapshot,
|
||||
'target': target_snapshot,
|
||||
'migrate': merge.detail_json['migrate'],
|
||||
'merge_id': merge.id,
|
||||
}
|
||||
except (ConflictError, NotFoundError, ValidationError):
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
@@ -16,7 +16,15 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier
|
||||
from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerLifecycleEvent,
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
is_public_email_domain,
|
||||
@@ -24,10 +32,54 @@ from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_short_code,
|
||||
)
|
||||
|
||||
CUSTOMER_STATUSES = frozenset({'active', 'inactive'})
|
||||
CUSTOMER_STATUSES = frozenset({'active', 'inactive', 'merged'})
|
||||
IDENTIFIER_STATUSES = frozenset({'pending', 'approved', 'disabled'})
|
||||
|
||||
|
||||
def _record_lifecycle_event(
|
||||
customer: ShippingCustomer,
|
||||
*,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
reason: str | None = None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入仅含客户快照的治理审计,避免生命周期日志反向阻断受控删除。"""
|
||||
db.session.add(ShippingCustomerLifecycleEvent(
|
||||
event_type=event_type,
|
||||
customer_id_snapshot=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
actor_id=actor_id,
|
||||
reason=reason,
|
||||
detail_json=detail or {},
|
||||
))
|
||||
|
||||
|
||||
def _required_change_reason(data: dict[str, Any]) -> str:
|
||||
"""返回高风险客户变更的必填审计原因,缺失时拒绝提交。"""
|
||||
reason = clean_text(data.get('reason'))
|
||||
if not reason:
|
||||
raise ValidationError(
|
||||
'Customer change reason is required',
|
||||
code='SHIPPING.CUSTOMER_CHANGE_REASON_REQUIRED',
|
||||
details={'field': 'reason'},
|
||||
)
|
||||
return reason
|
||||
|
||||
|
||||
def _identifier_snapshot(record: ShippingCustomerIdentifier) -> dict[str, Any]:
|
||||
"""生成识别证据变更前后对比所需的最小审计快照。"""
|
||||
return {
|
||||
'identifier_id': record.id,
|
||||
'identifier_type': record.identifier_type,
|
||||
'normalized_value': record.normalized_value,
|
||||
'status': record.status,
|
||||
'auto_match_allowed': bool(record.auto_match_allowed),
|
||||
'remark': record.remark,
|
||||
}
|
||||
|
||||
|
||||
def _strict_bool(value: Any, *, field: str) -> bool:
|
||||
"""只接受 JSON 布尔值,避免字符串 ``false`` 被 Python 判定为真。"""
|
||||
if isinstance(value, bool):
|
||||
@@ -83,6 +135,7 @@ def serialize_customer(
|
||||
'standard_name': record.standard_name,
|
||||
'short_code': record.short_code,
|
||||
'status': record.status,
|
||||
'merged_into_customer_id': record.merged_into_customer_id,
|
||||
'remark': record.remark,
|
||||
'created_by_id': record.created_by_id,
|
||||
'updated_by_id': record.updated_by_id,
|
||||
@@ -93,6 +146,8 @@ def serialize_customer(
|
||||
}
|
||||
if include_identifiers:
|
||||
payload['identifiers'] = [serialize_identifier(item) for item in record.identifiers]
|
||||
payload['external_refs'] = [serialize_external_ref(item) for item in record.external_refs]
|
||||
payload['sites'] = [serialize_site(item) for item in record.sites]
|
||||
return payload
|
||||
|
||||
|
||||
@@ -204,7 +259,7 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code)
|
||||
status = clean_text(data.get('status') or 'active').lower()
|
||||
if status not in CUSTOMER_STATUSES:
|
||||
if status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
record = ShippingCustomer(
|
||||
standard_name=standard_name,
|
||||
@@ -215,6 +270,13 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
updated_by_id=actor_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
_record_lifecycle_event(
|
||||
record,
|
||||
event_type='created',
|
||||
actor_id=actor_id,
|
||||
detail={'after': {'standard_name': standard_name, 'short_code': short_code, 'status': status}},
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
@@ -223,28 +285,81 @@ def create_customer(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def serialize_external_ref(record: ShippingCustomerExternalRef) -> dict[str, Any]:
|
||||
"""序列化客户在外部系统中的稳定客户编码。"""
|
||||
return {
|
||||
'id': record.id, 'customer_id': record.customer_id,
|
||||
'source_system': record.source_system, 'customer_code': record.legacy_customer_key,
|
||||
}
|
||||
|
||||
|
||||
def serialize_site(record: ShippingCustomerSite) -> dict[str, Any]:
|
||||
"""序列化送货站点及其名称/外部编码标识。"""
|
||||
return {
|
||||
'id': record.id, 'customer_id': record.customer_id, 'site_name': record.site_name,
|
||||
'site_code': record.site_code, 'address': record.address, 'city': record.city,
|
||||
'country': record.country, 'status': record.status, 'remark': record.remark,
|
||||
'identifiers': [{
|
||||
'id': item.id, 'identifier_type': item.identifier_type,
|
||||
'source_system': item.source_system, 'raw_value': item.raw_value,
|
||||
'normalized_value': item.normalized_value, 'status': item.status,
|
||||
} for item in record.identifiers],
|
||||
}
|
||||
|
||||
|
||||
def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新标准客户;历史业务号使用快照,不受简码修改影响。"""
|
||||
record = db.session.get(ShippingCustomer, customer_id)
|
||||
if record is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if record.status == 'merged':
|
||||
raise ConflictError('Merged customer cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
before = {
|
||||
'standard_name': record.standard_name,
|
||||
'short_code': record.short_code,
|
||||
'status': record.status,
|
||||
'remark': record.remark,
|
||||
}
|
||||
next_name = before['standard_name']
|
||||
next_short_code = before['short_code']
|
||||
next_status = before['status']
|
||||
next_remark = before['remark']
|
||||
if 'standard_name' in data:
|
||||
name = clean_text(data.get('standard_name'))
|
||||
if not name:
|
||||
raise ValidationError('Customer standard name is required', code='SHIPPING.CUSTOMER_NAME_REQUIRED')
|
||||
record.standard_name = name
|
||||
next_name = name
|
||||
if 'short_code' in data:
|
||||
short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(short_code, exclude_customer_id=customer_id)
|
||||
record.short_code = short_code
|
||||
next_short_code = normalize_short_code(data.get('short_code'))
|
||||
_assert_short_code_available(next_short_code, exclude_customer_id=customer_id)
|
||||
if 'status' in data:
|
||||
status = clean_text(data.get('status')).lower()
|
||||
if status not in CUSTOMER_STATUSES:
|
||||
next_status = clean_text(data.get('status')).lower()
|
||||
if next_status not in CUSTOMER_STATUSES - {'merged'}:
|
||||
raise ValidationError('Invalid customer status', code='SHIPPING.CUSTOMER_STATUS_INVALID')
|
||||
record.status = status
|
||||
if 'remark' in data:
|
||||
record.remark = clean_text(data.get('remark')) or None
|
||||
record.updated_by_id = actor_id
|
||||
next_remark = clean_text(data.get('remark')) or None
|
||||
after = {
|
||||
'standard_name': next_name,
|
||||
'short_code': next_short_code,
|
||||
'status': next_status,
|
||||
'remark': next_remark,
|
||||
}
|
||||
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
|
||||
if changes:
|
||||
high_risk_change = 'short_code' in changes or 'status' in changes
|
||||
change_reason = _required_change_reason(data) if high_risk_change else clean_text(data.get('reason')) or None
|
||||
record.standard_name = next_name
|
||||
record.short_code = next_short_code
|
||||
record.status = next_status
|
||||
record.remark = next_remark
|
||||
record.updated_by_id = actor_id
|
||||
_record_lifecycle_event(
|
||||
record,
|
||||
event_type='updated',
|
||||
actor_id=actor_id,
|
||||
reason=change_reason,
|
||||
detail={'changes': changes},
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
@@ -253,9 +368,9 @@ def update_customer(customer_id: int, data: dict[str, Any], *, actor_id: int | N
|
||||
return serialize_customer(record, include_identifiers=True)
|
||||
|
||||
|
||||
def deactivate_customer(customer_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
def deactivate_customer(customer_id: int, *, reason: object = None, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用客户;不物理删除,以保留业务单和识别审计。"""
|
||||
return update_customer(customer_id, {'status': 'inactive'}, actor_id=actor_id)
|
||||
return update_customer(customer_id, {'status': 'inactive', 'reason': reason}, actor_id=actor_id)
|
||||
|
||||
|
||||
def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
@@ -267,6 +382,8 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int |
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if customer.status == 'merged':
|
||||
raise ConflictError('Merged customer cannot receive identifiers', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
identifier_type = clean_text(data.get('identifier_type')).lower()
|
||||
raw_value = clean_text(data.get('raw_value') or data.get('identifier_value'))
|
||||
normalized_value = normalize_identifier(identifier_type, raw_value)
|
||||
@@ -297,6 +414,13 @@ def create_identifier(customer_id: int, data: dict[str, Any], *, actor_id: int |
|
||||
confirmed_at=datetime.utcnow() if status == 'approved' else None,
|
||||
)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
_record_lifecycle_event(
|
||||
customer,
|
||||
event_type='identifier_created',
|
||||
actor_id=actor_id,
|
||||
detail={'identifier': _identifier_snapshot(record)},
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
@@ -313,6 +437,10 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int
|
||||
record = db.session.get(ShippingCustomerIdentifier, identifier_id)
|
||||
if record is None:
|
||||
raise NotFoundError('Customer identifier not found', code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_FOUND')
|
||||
customer = db.session.get(ShippingCustomer, record.customer_id)
|
||||
if customer is None or customer.status == 'merged':
|
||||
raise ConflictError('Merged customer identifier cannot be edited', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
before = _identifier_snapshot(record)
|
||||
next_status = record.status
|
||||
if 'status' in data:
|
||||
next_status = clean_text(data.get('status')).lower()
|
||||
@@ -331,12 +459,101 @@ def update_identifier(identifier_id: int, data: dict[str, Any], *, actor_id: int
|
||||
'Only approved identifiers can enable automatic matching',
|
||||
code='SHIPPING.CUSTOMER_IDENTIFIER_NOT_APPROVED',
|
||||
)
|
||||
record.status = next_status
|
||||
record.auto_match_allowed = next_allowed
|
||||
if next_status == 'approved' and record.confirmed_at is None:
|
||||
record.confirmed_by_id = actor_id
|
||||
record.confirmed_at = datetime.utcnow()
|
||||
if 'remark' in data:
|
||||
record.remark = clean_text(data.get('remark')) or None
|
||||
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else record.remark
|
||||
after = {
|
||||
**before,
|
||||
'status': next_status,
|
||||
'auto_match_allowed': bool(next_allowed),
|
||||
'remark': next_remark,
|
||||
}
|
||||
changes = {key: {'before': before[key], 'after': after[key]} for key in before if before[key] != after[key]}
|
||||
if changes:
|
||||
requires_reason = 'status' in changes or 'auto_match_allowed' in changes
|
||||
change_reason = _required_change_reason(data) if requires_reason else clean_text(data.get('reason')) or None
|
||||
record.status = next_status
|
||||
record.auto_match_allowed = next_allowed
|
||||
if next_status == 'approved' and record.confirmed_at is None:
|
||||
record.confirmed_by_id = actor_id
|
||||
record.confirmed_at = datetime.utcnow()
|
||||
record.remark = next_remark
|
||||
_record_lifecycle_event(
|
||||
customer,
|
||||
event_type='identifier_updated',
|
||||
actor_id=actor_id,
|
||||
reason=change_reason,
|
||||
detail={'identifier_id': record.id, 'changes': changes},
|
||||
)
|
||||
db.session.commit()
|
||||
return serialize_identifier(record)
|
||||
|
||||
|
||||
def create_external_ref(customer_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""新增来源系统客户编码;同一来源和编码只能绑定一个标准客户。"""
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
source_system = clean_text(data.get('source_system')).upper()
|
||||
customer_code = clean_text(data.get('customer_code')).upper()
|
||||
if not source_system or not customer_code:
|
||||
raise ValidationError('Source system and customer code are required', code='SHIPPING.CUSTOMER_EXTERNAL_REF_INVALID')
|
||||
record = ShippingCustomerExternalRef(
|
||||
customer_id=customer.id, source_system=source_system, legacy_customer_key=customer_code,
|
||||
)
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Customer external reference already exists', code='SHIPPING.CUSTOMER_EXTERNAL_REF_CONFLICT') from exc
|
||||
return serialize_external_ref(record)
|
||||
|
||||
|
||||
def create_site(customer_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""新增客户送货站点,站点编码在同一标准客户内唯一。"""
|
||||
customer = db.session.get(ShippingCustomer, customer_id)
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
site_name = clean_text(data.get('site_name'))
|
||||
site_code = clean_text(data.get('site_code')).upper()
|
||||
if not site_name or not site_code:
|
||||
raise ValidationError('Site name and code are required', code='SHIPPING.CUSTOMER_SITE_INVALID')
|
||||
record = ShippingCustomerSite(
|
||||
customer_id=customer.id, site_name=site_name, site_code=site_code,
|
||||
address=clean_text(data.get('address')) or None, city=clean_text(data.get('city')) or None,
|
||||
country=clean_text(data.get('country')) or None, status='active',
|
||||
remark=clean_text(data.get('remark')) or None, created_by_id=actor_id, updated_by_id=actor_id,
|
||||
)
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Customer site already exists', code='SHIPPING.CUSTOMER_SITE_CONFLICT') from exc
|
||||
return serialize_site(record)
|
||||
|
||||
|
||||
def create_site_identifier(site_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""为送货站点新增名称别名、地址或带来源系统的外部站点编码。"""
|
||||
site = db.session.get(ShippingCustomerSite, site_id)
|
||||
if site is None:
|
||||
raise NotFoundError('Customer site not found', code='SHIPPING.CUSTOMER_SITE_NOT_FOUND')
|
||||
identifier_type = clean_text(data.get('identifier_type')).lower()
|
||||
if identifier_type not in {'name_alias', 'external_code', 'address'}:
|
||||
raise ValidationError('Site identifier type is invalid', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
|
||||
raw_value = clean_text(data.get('identifier_value'))
|
||||
source_system = clean_text(data.get('source_system')).upper() if identifier_type == 'external_code' else ''
|
||||
if not raw_value or (identifier_type == 'external_code' and not source_system):
|
||||
raise ValidationError('Site identifier is incomplete', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_INVALID')
|
||||
normalized = normalize_identifier('name_alias', raw_value) if identifier_type == 'name_alias' else raw_value.upper()
|
||||
record = ShippingCustomerSiteIdentifier(
|
||||
site_id=site.id, identifier_type=identifier_type, source_system=source_system,
|
||||
raw_value=raw_value, normalized_value=normalized, status='approved',
|
||||
remark=clean_text(data.get('remark')) or None,
|
||||
)
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except IntegrityError as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Site identifier already exists', code='SHIPPING.CUSTOMER_SITE_IDENTIFIER_CONFLICT') from exc
|
||||
return serialize_site(site)
|
||||
@@ -0,0 +1,855 @@
|
||||
"""
|
||||
services/admin/shipping_inventory_service.py
|
||||
|
||||
用途:管理库存源、RPA Profile、路由规则和外部系统映射主数据。
|
||||
依赖:db、库存配置模型、凭据加密、Source/Profile 校验、统一 AppError。
|
||||
逻辑:管理 API 委托本服务完成校验和事务;运行期库存匹配不从本服务读取明文凭据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingTask,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingExcelTemplate,
|
||||
)
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.routing_facts import ALLOWED_SYSTEM_FACT_KEYS
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
|
||||
|
||||
def _text(data: dict[str, Any], field: str, *, required: bool = False) -> str | None:
|
||||
value = str(data.get(field) or '').strip()
|
||||
if required and not value:
|
||||
raise ValidationError(f'{field} is required', code='VALIDATION.INVALID_PARAM', details={'field': field})
|
||||
return value or None
|
||||
|
||||
|
||||
def _bool(data: dict[str, Any], field: str, default: bool = True) -> bool:
|
||||
value = data.get(field, default)
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError(f'{field} must be a boolean', details={'field': field})
|
||||
return value
|
||||
|
||||
|
||||
def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
"""读取并复制对象型 JSON 配置。
|
||||
|
||||
Args:
|
||||
data: 管理 API 的请求载荷。
|
||||
field: 只允许 JSON object 的字段名。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 空值规范化为空对象后的可写入配置。
|
||||
|
||||
Raises:
|
||||
ValidationError: 字段不是 JSON object。
|
||||
"""
|
||||
value = data.get(field, {})
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(f'{field} must be an object', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
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', {})
|
||||
if not isinstance(value, dict) or set(value) - {'auth_mode'}:
|
||||
raise ValidationError('login_config_json is invalid', code='SHIPPING.RPA_PROFILE_CONFIG_INVALID')
|
||||
auth_mode = str(value.get('auth_mode') or 'password').strip().lower()
|
||||
if auth_mode != 'password':
|
||||
raise ValidationError(
|
||||
'Only password authentication is currently supported',
|
||||
code='SHIPPING.RPA_PROFILE_CONFIG_INVALID',
|
||||
)
|
||||
return {'auth_mode': auth_mode}
|
||||
|
||||
|
||||
def _validate_report_path(connector_type: str, report_path: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验 DBS 四级报表路径,防止技术选择器混入业务配置。"""
|
||||
allowed = {'program_group', 'program_label', 'report_group', 'report_name'}
|
||||
if set(report_path) - allowed:
|
||||
raise ValidationError('report_path_json contains unsupported fields', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
normalized = {key: str(value or '').strip() for key, value in report_path.items()}
|
||||
if connector_type == 'dbs':
|
||||
missing = [key for key in allowed if not normalized.get(key)]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'DBS inventory source requires a complete report path',
|
||||
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'missing': sorted(missing)},
|
||||
)
|
||||
elif normalized:
|
||||
raise ValidationError(
|
||||
'Only DBS inventory sources can define report_path_json',
|
||||
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID',
|
||||
)
|
||||
return {key: normalized[key] for key in allowed if normalized.get(key)}
|
||||
|
||||
|
||||
def _validate_query_parameters(data: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Source 的可视化查询参数列表,禁止保存 selector 等 Driver 实现细节。"""
|
||||
raw = data.get('query_parameters_json', [])
|
||||
if not isinstance(raw, list):
|
||||
raise ValidationError('query_parameters_json must be a list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
result: list[dict[str, Any]] = []
|
||||
seen_names: set[str] = set()
|
||||
allowed = {'name', 'mode', 'values', 'required', 'select_all', 'joiner'}
|
||||
for index, item in enumerate(raw):
|
||||
if not isinstance(item, dict) or set(item) - allowed:
|
||||
raise ValidationError(
|
||||
'query parameter contains unsupported fields',
|
||||
code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID', details={'index': index},
|
||||
)
|
||||
name = str(item.get('name') or '').strip()
|
||||
mode = str(item.get('mode') or 'single').strip().lower()
|
||||
values = item.get('values', [])
|
||||
required = item.get('required', False)
|
||||
select_all = item.get('select_all', False)
|
||||
if not name or name.lower() in seen_names or mode not in {'single', 'multi_text', 'multi_select'}:
|
||||
raise ValidationError('query parameter name or mode is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(values, list) or any(not isinstance(value, str) for value in values):
|
||||
raise ValidationError('query parameter values must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
if not isinstance(required, bool) or not isinstance(select_all, bool):
|
||||
raise ValidationError('query parameter flags must be boolean', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
normalized_values = [value.strip() for value in values if value.strip()]
|
||||
if required and not normalized_values and not select_all:
|
||||
raise ValidationError('required query parameter needs values or select_all', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
if select_all and mode != 'multi_select':
|
||||
raise ValidationError('select_all only applies to multi_select', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
parameter: dict[str, Any] = {
|
||||
'name': name, 'mode': mode, 'values': normalized_values,
|
||||
'required': required, 'select_all': select_all,
|
||||
}
|
||||
if mode == 'multi_text':
|
||||
joiner = str(item.get('joiner') or ',').strip()
|
||||
if not joiner:
|
||||
raise ValidationError('multi_text query parameter needs joiner', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
parameter['joiner'] = joiner
|
||||
seen_names.add(name.lower())
|
||||
result.append(parameter)
|
||||
return result
|
||||
|
||||
|
||||
def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'connector_type': profile.connector_type, 'login_url': profile.login_url,
|
||||
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
|
||||
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
|
||||
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
|
||||
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _mask(ciphertext: str | None) -> str | None:
|
||||
"""凭据密文不支持反向展示;仅以配置状态提示管理员。"""
|
||||
return 'configured' if ciphertext else None
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出 Profile 元数据,不返回可恢复的凭据。"""
|
||||
return [_profile_payload(item) for item in ShippingRpaProfile.query.order_by(ShippingRpaProfile.profile_code).all()]
|
||||
|
||||
|
||||
def delete_profile(profile_id: int) -> None:
|
||||
"""删除未绑定库存源的错误连接配置,保留已使用连接的可追溯性。"""
|
||||
profile = db.session.get(ShippingRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
if ShippingInventorySource.query.filter_by(rpa_profile_id=profile.id).count():
|
||||
raise ConflictError('RPA Profile is referenced by inventory sources', code='SHIPPING.RPA_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新货代登录连接;密码留空表示保留既有密文。"""
|
||||
profile = db.session.get(ShippingRpaProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
|
||||
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
|
||||
profile.display_name = str(_text(data, 'display_name', required=True))
|
||||
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
profile.login_url = str(_text(data, 'login_url', required=True))
|
||||
profile.login_config_json = _validate_profile_login_config(data)
|
||||
profile.enabled = _bool(data, 'enabled', bool(profile.enabled) if profile_id else True)
|
||||
if not profile.enabled and any(source.enabled for source in profile.sources):
|
||||
raise ConflictError(
|
||||
'Disable inventory sources before disabling their RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLE_BLOCKED',
|
||||
)
|
||||
username = _text(data, 'username')
|
||||
password = _text(data, 'password')
|
||||
if username is not None:
|
||||
profile.username_ciphertext = encrypt_credential(username)
|
||||
if password is not None:
|
||||
profile.password_ciphertext = encrypt_credential(password)
|
||||
if username is not None or password is not None:
|
||||
profile.credential_updated_at = datetime.utcnow()
|
||||
profile.updated_by = actor_id
|
||||
if profile_id:
|
||||
profile.config_version += 1
|
||||
if not profile_id:
|
||||
profile.created_by = actor_id
|
||||
db.session.add(profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Profile code already exists', code='SHIPPING.RPA_PROFILE_CONFLICT') from exc
|
||||
return _profile_payload(profile)
|
||||
|
||||
|
||||
def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""序列化库存站点及其是否满足正式启用前置条件。"""
|
||||
return {
|
||||
'id': source.id, 'source_code': source.source_code, 'display_name': source.display_name,
|
||||
'connector_type': source.connector_type, 'rpa_profile_id': source.rpa_profile_id,
|
||||
'parsing_profile_id': source.parsing_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode, 'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'report_path_json': source.report_path_json or {}, 'query_parameters_json': source.query_parameters_json or [],
|
||||
'match_aliases_json': source.match_aliases_json or [],
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds, 'enabled': bool(source.enabled),
|
||||
'config_version': source.config_version, 'created_at': _iso(source.created_at), 'updated_at': _iso(source.updated_at),
|
||||
'activation': get_source_activation_status(source),
|
||||
}
|
||||
|
||||
|
||||
def list_sources() -> list[dict[str, Any]]:
|
||||
"""列出库存源及其稳定业务配置。"""
|
||||
return [_source_payload(item) for item in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all()]
|
||||
|
||||
|
||||
def delete_source(source_id: int) -> None:
|
||||
"""删除未参与映射、快照或规则的错误库存源,避免破坏历史路由身份。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
source_code = str(source.source_code or '').strip().upper()
|
||||
has_mapping = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id).count() > 0
|
||||
has_snapshot = ShippingInventoryFile.query.filter_by(source_code=source_code).count() > 0
|
||||
has_rule = any(
|
||||
source_code in {str(code).strip().upper() for code in candidates}
|
||||
for rule in ShippingInventoryRoutingRule.query.all()
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = ShippingTask.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
for source_codes in [(run.api_request_json or {}).get('source_codes', [])]
|
||||
if isinstance(source_codes, list)
|
||||
)
|
||||
if has_mapping or has_snapshot or has_rule or has_task or has_export_run:
|
||||
raise ConflictError('Inventory Source has operational references', code='SHIPPING.INVENTORY_SOURCE_DELETE_BLOCKED')
|
||||
db.session.delete(source)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _snapshot_payload(snapshot: ShippingInventoryFile) -> dict[str, Any]:
|
||||
"""投影库存快照的管理端只读行,不暴露存储路径或库存明细。"""
|
||||
return {
|
||||
'id': snapshot.id, 'inventory_file_no': snapshot.inventory_file_no,
|
||||
'source_code': snapshot.source_code, 'warehouse_id': snapshot.warehouse_id,
|
||||
'snapshot_status': snapshot.snapshot_status, 'identity_status': snapshot.identity_status,
|
||||
'line_count': snapshot.line_count, 'share_mode': snapshot.share_mode,
|
||||
'exported_at': _iso(snapshot.exported_at), 'expires_at': _iso(snapshot.expires_at),
|
||||
'rpa_run_no': snapshot.rpa_run_no, 'schedule_run_id': snapshot.schedule_run_id,
|
||||
'source_file_name': snapshot.source_file_name, 'created_at': _iso(snapshot.created_at),
|
||||
'download_available': bool(snapshot.storage_path and not str(snapshot.storage_path).startswith('failed://')),
|
||||
'error_message': (snapshot.schema_preview_json or {}).get('error') if snapshot.snapshot_status == 'failed' else None,
|
||||
}
|
||||
|
||||
|
||||
def list_snapshots(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出最新库存快照,供管理员确认当前可用的库存文件。"""
|
||||
rows = ShippingInventoryFile.query.order_by(
|
||||
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
return [_snapshot_payload(row) for row in rows]
|
||||
|
||||
|
||||
def get_snapshot_download(snapshot_id: int) -> tuple[str, str]:
|
||||
"""返回管理员可下载的库存快照路径及安全文件名。
|
||||
|
||||
Args:
|
||||
snapshot_id: 库存快照主键。
|
||||
|
||||
Returns:
|
||||
本地托管文件绝对路径和面向下载的文件名。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 快照不存在或托管文件已不存在。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
snapshot = db.session.get(ShippingInventoryFile, snapshot_id)
|
||||
if snapshot is None:
|
||||
raise NotFoundError('Inventory snapshot not found', code='SHIPPING.INVENTORY_SNAPSHOT_NOT_FOUND')
|
||||
path = Path(str(snapshot.storage_path or '')).resolve()
|
||||
if not str(snapshot.storage_path or '') or str(snapshot.storage_path).startswith('failed://') or not path.is_file():
|
||||
raise NotFoundError('Inventory snapshot file not found', code='SHIPPING.INVENTORY_SNAPSHOT_FILE_NOT_FOUND')
|
||||
filename = str(snapshot.source_file_name or f'{snapshot.inventory_file_no}{path.suffix or ".xlsx"}')
|
||||
return str(path), filename
|
||||
|
||||
|
||||
def list_export_records(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""列出 RPA 导出记录,合并已归档文件与排程失败/跳过结果。"""
|
||||
file_rows = ShippingInventoryFile.query.filter(
|
||||
ShippingInventoryFile.rpa_run_no.is_not(None),
|
||||
).order_by(
|
||||
ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc(),
|
||||
).limit(max(1, min(limit, 200))).all()
|
||||
records = [_snapshot_payload(row) for row in file_rows]
|
||||
known_identities = {
|
||||
(str(item.get('rpa_run_no') or ''), str(item.get('source_code') or ''), str(item.get('warehouse_id') or ''))
|
||||
for item in records
|
||||
}
|
||||
|
||||
# 失败或跳过的 RPA 执行不会生成库存文件,必须从 ScheduleRun 补齐审计记录。
|
||||
schedule_runs = ScheduleRun.query.join(ScheduleTask).filter(
|
||||
ScheduleTask.platform_api_path == 'shipping-inventory-rpa',
|
||||
).order_by(ScheduleRun.created_at.desc()).limit(max(1, min(limit, 200))).all()
|
||||
for run in schedule_runs:
|
||||
response = run.api_response_json if isinstance(run.api_response_json, dict) else {}
|
||||
request_data = run.api_request_json if isinstance(run.api_request_json, dict) else {}
|
||||
run_no = str(response.get('run_no') or request_data.get('run_no') or run.run_no or '').strip()
|
||||
items: list[tuple[str, dict[str, Any]]] = []
|
||||
for status, key in (('skipped', 'skipped'), ('failed', 'failed')):
|
||||
for item in response.get(key) if isinstance(response.get(key), list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append((status, item))
|
||||
if not items and run.status in {'queued', 'running'}:
|
||||
pending = (run.response_summary_json or {}).get('pending_details', [])
|
||||
for item in pending if isinstance(pending, list) else []:
|
||||
if isinstance(item, dict):
|
||||
items.append(('awaiting_rpa', item))
|
||||
if not items and run.status in {'failed', 'partial_failed'}:
|
||||
for source_code in request_data.get('source_codes') if isinstance(request_data.get('source_codes'), list) else []:
|
||||
items.append(('failed', {'source_code': source_code, 'error_message': run.error_message}))
|
||||
for status, item in items:
|
||||
source_code = str(item.get('source_code') or '').strip()
|
||||
warehouse_id = str(item.get('warehouse_id') or '').strip()
|
||||
identity = (run_no, source_code, warehouse_id)
|
||||
if identity in known_identities:
|
||||
continue
|
||||
known_identities.add(identity)
|
||||
records.append({
|
||||
'id': f'schedule-{run.id}-{status}-{source_code}-{warehouse_id}',
|
||||
'inventory_file_no': None,
|
||||
'source_code': source_code or None,
|
||||
'warehouse_id': warehouse_id or None,
|
||||
'snapshot_status': status,
|
||||
'export_status': status,
|
||||
'identity_status': None,
|
||||
'line_count': 0,
|
||||
'share_mode': None,
|
||||
'exported_at': _iso(run.finished_at or run.created_at),
|
||||
'expires_at': None,
|
||||
'rpa_run_no': run_no or None,
|
||||
'schedule_run_id': run.id,
|
||||
'source_file_name': None,
|
||||
'created_at': _iso(run.created_at),
|
||||
'error_message': str(item.get('error_message') or item.get('error') or run.error_message or '')[:500] or None,
|
||||
})
|
||||
records.sort(key=lambda item: str(item.get('exported_at') or item.get('created_at') or ''), reverse=True)
|
||||
return records[:max(1, min(limit, 200))]
|
||||
|
||||
|
||||
def _enabled_external_mapping_exists(source: ShippingInventorySource, warehouse_id: str | None) -> bool:
|
||||
"""判断已确认的货代仓库是否已有精确映射或库存源默认映射。"""
|
||||
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
|
||||
warehouse = str(warehouse_id or '').strip().upper()
|
||||
if warehouse and query.filter_by(freight_warehouse_id=warehouse).first() is not None:
|
||||
return True
|
||||
return query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first() is not None
|
||||
|
||||
|
||||
def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""复核当前测试文件与已绑定方案,返回解析和仓库映射的启用前置条件。"""
|
||||
missing: list[str] = []
|
||||
details: dict[str, Any] = {'sample_warehouses': []}
|
||||
confirmed_test = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source.id,
|
||||
status='completed',
|
||||
source_config_version=source.config_version,
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
|
||||
if not confirmed_test or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0):
|
||||
return ['configuration_test'], details
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
|
||||
profile = source.parsing_profile
|
||||
if analysis is None or profile is None:
|
||||
return ['configuration_test'], details
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
selected = next((item for item in candidates if isinstance(item, dict)
|
||||
and item.get('sheet_name') == definition.get('sheet_name')
|
||||
and item.get('header_row_index') == definition.get('header_row_index')), None)
|
||||
headers = [str(item).strip() for item in (selected or {}).get('headers', []) if str(item).strip()]
|
||||
duplicate_headers = {
|
||||
str(item.get('header') or '').strip()
|
||||
for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and item.get('duplicate')
|
||||
}
|
||||
mapping = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
runtime_mapping, catalog = runtime_field_mapping(mapping)
|
||||
usages = usage_field_ids()
|
||||
mapped_ids = set(runtime_mapping)
|
||||
match_fields = mapped_ids & usages.get('match_identity', set())
|
||||
quantity_fields = mapped_ids & usages.get('inventory_quantity', set())
|
||||
required_fields = match_fields | quantity_fields
|
||||
if (
|
||||
not selected
|
||||
or not match_fields
|
||||
or len(quantity_fields) != 1
|
||||
or not required_fields <= set(runtime_mapping)
|
||||
or any(str(runtime_mapping.get(field) or '').strip() not in headers for field in required_fields)
|
||||
or any(str(value or '').strip() in duplicate_headers for value in mapping.values())
|
||||
or not int((selected or {}).get('sample_row_count') or 0)
|
||||
):
|
||||
missing.append('parsing_validation')
|
||||
return missing, details
|
||||
column_by_header = {
|
||||
str(item.get('header') or '').strip(): item
|
||||
for item in (selected or {}).get('columns', []) if isinstance(item, dict)
|
||||
}
|
||||
quantity_codes = quantity_fields
|
||||
quantity_column = next((
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in quantity_codes
|
||||
), {})
|
||||
identifier_columns = [
|
||||
column_by_header.get(str(runtime_mapping.get(field) or '').strip(), {})
|
||||
for field in match_fields
|
||||
]
|
||||
if (
|
||||
quantity_column.get('inferred_type') != 'number'
|
||||
or any(not item.get('sample_values') for item in identifier_columns)
|
||||
):
|
||||
missing.append('parsing_validation')
|
||||
return missing, details
|
||||
if source.warehouse_resolution_mode == 'fixed':
|
||||
if not _enabled_external_mapping_exists(source, source.fixed_warehouse_id):
|
||||
missing.append('warehouse_mapping')
|
||||
return missing, details
|
||||
warehouse_codes = mapped_ids & usages.get('warehouse_identity', set())
|
||||
if len(warehouse_codes) != 1:
|
||||
missing.append('warehouse_identification')
|
||||
return missing, details
|
||||
warehouse_header = next((str(runtime_mapping.get(field) or '').strip() for field in warehouse_codes), '')
|
||||
if not warehouse_header or warehouse_header not in headers or warehouse_header in duplicate_headers:
|
||||
missing.append('warehouse_identification')
|
||||
return missing, details
|
||||
column = next((item for item in (selected or {}).get('columns', [])
|
||||
if isinstance(item, dict) and str(item.get('header') or '').strip() == warehouse_header), {})
|
||||
sample_warehouses = sorted({str(value).strip().upper() for value in column.get('sample_values', []) if str(value).strip()})
|
||||
details['sample_warehouses'] = sample_warehouses
|
||||
if not sample_warehouses or any(not _enabled_external_mapping_exists(source, warehouse) for warehouse in sample_warehouses):
|
||||
missing.append('warehouse_mapping')
|
||||
return missing, details
|
||||
|
||||
|
||||
def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
|
||||
"""确认发货模板引用的库存字段均由当前解析方案提供,避免启用后才发现字段断链。"""
|
||||
template = source.excel_template
|
||||
profile = source.parsing_profile
|
||||
if template is None or profile is None:
|
||||
return []
|
||||
definition = template.definition_json if isinstance(template.definition_json, dict) else {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
inventory_fields = {str(field_id) for field_id in (profile_definition.get('field_mapping') or {}).keys()}
|
||||
invalid = any(
|
||||
isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '') not in inventory_fields
|
||||
for item in mappings
|
||||
)
|
||||
return ['template_validation'] if not mappings or invalid else []
|
||||
|
||||
|
||||
def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]:
|
||||
"""计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。"""
|
||||
missing: list[str] = []
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
missing.append('rpa_profile')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
missing.append('parsing_profile')
|
||||
if source.excel_template is None or source.excel_template.status != 'published':
|
||||
missing.append('excel_template')
|
||||
else:
|
||||
missing.extend(_template_validation_missing(source))
|
||||
validation_missing, validation_details = _test_analysis_validation(source)
|
||||
missing.extend(validation_missing)
|
||||
return missing, validation_details
|
||||
|
||||
|
||||
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""返回库存站点启用检查结果,供管理端展示下一步操作。"""
|
||||
missing, validation = _activation_missing_requirements(source)
|
||||
return {
|
||||
'ready': not missing,
|
||||
'missing_requirements': missing,
|
||||
'validation': validation,
|
||||
}
|
||||
|
||||
|
||||
def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""启用完成验证的库存站点;未通过任一前置条件时保持停用。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
status = get_source_activation_status(source)
|
||||
if not status['ready']:
|
||||
raise ConflictError(
|
||||
'Inventory Source is not ready for activation',
|
||||
code='SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED',
|
||||
details=status,
|
||||
)
|
||||
source.enabled = True
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""停用库存站点,保留其解析方案和历史运行审计以便后续重新测试。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
source.enabled = False
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
db.session.commit()
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def save_source(
|
||||
data: dict[str, Any], *, actor_id: int | None, source_id: int | None = None,
|
||||
allow_enable_transition: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""保存库存站点基础配置;管理 API 不允许通过普通保存直接启用站点。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id) if source_id else None
|
||||
if source_id and source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
try:
|
||||
profile_id = int(data.get('rpa_profile_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('rpa_profile_id is required') from exc
|
||||
profile = db.session.get(ShippingRpaProfile, profile_id)
|
||||
if profile is None:
|
||||
raise ValidationError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
|
||||
requested_enabled = _bool(data, 'enabled', bool(source.enabled) if source_id else False)
|
||||
if not allow_enable_transition:
|
||||
# 普通保存不承担状态切换:首次一律停用,已启用站点保留当前状态。
|
||||
enabled = bool(source.enabled) if source is not None else False
|
||||
else:
|
||||
enabled = requested_enabled
|
||||
if enabled and not profile.enabled:
|
||||
raise ValidationError(
|
||||
'Enabled Inventory Source requires an enabled RPA Profile',
|
||||
code='SHIPPING.RPA_PROFILE_DISABLED',
|
||||
)
|
||||
parsing_profile_id = data.get('parsing_profile_id')
|
||||
parsing_profile = db.session.get(ShippingInventoryParsingProfile, int(parsing_profile_id)) if str(parsing_profile_id or '').isdigit() else None
|
||||
if parsing_profile_id not in (None, '', 0, '0') and (parsing_profile is None or parsing_profile.status != 'published'):
|
||||
raise ValidationError('parsing_profile_id must reference a published profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
if enabled and parsing_profile is None:
|
||||
raise ValidationError('published parsing_profile_id is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
excel_template_id = data.get('excel_template_id')
|
||||
excel_template = db.session.get(ShippingExcelTemplate, int(excel_template_id)) if str(excel_template_id or '').isdigit() else None
|
||||
if excel_template_id not in (None, '', 0, '0') and (excel_template is None or excel_template.status != 'published'):
|
||||
raise ValidationError('excel_template_id must reference a published template', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
if enabled and excel_template is None:
|
||||
raise ValidationError('published excel_template_id is required', code='SHIPPING.EXCEL_TEMPLATE_REQUIRED')
|
||||
is_new = source is None
|
||||
source = source or ShippingInventorySource(
|
||||
source_code='', display_name='', connector_type='', warehouse_resolution_mode='fixed',
|
||||
)
|
||||
source.source_code = str(_text(data, 'source_code', required=True)).upper()
|
||||
source.display_name = str(_text(data, 'display_name', required=True))
|
||||
source.connector_type = str(_text(data, 'connector_type', required=True)).lower()
|
||||
source.rpa_profile = profile
|
||||
source.parsing_profile = parsing_profile
|
||||
source.excel_template = excel_template
|
||||
source.warehouse_resolution_mode = str(_text(data, 'warehouse_resolution_mode', required=True)).lower()
|
||||
source.fixed_warehouse_id = _text(data, 'fixed_warehouse_id')
|
||||
source.report_path_json = _validate_report_path(source.connector_type, _json_object(data, 'report_path_json'))
|
||||
source.query_parameters_json = _validate_query_parameters(data)
|
||||
source.match_aliases_json = _json_string_list(data, 'match_aliases_json')
|
||||
source.snapshot_ttl_seconds = int(data.get('snapshot_ttl_seconds') or 86400)
|
||||
source.enabled = enabled
|
||||
source.updated_by = actor_id
|
||||
if source_id:
|
||||
source.config_version += 1
|
||||
if is_new:
|
||||
source.created_by = actor_id
|
||||
db.session.add(source)
|
||||
validate_source_profile(source, profile)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ValidationError('Invalid Inventory Source configuration', code='SHIPPING.INVENTORY_SOURCE_INVALID') from exc
|
||||
return _source_payload(source)
|
||||
|
||||
|
||||
def _rule_payload(rule: ShippingInventoryRoutingRule) -> dict[str, Any]:
|
||||
return {
|
||||
'id': rule.id, 'rule_code': rule.rule_code, 'rule_name': rule.rule_name, 'scope': rule.scope,
|
||||
'priority': rule.priority, 'match_mode': rule.match_mode, 'status': rule.status,
|
||||
'action_type': rule.action_type, 'action_payload_json': rule.action_payload_json or {}, 'version': rule.version,
|
||||
'conditions': [{'source_kind': c.source_kind, 'order_field_id': c.order_field_id,
|
||||
'system_fact_key': c.system_fact_key, 'operator': c.operator, 'expected_value_json': c.expected_value_json,
|
||||
'condition_group': c.condition_group, 'sequence': c.sequence} for c in rule.conditions],
|
||||
}
|
||||
|
||||
|
||||
def _validate_rule_condition_expected(operator: str, value: Any) -> Any:
|
||||
"""按匹配符号规范化期望值,避免自由 JSON 在运行期才暴露配置错误。"""
|
||||
if operator in {'is_empty', 'is_not_empty'}:
|
||||
return None
|
||||
if operator in {'in', 'not_in'}:
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError('List operator requires a string list', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
normalized = [str(item).strip() for item in value if str(item).strip()]
|
||||
if not normalized:
|
||||
raise ValidationError('List operator requires at least one value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
return normalized
|
||||
if operator in {'numeric_length', 'string_length'}:
|
||||
try:
|
||||
length = int(value)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Length operator requires an integer', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID') from exc
|
||||
if length < 0:
|
||||
raise ValidationError('Length must not be negative', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
return length
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise ValidationError('Routing condition requires an expected value', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
return value.strip()
|
||||
|
||||
|
||||
def list_rules() -> list[dict[str, Any]]:
|
||||
"""列出规则及条件,用于草稿编辑和已发布规则查看。"""
|
||||
return [_rule_payload(item) for item in ShippingInventoryRoutingRule.query.order_by(ShippingInventoryRoutingRule.priority.desc()).all()]
|
||||
|
||||
|
||||
def delete_draft_rule(rule_id: int) -> None:
|
||||
"""删除从未发布的草稿规则;发布过的规则必须归档以保留审计定义。"""
|
||||
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be deleted', code='SHIPPING.INVENTORY_RULE_DELETE_BLOCKED')
|
||||
db.session.delete(rule)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def retire_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""归档已发布规则,使其不再参与新路由,同时保留已发布版本。"""
|
||||
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
if rule.status != 'published':
|
||||
raise ConflictError('Only published routing rules can be retired', code='SHIPPING.INVENTORY_RULE_RETIRE_INVALID')
|
||||
rule.status = 'retired'
|
||||
rule.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None = None) -> dict[str, Any]:
|
||||
"""保存草稿规则;发布规则必须以新版本创建,避免篡改历史定义。"""
|
||||
if rule_id:
|
||||
current = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if current is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
if current.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be updated', code='SHIPPING.INVENTORY_RULE_IMMUTABLE')
|
||||
rule = current if rule_id else ShippingInventoryRoutingRule(
|
||||
rule_code='', rule_name='', scope='', action_type='', action_payload_json={}
|
||||
)
|
||||
rule.rule_code = str(_text(data, 'rule_code', required=True)).upper()
|
||||
rule.rule_name = str(_text(data, 'rule_name', required=True))
|
||||
rule.scope = str(_text(data, 'scope', required=True)).lower()
|
||||
rule.priority = int(data.get('priority') or 0)
|
||||
rule.match_mode = str(data.get('match_mode') or 'all').lower()
|
||||
rule.status = 'draft'
|
||||
rule.action_type = str(_text(data, 'action_type', required=True)).lower()
|
||||
rule.action_payload_json = data.get('action_payload_json') if isinstance(data.get('action_payload_json'), dict) else {}
|
||||
rule.version = int(data.get('version') or 1)
|
||||
if not rule_id:
|
||||
rule.created_by = actor_id
|
||||
rule.updated_by = actor_id
|
||||
if rule.action_type not in ALLOWED_ACTIONS or rule.scope not in {'task', 'line'} or rule.match_mode not in {'all', 'any'}:
|
||||
raise ValidationError('Invalid routing rule metadata', code='SHIPPING.INVENTORY_RULE_INVALID')
|
||||
conditions = data.get('conditions')
|
||||
if not isinstance(conditions, list) or not conditions:
|
||||
raise ValidationError('Routing rule requires conditions', code='SHIPPING.INVENTORY_RULE_CONDITIONS_REQUIRED')
|
||||
# 草稿更新在同一版本内替换条件;发布后不可原地修改。
|
||||
if rule_id:
|
||||
db.session.query(ShippingInventoryRoutingRuleCondition).filter_by(rule_id=rule.id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.expire(rule, ['conditions'])
|
||||
for index, item in enumerate(conditions, start=1):
|
||||
if not isinstance(item, dict) or item.get('operator') not in ALLOWED_OPERATORS:
|
||||
raise ValidationError('Routing rule condition is not allowed', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
source_kind = str(item.get('source_kind') or 'order_field')
|
||||
order_field_id = str(item.get('order_field_id') or '') or None
|
||||
system_fact_key = str(item.get('system_fact_key') or '') or None
|
||||
field = db.session.get(ShippingOrderField, order_field_id) if order_field_id else None
|
||||
if source_kind == 'order_field':
|
||||
if field is None or field.status != 'active' or field.scope != rule.scope.replace('task', 'header'):
|
||||
raise ValidationError('Routing order field is invalid for rule scope', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
system_fact_key = None
|
||||
elif source_kind == 'system_fact':
|
||||
if system_fact_key not in ALLOWED_SYSTEM_FACT_KEYS:
|
||||
raise ValidationError('Routing system fact is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
order_field_id = None
|
||||
else:
|
||||
raise ValidationError('Routing condition source is invalid', code='SHIPPING.INVENTORY_RULE_CONDITION_INVALID')
|
||||
operator = str(item['operator'])
|
||||
rule.conditions.append(ShippingInventoryRoutingRuleCondition(
|
||||
condition_group=int(item.get('condition_group') or 1), source_kind=source_kind,
|
||||
order_field_id=order_field_id, system_fact_key=system_fact_key,
|
||||
operator=operator, expected_value_json=_validate_rule_condition_expected(
|
||||
operator, item.get('expected_value_json'),
|
||||
), sequence=index,
|
||||
))
|
||||
if not rule_id:
|
||||
db.session.add(rule)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Routing rule code and version already exist', code='SHIPPING.INVENTORY_RULE_CONFLICT') from exc
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布草稿并写入不可变规则定义快照。"""
|
||||
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
if rule.status != 'draft':
|
||||
raise ConflictError('Only draft routing rules can be published', code='SHIPPING.INVENTORY_RULE_PUBLISH_INVALID')
|
||||
if rule.action_type in {'add_source_candidates', 'exclude_source_candidates'}:
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
source_codes = {
|
||||
str(code or '').strip().upper()
|
||||
for code in payload.get('source_codes', [])
|
||||
if str(code or '').strip()
|
||||
}
|
||||
enabled_codes = {
|
||||
str(code).strip().upper()
|
||||
for (code,) in db.session.query(ShippingInventorySource.source_code).filter_by(enabled=True).all()
|
||||
}
|
||||
missing_codes = sorted(source_codes - enabled_codes)
|
||||
if missing_codes:
|
||||
raise ValidationError(
|
||||
'Routing rule references unavailable inventory sources',
|
||||
code='SHIPPING.INVENTORY_RULE_SOURCE_INVALID',
|
||||
details={'source_codes': missing_codes},
|
||||
)
|
||||
rule.status = 'published'
|
||||
rule.updated_by = actor_id
|
||||
db.session.add(ShippingInventoryRoutingRuleVersion(
|
||||
rule_id=rule.id, version=rule.version, definition_json=_rule_payload(rule), published_by=actor_id,
|
||||
))
|
||||
db.session.commit()
|
||||
return _rule_payload(rule)
|
||||
|
||||
|
||||
def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, Any]:
|
||||
return {
|
||||
'id': mapping.id, 'inventory_source_id': mapping.inventory_source_id,
|
||||
'freight_warehouse_id': mapping.freight_warehouse_id, 'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code, 'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code, 'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
|
||||
def list_external_mappings() -> list[dict[str, Any]]:
|
||||
"""列出库存源到外部系统仓库的映射,不执行调拨判断。"""
|
||||
return [_external_payload(item) for item in ShippingInventoryExternalMapping.query.order_by(ShippingInventoryExternalMapping.id).all()]
|
||||
|
||||
|
||||
def delete_external_mapping(mapping_id: int) -> None:
|
||||
"""删除错误的外部仓库映射;历史文件和任务不回写此实时配置。"""
|
||||
record = db.session.get(ShippingInventoryExternalMapping, mapping_id)
|
||||
if record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
db.session.delete(record)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新精确/默认外部系统映射。"""
|
||||
record = db.session.get(ShippingInventoryExternalMapping, mapping_id) if mapping_id else None
|
||||
if mapping_id and record is None:
|
||||
raise NotFoundError('External mapping not found', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_NOT_FOUND')
|
||||
try:
|
||||
source_id = int(data.get('inventory_source_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('inventory_source_id is required') from exc
|
||||
if db.session.get(ShippingInventorySource, source_id) is None:
|
||||
raise ValidationError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
record = record or ShippingInventoryExternalMapping(inventory_source_id=source_id, external_system_code='', external_warehouse_code='', external_warehouse_name='')
|
||||
record.inventory_source_id = source_id
|
||||
# Freight warehouse is a business identity token; normalize it to match runtime inventory rows.
|
||||
record.freight_warehouse_id = (_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
record.external_system_code = str(_text(data, 'external_system_code', required=True)).upper()
|
||||
record.external_organization_code = _text(data, 'external_organization_code')
|
||||
record.external_site_code = _text(data, 'external_site_code')
|
||||
record.external_warehouse_code = str(_text(data, 'external_warehouse_code', required=True)).upper()
|
||||
record.external_warehouse_name = str(_text(data, 'external_warehouse_name', required=True))
|
||||
record.enabled = _bool(data, 'enabled', bool(record.enabled) if mapping_id else True)
|
||||
record.updated_by = actor_id
|
||||
if not mapping_id:
|
||||
record.created_by = actor_id
|
||||
db.session.add(record)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Active external mapping already exists for this freight identity', code='SHIPPING.INVENTORY_EXTERNAL_MAPPING_CONFLICT') from exc
|
||||
return _external_payload(record)
|
||||
@@ -34,6 +34,8 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
|
||||
"refs.capability",
|
||||
"refs.intake_nos",
|
||||
"refs.file_name",
|
||||
"refs.temporary_inventory_asset_no",
|
||||
"refs.temporary_inventory_session_no",
|
||||
"refs.schedule_task_id",
|
||||
"refs.hxops_turn_id",
|
||||
"domain.type",
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/schedule/job_options.py
|
||||
|
||||
用途:平台任务参数 schema 的动态选项来源(options_source → 统一 label/value 列表)。
|
||||
依赖:models.Agent、shipping_notice.inventory_sources。
|
||||
依赖:models.Agent、shipping_notice.inventory_source_repository。
|
||||
逻辑:api/schedule/platform_tasks.py options 接口与 job_params 选项范围校验调用;
|
||||
前端只认识 options_source 字符串,不感知数据来自哪张表/哪个配置文件。
|
||||
"""
|
||||
@@ -32,8 +32,8 @@ def _agent_apps_options() -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
"""启用中的货代库存源(value=source_code,来自 backend/config/shipping_inventory_sources.yaml)。"""
|
||||
from app.services.shipping_notice.inventory_sources import list_inventory_sources
|
||||
"""启用中的货代库存源(value=source_code,来自数据库主数据)。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
|
||||
|
||||
return [
|
||||
{
|
||||
@@ -41,11 +41,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
"value": source.get("source_code"),
|
||||
"description": (
|
||||
f"{source.get('connector_type')} · "
|
||||
f"{source.get('site_id') or '-'} · "
|
||||
f"{source.get('warehouse_id')}"
|
||||
f"{source.get('warehouse_resolution_mode')} · "
|
||||
f"{source.get('fixed_warehouse_id') or '-'}"
|
||||
),
|
||||
}
|
||||
for source in list_inventory_sources()
|
||||
for source in list_database_inventory_sources()
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -36,14 +36,14 @@ _EMPTY_ARCHIVE_SUMMARY: dict[str, Any] = {
|
||||
def get_inventory_archive_dir() -> str:
|
||||
"""返回库存 RPA 原始 ZIP 归档根目录(自动创建)。"""
|
||||
archive_dir = Path(
|
||||
current_app.config.get("FREIGHT_RPA_INVENTORY_ARCHIVE_DIR")
|
||||
current_app.config.get("SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR")
|
||||
if current_app
|
||||
else ""
|
||||
)
|
||||
if not str(archive_dir):
|
||||
from app.core.config.settings import Config
|
||||
|
||||
archive_dir = Path(Config.FREIGHT_RPA_INVENTORY_ARCHIVE_DIR)
|
||||
archive_dir = Path(Config.SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR)
|
||||
archive_dir.mkdir(parents=True, exist_ok=True)
|
||||
return str(archive_dir)
|
||||
|
||||
@@ -195,7 +195,7 @@ def _is_allowed_inventory_archive_path(zip_path: Path) -> bool:
|
||||
"""
|
||||
校验归档 ZIP 路径是否安全可下载。
|
||||
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内。
|
||||
核心逻辑:文件存在、后缀为 .zip、真实路径必须在 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内。
|
||||
"""
|
||||
resolved = zip_path.resolve()
|
||||
if resolved.suffix.lower() != ".zip":
|
||||
@@ -216,7 +216,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
解析 run 已归档的原始库存 ZIP 路径供下载接口 send_file。
|
||||
|
||||
核心逻辑:读取 summary.raw_inventory_zip_path,校验文件存在、后缀为 .zip、
|
||||
且真实路径位于 FREIGHT_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
且真实路径位于 SHIPPING_NOTICE_RPA_INVENTORY_ARCHIVE_DIR 内;任一不满足则 404。
|
||||
|
||||
Returns:
|
||||
tuple[Path, str]: 归档 ZIP 绝对路径与建议下载文件名。
|
||||
|
||||
@@ -28,7 +28,6 @@ FinalizeScheduleRunResult = dict[str, Any]
|
||||
|
||||
_INVENTORY_RPA_HEADER_ORDER = [
|
||||
"source_code",
|
||||
"site_id",
|
||||
"warehouse_id",
|
||||
"display_name",
|
||||
"inventory_file_no",
|
||||
@@ -38,7 +37,6 @@ _INVENTORY_RPA_HEADER_ORDER = [
|
||||
]
|
||||
_INVENTORY_RPA_HEADER_LABELS = {
|
||||
"source_code": "库存源",
|
||||
"site_id": "站点",
|
||||
"warehouse_id": "仓库",
|
||||
"display_name": "名称",
|
||||
"inventory_file_no": "库存快照号",
|
||||
@@ -145,7 +143,6 @@ def _build_finalize_details(
|
||||
base = pending_by_key.get(key, {})
|
||||
details.append({
|
||||
"source_code": code or item.get("source_code"),
|
||||
"site_id": item.get("site_id") or base.get("site_id"),
|
||||
"warehouse_id": wh or base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": item.get("inventory_file_no"),
|
||||
@@ -163,7 +160,6 @@ def _build_finalize_details(
|
||||
base = pending_by_key.get(key, {})
|
||||
details.append({
|
||||
"source_code": code or item.get("source_code"),
|
||||
"site_id": item.get("site_id") or base.get("site_id"),
|
||||
"warehouse_id": wh or base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": "",
|
||||
@@ -181,7 +177,6 @@ def _build_finalize_details(
|
||||
base = pending_by_key.get(key, {})
|
||||
details.append({
|
||||
"source_code": code or item.get("source_code"),
|
||||
"site_id": item.get("site_id") or base.get("site_id"),
|
||||
"warehouse_id": wh or base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": "",
|
||||
@@ -194,7 +189,6 @@ def _build_finalize_details(
|
||||
continue
|
||||
details.append({
|
||||
"source_code": base.get("source_code"),
|
||||
"site_id": base.get("site_id"),
|
||||
"warehouse_id": base.get("warehouse_id"),
|
||||
"display_name": base.get("display_name"),
|
||||
"inventory_file_no": "",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_job.py
|
||||
|
||||
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
|
||||
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
|
||||
用途:排程触发货代库存 RPA 批量导出(每个 Inventory Source 一次执行)。
|
||||
依赖:inventory_source_repository、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
|
||||
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用;
|
||||
写 trigger 后返回 awaiting_rpa_callback;终态由 shipping_inventory_rpa_finalize 在 RPA 回调时写入。
|
||||
"""
|
||||
@@ -17,7 +17,7 @@ from app import db
|
||||
from app.core.errors import ServiceUnavailableError
|
||||
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_sources import build_rpa_inventory_source, list_inventory_sources
|
||||
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
|
||||
|
||||
@@ -53,34 +53,15 @@ def _normalize_filter_tokens(raw: Any) -> set[str]:
|
||||
return {str(item).strip().upper() for item in values if str(item).strip()}
|
||||
|
||||
|
||||
def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
|
||||
"""收集库存源可用于匹配的标识集合(source_code / site_id / warehouse_id / match_aliases)。"""
|
||||
tokens: set[str] = set()
|
||||
for key in ("source_code", "site_id", "warehouse_id"):
|
||||
value = str(source.get(key) or "").strip().upper()
|
||||
if value:
|
||||
tokens.add(value)
|
||||
for alias in source.get("match_aliases") or []:
|
||||
value = str(alias or "").strip().upper()
|
||||
if value:
|
||||
tokens.add(value)
|
||||
return tokens
|
||||
|
||||
|
||||
def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]:
|
||||
"""
|
||||
从 api_body_template 提取筛选 token。
|
||||
推荐键:source_codes;兼容:source_code / site_ids / site_id / warehouse_ids / warehouse_id / match_aliases。
|
||||
仅支持 source_codes/source_code,排程目标必须是 Inventory Source。
|
||||
"""
|
||||
wanted: set[str] = set()
|
||||
for key in (
|
||||
"source_codes",
|
||||
"source_code",
|
||||
"site_ids",
|
||||
"site_id",
|
||||
"warehouse_ids",
|
||||
"warehouse_id",
|
||||
"match_aliases",
|
||||
):
|
||||
if key in body_template:
|
||||
wanted |= _normalize_filter_tokens(body_template.get(key))
|
||||
@@ -107,18 +88,18 @@ def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None:
|
||||
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
|
||||
"""
|
||||
读取 enabled 库存源;job_params / api_body_template 可限定子集。
|
||||
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / site_id / warehouse_id / match_aliases 命中。
|
||||
核心逻辑:无筛选则导出全部启用 Source;有筛选时严格按 source_code 命中。
|
||||
"""
|
||||
enabled = list_inventory_sources()
|
||||
enabled = list_database_inventory_sources()
|
||||
body_template = _resolve_filter_payload(task)
|
||||
if body_template:
|
||||
wanted = _extract_wanted_tokens(body_template)
|
||||
if wanted:
|
||||
enabled = [
|
||||
item for item in enabled
|
||||
if _source_identity_tokens(item) & wanted
|
||||
if str(item.get('source_code') or '').strip().upper() in wanted
|
||||
]
|
||||
return [source for source in enabled if build_rpa_inventory_source(source.get("source_code"))]
|
||||
return enabled
|
||||
|
||||
|
||||
def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
@@ -183,8 +164,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
|
||||
details = [
|
||||
{
|
||||
"source_code": item.get("source_code"),
|
||||
"site_id": item.get("site_id"),
|
||||
"warehouse_id": item.get("warehouse_id"),
|
||||
"warehouse_id": item.get("fixed_warehouse_id"),
|
||||
"display_name": item.get("display_name"),
|
||||
}
|
||||
for item in sources
|
||||
|
||||
@@ -675,7 +675,8 @@ def create_shipping_batch_from_candidates(
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter_by(task_no=target_no, user_id=int(user_id))
|
||||
.with_for_update()
|
||||
# Lock only ShippingTask. Its eager nullable ShippingCase join cannot be locked by PostgreSQL.
|
||||
.with_for_update(of=ShippingTask)
|
||||
.first()
|
||||
)
|
||||
if target is None:
|
||||
|
||||
@@ -157,7 +157,24 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason in {"", PH_RPA_PENDING}
|
||||
and pending_reason == PH_RPA_PENDING
|
||||
):
|
||||
# A pending task already has an explicit RPA attempt. Poll its timeout
|
||||
# state through the RPA workflow; normal auto-progress must not start RPA.
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode="auto")
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif (
|
||||
process_status == "waiting_inventory"
|
||||
and not getattr(task, "inventory_lines_json", None)
|
||||
and pending_reason == ""
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
@@ -370,7 +387,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING:
|
||||
result = auto_progress({"task_id": task.task_no, "mode": "auto"})
|
||||
# This is a poll of an existing request, never an implicit new RPA run.
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode="auto")
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/business_case_service.py
|
||||
|
||||
用途:为新建货代任务创建或继承业务单聚合。
|
||||
依赖:db、ShippingCase、ShippingTask、uuid/datetime。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单,必要时为历史父任务补建。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -50,8 +50,8 @@ def resolve_shipping_case_for_new_task(
|
||||
"""
|
||||
为即将创建的任务解析业务单归属。
|
||||
|
||||
核心逻辑:revision 继承父任务业务单;历史父任务未关联时在同一事务补建;
|
||||
normal/force_create 均创建独立业务单,保证强制新建重新占用未来流水。
|
||||
核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单,
|
||||
保证强制新建重新占用未来流水。
|
||||
|
||||
Args:
|
||||
supersedes_task_id: 修订目标任务主键,仅 revision 使用。
|
||||
@@ -78,11 +78,11 @@ def resolve_shipping_case_for_new_task(
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
details={'supersedes_task_id': supersedes_task_id},
|
||||
)
|
||||
if parent.shipping_case is not None:
|
||||
return parent.shipping_case
|
||||
|
||||
case = create_shipping_case(created_by_id=parent.user_id or created_by_id)
|
||||
parent.shipping_case = case
|
||||
db.session.flush()
|
||||
return case
|
||||
if parent.shipping_case is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务缺少业务单关联',
|
||||
code='SHIPPING_NOTICE.REVISION_CASE_MISSING',
|
||||
details={'supersedes_task_id': supersedes_task_id},
|
||||
)
|
||||
return parent.shipping_case
|
||||
|
||||
@@ -1,27 +1,24 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/chat_action_extended_handlers.py
|
||||
|
||||
用途:货代 Chat Turn 扩展 Action Handler(上传/映射/切票/缺口查询)。
|
||||
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
|
||||
依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from typing import Any, Iterator
|
||||
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.services.chat.action_registry import register_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK, MAP_JSON
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_by_ref,
|
||||
get_task_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
@@ -61,16 +58,11 @@ def _require_task(ctx: TurnContext):
|
||||
return task
|
||||
|
||||
|
||||
def _filestorage_from_staged(staged: dict[str, Any]) -> FileStorage:
|
||||
data = staged.get("data")
|
||||
if not isinstance(data, (bytes, bytearray)):
|
||||
raise ValidationError("upload file data is missing")
|
||||
filename = str(staged.get("filename") or "upload").strip() or "upload"
|
||||
content_type = str(staged.get("content_type") or "").strip() or None
|
||||
return FileStorage(stream=io.BytesIO(bytes(data)), filename=filename, content_type=content_type)
|
||||
def _first_staged_upload(ctx: TurnContext):
|
||||
"""将当前 Chat Turn 暂存附件转换为通知替换流程可读取的文件对象。"""
|
||||
from io import BytesIO
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
|
||||
def _first_staged_upload(ctx: TurnContext) -> FileStorage:
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
staged_files = payload.get("_staged_files")
|
||||
if not isinstance(staged_files, list) or not staged_files:
|
||||
@@ -78,18 +70,14 @@ def _first_staged_upload(ctx: TurnContext) -> FileStorage:
|
||||
first = staged_files[0]
|
||||
if not isinstance(first, dict):
|
||||
raise ValidationError("invalid staged upload")
|
||||
return _filestorage_from_staged(first)
|
||||
|
||||
|
||||
def _format_inventory_upload_message(result: dict[str, Any], task_no: str) -> str:
|
||||
base = tool_result_message(result) or "库存文件已上传。"
|
||||
lines = [base, f"任务编号:{task_no}"]
|
||||
checkpoint = str(result.get("checkpoint") or "").strip()
|
||||
if checkpoint == "map_infer":
|
||||
lines.append("下一步:请确认或调整列映射。")
|
||||
elif checkpoint == "align_review":
|
||||
lines.append("下一步:请核对字段对齐结果。")
|
||||
return "\n".join(lines)
|
||||
data = first.get("data")
|
||||
if not isinstance(data, (bytes, bytearray)):
|
||||
raise ValidationError("upload file data is missing")
|
||||
return FileStorage(
|
||||
stream=BytesIO(bytes(data)),
|
||||
filename=str(first.get("filename") or "upload").strip() or "upload",
|
||||
content_type=str(first.get("content_type") or "").strip() or None,
|
||||
)
|
||||
|
||||
|
||||
def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str:
|
||||
@@ -105,45 +93,6 @@ def _format_replace_notice_message(result: dict[str, Any], task_no: str) -> str:
|
||||
return "\n".join(line for line in lines if line)
|
||||
|
||||
|
||||
def _format_mapping_applied_message(result: dict[str, Any], task_no: str, mapping: dict[str, str]) -> str:
|
||||
mapping_text = ",".join(f"{key}={value}" for key, value in mapping.items())
|
||||
hint = tool_result_message(result)
|
||||
lines = [
|
||||
f"映射已应用:{mapping_text}" if mapping_text else "映射已应用并解析库存。",
|
||||
f"任务编号:{task_no}",
|
||||
hint,
|
||||
]
|
||||
return "\n".join(line for line in lines if line)
|
||||
|
||||
|
||||
class ShippingUploadInventoryAction:
|
||||
action_type = "shipping.upload_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
upload = _first_staged_upload(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."})
|
||||
result = shipping_tools.upload_inventory_file(task.task_no, upload)
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "upload_inventory failed")
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield shipping_task_ui_state_event(refreshed)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
message_payload: dict[str, Any] = {
|
||||
"task_no": task.task_no,
|
||||
"tool_result": result,
|
||||
"checkpoint": result.get("checkpoint"),
|
||||
}
|
||||
preview = data.get("schema_preview")
|
||||
if isinstance(preview, dict):
|
||||
message_payload["schema_preview"] = preview
|
||||
content = _format_inventory_upload_message(result, task.task_no)
|
||||
yield from stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
|
||||
|
||||
|
||||
class ShippingReplaceNoticeAction:
|
||||
action_type = "shipping.replace_notice"
|
||||
|
||||
@@ -190,34 +139,37 @@ class ShippingReplaceNoticeAction:
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"})
|
||||
|
||||
|
||||
class ShippingApplyInventoryMappingAction:
|
||||
action_type = "shipping.apply_inventory_mapping"
|
||||
class ShippingUploadInventoryAction:
|
||||
"""为已有发货任务上传正式库存文件,并使用库存站点发布方案解析。"""
|
||||
|
||||
action_type = "shipping.upload_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
mapping_raw = payload.get(MAP_JSON) or payload.get("map_json") or payload.get("mapping")
|
||||
if not isinstance(mapping_raw, dict) or not mapping_raw:
|
||||
raise ValidationError(f"{MAP_JSON} is required")
|
||||
mapping = {str(k): str(v) for k, v in mapping_raw.items() if str(v or "").strip()}
|
||||
if not mapping.get("part_number") or not mapping.get("available_qty"):
|
||||
raise ValidationError("part_number and available_qty mapping are required")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "apply_inventory_mapping", "label": "应用列映射..."})
|
||||
result = shipping_tools.apply_inventory_mapping({
|
||||
"task_id": task.task_no,
|
||||
MAP_JSON: mapping,
|
||||
AUTO_CHAIN_FALLBACK: True,
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "apply_inventory_mapping failed")
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
"""
|
||||
保存当前 Turn 的库存附件并返回确定性解析结果。
|
||||
|
||||
核心逻辑:先按当前用户反查任务,再将 multipart 暂存附件交给既有库存工作流;
|
||||
本 Handler 不调用 Dify、不创建临时库存会话,也不允许任务级猜列或字段映射确认。
|
||||
"""
|
||||
task = _require_task(ctx)
|
||||
upload = _first_staged_upload(ctx)
|
||||
yield TurnEvent(event="step.started", data={"step_id": "upload_inventory", "label": "上传库存文件..."})
|
||||
result = shipping_tools.upload_inventory_file(task.task_no, upload)
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(tool_result_message(result if isinstance(result, dict) else {}) or "upload_inventory failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield shipping_task_ui_state_event(refreshed)
|
||||
content = _format_mapping_applied_message(result, task.task_no, mapping)
|
||||
yield from stream_text_events(content, payload={"task_no": task.task_no, "mapping": mapping, "tool_result": result})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "apply_inventory_mapping"})
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
content = "\n".join(filter(None, [tool_result_message(result), f"任务编号:{task.task_no}"]))
|
||||
yield from stream_text_events(
|
||||
content,
|
||||
payload={
|
||||
"task_no": task.task_no,
|
||||
"inventory_file_no": data.get("inventory_file_no"),
|
||||
"tool_result": result,
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
|
||||
|
||||
|
||||
class ShippingSwitchBatchFocusAction:
|
||||
@@ -274,9 +226,8 @@ class ShippingQueryShortageDetailsAction:
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingUploadInventoryAction(),
|
||||
ShippingReplaceNoticeAction(),
|
||||
ShippingApplyInventoryMappingAction(),
|
||||
ShippingUploadInventoryAction(),
|
||||
ShippingSwitchBatchFocusAction(),
|
||||
ShippingQueryShortageDetailsAction(),
|
||||
)
|
||||
|
||||
@@ -51,35 +51,8 @@ def _require_task(ctx: TurnContext):
|
||||
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
|
||||
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
|
||||
lines = [_tool_result_message(result) or "操作已完成。"]
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
if decision == "correct_inventory_mapping":
|
||||
preview = data.get("schema_preview") if isinstance(data.get("schema_preview"), dict) else {}
|
||||
headers = [str(item) for item in (preview.get("headers") or []) if item]
|
||||
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
|
||||
header_row_index = preview.get("header_row_index")
|
||||
if header_row_index:
|
||||
lines.extend(["", f"表头在第 {header_row_index} 行:{' | '.join(headers)}"])
|
||||
elif headers:
|
||||
lines.extend(["", f"当前表头:{' | '.join(headers)}"])
|
||||
mapping_lines = [
|
||||
f"- part_number → {suggested['part_number']}" if suggested.get("part_number") else None,
|
||||
f"- aws_part_number → {suggested['aws_part_number']}" if suggested.get("aws_part_number") else None,
|
||||
f"- reservation_id → {suggested['reservation_id']}" if suggested.get("reservation_id") else None,
|
||||
f"- available_qty → {suggested['available_qty']}" if suggested.get("available_qty") else None,
|
||||
]
|
||||
mapping_lines = [line for line in mapping_lines if line]
|
||||
if mapping_lines:
|
||||
lines.extend(["", "建议列映射:", *mapping_lines])
|
||||
lines.extend([
|
||||
"",
|
||||
"如需调整,请说明要改的列(例如:available_qty 改用 Qty Available)。",
|
||||
"也可点击「选择库存文件」重新上传。",
|
||||
])
|
||||
elif decision == "confirm_inventory_mapping":
|
||||
if str(result.get("checkpoint") or "").strip() == "map_ok":
|
||||
lines.extend(["", "下一步:匹配库存与发货需求。"])
|
||||
elif decision == "reparse_inventory":
|
||||
lines.extend(["", "请重新上传或粘贴库存 Excel。"])
|
||||
if decision == "reparse_inventory":
|
||||
lines.extend(["", "请点击「选择库存文件」重新上传。"])
|
||||
lines.extend(["", f"任务编号:{task_no}"])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@@ -8,23 +8,11 @@ services/shipping_notice/constants.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
# HTTP JSON request/response fields
|
||||
MAP_JSON = "map_json"
|
||||
SUGGEST_OK = "suggest_ok"
|
||||
AUTO_MAP = "auto_map"
|
||||
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
|
||||
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
|
||||
|
||||
# Legacy request field names (read-only compat)
|
||||
MAP_JSON_LEGACY = "column_mapping_json"
|
||||
|
||||
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
|
||||
CP_ALIGN_REVIEW = "align_review"
|
||||
CP_MAP_INFER = "map_infer"
|
||||
CP_UPLOAD_REQ = "upload_req"
|
||||
CP_MAP_OK = "map_ok"
|
||||
CP_PARSE_OK = "parse_ok"
|
||||
CP_PARSE_REVIEW = "parse_review"
|
||||
CP_CUSTOMER_REVIEW = "customer_review"
|
||||
@@ -45,7 +33,6 @@ CP_UPLOADED = "uploaded"
|
||||
CP_COMPLETED = "completed"
|
||||
|
||||
# review_status
|
||||
RS_ALIGN_REVIEW = "align_review"
|
||||
RS_PARSE_REVIEW = "parse_review"
|
||||
RS_SHORTAGE_REVIEW = "shortage_review"
|
||||
RS_RSV_REQ = "rsv_req"
|
||||
@@ -53,8 +40,6 @@ RS_REJECTED = "rejected"
|
||||
RS_CONFIRMED = "confirmed"
|
||||
|
||||
# pending_human_reason (internal; shortened)
|
||||
PH_ALIGN_REVIEW = CP_ALIGN_REVIEW
|
||||
PH_MAP_INFER = CP_MAP_INFER
|
||||
PH_LOW_CONF = "low_confidence"
|
||||
PH_RSV_REQ = CP_RSV_REQ
|
||||
PH_SHORTAGE = "shortage"
|
||||
@@ -65,13 +50,3 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
|
||||
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
|
||||
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
|
||||
|
||||
|
||||
def payload_map_json(payload: dict[str, Any]) -> Any:
|
||||
"""从请求体读取列映射 JSON,兼容 map_json 与 legacy column_mapping_json 字段名。"""
|
||||
raw = payload.get(MAP_JSON)
|
||||
if raw is None:
|
||||
raw = payload.get(MAP_JSON_LEGACY)
|
||||
if raw is None:
|
||||
raw = payload.get("field_mapping")
|
||||
return raw
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/context_adapter.py
|
||||
|
||||
用途:发货通知 Agent 的 Context Adapter,构建 agent_runtime_context Dify inputs。
|
||||
依赖:shipping_notice.dify_inputs.build_dify_chat_inputs、agent_runtime_context.registry。
|
||||
逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传 task/batch。
|
||||
逻辑:agent_code=shipping_notice 时由 build_chat_dify_inputs 分发至本模块;adapter_hints.shipping_notice 透传任务锚点或临时库存资产锚点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,7 +28,7 @@ def build_shipping_notice_context_adapter(
|
||||
"""
|
||||
构建发货通知 Dify Start inputs。
|
||||
|
||||
核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch 或待抽取 Intake 集合,委托 dify_inputs 组装 runtime_context。
|
||||
核心逻辑:从 adapter_hints.shipping_notice 读取 task/batch、待抽取 Intake 集合或临时库存资产,委托 dify_inputs 组装 runtime_context。
|
||||
|
||||
Args:
|
||||
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
|
||||
@@ -52,4 +52,6 @@ def build_shipping_notice_context_adapter(
|
||||
locale=locale,
|
||||
intake_nos=shipping_hints.get('intake_nos'),
|
||||
capability=shipping_hints.get('capability'),
|
||||
temporary_inventory_asset_no=shipping_hints.get('temporary_inventory_asset_no'),
|
||||
temporary_inventory_session_no=shipping_hints.get('temporary_inventory_session_no'),
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
services/shipping_notice/credential_crypto.py
|
||||
|
||||
用途:加密和解密库存 RPA Profile 的登录凭据。
|
||||
依赖:Flask current_app、cryptography.fernet;调用方仅保存密文,不将凭据写入日志或 API 响应。
|
||||
逻辑:管理服务写入 Profile 前调用 encrypt_credential;RPA 配置读取服务在受控内存中调用 decrypt_credential。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
"""
|
||||
构造当前环境的凭据加密器。
|
||||
|
||||
核心逻辑:主密钥只从运行环境读取,缺失或格式无效时拒绝继续,避免写入无法恢复的密文。
|
||||
|
||||
Returns:
|
||||
Fernet: 可执行对称加密的实例。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: 未配置或配置了无效的主密钥。
|
||||
"""
|
||||
key = str(current_app.config.get('SHIPPING_NOTICE_RPA_CREDENTIAL_KEY') or '').strip()
|
||||
if not key:
|
||||
raise ServiceUnavailableError(
|
||||
'SHIPPING_NOTICE_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',
|
||||
code='SHIPPING.RPA_CREDENTIAL_KEY_INVALID',
|
||||
) from exc
|
||||
|
||||
|
||||
def encrypt_credential(value: str) -> str:
|
||||
"""
|
||||
加密单个 RPA 凭据字段以便持久化。
|
||||
|
||||
Args:
|
||||
value: 非空明文凭据;调用方不得记录此值。
|
||||
|
||||
Returns:
|
||||
str: 可安全保存到数据库的 Fernet 密文。
|
||||
|
||||
Raises:
|
||||
ValidationError: 传入空凭据。
|
||||
"""
|
||||
plaintext = str(value or '')
|
||||
if not plaintext:
|
||||
raise ValidationError('RPA credential must not be empty', code='SHIPPING.RPA_CREDENTIAL_EMPTY')
|
||||
return _fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
|
||||
|
||||
def decrypt_credential(ciphertext: str) -> str:
|
||||
"""
|
||||
在受控运行时解密 RPA 凭据。
|
||||
|
||||
Args:
|
||||
ciphertext: 数据库中保存的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
str: 仅供 RPA 执行内存使用的明文。
|
||||
|
||||
Raises:
|
||||
ValidationError: 密文为空、已损坏或使用了错误主密钥。
|
||||
"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError('RPA credential ciphertext is missing', code='SHIPPING.RPA_CREDENTIAL_MISSING')
|
||||
try:
|
||||
return _fernet().decrypt(value.encode('ascii')).decode('utf-8')
|
||||
except (InvalidToken, UnicodeDecodeError) as exc:
|
||||
raise ValidationError('RPA credential ciphertext is invalid', code='SHIPPING.RPA_CREDENTIAL_INVALID') from exc
|
||||
@@ -25,7 +25,7 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.customer_normalization import is_public_email_domain
|
||||
from app.services.shipping_notice.tool_common import cfg_bool
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int
|
||||
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
@@ -35,7 +35,6 @@ CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
"customer_auto_resolution_evaluated",
|
||||
"customer_auto_confirmed",
|
||||
"customer_correction_applied",
|
||||
"customer_historical_backfilled",
|
||||
)
|
||||
|
||||
|
||||
@@ -44,6 +43,48 @@ def auto_customer_resolution_enabled() -> bool:
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False)
|
||||
|
||||
|
||||
def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
"""
|
||||
评估自动确认质量门禁,只以当前强规则会唯一命中的已人工标注样本为分母。
|
||||
|
||||
人工标签覆盖的是解析不稳定的真实来件;未达到样本量或准确率时,宁可保留人工复核,
|
||||
不允许生成不可逆的客户绑定和业务编号。
|
||||
"""
|
||||
min_samples = cfg_int('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_LABELED_SAMPLES', 20, min_value=0)
|
||||
min_accuracy = cfg_float('SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY', 0.98, min_value=0.0, max_value=1.0)
|
||||
labeled = (
|
||||
db.session.query(ShippingCustomerShadowResolution)
|
||||
.filter(ShippingCustomerShadowResolution.manual_customer_id.isnot(None))
|
||||
.all()
|
||||
)
|
||||
eligible_samples = 0
|
||||
correct_samples = 0
|
||||
for shadow in labeled:
|
||||
decision = _resolve_auto_customer_from_evidence(shadow.evidence_json or [])
|
||||
if decision['status'] != 'unique_strong_match':
|
||||
continue
|
||||
eligible_samples += 1
|
||||
if int(decision['customer_id']) == int(shadow.manual_customer_id):
|
||||
correct_samples += 1
|
||||
accuracy = (correct_samples / eligible_samples) if eligible_samples else None
|
||||
if eligible_samples < min_samples:
|
||||
status = 'insufficient_labeled_samples'
|
||||
# min_samples=0 是显式受控放行配置;无样本时不存在可计算的准确率,不应误判为失败。
|
||||
elif min_samples > 0 and (accuracy is None or accuracy < min_accuracy):
|
||||
status = 'insufficient_accuracy'
|
||||
else:
|
||||
status = 'eligible'
|
||||
return {
|
||||
'status': status,
|
||||
'is_eligible': status == 'eligible',
|
||||
'labeled_sample_count': eligible_samples,
|
||||
'correct_sample_count': correct_samples,
|
||||
'accuracy': accuracy,
|
||||
'min_labeled_samples': min_samples,
|
||||
'min_accuracy': min_accuracy,
|
||||
}
|
||||
|
||||
|
||||
def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
|
||||
"""判断识别证据是否达到自动确认门槛。"""
|
||||
if identifier.status != "approved" or not identifier.auto_match_allowed:
|
||||
@@ -55,33 +96,10 @@ def _eligible_identifier(identifier: ShippingCustomerIdentifier) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
使用任务来源 Candidate 的影子证据执行受控自动裁决。
|
||||
|
||||
Args:
|
||||
task: 已创建但客户仍 pending 的任务。
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
if task.source_candidate_id is None:
|
||||
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
candidate_id=int(task.source_candidate_id),
|
||||
).first()
|
||||
if shadow is None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
if candidate is not None:
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
|
||||
shadow = refresh_candidate_shadow_resolution(candidate)
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
def _resolve_auto_customer_from_evidence(evidence_rows: list[object]) -> dict[str, Any]:
|
||||
"""以候选的规范化证据求唯一强规则客户,不读取总开关或质量门禁。"""
|
||||
matched: dict[int, list[dict[str, Any]]] = {}
|
||||
for evidence in shadow.evidence_json or []:
|
||||
for evidence in evidence_rows:
|
||||
if not isinstance(evidence, dict):
|
||||
continue
|
||||
kind = str(evidence.get("type") or "").strip()
|
||||
@@ -120,6 +138,43 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
使用任务来源 Candidate 的影子证据执行受控自动裁决。
|
||||
|
||||
Args:
|
||||
task: 已创建但客户仍 pending 的任务。
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
quality_gate = _auto_confirmation_quality_gate()
|
||||
if not quality_gate['is_eligible']:
|
||||
return {
|
||||
'status': quality_gate['status'],
|
||||
'rule_version': AUTO_RESOLUTION_VERSION,
|
||||
'customer_id': None,
|
||||
'evidence': [],
|
||||
'quality_gate': quality_gate,
|
||||
}
|
||||
if task.source_candidate_id is None:
|
||||
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
candidate_id=int(task.source_candidate_id),
|
||||
).first()
|
||||
if shadow is None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
if candidate is not None:
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
|
||||
shadow = refresh_candidate_shadow_resolution(candidate)
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
return {**_resolve_auto_customer_from_evidence(shadow.evidence_json or []), 'quality_gate': quality_gate}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
"""
|
||||
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
|
||||
@@ -157,52 +212,6 @@ def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no}
|
||||
|
||||
|
||||
def backfill_historical_task_customer(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
customer_id: int,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为历史无业务单任务回填标准客户,但默认不生成历史业务编号。
|
||||
|
||||
Args:
|
||||
task: shipping_case_id 为空且 task_no 为历史技术号的任务。
|
||||
customer_id: 管理员确认的标准客户 ID。
|
||||
actor_id: 管理员审计 ID。
|
||||
Returns:
|
||||
回填后的 task_no、customer_id、business_no(None)。
|
||||
"""
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
raise ValueError("active customer is required")
|
||||
if task.shipping_case_id is not None:
|
||||
raise ValueError("historical backfill only supports tasks without a shipping case")
|
||||
case = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
numbering_status="historical_unnumbered",
|
||||
status="open",
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
task.shipping_case_id = case.id
|
||||
task.customer_resolution_status = "confirmed"
|
||||
task.customer_resolution_method = "historical_backfill"
|
||||
task.customer_confirmed_by = actor_id
|
||||
task.customer_confirmed_at = datetime.utcnow()
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type="customer_historical_backfilled",
|
||||
detail_json={"customer_id": customer.id, "business_no": None},
|
||||
))
|
||||
db.session.commit()
|
||||
return {"task_no": task.task_no, "customer_id": customer.id, "business_no": None}
|
||||
|
||||
|
||||
def correct_numbered_task_customer(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
@@ -264,6 +273,8 @@ def correct_numbered_task_customer(
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
|
||||
if customer.status == "merged":
|
||||
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
|
||||
if customer.status != "active":
|
||||
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
|
||||
if original_case.customer_id == customer.id:
|
||||
@@ -339,7 +350,6 @@ def correct_numbered_task_customer(
|
||||
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
|
||||
latest.inventory_source_code = None
|
||||
latest.inventory_connector_type = None
|
||||
latest.inventory_site_id = None
|
||||
latest.inventory_warehouse_id = None
|
||||
latest.inventory_source_status = None
|
||||
latest.inventory_source_method = None
|
||||
@@ -383,7 +393,7 @@ def correct_numbered_task_customer(
|
||||
|
||||
|
||||
def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
"""汇总自动裁决、纠错和回填事件,供管理员监控、查询与降级判断。"""
|
||||
"""汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。"""
|
||||
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_auto_resolution_evaluated",
|
||||
).distinct().count()
|
||||
@@ -393,9 +403,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_correction_applied",
|
||||
).distinct().count()
|
||||
backfilled = db.session.query(ShippingTaskEvent.task_id).filter_by(
|
||||
event_type="customer_historical_backfilled",
|
||||
).distinct().count()
|
||||
recent_events = (
|
||||
db.session.query(ShippingTaskEvent, ShippingTask.task_no)
|
||||
.join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id)
|
||||
@@ -407,10 +414,10 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
return {
|
||||
"enabled": auto_customer_resolution_enabled(),
|
||||
"rule_version": AUTO_RESOLUTION_VERSION,
|
||||
'quality_gate': _auto_confirmation_quality_gate(),
|
||||
"evaluated_count": evaluated,
|
||||
"auto_confirmed_count": confirmed,
|
||||
"corrected_task_count": corrected,
|
||||
"historical_backfilled_count": backfilled,
|
||||
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
|
||||
"recent_events": [
|
||||
{
|
||||
|
||||
@@ -24,9 +24,9 @@ CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
|
||||
def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
"""判断任务是否通过客户 Gate;无业务单历史任务兼容放行。"""
|
||||
"""判断任务是否已关联业务单并通过标准客户确认。"""
|
||||
if task.shipping_case_id is None:
|
||||
return True
|
||||
return False
|
||||
case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id))
|
||||
if case is None or case.customer_id is None:
|
||||
return False
|
||||
@@ -36,10 +36,10 @@ def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
|
||||
def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None:
|
||||
"""
|
||||
标准客户硬门禁;新业务单未确认时阻断库存、RPA、匹配、Excel 与上传。
|
||||
标准客户硬门禁;业务单缺失或客户未确认时阻断库存、RPA、匹配、Excel 与上传。
|
||||
|
||||
Args:
|
||||
task: 当前发货任务;历史无业务单任务兼容放行。
|
||||
task: 当前发货任务。
|
||||
operation: 触发门禁的操作名,写入错误详情。
|
||||
Raises:
|
||||
AppError: 客户尚未确认、客户已停用或业务单关联无效。
|
||||
@@ -101,8 +101,8 @@ def confirm_task_customer(
|
||||
"""
|
||||
if task.shipping_case_id is None:
|
||||
raise ConflictError(
|
||||
'Legacy tasks without a shipping case cannot confirm customer in this workflow',
|
||||
code='SHIPPING.CUSTOMER_CONFIRMATION_LEGACY_UNSUPPORTED',
|
||||
'Shipping task is missing its required shipping case',
|
||||
code='SHIPPING.CUSTOMER_CASE_REQUIRED',
|
||||
)
|
||||
case = (
|
||||
db.session.query(ShippingCase)
|
||||
@@ -115,6 +115,8 @@ def confirm_task_customer(
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if customer.status == 'merged':
|
||||
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
if customer.status != 'active':
|
||||
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
|
||||
if case.business_no and case.customer_id not in {None, customer.id}:
|
||||
|
||||
@@ -17,10 +17,11 @@ from typing import Any
|
||||
from sqlalchemy import func
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
@@ -135,6 +136,24 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S
|
||||
row.candidate_matches_json = matches
|
||||
row.top_customer_id = int(matches[0]['customer_id']) if status == 'unique_candidate' else None
|
||||
row.top_score = top_score
|
||||
# 规范化候选关联用于客户生命周期约束;JSON 继续保留完整证据供展示与审计。
|
||||
# 先落库删除旧快照,避免 SQLite/PostgreSQL 在同次 flush 中先插入后删除而触发唯一约束。
|
||||
db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete(
|
||||
synchronize_session=False,
|
||||
)
|
||||
db.session.flush()
|
||||
db.session.expire(row, ['matches'])
|
||||
row.matches = [
|
||||
ShippingCustomerShadowMatch(
|
||||
customer_id=int(item['customer_id']),
|
||||
match_rank=index,
|
||||
score=float(item['score']),
|
||||
standard_name_snapshot=str(item['standard_name']),
|
||||
short_code_snapshot=str(item['short_code']),
|
||||
reasons_json=list(item.get('reasons') or []),
|
||||
)
|
||||
for index, item in enumerate(matches, start=1)
|
||||
]
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return row
|
||||
@@ -168,6 +187,9 @@ def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidat
|
||||
row.candidate_matches_json = []
|
||||
row.top_customer_id = None
|
||||
row.top_score = None
|
||||
db.session.query(ShippingCustomerShadowMatch).filter_by(resolution_id=row.id).delete(
|
||||
synchronize_session=False,
|
||||
)
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
except Exception:
|
||||
@@ -186,6 +208,8 @@ def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: i
|
||||
raise NotFoundError('Shadow resolution not found', code='SHIPPING.CUSTOMER_SHADOW_NOT_FOUND')
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if customer.status == 'merged':
|
||||
raise ConflictError('Merged customer cannot be used as a new label', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
row.manual_customer_id = customer.id
|
||||
row.labeled_by_id = actor_id
|
||||
row.labeled_at = datetime.utcnow()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/decision_workflow.py
|
||||
|
||||
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
|
||||
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow、task_line_store。
|
||||
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
|
||||
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、task_line_store。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。
|
||||
"""
|
||||
|
||||
@@ -11,9 +11,9 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_OK,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
@@ -23,32 +23,12 @@ from app.services.shipping_notice.constants import (
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
|
||||
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
|
||||
from app.services.shipping_notice.task_line_store import clear_task_order_lines
|
||||
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_mapping_checkpoint_response,
|
||||
latest_inventory_column_meta,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
linked_task_nos_for_inventory_file,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
read_task_inventory_schema_preview,
|
||||
resolve_task_inventory_upload_path,
|
||||
task_inventory_upload_path,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
adjudicate_and_apply_inventory_source,
|
||||
ensure_inventory_source_review_state,
|
||||
task_needs_parse_review,
|
||||
transition_task_to_inventory_source_review,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
@@ -91,12 +71,26 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
|
||||
task.error_message = None
|
||||
|
||||
|
||||
def _prepare_task_for_inventory_reupload(task) -> None:
|
||||
"""
|
||||
解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。
|
||||
|
||||
【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。
|
||||
历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。
|
||||
"""
|
||||
if task.id is not None:
|
||||
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all():
|
||||
link.is_active = False
|
||||
_reset_inventory_state_for_forced_rpa(task)
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
|
||||
|
||||
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
|
||||
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“更正映射”“关闭任务”等决策类指令时调用。
|
||||
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
|
||||
|
||||
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。
|
||||
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支;rematch 会同步调用 match_inventory 完成重算。
|
||||
Args:
|
||||
payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。
|
||||
|
||||
@@ -115,6 +109,37 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lang = resolve_lang(payload)
|
||||
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
|
||||
|
||||
# Published parsing profiles are the only production mapping contract.
|
||||
# Reject legacy task-level mapping decisions instead of reopening a manual
|
||||
# mapping path that could override the source's configured profile.
|
||||
if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if decision == "reparse_inventory":
|
||||
_prepare_task_for_inventory_reupload(task)
|
||||
log_task_action_event(
|
||||
task,
|
||||
"inventory_reupload_requested",
|
||||
action="reparse_inventory",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="upload_req",
|
||||
human_options=["upload_inventory_file", "retry_rpa"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
# [STEP 1] 先处理终止型决策。
|
||||
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
|
||||
if decision == "reject":
|
||||
@@ -240,7 +265,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
human_options=resolve_task_ui_state(task).human_options,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
|
||||
if not task.inventory_lines_json:
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
@@ -289,10 +314,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
|
||||
if task.inventory_lines_json or task.process_status == "inventory_ready":
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
@@ -310,7 +331,7 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
# [STEP 3] 处理重算型决策。
|
||||
# retry_rpa / rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
|
||||
# retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路,
|
||||
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
|
||||
if decision == "retry_rpa":
|
||||
_reset_inventory_state_for_forced_rpa(task)
|
||||
@@ -350,186 +371,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
return match_result
|
||||
|
||||
if decision == "confirm_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.mapping_not_needed", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
|
||||
res_source = None
|
||||
if isinstance(inv_mapping.get("reservation_id"), dict):
|
||||
res_source = inv_mapping["reservation_id"].get("source_column")
|
||||
if not str(res_source or "").strip():
|
||||
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
|
||||
db.session.commit()
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
warning = t("workflow.decision.mapping_missing_reservation_warning", lang=lang)
|
||||
ui = resolve_task_ui_state(task)
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=warning,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=ui.checkpoint,
|
||||
human_options=ui.human_options,
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
|
||||
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
|
||||
if headers and field_mapping and mapping_is_complete(field_mapping):
|
||||
upsert_inventory_mapping(
|
||||
task.customer_code,
|
||||
preview={
|
||||
"headers": headers,
|
||||
"header_row_index": meta.get("header_row_index") or 1,
|
||||
},
|
||||
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_task_nos = [task.task_no]
|
||||
if inv_file:
|
||||
inv_file.mapping_confirmed = True
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
**{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
**{
|
||||
"action": "confirm_inventory_mapping",
|
||||
"source": event_source,
|
||||
"target_type": "task",
|
||||
"target_id": task.task_no,
|
||||
"batch_no": task.batch.batch_no if task.batch else "",
|
||||
"conversation_id": task.conversation_id or "",
|
||||
},
|
||||
},
|
||||
)
|
||||
for link in inv_file.links or []:
|
||||
linked_task = link.task
|
||||
if not link.is_active or not linked_task:
|
||||
continue
|
||||
linked_task_nos.append(linked_task.task_no)
|
||||
if awaiting_inventory_mapping_confirm(linked_task):
|
||||
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
"inventory_mapping_confirmed",
|
||||
{
|
||||
**{
|
||||
"comment": comment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
**{
|
||||
"action": "confirm_inventory_mapping",
|
||||
"source": event_source,
|
||||
"target_type": "task",
|
||||
"target_id": linked_task.task_no,
|
||||
"batch_no": linked_task.batch.batch_no if linked_task.batch else "",
|
||||
"conversation_id": linked_task.conversation_id or "",
|
||||
},
|
||||
},
|
||||
)
|
||||
else:
|
||||
log_task_action_event(
|
||||
task,
|
||||
"inventory_mapping_confirmed",
|
||||
action="confirm_inventory_mapping",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
)
|
||||
db.session.commit()
|
||||
orchestrator_started = (
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
if inv_file
|
||||
else start_task_orchestrator(task.task_no)
|
||||
)
|
||||
if inv_file:
|
||||
linked_task_nos = linked_task_nos_for_inventory_file(inv_file)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
task=task,
|
||||
message=t("workflow.decision.mapping_confirmed_running", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "linked_task_nos": linked_task_nos},
|
||||
)
|
||||
|
||||
if decision == "correct_inventory_mapping":
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.mapping_correction_invalid_state", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
task.inventory_lines_json = None
|
||||
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
|
||||
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
|
||||
db.session.commit()
|
||||
upload_path = resolve_task_inventory_upload_path(task.task_no)
|
||||
if upload_path is not None:
|
||||
try:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.read_inventory_preview_failed", lang=lang).format(error=exc),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
else:
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
preview = {
|
||||
"headers": meta.get("headers") or [],
|
||||
"sample_rows": [],
|
||||
"suggested_mapping": meta.get("field_mapping") or {},
|
||||
"note": t("workflow.decision.mapping_preview_note", lang=lang),
|
||||
}
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.decision.mapping_correction_needed", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
if decision == "reparse_inventory":
|
||||
task.inventory_lines_json = None
|
||||
if task.process_status == "inventory_ready":
|
||||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
|
||||
else:
|
||||
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
|
||||
for suffix in (".xlsx", ".csv"):
|
||||
upload_path = task_inventory_upload_path(task.task_no, suffix=suffix)
|
||||
if upload_path.is_file():
|
||||
try:
|
||||
upload_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
log_task_event(task, "inventory_reparse_requested", {"comment": comment})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.decision.inventory_cleared", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
next_required_action=t("workflow.decision.mapping_correction_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
# [STEP 4] 最后处理整单重新解析。
|
||||
# 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。
|
||||
if decision == "reparse":
|
||||
|
||||
@@ -10,9 +10,10 @@ services/shipping_notice/dify_inputs.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.models import ShippingBatch, ShippingTask, ShippingTemporaryInventorySession
|
||||
from app.services.agent_runtime_context.builder import serialize_for_dify
|
||||
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
|
||||
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
|
||||
@@ -38,6 +39,35 @@ def _task_by_task_no(task_id: str) -> ShippingTask | None:
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
|
||||
"""
|
||||
恢复当前聊天中仍待用户处理的临时库存会话锚点。
|
||||
|
||||
Args:
|
||||
conversation_id: HXOPS 本地聊天会话 ID。
|
||||
|
||||
Returns:
|
||||
最新未过期待处理会话号;没有符合条件的会话时返回 None。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized:
|
||||
return None
|
||||
item = ShippingTemporaryInventorySession.query.filter(
|
||||
ShippingTemporaryInventorySession.conversation_id == normalized,
|
||||
ShippingTemporaryInventorySession.status.in_([
|
||||
'created',
|
||||
'awaiting_profile_confirmation',
|
||||
'awaiting_mapping_suggestion',
|
||||
'awaiting_mapping_confirmation',
|
||||
]),
|
||||
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
|
||||
).order_by(
|
||||
ShippingTemporaryInventorySession.updated_at.desc(),
|
||||
ShippingTemporaryInventorySession.id.desc(),
|
||||
).first()
|
||||
return str(item.session_no or '').strip().upper() or None if item else None
|
||||
|
||||
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
|
||||
"""
|
||||
解析当前显式焦点任务行。
|
||||
@@ -70,6 +100,8 @@ def build_dify_chat_inputs(
|
||||
locale: str | None = None,
|
||||
intake_nos: list[str] | None = None,
|
||||
capability: str | None = None,
|
||||
temporary_inventory_asset_no: str | None = None,
|
||||
temporary_inventory_session_no: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建发货通知 Dify Chatflow inputs。
|
||||
@@ -83,6 +115,15 @@ def build_dify_chat_inputs(
|
||||
|
||||
explicit_task = str(task_id or "").strip().upper()
|
||||
explicit_batch = str(batch_no or "").strip().upper()
|
||||
explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper()
|
||||
resolved_temporary_session = (
|
||||
explicit_temporary_session
|
||||
or (
|
||||
_latest_pending_temporary_inventory_session(conv_id)
|
||||
if trigger_source != 'backend_orchestrator'
|
||||
else None
|
||||
)
|
||||
)
|
||||
|
||||
batch = _latest_batch_for_conversation(conv_id)
|
||||
explicit_task_row = _task_by_task_no(explicit_task)
|
||||
@@ -113,10 +154,12 @@ def build_dify_chat_inputs(
|
||||
run_purpose=(
|
||||
"parse_notice"
|
||||
if trigger_source == "backend_orchestrator"
|
||||
else ("order_extraction" if intake_nos else "chat_turn")
|
||||
else ("temporary_inventory" if temporary_inventory_asset_no else ("order_extraction" if intake_nos else "chat_turn"))
|
||||
),
|
||||
intake_nos=intake_nos,
|
||||
capability=capability,
|
||||
capability=capability or ("temporary_inventory" if temporary_inventory_asset_no else None),
|
||||
temporary_inventory_asset_no=temporary_inventory_asset_no,
|
||||
temporary_inventory_session_no=resolved_temporary_session,
|
||||
)
|
||||
if not runtime_context:
|
||||
return {}
|
||||
|
||||
@@ -320,6 +320,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
summary = cand.structured_result_json.get('business_summary')
|
||||
structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {}
|
||||
extraction = structured.get('extraction') if isinstance(structured.get('extraction'), dict) else {}
|
||||
customer_matches = (
|
||||
extraction.get('customer_matches')
|
||||
if isinstance(extraction.get('customer_matches'), list)
|
||||
else []
|
||||
)
|
||||
adjudication = (
|
||||
extraction.get('field_adjudication')
|
||||
if isinstance(extraction.get('field_adjudication'), dict)
|
||||
@@ -354,6 +359,7 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
'observation_history': list(adjudication.get('observation_history') or []),
|
||||
'conflicts': list(adjudication.get('conflicts') or []),
|
||||
} if adjudication else None,
|
||||
'customer_matches': list(customer_matches),
|
||||
'duplicate': {
|
||||
'status': status,
|
||||
'blocking': blocking,
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
"""
|
||||
services/shipping_notice/excel_template.py
|
||||
|
||||
用途:管理发货 Excel 模板草稿、映射定义、发布版本与受管模板文件。
|
||||
依赖:openpyxl、ShippingExcelTemplate、订单字段目录、Flask 配置与统一业务异常。
|
||||
逻辑:上传 xlsx 创建草稿;草稿可改定义;发布时验证工作表、字段引用和映射目标并计算不可变校验和。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.utils import get_column_letter
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderField,
|
||||
)
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'constant'}
|
||||
ALLOWED_ROW_MODES = {'header', 'line'}
|
||||
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
|
||||
ALLOWED_SYSTEM_FACTS = {'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date'}
|
||||
|
||||
|
||||
def _storage_key(template_code: str, version: int) -> str:
|
||||
"""构造长期私有模板对象键,与临时上传资产生命周期隔离。"""
|
||||
return f'shipping-excel-templates/{template_code}/v{version}/{uuid.uuid4().hex}.xlsx'
|
||||
|
||||
|
||||
def _checksum_json(value: Any) -> str:
|
||||
payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _payload(item: ShippingExcelTemplate) -> dict[str, Any]:
|
||||
"""序列化模板元数据,绝不向管理端暴露服务器存储路径。"""
|
||||
return {
|
||||
'id': item.id, 'template_code': item.template_code, 'display_name': item.display_name,
|
||||
'version': item.version, 'status': item.status, 'original_filename': item.original_filename,
|
||||
'file_checksum': item.file_checksum, 'definition': item.definition_json or {},
|
||||
'definition_checksum': item.definition_checksum,
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'published_at': item.published_at.isoformat() if item.published_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_templates() -> list[dict[str, Any]]:
|
||||
"""按编码和版本列出模板,供库存源绑定及草稿编辑。"""
|
||||
rows = ShippingExcelTemplate.query.order_by(
|
||||
ShippingExcelTemplate.template_code, ShippingExcelTemplate.version.desc(),
|
||||
).all()
|
||||
return [_payload(item) for item in rows]
|
||||
|
||||
|
||||
def _next_version(template_code: str) -> int:
|
||||
latest = ShippingExcelTemplate.query.filter_by(template_code=template_code).order_by(
|
||||
ShippingExcelTemplate.version.desc(),
|
||||
).first()
|
||||
return int(latest.version) + 1 if latest else 1
|
||||
|
||||
|
||||
def create_draft(upload: FileStorage | None, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""
|
||||
上传模板文件并创建新草稿版本。
|
||||
|
||||
Args:
|
||||
upload: 必须为非空 xlsx 文件;宏工作簿和 CSV 不接受。
|
||||
data: template_code、display_name 与 JSON definition。
|
||||
actor_id: 当前管理员 ID。
|
||||
"""
|
||||
code = str(data.get('template_code') or '').strip().upper()
|
||||
name = str(data.get('display_name') or '').strip()
|
||||
filename = str(getattr(upload, 'filename', '') or '').strip()
|
||||
if not code or not name or upload is None or not filename.lower().endswith('.xlsx'):
|
||||
raise ValidationError('template_code, display_name and xlsx file are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
if not re.fullmatch(r'[A-Z0-9_-]{2,64}', code):
|
||||
raise ValidationError('template_code format is invalid', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
if ShippingExcelTemplate.query.filter_by(template_code=code, status='draft').count():
|
||||
raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS')
|
||||
raw = upload.read()
|
||||
if not raw:
|
||||
raise ValidationError('Template file is empty', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
max_mb = max(int(current_app.config.get('SHIPPING_EXCEL_TEMPLATE_MAX_SIZE_MB') or 20), 1)
|
||||
if len(raw) > max_mb * 1024 * 1024:
|
||||
raise ValidationError('Template file exceeds size limit', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
try:
|
||||
workbook = load_workbook(BytesIO(raw), read_only=True)
|
||||
workbook.close()
|
||||
except Exception as exc:
|
||||
raise ValidationError('Template file is not a valid xlsx workbook', code='SHIPPING.EXCEL_TEMPLATE_INVALID') from exc
|
||||
definition = data.get('definition') if isinstance(data.get('definition'), dict) else {}
|
||||
version = _next_version(code)
|
||||
storage_key = _storage_key(code, version)
|
||||
file_asset_storage.upload_bytes(
|
||||
storage_key=storage_key, data=raw,
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
item = ShippingExcelTemplate(
|
||||
template_code=code, display_name=name, version=version, status='draft',
|
||||
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
|
||||
original_filename=filename[:255],
|
||||
file_checksum=hashlib.sha256(raw).hexdigest(), definition_json=definition,
|
||||
created_by=actor_id,
|
||||
)
|
||||
try:
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
try:
|
||||
file_asset_storage.delete_object(storage_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def update_draft(template_id: int, data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""更新草稿显示名称和映射定义;发布版本禁止原地修改。"""
|
||||
item = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
if item.status != 'draft':
|
||||
raise ConflictError('Published template is immutable', code='SHIPPING.EXCEL_TEMPLATE_IMMUTABLE')
|
||||
name = str(data.get('display_name') or '').strip()
|
||||
definition = data.get('definition')
|
||||
if not name or not isinstance(definition, dict):
|
||||
raise ValidationError('display_name and definition are required', code='SHIPPING.EXCEL_TEMPLATE_INVALID')
|
||||
item.display_name = name
|
||||
item.definition_json = definition
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def _workbook_layout(raw: bytes, definition: dict[str, Any]) -> dict[str, list[dict[str, Any]]]:
|
||||
"""读取受管模板的工作表和首行栏位,供编辑器重新加载已保存文件的结构。"""
|
||||
workbook = load_workbook(BytesIO(raw), read_only=True, data_only=False)
|
||||
try:
|
||||
header_rows: dict[str, int] = {}
|
||||
for mapping in definition.get('mappings', []):
|
||||
if not isinstance(mapping, dict):
|
||||
continue
|
||||
sheet_name = str(mapping.get('sheet') or '')
|
||||
start_row = int(mapping.get('start_row') or 1)
|
||||
candidate_row = max(start_row - 1, 1)
|
||||
header_rows[sheet_name] = min(header_rows.get(sheet_name, candidate_row), candidate_row)
|
||||
layout: dict[str, list[dict[str, Any]]] = {}
|
||||
for sheet_name in workbook.sheetnames:
|
||||
sheet = workbook[sheet_name]
|
||||
if sheet.max_column is None:
|
||||
sheet.calculate_dimension(force=True)
|
||||
header_row = header_rows.get(sheet_name, 1)
|
||||
max_column = int(sheet.max_column or 0)
|
||||
columns: list[dict[str, Any]] = []
|
||||
for column_index in range(1, max_column + 1):
|
||||
value = sheet.cell(header_row, column_index).value
|
||||
column = get_column_letter(column_index)
|
||||
columns.append({'index': column_index, 'label': f'{column} - {value}' if value else column})
|
||||
layout[sheet_name] = columns
|
||||
return layout
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def get_layout(template_id: int) -> dict[str, Any]:
|
||||
"""返回已保存模板的工作表和目标列信息,不要求用户重新上传文件。"""
|
||||
item = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
raw = file_asset_storage.get_bytes(item.storage_key)
|
||||
if hashlib.sha256(raw).hexdigest() != item.file_checksum:
|
||||
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
|
||||
return {'template_id': item.id, 'sheets': _workbook_layout(raw, item.definition_json or {})}
|
||||
|
||||
|
||||
def create_draft_from_existing(template_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""复制已保存模板文件和映射定义,创建可编辑的新草稿版本。"""
|
||||
source = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
if source.status not in {'draft', 'published', 'retired'}:
|
||||
raise ConflictError('Template status cannot create a new version', code='SHIPPING.EXCEL_TEMPLATE_VERSION_INVALID')
|
||||
if ShippingExcelTemplate.query.filter_by(template_code=source.template_code, status='draft').count():
|
||||
raise ConflictError('A draft already exists for this template code', code='SHIPPING.EXCEL_TEMPLATE_DRAFT_EXISTS')
|
||||
raw = file_asset_storage.get_bytes(source.storage_key)
|
||||
if hashlib.sha256(raw).hexdigest() != source.file_checksum:
|
||||
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
|
||||
version = _next_version(source.template_code)
|
||||
storage_key = _storage_key(source.template_code, version)
|
||||
file_asset_storage.upload_bytes(
|
||||
storage_key=storage_key, data=raw,
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
item = ShippingExcelTemplate(
|
||||
template_code=source.template_code, display_name=source.display_name, version=version, status='draft',
|
||||
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
|
||||
original_filename=source.original_filename, file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
definition_json=json.loads(json.dumps(source.definition_json or {}, ensure_ascii=False)), created_by=actor_id,
|
||||
)
|
||||
try:
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
try:
|
||||
file_asset_storage.delete_object(storage_key)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def _validate_definition(item: ShippingExcelTemplate) -> dict[str, Any]:
|
||||
"""验证模板定义、实际工作表和稳定字段引用,返回规范化定义。"""
|
||||
definition = item.definition_json if isinstance(item.definition_json, dict) else {}
|
||||
mappings = definition.get('mappings')
|
||||
filename_pattern = str(definition.get('filename_pattern') or '').strip()
|
||||
if not isinstance(mappings, list) or not mappings or not filename_pattern:
|
||||
raise ValidationError('Template mappings and filename_pattern are required', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
|
||||
try:
|
||||
rendered_name = filename_pattern.format(
|
||||
task_no='TASK', business_no='BUSINESS', source_code='SOURCE', ts='20260101000000', date='20260101',
|
||||
customer_short_code='CUSTOMER', business_date='260602', sequence='01',
|
||||
)
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise ValidationError('Template filename_pattern is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
|
||||
if not rendered_name.strip():
|
||||
raise ValidationError('Template filename_pattern is empty', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
|
||||
raw = file_asset_storage.get_bytes(item.storage_key)
|
||||
if hashlib.sha256(raw).hexdigest() != item.file_checksum:
|
||||
raise ValidationError('Template asset is missing or changed', code='SHIPPING.EXCEL_TEMPLATE_ASSET_INVALID')
|
||||
wb = load_workbook(BytesIO(raw), read_only=True)
|
||||
sheet_names = set(wb.sheetnames)
|
||||
wb.close()
|
||||
published_field_ids: set[str] = set()
|
||||
if any(isinstance(mapping, dict) and mapping.get('source_kind') == 'order_field' for mapping in mappings):
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
published_field_ids = {
|
||||
str(field.get('field_id') or '')
|
||||
for field in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
normalized: list[dict[str, Any]] = []
|
||||
seen_targets: set[tuple[str, str, int]] = set()
|
||||
for index, raw in enumerate(mappings):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('Template mapping must be an object', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
|
||||
sheet = str(raw.get('sheet') or '').strip()
|
||||
row_mode = str(raw.get('row_mode') or '').strip().lower()
|
||||
source_kind = str(raw.get('source_kind') or '').strip().lower()
|
||||
source_key = str(raw.get('source_key') or '').strip()
|
||||
formatter = str(raw.get('formatter') or 'text').strip().lower()
|
||||
try:
|
||||
start_row = int(raw.get('start_row'))
|
||||
target_column = int(raw.get('target_column'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Template target row and column must be integers', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID') from exc
|
||||
if sheet not in sheet_names or row_mode not in ALLOWED_ROW_MODES or source_kind not in ALLOWED_SOURCE_KINDS:
|
||||
raise ValidationError('Template mapping metadata is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID', details={'index': index})
|
||||
if start_row < 1 or target_column < 1 or formatter not in ALLOWED_FORMATTERS:
|
||||
raise ValidationError('Template mapping target or formatter is invalid', code='SHIPPING.EXCEL_TEMPLATE_DEFINITION_INVALID')
|
||||
if source_kind == 'order_field':
|
||||
field = db.session.get(ShippingOrderField, source_key)
|
||||
allowed_scopes = {'header'} if row_mode == 'header' else {'header', 'line'}
|
||||
if field is None or field.status != 'active' or field.scope not in allowed_scopes or field.id not in published_field_ids:
|
||||
raise ValidationError('Order field is invalid for mapping scope', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
|
||||
elif source_kind == 'inventory_field':
|
||||
try:
|
||||
inventory_field_id = int(source_key)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Inventory field is invalid', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID') from exc
|
||||
inventory_field = db.session.get(ShippingInventoryField, inventory_field_id)
|
||||
if inventory_field is None or inventory_field.status != 'active':
|
||||
raise ValidationError('Inventory field is unavailable', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
|
||||
source_key = str(inventory_field.id)
|
||||
elif source_kind == 'system_fact' and source_key not in ALLOWED_SYSTEM_FACTS:
|
||||
raise ValidationError('System fact is not allowed', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
|
||||
elif source_kind != 'constant' and not source_key:
|
||||
raise ValidationError('source_key is required', code='SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID')
|
||||
target = (sheet, row_mode, target_column)
|
||||
if target in seen_targets:
|
||||
raise ValidationError('Duplicate template target column', code='SHIPPING.EXCEL_TEMPLATE_TARGET_DUPLICATE')
|
||||
seen_targets.add(target)
|
||||
normalized.append({
|
||||
'sheet': sheet, 'row_mode': row_mode, 'start_row': start_row,
|
||||
'target_column': target_column, 'source_kind': source_kind,
|
||||
'source_key': source_key, 'formatter': formatter,
|
||||
})
|
||||
return {'filename_pattern': filename_pattern, 'mappings': normalized}
|
||||
|
||||
|
||||
def publish(template_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""验证并发布模板版本;发布后文件和定义均不可变。"""
|
||||
item = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
if item.status != 'draft':
|
||||
raise ConflictError('Only draft template can be published', code='SHIPPING.EXCEL_TEMPLATE_PUBLISH_INVALID')
|
||||
definition = _validate_definition(item)
|
||||
item.definition_json = definition
|
||||
item.definition_checksum = _checksum_json(definition)
|
||||
item.status = 'published'
|
||||
item.published_by = actor_id
|
||||
item.published_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def retire(template_id: int) -> dict[str, Any]:
|
||||
"""退役不再供新库存源绑定的模板;现有产物引用保持不变。"""
|
||||
item = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
if item.status != 'published':
|
||||
raise ConflictError('Only published template can be retired', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_INVALID')
|
||||
if ShippingInventorySource.query.filter_by(excel_template_id=item.id).count():
|
||||
raise ConflictError('Rebind inventory sources first', code='SHIPPING.EXCEL_TEMPLATE_RETIRE_BLOCKED')
|
||||
item.status = 'retired'
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def delete_draft(template_id: int) -> None:
|
||||
"""删除未发布草稿及其受管文件;已有 Artifact 的模板永远不可删除。"""
|
||||
item = db.session.get(ShippingExcelTemplate, template_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Excel template not found', code='SHIPPING.EXCEL_TEMPLATE_NOT_FOUND')
|
||||
if item.status != 'draft' or ShippingExportArtifact.query.filter_by(template_id=item.id).count():
|
||||
raise ConflictError('Only unused draft can be deleted', code='SHIPPING.EXCEL_TEMPLATE_DELETE_BLOCKED')
|
||||
storage_key = item.storage_key
|
||||
raw = file_asset_storage.get_bytes(storage_key)
|
||||
file_asset_storage.delete_object(storage_key)
|
||||
try:
|
||||
db.session.delete(item)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
file_asset_storage.upload_bytes(
|
||||
storage_key=storage_key, data=raw,
|
||||
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
)
|
||||
raise
|
||||
@@ -1,311 +1,383 @@
|
||||
"""
|
||||
services/shipping_notice/export.py
|
||||
|
||||
用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。
|
||||
依赖:openpyxl、app.models.ShippingTask、path_utils、task_line_store、Flask current_app 配置。
|
||||
逻辑:由 fulfillment_workflow.generate_excel 调用本文件;订单行经 read_task_order_lines 读取。
|
||||
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
|
||||
依赖:ShippingExcelTemplate/ShippingExportArtifact、动态订单 FieldValue、库存快照与 openpyxl。
|
||||
逻辑:锁定 Source、模板、订单 Schema/Extraction、库存解析 Profile 和库存快照,按白名单映射写入模板。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from shutil import copy2
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from flask import current_app
|
||||
from openpyxl import Workbook, load_workbook
|
||||
from openpyxl import load_workbook
|
||||
from sqlalchemy import update
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.path_utils import backend_dir, resolve_backend_relative_path
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
|
||||
DEFAULT_HEADERS = [
|
||||
"客户名称",
|
||||
"客户代码",
|
||||
"收货地址",
|
||||
"要求交期",
|
||||
"料号",
|
||||
"发货数量",
|
||||
"单位",
|
||||
"备注",
|
||||
]
|
||||
|
||||
HEADER_SHEET = "PVMI Pull Request Header"
|
||||
DETAIL_SHEET = "PVMI Pull Request Detail"
|
||||
DATA_START_ROW = 4
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def _storage_root() -> Path:
|
||||
"""发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。"""
|
||||
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
|
||||
if root:
|
||||
return Path(resolve_backend_relative_path(root))
|
||||
return Path(current_app.instance_path) / "shipping_notice"
|
||||
|
||||
|
||||
def _default_template_path() -> Path | None:
|
||||
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
|
||||
"""返回发货通知文件根目录。"""
|
||||
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
|
||||
if configured:
|
||||
path = Path(resolve_backend_relative_path(configured))
|
||||
if path.is_file():
|
||||
return path
|
||||
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
|
||||
return bundled if bundled.is_file() else None
|
||||
return Path(resolve_backend_relative_path(configured))
|
||||
return Path(current_app.instance_path) / 'shipping_notice'
|
||||
|
||||
|
||||
def _is_pvmi_workbook(wb) -> bool:
|
||||
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
|
||||
|
||||
|
||||
def _format_delivery_date(value: Any) -> str:
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return ""
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
|
||||
try:
|
||||
parsed = datetime.strptime(text[:10], fmt)
|
||||
return parsed.strftime("%m/%d/%Y")
|
||||
except ValueError:
|
||||
continue
|
||||
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
|
||||
try:
|
||||
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
|
||||
return parsed.strftime("%m/%d/%Y")
|
||||
except ValueError:
|
||||
pass
|
||||
return text
|
||||
|
||||
|
||||
def _delivery_date_for_task(task: ShippingTask) -> str:
|
||||
if task.required_date:
|
||||
formatted = _format_delivery_date(task.required_date)
|
||||
if formatted:
|
||||
return formatted
|
||||
for line in read_task_order_lines(task):
|
||||
formatted = _format_delivery_date(line.get("required_date"))
|
||||
if formatted:
|
||||
return formatted
|
||||
return ""
|
||||
|
||||
|
||||
def _resolve_odm_id(task: ShippingTask) -> str:
|
||||
"""
|
||||
按订单内部料号与 Reservation 定位当前库存投影中的 ODM ID。
|
||||
|
||||
核心逻辑:订单与库存统一按 part_number + reservation_id 配对。
|
||||
Args:
|
||||
task: 已关联库存快照的发货任务。
|
||||
Returns:
|
||||
首个匹配库存行的 ODM ID;未命中时回退库存中的首个非空值。
|
||||
"""
|
||||
notice_lines = read_task_order_lines(task)
|
||||
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not inventory_lines:
|
||||
return ""
|
||||
|
||||
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for row in inventory_lines:
|
||||
key = (
|
||||
str(row.get("part_number") or "").strip(),
|
||||
str(row.get("reservation_id") or "").strip(),
|
||||
)
|
||||
inv_by_key[key] = row
|
||||
|
||||
for line in notice_lines:
|
||||
key = (
|
||||
str(line.get("part_number") or "").strip(),
|
||||
str(line.get("reservation_id") or "").strip(),
|
||||
)
|
||||
matched = inv_by_key.get(key)
|
||||
if matched:
|
||||
odm_id = str(matched.get("odm_id") or "").strip()
|
||||
if odm_id:
|
||||
return odm_id
|
||||
|
||||
for row in inventory_lines:
|
||||
odm_id = str(row.get("odm_id") or "").strip()
|
||||
if odm_id:
|
||||
return odm_id
|
||||
return ""
|
||||
|
||||
|
||||
def _shipment_warehouse_id(task: ShippingTask) -> str:
|
||||
"""
|
||||
解析发货 Excel Header 的 Warehouse ID。
|
||||
核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。
|
||||
"""
|
||||
try:
|
||||
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
|
||||
|
||||
snapshot = serialize_inventory_snapshot_link(task)
|
||||
except Exception:
|
||||
snapshot = None
|
||||
if isinstance(snapshot, dict):
|
||||
value = str(snapshot.get("warehouse_id") or "").strip()
|
||||
if value:
|
||||
def _typed_value(item: ShippingOrderFieldValue) -> Any:
|
||||
"""从类型化投影读取唯一业务值,禁止回退旧任务固定列。"""
|
||||
for value in (
|
||||
item.value_text, item.value_decimal, item.value_integer,
|
||||
item.value_date, item.value_boolean, item.value_json,
|
||||
):
|
||||
if value is not None:
|
||||
return value
|
||||
return "AWSDU"
|
||||
return None
|
||||
|
||||
|
||||
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
|
||||
for value in (line.get("po_number"), task.po_number):
|
||||
text = str(value or "").strip()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
def _order_values(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""将稳定 field_id 投影为 Header 字典及按订单行 position 排序的字典列表。"""
|
||||
header: dict[str, Any] = {}
|
||||
line_positions = {line.id: line.position for line in extraction.lines}
|
||||
lines: dict[int, dict[str, Any]] = {position: {} for position in line_positions.values()}
|
||||
for item in extraction.values:
|
||||
value = _typed_value(item)
|
||||
if item.line_id is None:
|
||||
header[item.field_id] = value
|
||||
elif item.line_id in line_positions:
|
||||
lines[line_positions[item.line_id]][item.field_id] = value
|
||||
return header, [lines[position] for position in sorted(lines)]
|
||||
|
||||
|
||||
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
|
||||
for value in (line.get("currency"), getattr(task, "currency", None)):
|
||||
text = str(value or "").strip().upper()
|
||||
if text:
|
||||
return text
|
||||
return ""
|
||||
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""读取任务当前已接受订单解析,并按稳定字段 ID 返回 Header 与明细值。"""
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
)
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ValueError('任务没有可用于库存匹配的订单解析版本')
|
||||
return _order_values(extraction)
|
||||
|
||||
|
||||
def _line_part_number(line: dict[str, Any]) -> str:
|
||||
"""返回货代明细使用的内部料号。"""
|
||||
return str(line.get("part_number") or "").strip()
|
||||
def _system_fact(task: ShippingTask, key: str) -> Any:
|
||||
"""读取受控任务事实,模板不能通过任意属性路径访问 ORM。"""
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': task.shipping_case.business_no if task.shipping_case else None,
|
||||
'warehouse_id': task.inventory_warehouse_id,
|
||||
'inventory_source_code': task.inventory_source_code,
|
||||
'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
}
|
||||
return values.get(key)
|
||||
|
||||
|
||||
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
|
||||
if ws.max_row < from_row:
|
||||
return
|
||||
for row_idx in range(from_row, ws.max_row + 1):
|
||||
for col_idx in range(1, ws.max_column + 1):
|
||||
ws.cell(row_idx, col_idx).value = None
|
||||
def _format_value(value: Any, formatter: str) -> Any:
|
||||
"""应用发布契约允许的确定性格式化器。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if formatter == 'upper':
|
||||
return str(value).upper()
|
||||
if formatter == 'lower':
|
||||
return str(value).lower()
|
||||
if formatter == 'date_mmddyyyy':
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.strftime('%m/%d/%Y')
|
||||
text = str(value).strip()
|
||||
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d', '%m/%d/%Y'):
|
||||
try:
|
||||
return datetime.strptime(text[:10], pattern).strftime('%m/%d/%Y')
|
||||
except ValueError:
|
||||
continue
|
||||
return text
|
||||
if formatter == 'integer':
|
||||
return int(Decimal(str(value)))
|
||||
if formatter == 'decimal':
|
||||
return float(Decimal(str(value)))
|
||||
return str(value) if isinstance(value, (Decimal, date, datetime)) else value
|
||||
|
||||
|
||||
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
|
||||
"""将业务号作为货代主引用写入 PVMI 模板,技术任务号仍用于系统追踪和文件名。"""
|
||||
wb = load_workbook(filename=str(path))
|
||||
header_ws = wb[HEADER_SHEET]
|
||||
detail_ws = wb[DETAIL_SHEET]
|
||||
|
||||
_clear_sheet_data_rows(detail_ws)
|
||||
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
|
||||
|
||||
header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task)
|
||||
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 2).value = "n"
|
||||
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
|
||||
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
|
||||
header_ws.cell(DATA_START_ROW, 4).value = "normal"
|
||||
|
||||
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
|
||||
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
|
||||
business_ref = task.shipping_case.business_no if task.shipping_case and task.shipping_case.business_no else task.task_no
|
||||
header_ws.cell(DATA_START_ROW, 7).value = business_ref
|
||||
|
||||
notice_lines = read_task_order_lines(task)
|
||||
if not notice_lines:
|
||||
notice_lines = [{}]
|
||||
|
||||
for index, line in enumerate(notice_lines, start=1):
|
||||
row_idx = DATA_START_ROW + index - 1
|
||||
line_no = str(line.get("line_no") or index).strip()
|
||||
qty = line.get("qty")
|
||||
amount = line.get("amount")
|
||||
|
||||
detail_ws.cell(row_idx, 1).value = business_ref
|
||||
detail_ws.cell(row_idx, 2).value = line_no
|
||||
detail_ws.cell(row_idx, 4).value = _line_part_number(line)
|
||||
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
|
||||
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
|
||||
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
|
||||
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
|
||||
|
||||
wb.save(path)
|
||||
def _mapping_value(
|
||||
mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
||||
header_values: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
"""按映射来源类型读取值;未知来源已在模板发布时被拒绝。"""
|
||||
kind = mapping['source_kind']
|
||||
key = mapping['source_key']
|
||||
if kind == 'order_field':
|
||||
value = order_values.get(key)
|
||||
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
|
||||
value = header_values.get(key)
|
||||
elif kind == 'inventory_field':
|
||||
value = inventory_values.get(str(key))
|
||||
elif kind == 'system_fact':
|
||||
value = _system_fact(task, key)
|
||||
else:
|
||||
value = key
|
||||
return _format_value(value, mapping['formatter'])
|
||||
|
||||
|
||||
def _row_values(task: ShippingTask, line: dict | None) -> list:
|
||||
line = line or {}
|
||||
return [
|
||||
task.customer_name or "",
|
||||
task.customer_code or "",
|
||||
task.ship_to or "",
|
||||
task.required_date or "",
|
||||
line.get("part_number") or "",
|
||||
line.get("qty") or "",
|
||||
line.get("uom") or "EA",
|
||||
line.get("remark") or "",
|
||||
]
|
||||
def _match_text(value: Any) -> str:
|
||||
"""规范化订单与库存匹配键;仅做确定性文本比较,不进行模糊推断。"""
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, Decimal):
|
||||
return format(value.normalize(), 'f')
|
||||
return str(value).strip().casefold()
|
||||
|
||||
|
||||
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
|
||||
"""填充 legacy 模板;技术任务号继续保留在导出文件名与系统记录中。"""
|
||||
wb = load_workbook(filename=str(path))
|
||||
ws = wb.active
|
||||
lines = read_task_order_lines(task) or [None]
|
||||
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
|
||||
ws.append(DEFAULT_HEADERS)
|
||||
for line in lines:
|
||||
ws.append(_row_values(task, line))
|
||||
wb.save(path)
|
||||
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
|
||||
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
|
||||
raw_ids = {
|
||||
str(item['source_key']) for item in mappings
|
||||
if item.get('row_mode') == row_mode and item.get('source_kind') == 'inventory_field'
|
||||
}
|
||||
ids = {int(item) for item in raw_ids if item.isdigit()}
|
||||
if len(ids) != len(raw_ids):
|
||||
raise ValueError('发货模板引用的库存字段无效')
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
|
||||
).all() if ids else []
|
||||
if len(rows) != len(ids):
|
||||
raise ValueError('发货模板引用的库存字段已不存在')
|
||||
return {str(item.id) for item in rows}
|
||||
|
||||
|
||||
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
|
||||
"""生成无模板工作簿;技术任务号继续保留在导出文件名与系统记录中。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Shipment"
|
||||
ws.append(DEFAULT_HEADERS)
|
||||
lines = read_task_order_lines(task) or [None]
|
||||
for line in lines:
|
||||
ws.append(_row_values(task, line))
|
||||
wb.save(path)
|
||||
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
|
||||
if not rows:
|
||||
return {}
|
||||
resolved = dict(rows[0])
|
||||
for field in required_fields:
|
||||
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
|
||||
if len(values) > 1:
|
||||
raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致')
|
||||
if values:
|
||||
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
|
||||
return resolved
|
||||
|
||||
|
||||
def _sanitize_filename(name: str) -> str:
|
||||
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
|
||||
return cleaned or "shipment.xlsx"
|
||||
def _match_inventory_lines(
|
||||
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
|
||||
match_keys: list[dict[str, str]], required_fields: set[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
|
||||
if not order_lines:
|
||||
return []
|
||||
if not match_keys:
|
||||
raise ValueError('库存解析模板缺少订单与库存匹配键')
|
||||
from app.models import ShippingInventoryField
|
||||
|
||||
ids = {
|
||||
int(item.get('inventory_field_id'))
|
||||
for item in match_keys
|
||||
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
|
||||
}
|
||||
catalog = {
|
||||
str(item.id): str(item.id)
|
||||
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(ids)).all()
|
||||
}
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
for item in match_keys:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError('库存解析模板匹配键无效')
|
||||
field_id = str(item.get('inventory_field_id') or '').strip()
|
||||
inventory_field = catalog.get(field_id)
|
||||
if not inventory_field:
|
||||
raise ValueError('库存解析模板引用的库存字段已不可用')
|
||||
normalized_keys.append({
|
||||
'order_field_id': str(item.get('order_field_id') or ''),
|
||||
'inventory_field': inventory_field,
|
||||
})
|
||||
result: list[dict[str, Any]] = []
|
||||
for position, order_line in enumerate(order_lines, start=1):
|
||||
expected = [
|
||||
(_match_text(order_line.get(item['order_field_id'])), item['inventory_field'])
|
||||
for item in normalized_keys
|
||||
]
|
||||
if any(not value for value, _field in expected):
|
||||
raise ValueError(f'第 {position} 条订单行缺少库存匹配键值')
|
||||
matched = [
|
||||
row for row in inventory_lines
|
||||
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
|
||||
]
|
||||
if not matched:
|
||||
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
|
||||
result.append(_collapse_inventory_matches(matched, required_fields))
|
||||
return result
|
||||
|
||||
|
||||
def _export_filename(task: ShippingTask, ts: str) -> str:
|
||||
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
|
||||
if not pattern:
|
||||
pattern = "shipment_{task_no}_{ts}.xlsx"
|
||||
def _header_inventory_values(
|
||||
matched_lines: list[dict[str, Any]], required_fields: set[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Header 库存字段必须在所有订单行匹配结果中一致,否则不能生成单一 Header。"""
|
||||
return _collapse_inventory_matches(matched_lines, required_fields)
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
"""清理配置化文件名,防止路径穿越并强制 xlsx 扩展名。"""
|
||||
cleaned = ''.join(ch for ch in name if ch.isalnum() or ch in {'-', '_', '.'}).strip('.')
|
||||
cleaned = cleaned or 'shipment.xlsx'
|
||||
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
|
||||
|
||||
|
||||
def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
|
||||
"""按发布规则生成下载名,业务单变量始终取已锁定的客户与编号快照。"""
|
||||
pattern = str((template.definition_json or {}).get('filename_pattern') or '')
|
||||
now = datetime.utcnow().strftime('%Y%m%d%H%M%S')
|
||||
shipping_case = task.shipping_case
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no,
|
||||
'source_code': task.inventory_source_code or '',
|
||||
'ts': now,
|
||||
'date': now[:8],
|
||||
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
|
||||
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
|
||||
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
|
||||
}
|
||||
try:
|
||||
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
|
||||
except Exception:
|
||||
name = f"shipment_{task.task_no}_{ts}.xlsx"
|
||||
if not str(name).lower().endswith(".xlsx"):
|
||||
name = f"{name}.xlsx"
|
||||
return _sanitize_filename(str(name))
|
||||
return _safe_filename(pattern.format(**values))
|
||||
except (KeyError, ValueError) as exc:
|
||||
raise ValueError('发货 Excel 文件名规则无效') from exc
|
||||
|
||||
|
||||
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
|
||||
def _input_checksum(
|
||||
task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
||||
extraction: ShippingOrderExtraction, header: dict[str, Any], lines: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
|
||||
payload = {
|
||||
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
|
||||
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
|
||||
'schema_version_id': extraction.schema_version_id, 'extraction_id': extraction.id,
|
||||
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
|
||||
'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [],
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
基于任务数据生成货代发货 Excel 并写入 exports 目录。
|
||||
【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。
|
||||
|
||||
核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
|
||||
Returns:
|
||||
tuple[str, str]: (export_file_path, export_file_name)。
|
||||
(绝对文件路径, 下载文件名, 待随任务事务提交的 Artifact)。
|
||||
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
"""
|
||||
root = _storage_root() / "exports"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
source_code = str(task.inventory_source_code or '').strip().upper()
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
|
||||
# Fixed Sources receive this value from configuration; dynamic Sources receive it
|
||||
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
|
||||
if not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
template = source.excel_template
|
||||
if template is None or template.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的库存解析模板')
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
)
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ValueError('任务没有可用于导出的订单解析版本')
|
||||
header_values, line_values = _order_values(extraction)
|
||||
inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)]
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
raise ValueError('发货 Excel 模板没有已发布的字段映射')
|
||||
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')
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
matched_inventory_lines = _match_inventory_lines(
|
||||
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
|
||||
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
|
||||
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
|
||||
|
||||
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
|
||||
filename = _export_filename(task, ts)
|
||||
path = root / filename
|
||||
|
||||
template = _default_template_path()
|
||||
if template:
|
||||
copy2(template, path)
|
||||
wb = load_workbook(filename=str(path), read_only=True)
|
||||
filename = _filename(task, template)
|
||||
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
|
||||
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f'{artifact_no}_{filename}'
|
||||
template_bytes = file_asset_storage.get_bytes(template.storage_key)
|
||||
if hashlib.sha256(template_bytes).hexdigest() != template.file_checksum:
|
||||
raise ValueError('发货 Excel 模板文件缺失或校验失败')
|
||||
try:
|
||||
path.write_bytes(template_bytes)
|
||||
wb = load_workbook(path)
|
||||
try:
|
||||
is_pvmi = _is_pvmi_workbook(wb)
|
||||
for mapping in mappings:
|
||||
ws = wb[mapping['sheet']]
|
||||
start_row = int(mapping['start_row'])
|
||||
column = int(mapping['target_column'])
|
||||
if mapping['row_mode'] == 'header':
|
||||
ws.cell(start_row, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
|
||||
)
|
||||
continue
|
||||
row_count = max(len(line_values), 1)
|
||||
for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1):
|
||||
ws.cell(row_index, column).value = None
|
||||
for index in range(row_count):
|
||||
order_line = line_values[index] if index < len(line_values) else {}
|
||||
inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {}
|
||||
ws.cell(start_row + index, column).value = _mapping_value(
|
||||
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
|
||||
header_values=header_values,
|
||||
)
|
||||
wb.save(path)
|
||||
finally:
|
||||
wb.close()
|
||||
if is_pvmi:
|
||||
_fill_pvmi_template(task, path)
|
||||
else:
|
||||
_fill_legacy_template(task, path)
|
||||
else:
|
||||
_fill_blank_workbook(task, path)
|
||||
|
||||
return str(path), filename
|
||||
content = path.read_bytes()
|
||||
db.session.execute(
|
||||
update(ShippingExportArtifact)
|
||||
.where(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status == 'ready',
|
||||
)
|
||||
.values(status='superseded')
|
||||
)
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_id, template_id=template.id,
|
||||
order_schema_version_id=extraction.schema_version_id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
input_checksum=_input_checksum(task, source, template, extraction, header_values, line_values),
|
||||
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
|
||||
file_size=len(content), status='ready',
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
if path.is_file():
|
||||
path.unlink()
|
||||
raise
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
services/shipping_notice/export_archive.py
|
||||
|
||||
用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
|
||||
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
|
||||
逻辑:只选每票最新 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from tempfile import SpooledTemporaryFile
|
||||
from typing import BinaryIO
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingTask
|
||||
from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
|
||||
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingTask], str]:
|
||||
"""按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。"""
|
||||
normalized_batch = str(batch_no or '').strip()
|
||||
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
|
||||
if bool(normalized_batch) == bool(normalized_tasks):
|
||||
raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
if normalized_batch:
|
||||
batch = get_batch_for_user(normalized_batch, user_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
archive_key = normalized_batch
|
||||
else:
|
||||
tasks = []
|
||||
for task_no in normalized_tasks:
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None:
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
tasks.append(task)
|
||||
archive_key = 'selected'
|
||||
if not tasks:
|
||||
raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY')
|
||||
if len(tasks) > MAX_ARCHIVE_TASKS:
|
||||
raise ValidationError(
|
||||
f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once',
|
||||
code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS},
|
||||
)
|
||||
return tasks, archive_key
|
||||
|
||||
|
||||
def _latest_ready_artifacts(tasks: list[ShippingTask]) -> dict[int, ShippingExportArtifact]:
|
||||
"""批量查询每票最新 ready Artifact,避免 N+1。"""
|
||||
task_ids = [int(task.id) for task in tasks if task.id is not None]
|
||||
rows = ShippingExportArtifact.query.join(ShippingTask, ShippingTask.id == ShippingExportArtifact.task_id).filter(
|
||||
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
|
||||
ShippingTask.export_file_path == ShippingExportArtifact.file_path,
|
||||
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).all()
|
||||
result: dict[int, ShippingExportArtifact] = {}
|
||||
for item in rows:
|
||||
result.setdefault(int(item.task_id), item)
|
||||
return result
|
||||
|
||||
|
||||
def _archive_name(filename: str, task_no: str, used: set[str]) -> str:
|
||||
"""保留原下载名;冲突时追加 task_no,仍冲突再追加序号。"""
|
||||
safe = Path(filename or f'{task_no}.xlsx').name
|
||||
candidate = safe
|
||||
if candidate.lower() in used:
|
||||
stem = Path(safe).stem
|
||||
suffix = Path(safe).suffix or '.xlsx'
|
||||
candidate = f'{stem}_{task_no}{suffix}'
|
||||
sequence = 2
|
||||
base = candidate
|
||||
while candidate.lower() in used:
|
||||
candidate = f'{Path(base).stem}_{sequence}{Path(base).suffix}'
|
||||
sequence += 1
|
||||
used.add(candidate.lower())
|
||||
return candidate
|
||||
|
||||
|
||||
def build_export_archive(
|
||||
*, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None,
|
||||
) -> tuple[BinaryIO, str, dict]:
|
||||
"""
|
||||
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
|
||||
|
||||
Returns:
|
||||
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
|
||||
"""
|
||||
tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos)
|
||||
artifacts = _latest_ready_artifacts(tasks)
|
||||
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
|
||||
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
|
||||
used_names: set[str] = {'manifest.json'}
|
||||
entries: list[dict] = []
|
||||
included = 0
|
||||
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
|
||||
for task in tasks:
|
||||
artifact = artifacts.get(int(task.id)) if task.id is not None else None
|
||||
entry = {'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None}
|
||||
if artifact is not None:
|
||||
entry['artifact_no'] = artifact.artifact_no
|
||||
path = Path(artifact.file_path)
|
||||
if not path.is_file():
|
||||
entry['status'] = 'missing_file'
|
||||
else:
|
||||
content = path.read_bytes()
|
||||
if hashlib.sha256(content).hexdigest() != artifact.file_checksum:
|
||||
entry['status'] = 'checksum_mismatch'
|
||||
else:
|
||||
name = _archive_name(artifact.file_name, task.task_no, used_names)
|
||||
archive.writestr(name, content)
|
||||
entry.update({'status': 'included', 'file_name': name, 'file_checksum': artifact.file_checksum})
|
||||
included += 1
|
||||
entries.append(entry)
|
||||
manifest = {
|
||||
'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []},
|
||||
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
|
||||
'included_count': included, 'excluded_count': len(tasks) - included, 'entries': entries,
|
||||
}
|
||||
archive.writestr('manifest.json', json.dumps(manifest, ensure_ascii=False, indent=2).encode('utf-8'))
|
||||
stream.seek(0)
|
||||
filename = f'shipping_exports_{archive_key}_{datetime.utcnow():%Y%m%d%H%M%S}.zip'
|
||||
return stream, filename, manifest
|
||||
@@ -105,9 +105,7 @@ def format_field_alignment_summary(
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> str:
|
||||
"""
|
||||
生成字段对齐确认的固定 Markdown 摘要(apply_inventory_mapping / align_review 用)。
|
||||
|
||||
Agent 须原文展示 message 给用户后再等待 confirm_inventory_mapping。
|
||||
生成库存与订单字段对照的固定 Markdown 摘要,仅用于解析审计和结果展示。
|
||||
"""
|
||||
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
|
||||
inv_count = inventory_row_count
|
||||
|
||||
@@ -9,6 +9,8 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
@@ -17,11 +19,7 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING
|
||||
from app.services.shipping_notice.export import generate_shipment_excel
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_mapping_checkpoint_response,
|
||||
)
|
||||
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
from app.services.shipping_notice.inventory_workflow import (
|
||||
ensure_inventory,
|
||||
@@ -34,7 +32,6 @@ from app.services.shipping_notice.query_service import (
|
||||
task_export_error_message,
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
from app.services.shipping_notice.reservation_gate import reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
@@ -232,6 +229,27 @@ def try_auto_chain_after_match(
|
||||
return result
|
||||
|
||||
|
||||
def _order_extraction_gate_response(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
forbidden_next_tools: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""要求任务绑定已接受的动态订单解析版本,禁止旧固定字段任务进入履约副作用。"""
|
||||
try:
|
||||
order_field_id_values(task)
|
||||
except ValueError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message=str(exc),
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=forbidden_next_tools,
|
||||
next_required_action="请重新提交订单解析并确认动态订单字段后继续。",
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。
|
||||
@@ -272,12 +290,14 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if reservation_gate is not None:
|
||||
return reservation_gate
|
||||
|
||||
# [STEP 1] 先确认字段对齐与库存快照是否已经就绪。
|
||||
# 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
extraction_gate = _order_extraction_gate_response(
|
||||
task,
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
if extraction_gate is not None:
|
||||
return extraction_gate
|
||||
|
||||
# [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
if inventory_lines:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
@@ -290,6 +310,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inv_payload["lang"] = lang
|
||||
return ensure_inventory(inv_payload)
|
||||
notice_lines = read_task_order_lines(task)
|
||||
_order_header_values, order_field_lines = order_field_id_values(task)
|
||||
for index, order_line in enumerate(order_field_lines):
|
||||
legacy_line = notice_lines[index] if index < len(notice_lines) else {}
|
||||
order_line['__required_qty'] = legacy_line.get('qty')
|
||||
order_line['__display_part_number'] = legacy_line.get('part_number')
|
||||
order_line['__display_reservation_id'] = legacy_line.get('reservation_id')
|
||||
total_notice_lines = len(notice_lines)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -304,13 +330,6 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 订单侧 Reservation 已在任何库存副作用前校验;此处只统计库存侧缺失。
|
||||
inv_missing_count = sum(
|
||||
1
|
||||
for row in (inventory_lines or [])
|
||||
if not is_valid_reservation_id((row or {}).get("reservation_id"))
|
||||
)
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -339,13 +358,29 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if processed == total or processed % 50 == 0:
|
||||
db.session.flush()
|
||||
|
||||
from app.models import ShippingInventoryField, ShippingInventorySource
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
|
||||
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
|
||||
mapped_field_ids = [
|
||||
int(field_id) for field_id in (definition.get('field_mapping') or {})
|
||||
if str(field_id).isdigit()
|
||||
] if isinstance(definition, dict) else []
|
||||
quantity_fields = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(mapped_field_ids),
|
||||
ShippingInventoryField.status == 'active',
|
||||
ShippingInventoryField.usage_type == 'inventory_quantity',
|
||||
).all() if mapped_field_ids else []
|
||||
if len(quantity_fields) != 1:
|
||||
raise ValueError('库存解析方案必须且只能配置一个库存数量字段')
|
||||
match_status, line_results, shortage = match_notice_lines(
|
||||
notice_lines,
|
||||
order_field_lines,
|
||||
inventory_lines or [],
|
||||
match_keys=match_keys,
|
||||
quantity_field_id=str(quantity_fields[0].id),
|
||||
progress_callback=_on_match_progress,
|
||||
)
|
||||
if inv_missing_count and isinstance(shortage, dict):
|
||||
shortage.pop("warnings", None)
|
||||
task.match_status = match_status
|
||||
task.line_results_json = line_results
|
||||
task.shortage_json = shortage
|
||||
@@ -396,6 +431,18 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def _commit_generated_export(path: str) -> None:
|
||||
"""提交任务与 Artifact;提交失败时回滚并删除本次生成文件。"""
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
generated_path = Path(path)
|
||||
if generated_path.is_file():
|
||||
generated_path.unlink()
|
||||
raise
|
||||
|
||||
|
||||
def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
|
||||
@@ -430,6 +477,13 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if reservation_gate is not None:
|
||||
return reservation_gate
|
||||
|
||||
extraction_gate = _order_extraction_gate_response(
|
||||
task,
|
||||
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
if extraction_gate is not None:
|
||||
return extraction_gate
|
||||
|
||||
if not is_inventory_source_stable(task):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
@@ -475,7 +529,16 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
|
||||
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
|
||||
path, filename = generate_shipment_excel(task)
|
||||
try:
|
||||
path, filename, artifact = generate_shipment_excel(task)
|
||||
except ValueError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message=str(exc),
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
)
|
||||
task.export_file_path = path
|
||||
task.export_file_name = filename
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
@@ -488,8 +551,8 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
progress_percent=100,
|
||||
detail=filename,
|
||||
)
|
||||
log_task_event(task, "export_generated", {"file_name": filename})
|
||||
db.session.commit()
|
||||
log_task_event(task, "export_generated", {"file_name": filename, "artifact_no": artifact.artifact_no})
|
||||
_commit_generated_export(path)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
@@ -823,4 +886,3 @@ def run_auto_progress_fulfillment_steps(
|
||||
return up
|
||||
|
||||
return None
|
||||
|
||||
@@ -84,14 +84,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.parse_confirmed_wait": "等待后台继续处理或稍后刷新任务状态",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory 或 parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "已确认,可继续生成 Excel 并上传货代系统。",
|
||||
"workflow.decision.confirm_invalid_state": "当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
|
||||
"workflow.decision.mapping_not_needed": "当前无需确认库存字段对齐。",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "库存表必须包含 Reservation ID 列标题(该列允许为空值)。请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。",
|
||||
"workflow.decision.mapping_correction_invalid_state": "当前不在库存字段对齐确认步骤,无法更正映射。",
|
||||
"workflow.decision.read_inventory_preview_failed": "读取库存表头失败: {error}",
|
||||
"workflow.decision.mapping_preview_note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
|
||||
"workflow.decision.mapping_correction_needed": "已回到列映射步骤。请根据 schema_preview 提供新的 map_json,再调用 apply_inventory_mapping。",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.confirm_invalid_state": "当前状态无法使用确认。请先完成库存匹配,或选择重新解析订单。",
|
||||
"workflow.decision.inventory_cleared": "已清除库存快照。请重新上传或粘贴库存,后续继续在当前任务中处理。",
|
||||
"workflow.decision.unknown": "未知 decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "未找到任务编号",
|
||||
@@ -99,23 +92,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.text_too_large": "库存文本过大({chars} 字符,上限 {max_chars})。请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 POST /tools/upload_inventory_file 上传,再 parse_inventory(use_uploaded_file=true)。",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
|
||||
"workflow.inventory.preview_read_failed": "读取库存表头失败: {error}",
|
||||
"workflow.inventory.preview_ready": "已读取库存表头与样例行。请根据 schema_preview 推断列映射,调用 apply_inventory_mapping(map_json=...)。",
|
||||
"workflow.inventory.preview_next": "根据 data.schema_preview.headers 与 sample_rows 推断 JSON:{\"part_number\":\"<Supplier Sku列>\",\"aws_part_number\":\"<AWS Sku列,可选>\",\"reservation_id\":\"<列名>\",\"available_qty\":\"<列名>\"},再调用 apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "未找到已上传的库存文件。请先 upload_inventory_file。",
|
||||
"workflow.inventory.mapping_invalid": "map_json 无效或不完整。需要提供 {\"part_number\":\"Supplier Sku列\",\"reservation_id\":\"列名\",\"available_qty\":\"列名\"};aws_part_number 可选。",
|
||||
"workflow.inventory.mapping_header_mismatch": "列映射与 Excel 表头不匹配。(表头在第 {row} 行){errors} 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "未收到 file 字段",
|
||||
"workflow.inventory.file_type_unsupported": "仅支持 .xlsx / .csv 库存文件",
|
||||
"workflow.inventory.file_type_unsupported": "仅支持 .xls / .xlsx / .csv 库存文件",
|
||||
"workflow.inventory.uploading": "正在上传并解析库存文件",
|
||||
"workflow.inventory.uploading_detail": "正在处理库存文件 {filename}",
|
||||
"workflow.inventory.save_failed": "保存库存文件失败: {error}",
|
||||
"workflow.inventory.completed_task_locked": "该任务已完成,不能再重新上传库存。请切换到仍待处理的任务后再上传库存文件。",
|
||||
"workflow.inventory.uploaded": "库存文件已上传。",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。",
|
||||
"workflow.inventory.uploaded_need_llm": " 请由画布 LLM 推断列映射后 apply_inventory_mapping。",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "已有库存快照且字段对齐已确认,可调用 match_inventory。",
|
||||
"workflow.inventory.unavailable": "暂无可用库存数据。请重新获取库存,或手动上传货代库存 Excel。",
|
||||
"workflow.fulfillment.task_not_found": "未找到任务编号",
|
||||
@@ -222,14 +207,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.parse_confirmed_wait": "Wait for backend processing or refresh the task status later.",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory or parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "Confirmed. You may continue to generate the Excel and upload to the freight system.",
|
||||
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Please complete inventory matching first, or use confirm_inventory_mapping / reparse.",
|
||||
"workflow.decision.mapping_not_needed": "Inventory field alignment confirmation is not needed right now.",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "The inventory sheet must contain a Reservation ID column header (the values in that column may be empty). Please use Fix Mapping to choose the Reservation ID column again, or re-upload an inventory Excel that contains that column.",
|
||||
"workflow.decision.mapping_correction_invalid_state": "The task is not currently in the inventory field alignment confirmation step, so the mapping cannot be corrected.",
|
||||
"workflow.decision.read_inventory_preview_failed": "Failed to read inventory headers: {error}",
|
||||
"workflow.decision.mapping_preview_note": "No uploaded Excel was found. Please paste a small inventory table or re-upload, then call apply_inventory_mapping / parse_inventory.",
|
||||
"workflow.decision.mapping_correction_needed": "The task has returned to the mapping step. Please provide a new map_json based on schema_preview, then call apply_inventory_mapping.",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.confirm_invalid_state": "Confirm cannot be used in the current state. Complete inventory matching first, or reparse the order.",
|
||||
"workflow.decision.inventory_cleared": "The inventory snapshot has been cleared. Please re-upload or paste inventory data, then continue in the current task.",
|
||||
"workflow.decision.unknown": "Unknown decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "Task ID not found.",
|
||||
@@ -237,23 +215,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.text_too_large": "The inventory text is too large ({chars} characters, limit {max_chars}). Do not send the full Excel content to the LLM. Please call POST /tools/upload_inventory_file first, then parse_inventory(use_uploaded_file=true).",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "Inventory lines could not be parsed. For large Excel files, use upload_inventory_file; for small tables, paste the content; if inventory is unavailable, use RPA.",
|
||||
"workflow.inventory.preview_read_failed": "Failed to read inventory headers: {error}",
|
||||
"workflow.inventory.preview_ready": "Inventory headers and sample rows have been loaded. Please infer the column mapping from schema_preview and call apply_inventory_mapping(map_json=...).",
|
||||
"workflow.inventory.preview_next": "Infer JSON from data.schema_preview.headers and sample_rows: {\"part_number\":\"<Supplier Sku column>\",\"aws_part_number\":\"<AWS Sku column, optional>\",\"reservation_id\":\"<column>\",\"available_qty\":\"<column>\"}, then call apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "No uploaded inventory file was found. Please call upload_inventory_file first.",
|
||||
"workflow.inventory.mapping_invalid": "map_json is invalid or incomplete. Provide part_number (Supplier Sku), reservation_id, and available_qty mappings; aws_part_number is optional.",
|
||||
"workflow.inventory.mapping_header_mismatch": "The column mapping does not match the Excel headers. (The header row is row {row}) {errors} Please call apply_inventory_mapping again using schema_preview.headers.",
|
||||
"workflow.inventory.parse_failed_detail": "Failed to parse inventory: {error}",
|
||||
"workflow.inventory.file_missing": "The file field was not received.",
|
||||
"workflow.inventory.file_type_unsupported": "Only .xlsx / .csv inventory files are supported.",
|
||||
"workflow.inventory.file_type_unsupported": "Only .xls / .xlsx / .csv inventory files are supported.",
|
||||
"workflow.inventory.uploading": "Uploading and parsing the inventory file.",
|
||||
"workflow.inventory.uploading_detail": "Processing inventory file {filename}",
|
||||
"workflow.inventory.save_failed": "Failed to save inventory file: {error}",
|
||||
"workflow.inventory.completed_task_locked": "This task is already completed, so inventory cannot be uploaded again. Please switch to a task that still needs processing.",
|
||||
"workflow.inventory.uploaded": "The inventory file has been uploaded.",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping is complete, so the canvas can call apply_inventory_mapping directly without using the LLM.",
|
||||
"workflow.inventory.uploaded_need_llm": " Please let the canvas LLM infer the column mapping and then call apply_inventory_mapping.",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "An inventory snapshot already exists and the field alignment has been confirmed. You may call match_inventory.",
|
||||
"workflow.inventory.unavailable": "No usable inventory data is available yet. Please retry the RPA export or upload the freight inventory Excel manually.",
|
||||
"workflow.fulfillment.task_not_found": "Task ID not found.",
|
||||
@@ -360,14 +330,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.decision.parse_confirmed_wait": "รอให้ระบบหลังบ้านดำเนินการต่อ หรือกลับมาตรวจสอบสถานะงานภายหลัง",
|
||||
"workflow.decision.parse_confirmed_manual_next": "ensure_inventory หรือ parse_inventory",
|
||||
"workflow.decision.matched_confirmed": "ยืนยันแล้ว สามารถดำเนินการสร้างไฟล์ Excel และอัปโหลดไปยังระบบขนส่งต่อได้",
|
||||
"workflow.decision.confirm_invalid_state": "ไม่สามารถใช้ confirm ในสถานะปัจจุบันได้ โปรดทำ inventory matching ให้เสร็จก่อน หรือใช้ confirm_inventory_mapping / reparse",
|
||||
"workflow.decision.mapping_not_needed": "ขณะนี้ยังไม่ต้องยืนยันการจับคู่คอลัมน์สต็อก",
|
||||
"workflow.decision.mapping_missing_reservation_warning": "ไฟล์สต็อกต้องมีหัวคอลัมน์ Reservation ID (ค่าภายในคอลัมน์นี้สามารถเว้นว่างได้) โปรดใช้ Fix Mapping เพื่อเลือกคอลัมน์ Reservation ID ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกที่มีคอลัมน์นี้อีกครั้ง",
|
||||
"workflow.decision.mapping_correction_invalid_state": "ขณะนี้งานไม่ได้อยู่ในขั้นตอนยืนยันการจับคู่คอลัมน์สต็อก จึงไม่สามารถแก้ไข mapping ได้",
|
||||
"workflow.decision.read_inventory_preview_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.decision.mapping_preview_note": "ไม่พบไฟล์ Excel ที่อัปโหลดไว้ โปรดวางตารางสต็อกขนาดเล็กหรืออัปโหลดใหม่ แล้วจึงเรียก apply_inventory_mapping / parse_inventory",
|
||||
"workflow.decision.mapping_correction_needed": "งานได้ย้อนกลับมาที่ขั้นตอนจับคู่คอลัมน์แล้ว โปรดส่ง map_json ใหม่ตาม schema_preview แล้วเรียก apply_inventory_mapping",
|
||||
"workflow.decision.mapping_correction_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.decision.confirm_invalid_state": "ไม่สามารถยืนยันในสถานะปัจจุบันได้ โปรดจับคู่สต็อกให้เสร็จก่อน หรือแยกวิเคราะห์คำสั่งซื้อใหม่",
|
||||
"workflow.decision.inventory_cleared": "ล้าง snapshot สต็อกแล้ว โปรดอัปโหลดใหม่หรือวางข้อมูลสต็อก แล้วดำเนินการต่อในงานปัจจุบัน",
|
||||
"workflow.decision.unknown": "ไม่รู้จัก decision: {decision}",
|
||||
"workflow.inventory.task_not_found": "ไม่พบรหัสงาน",
|
||||
@@ -375,23 +338,15 @@ _MESSAGES: dict[str, dict[str, str]] = {
|
||||
"workflow.inventory.text_too_large": "ข้อความสต็อกมีขนาดใหญ่เกินไป ({chars} ตัวอักษร, จำกัด {max_chars}) โปรดอย่าส่งเนื้อหา Excel ทั้งหมดเข้า LLM ให้เรียก POST /tools/upload_inventory_file ก่อน แล้วจึงใช้ parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.upload_then_parse": "upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
|
||||
"workflow.inventory.parse_failed": "ไม่สามารถแยกรายการสต็อกได้ สำหรับไฟล์ Excel ขนาดใหญ่ให้ใช้ upload_inventory_file; สำหรับตารางเล็กสามารถวางข้อความได้; หากไม่มีสต็อกให้ใช้ RPA",
|
||||
"workflow.inventory.preview_read_failed": "อ่านหัวตารางสต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.inventory.preview_ready": "อ่านหัวตารางและแถวตัวอย่างของสต็อกแล้ว โปรดอนุมานการจับคู่คอลัมน์จาก schema_preview แล้วเรียก apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.preview_next": "อนุมาน JSON จาก data.schema_preview.headers และ sample_rows โดยใช้ part_number จาก Supplier Sku, aws_part_number จาก AWS Sku (ไม่บังคับ), reservation_id และ available_qty แล้วเรียก apply_inventory_mapping",
|
||||
"workflow.inventory.uploaded_file_missing_short": "ไม่พบไฟล์สต็อกที่อัปโหลดไว้ โปรดเรียก upload_inventory_file ก่อน",
|
||||
"workflow.inventory.mapping_invalid": "map_json ไม่ถูกต้องหรือไม่ครบ ต้องระบุ part_number (Supplier Sku), reservation_id และ available_qty; aws_part_number เป็นตัวเลือก",
|
||||
"workflow.inventory.mapping_header_mismatch": "การจับคู่คอลัมน์ไม่ตรงกับหัวตาราง Excel (หัวตารางอยู่ที่แถว {row}) {errors} โปรดเรียก apply_inventory_mapping ใหม่โดยอ้างอิง schema_preview.headers",
|
||||
"workflow.inventory.parse_failed_detail": "解析库存失败: {error}",
|
||||
"workflow.inventory.file_missing": "ไม่ได้รับฟิลด์ file",
|
||||
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xlsx / .csv",
|
||||
"workflow.inventory.file_type_unsupported": "รองรับเฉพาะไฟล์สต็อก .xls / .xlsx / .csv",
|
||||
"workflow.inventory.uploading": "กำลังอัปโหลดและ解析ไฟล์สต็อก",
|
||||
"workflow.inventory.uploading_detail": "กำลังประมวลผลไฟล์สต็อก {filename}",
|
||||
"workflow.inventory.save_failed": "บันทึกไฟล์สต็อกไม่สำเร็จ: {error}",
|
||||
"workflow.inventory.completed_task_locked": "งานนี้เสร็จสิ้นแล้ว จึงไม่สามารถอัปโหลดสต็อกซ้ำได้ โปรดสลับไปยังงานที่ยังต้องดำเนินการ",
|
||||
"workflow.inventory.uploaded": "อัปโหลดไฟล์สต็อกแล้ว",
|
||||
"workflow.inventory.uploaded_suggested_complete": " suggested_mapping ครบแล้ว จึงสามารถเรียก apply_inventory_mapping ได้ตรงจาก canvas โดยไม่ต้องผ่าน LLM",
|
||||
"workflow.inventory.uploaded_need_llm": " โปรดให้ LLM บน canvas อนุมานการจับคู่คอลัมน์ แล้วจึงเรียก apply_inventory_mapping",
|
||||
"workflow.inventory.apply_mapping_next": "apply_inventory_mapping(map_json=...)",
|
||||
"workflow.inventory.ready_for_match": "มี inventory snapshot อยู่แล้วและยืนยันการจับคู่คอลัมน์แล้ว สามารถเรียก match_inventory ได้",
|
||||
"workflow.inventory.unavailable": "ยังไม่มีข้อมูลสต็อกที่ใช้งานได้ โปรดลองส่งออกผ่าน RPA ใหม่ หรืออัปโหลดไฟล์ Excel สต็อกของผู้ให้บริการขนส่งด้วยตนเอง",
|
||||
"workflow.fulfillment.task_not_found": "ไม่พบรหัสงาน",
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_configuration_test.py
|
||||
|
||||
用途:编排库存站点测试导出、RPA 回调文件分析和管理员确认解析方案。
|
||||
依赖:库存站点/RPA trigger、库存结构分析、库存解析方案模型。
|
||||
逻辑:管理端仅对停用站点发起测试;RPA 文件只写测试运行和结构分析,不创建生产快照、不关联订单任务。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryConfigurationTestRun,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
)
|
||||
|
||||
|
||||
def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
|
||||
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
|
||||
return {
|
||||
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
|
||||
'source_config_version': run.source_config_version, 'status': run.status, 'stage': run.stage,
|
||||
'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message,
|
||||
'created_at': run.created_at.isoformat() if run.created_at else None,
|
||||
'completed_at': run.completed_at.isoformat() if run.completed_at else None,
|
||||
}
|
||||
|
||||
|
||||
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
if source.enabled:
|
||||
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
|
||||
if source.rpa_profile is None or not source.rpa_profile.enabled:
|
||||
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
|
||||
active = ShippingInventoryConfigurationTestRun.query.filter(
|
||||
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
|
||||
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
|
||||
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
|
||||
if active:
|
||||
return _payload(active)
|
||||
from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
|
||||
run = ShippingInventoryConfigurationTestRun(
|
||||
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
|
||||
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
source_payload = get_database_inventory_source(source.source_code, enabled_only=False)
|
||||
if source_payload is None:
|
||||
raise ValidationError('Inventory Source is invalid', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
try:
|
||||
trigger = write_inventory_export_batch_trigger(run_no, [source_payload], payload={
|
||||
'trigger_type': 'configuration_test', 'configuration_test_run_id': run.id,
|
||||
})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
if not trigger:
|
||||
db.session.rollback()
|
||||
raise ConflictError('RPA Worker is not ready', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_UNAVAILABLE')
|
||||
run.result_json = {'trigger_written': True}
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
|
||||
|
||||
def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
|
||||
"""读取指定库存站点的测试运行,防止跨站点查看结果。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(
|
||||
inventory_source_id=source_id, run_no=str(run_no or '').strip(),
|
||||
).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
return _payload(run)
|
||||
|
||||
|
||||
def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""处理 Worker 测试回调:分析文件并生成推荐,绝不创建生产库存快照。"""
|
||||
run_no = str(payload.get('run_no') or '').strip()
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
|
||||
if run.status == 'completed':
|
||||
return _payload(run)
|
||||
source = db.session.get(ShippingInventorySource, run.inventory_source_id)
|
||||
if source is None or source.config_version != run.source_config_version:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
status = str(payload.get('status') or 'success').lower()
|
||||
if status != 'success':
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
path = Path(str(payload.get('file_path') or ''))
|
||||
if not path.is_file():
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, _analysis_root, serialize_analysis
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.models import ShippingInventoryStructureAnalysis
|
||||
import hashlib
|
||||
import uuid
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
|
||||
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
|
||||
suffix = resolve_inventory_upload_suffix(path.name)
|
||||
raw = path.read_bytes()
|
||||
target_dir = _analysis_root() / uuid.uuid4().hex
|
||||
target_dir.mkdir(parents=True, exist_ok=False)
|
||||
target = target_dir / f'test{suffix}'
|
||||
try:
|
||||
shutil.copy2(path, target)
|
||||
structure, suggested, summary, warnings = _analyse_path(target, suffix)
|
||||
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
|
||||
analysis = ShippingInventoryStructureAnalysis(
|
||||
source_kind='configuration_test', source_file_name=path.name, storage_path=str(target), file_checksum=hashlib.sha256(raw).hexdigest(),
|
||||
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
|
||||
validation_summary_json=summary, warning_json=warnings, created_by=run.created_by,
|
||||
exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]),
|
||||
)
|
||||
db.session.add(analysis); db.session.flush()
|
||||
analysis.match_result_json = recommend_profiles({'structure': structure, 'suggested_mapping': suggested, 'exact_structure_fingerprint': analysis.exact_structure_fingerprint, 'compatibility_fingerprint': analysis.compatibility_fingerprint})
|
||||
run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
shutil.rmtree(target_dir, ignore_errors=True)
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _payload(run)
|
||||
|
||||
|
||||
def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""管理员确认测试结果使用的已发布方案,才更新停用库存站点的解析方案绑定。"""
|
||||
run = ShippingInventoryConfigurationTestRun.query.filter_by(inventory_source_id=source_id, run_no=run_no).first()
|
||||
if run is None or run.status != 'completed' or run.analysis_id is None:
|
||||
raise ConflictError('Configuration test is not ready for confirmation', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_READY')
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if source is None or profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
if source.enabled or source.config_version != run.source_config_version:
|
||||
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
|
||||
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
|
||||
|
||||
adopt_published_profile(run.analysis_id, profile_id)
|
||||
source.parsing_profile_id = profile.id
|
||||
source.updated_by = actor_id
|
||||
source.config_version += 1
|
||||
run.source_config_version = source.config_version
|
||||
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
|
||||
db.session.commit()
|
||||
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_external_mapping.py
|
||||
|
||||
用途:解析库存来源与已确定 Warehouse 对应的外部系统仓库。
|
||||
依赖:ShippingInventoryExternalMapping、ShippingInventorySource。
|
||||
逻辑:Excel 与后续调拨 Agent 可复用本内部服务;本模块不提供 Tool API,也不决定是否调拨。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
|
||||
|
||||
def resolve_external_warehouse(*, source_code: str | None, freight_warehouse_id: str | None) -> dict[str, Any] | None:
|
||||
"""按精确 Warehouse 映射优先、Source 默认映射兜底的顺序解析外部系统仓库。"""
|
||||
code = str(source_code or '').strip().upper()
|
||||
warehouse = str(freight_warehouse_id or '').strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code, enabled=True).first()
|
||||
if source is None:
|
||||
return None
|
||||
query = ShippingInventoryExternalMapping.query.filter_by(inventory_source_id=source.id, enabled=True)
|
||||
mapping = query.filter_by(freight_warehouse_id=warehouse).first() if warehouse else None
|
||||
mapping = mapping or query.filter(ShippingInventoryExternalMapping.freight_warehouse_id.is_(None)).first()
|
||||
if mapping is None:
|
||||
return None
|
||||
return {
|
||||
'external_system_code': mapping.external_system_code,
|
||||
'external_organization_code': mapping.external_organization_code,
|
||||
'external_site_code': mapping.external_site_code,
|
||||
'external_warehouse_code': mapping.external_warehouse_code,
|
||||
'external_warehouse_name': mapping.external_warehouse_name,
|
||||
'freight_warehouse_id': warehouse or None,
|
||||
'mapping_id': mapping.id,
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_field_catalog.py
|
||||
|
||||
用途:维护货代库存统一业务字段目录,供后续库存解析方案和发货模板安全引用。
|
||||
依赖:ShippingInventoryField、统一业务异常和 SQLAlchemy 事务。
|
||||
逻辑:目录初始为空;管理员维护字段名称与业务用途,引用保护只依据实际配置和历史使用情况。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from hashlib import sha1
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryParsingProfile
|
||||
|
||||
|
||||
ALLOWED_VALUE_TYPES = {'text', 'integer', 'decimal', 'date'}
|
||||
ALLOWED_USAGE_TYPES = {'match_identity', 'inventory_quantity', 'warehouse_identity', 'general'}
|
||||
|
||||
|
||||
def _payload(item: ShippingInventoryField) -> dict[str, Any]:
|
||||
"""输出业务字段目录记录,不向管理端暴露内部字段编码。"""
|
||||
return {
|
||||
'id': item.id,
|
||||
'display_name': item.display_name,
|
||||
'description': item.description or '',
|
||||
'value_type': item.value_type,
|
||||
'usage_type': item.usage_type,
|
||||
'status': item.status,
|
||||
'sort_order': item.sort_order,
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'updated_at': item.updated_at.isoformat() if item.updated_at else None,
|
||||
}
|
||||
|
||||
|
||||
def list_fields(*, include_retired: bool = False) -> list[dict[str, Any]]:
|
||||
"""按业务展示顺序返回库存字段目录;当前配置默认不显示已归档字段。"""
|
||||
query = ShippingInventoryField.query
|
||||
if not include_retired:
|
||||
query = query.filter_by(status='active')
|
||||
return [_payload(item) for item in query.order_by(
|
||||
ShippingInventoryField.sort_order, ShippingInventoryField.id,
|
||||
).all()]
|
||||
|
||||
|
||||
def _normalized_payload(data: dict[str, Any], *, existing: ShippingInventoryField | None = None) -> dict[str, Any]:
|
||||
"""校验管理员输入,稳定编码只在创建时由显示名称生成并在后台保存。"""
|
||||
display_name = str(data.get('display_name') or '').strip()
|
||||
description = str(data.get('description') or '').strip() or None
|
||||
value_type = str(data.get('value_type') or 'text').strip().lower()
|
||||
usage_type = str(data.get('usage_type') or 'general').strip().lower()
|
||||
try:
|
||||
sort_order = int(data.get('sort_order') if data.get('sort_order') is not None else 100)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID') from exc
|
||||
if not display_name or len(display_name) > 128 or value_type not in ALLOWED_VALUE_TYPES or usage_type not in ALLOWED_USAGE_TYPES:
|
||||
raise ValidationError('Inventory field data is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
|
||||
if sort_order < 0 or sort_order > 9999:
|
||||
raise ValidationError('Inventory field sort_order is invalid', code='SHIPPING.INVENTORY_FIELD_INVALID')
|
||||
return {
|
||||
'display_name': display_name,
|
||||
'description': description,
|
||||
'value_type': value_type,
|
||||
'usage_type': usage_type,
|
||||
'sort_order': sort_order,
|
||||
}
|
||||
|
||||
|
||||
def _field_code(display_name: str) -> str:
|
||||
"""为扩展字段生成稳定内部编码;重复时追加序号,管理员无需维护该技术值。"""
|
||||
stem = re.sub(r'[^a-z0-9]+', '_', display_name.lower()).strip('_')
|
||||
if not stem:
|
||||
# Chinese business names have no ASCII transliteration requirement; derive a stable opaque code instead.
|
||||
stem = f'custom_{sha1(display_name.encode("utf-8")).hexdigest()[:12]}'
|
||||
stem = stem[:52]
|
||||
code = stem
|
||||
sequence = 2
|
||||
while ShippingInventoryField.query.filter_by(field_code=code).first() is not None:
|
||||
suffix = f'_{sequence}'
|
||||
code = f'{stem[:64 - len(suffix)]}{suffix}'
|
||||
sequence += 1
|
||||
return code
|
||||
|
||||
|
||||
def create_field(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""创建用户定义的库存字段;内部编码仅供审计,不参与运行判断。"""
|
||||
values = _normalized_payload(data)
|
||||
if ShippingInventoryField.query.filter_by(display_name=values['display_name']).first() is not None:
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
|
||||
item = ShippingInventoryField(
|
||||
field_code=_field_code(values['display_name']), status='active', created_by=actor_id, updated_by=actor_id,
|
||||
**values,
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def update_field(field_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""更新未退役字段;存在运行配置引用时禁止改变数据格式或业务用途。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
if item.status != 'active':
|
||||
raise ConflictError('Retired inventory field cannot be edited', code='SHIPPING.INVENTORY_FIELD_IMMUTABLE')
|
||||
values = _normalized_payload(data, existing=item)
|
||||
references = _runtime_references(item.id)
|
||||
if references and (values['value_type'] != item.value_type or values['usage_type'] != item.usage_type):
|
||||
raise ConflictError(
|
||||
'Referenced inventory field type or usage cannot be changed',
|
||||
code='SHIPPING.INVENTORY_FIELD_IMMUTABLE', details={'references': references},
|
||||
)
|
||||
duplicate = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.display_name == values['display_name'],
|
||||
ShippingInventoryField.id != item.id,
|
||||
).first()
|
||||
if duplicate is not None:
|
||||
raise ConflictError('Inventory field display name already exists', code='SHIPPING.INVENTORY_FIELD_CONFLICT')
|
||||
for key, value in values.items():
|
||||
setattr(item, key, value)
|
||||
item.updated_by = actor_id
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def delete_field(field_id: int) -> dict[str, Any]:
|
||||
"""物理删除从未被配置引用的用户字段。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
references = _runtime_references(item.id)
|
||||
if references:
|
||||
raise ConflictError(
|
||||
'Inventory field is referenced by runtime configuration',
|
||||
code='SHIPPING.INVENTORY_FIELD_DELETE_BLOCKED', details={'references': references},
|
||||
)
|
||||
db.session.delete(item)
|
||||
db.session.commit()
|
||||
return {'action': 'deleted'}
|
||||
|
||||
|
||||
def retire_field(field_id: int) -> dict[str, Any]:
|
||||
"""退役不再用于新配置的用户字段;被当前配置引用时必须先解除引用。"""
|
||||
item = db.session.get(ShippingInventoryField, field_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory field not found', code='SHIPPING.INVENTORY_FIELD_NOT_FOUND')
|
||||
references = _runtime_references(item.id)
|
||||
if references:
|
||||
raise ConflictError(
|
||||
'Inventory field is referenced by runtime configuration',
|
||||
code='SHIPPING.INVENTORY_FIELD_RETIRE_BLOCKED', details={'references': references},
|
||||
)
|
||||
item.status = 'retired'
|
||||
db.session.commit()
|
||||
return _payload(item)
|
||||
|
||||
|
||||
def _runtime_references(field_id: int) -> list[str]:
|
||||
"""列出字段目录的运行配置引用;阶段三会在此处补充发货模板引用。"""
|
||||
reference = str(field_id)
|
||||
parsing_profiles = [
|
||||
f'parsing_profile:{item.profile_code}:v{item.version}'
|
||||
for item in ShippingInventoryParsingProfile.query.filter(
|
||||
ShippingInventoryParsingProfile.status.in_(['draft', 'published']),
|
||||
).all()
|
||||
if reference in {
|
||||
str(key) for key in ((item.definition_json or {}).get('field_mapping') or {}).keys()
|
||||
}
|
||||
or any(
|
||||
str(key.get('inventory_field_id') or '') == reference
|
||||
for key in ((item.definition_json or {}).get('match_keys') or [])
|
||||
if isinstance(key, dict)
|
||||
)
|
||||
]
|
||||
templates = [
|
||||
f'excel_template:{item.template_code}:v{item.version}'
|
||||
for item in ShippingExcelTemplate.query.filter(
|
||||
ShippingExcelTemplate.status.in_(['draft', 'published']),
|
||||
).all()
|
||||
if any(
|
||||
isinstance(mapping, dict)
|
||||
and mapping.get('source_kind') == 'inventory_field'
|
||||
and str(mapping.get('source_key') or '') == reference
|
||||
for mapping in ((item.definition_json or {}).get('mappings') or [])
|
||||
)
|
||||
]
|
||||
return parsing_profiles + templates
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_file_identity.py
|
||||
|
||||
用途:校验库存 Excel/CSV 文件内容与任务/快照预期库位是否一致。
|
||||
依赖:openpyxl、csv、app.core.errors.AppError。
|
||||
依赖:openpyxl、xlrd、csv、app.core.errors.AppError。
|
||||
逻辑:RPA 回调、人工上传、快照入库前统一调用;流式扫描 Warehouse 列,避免大文件全量加载。
|
||||
"""
|
||||
|
||||
@@ -107,6 +107,54 @@ def _iter_xlsx_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int
|
||||
wb.close()
|
||||
|
||||
|
||||
def _load_xls_header_rows(path: Path, *, max_rows: int = _HEADER_SCAN_ROWS) -> list[tuple[Any, ...]]:
|
||||
"""仅读取旧 xls 前若干行供 Warehouse 表头定位。"""
|
||||
import xlrd
|
||||
|
||||
try:
|
||||
book = xlrd.open_workbook(filename=str(path), on_demand=True)
|
||||
except Exception:
|
||||
return []
|
||||
try:
|
||||
sheet = book.sheet_by_index(0)
|
||||
return [
|
||||
tuple(_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols))
|
||||
for row_index in range(min(max_rows, sheet.nrows))
|
||||
]
|
||||
finally:
|
||||
book.release_resources()
|
||||
|
||||
|
||||
def _iter_xls_warehouse_values(path: Path, *, header_row_idx: int, col_idx: int) -> Iterator[str]:
|
||||
"""流式遍历旧 xls Warehouse 列非空值。"""
|
||||
import xlrd
|
||||
|
||||
book = xlrd.open_workbook(filename=str(path), on_demand=True)
|
||||
try:
|
||||
sheet = book.sheet_by_index(0)
|
||||
for row_index in range(header_row_idx + 1, sheet.nrows):
|
||||
if col_idx >= sheet.ncols:
|
||||
continue
|
||||
value = str(_xls_cell_value(book, sheet.cell(row_index, col_idx)) or '').strip().upper()
|
||||
if value:
|
||||
yield value
|
||||
finally:
|
||||
book.release_resources()
|
||||
|
||||
|
||||
def _xls_cell_value(book: Any, cell: Any) -> Any:
|
||||
"""将 xlrd 旧 Excel 单元格转换为与 xlsx 读取一致的值。"""
|
||||
import xlrd
|
||||
|
||||
if cell.ctype == xlrd.XL_CELL_EMPTY:
|
||||
return None
|
||||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||||
return xlrd.xldate_as_datetime(cell.value, book.datemode)
|
||||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
|
||||
return int(cell.value)
|
||||
return cell.value
|
||||
|
||||
|
||||
def _detect_csv_dialect(sample: str) -> csv.Dialect:
|
||||
"""探测 CSV 分隔符(逗号/分号/Tab 等),失败时回退 excel 方言。"""
|
||||
try:
|
||||
@@ -219,7 +267,13 @@ def extract_warehouse_ids_from_inventory_excel(path: Path) -> set[str]:
|
||||
_iter_xlsx_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
|
||||
)
|
||||
if suffix == ".xls":
|
||||
return set()
|
||||
header_rows = _load_xls_header_rows(path)
|
||||
header_row_idx, col_idx = _find_warehouse_column(header_rows)
|
||||
if header_row_idx is None or col_idx is None:
|
||||
return set()
|
||||
return _collect_unique_warehouse_values(
|
||||
_iter_xls_warehouse_values(path, header_row_idx=header_row_idx, col_idx=col_idx)
|
||||
)
|
||||
return set()
|
||||
|
||||
|
||||
@@ -254,10 +308,10 @@ def assert_inventory_excel_warehouse_identity(
|
||||
)
|
||||
|
||||
suffix = path.suffix.lower()
|
||||
if suffix not in {".xlsx", ".csv"}:
|
||||
if suffix not in {".xls", ".xlsx", ".csv"}:
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存源身份校验仅支持 .xlsx / .csv,请转换后重新上传",
|
||||
message="库存源身份校验仅支持 .xls / .xlsx / .csv",
|
||||
http_status=409,
|
||||
details={"operation": operation, "file_suffix": suffix},
|
||||
)
|
||||
|
||||
@@ -28,7 +28,7 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
task_inventory_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
@@ -50,16 +50,17 @@ def generate_inventory_file_no() -> str:
|
||||
return f"SIF-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xlsx", ".csv"})
|
||||
_ALLOWED_INVENTORY_UPLOAD_SUFFIXES = frozenset({".xls", ".xlsx", ".csv"})
|
||||
|
||||
|
||||
def resolve_inventory_upload_suffix(filename: str) -> str:
|
||||
"""
|
||||
解析人工上传库存文件的合法落盘后缀。
|
||||
核心逻辑:仅允许 .xlsx / .csv;.xls 明确拒绝,避免按 xlsx 误读导致身份校验失败。
|
||||
核心逻辑:允许 .xls / .xlsx / .csv;旧 Excel 由库存解析器使用 xlrd 读取,
|
||||
不将 .xls 伪装为 .xlsx 处理。
|
||||
|
||||
Raises:
|
||||
AppError: 后缀缺失、不支持或为 .xls。
|
||||
AppError: 后缀缺失或不支持。
|
||||
"""
|
||||
name = str(filename or "").strip().lower()
|
||||
if not name or "." not in name:
|
||||
@@ -73,14 +74,10 @@ def resolve_inventory_upload_suffix(filename: str) -> str:
|
||||
if name.endswith(".csv"):
|
||||
return ".csv"
|
||||
if name.endswith(".xls"):
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传不支持 .xls,请转换为 .xlsx 或 .csv 后重新上传",
|
||||
http_status=409,
|
||||
)
|
||||
return ".xls"
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_FILE_FORMAT_UNSUPPORTED",
|
||||
message="库存上传仅支持 .xlsx / .csv",
|
||||
message="库存上传仅支持 .xls / .xlsx / .csv",
|
||||
http_status=409,
|
||||
)
|
||||
|
||||
@@ -161,7 +158,6 @@ def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> boo
|
||||
right = task_inventory_identity(rhs)
|
||||
return (
|
||||
left["inventory_source_code"] == right["inventory_source_code"]
|
||||
and left["inventory_site_id"] == right["inventory_site_id"]
|
||||
and left["inventory_warehouse_id"] == right["inventory_warehouse_id"]
|
||||
)
|
||||
|
||||
@@ -171,7 +167,8 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
保存库存 Excel 并创建批次级库存快照。
|
||||
|
||||
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
|
||||
核心逻辑:快照须携带任务正式库存源身份;批次 link 仅覆盖与上传票库存源一致的可重链任务。
|
||||
核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析;
|
||||
快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
raise AppError(
|
||||
@@ -182,7 +179,6 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
|
||||
identity = task_inventory_identity(task)
|
||||
source_code = identity["inventory_source_code"] or ""
|
||||
site_id = identity["inventory_site_id"]
|
||||
warehouse_id = identity["inventory_warehouse_id"]
|
||||
from datetime import datetime
|
||||
|
||||
@@ -192,17 +188,44 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
upload.save(str(path))
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
|
||||
structure_check = validate_production_inventory_structure(source_code=source_code, path=path)
|
||||
inventory_lines, column_meta = parse_inventory_excel_with_meta(
|
||||
path,
|
||||
field_mapping=structure_check['field_mapping'],
|
||||
mapping_source='parsing_profile',
|
||||
header_row_index=structure_check['header_row_index'],
|
||||
sheet_name=structure_check['sheet_name'],
|
||||
)
|
||||
column_meta.update({
|
||||
'sheet_name': structure_check['sheet_name'],
|
||||
'header_row_index': structure_check['header_row_index'],
|
||||
'structure_validation': {
|
||||
'level': structure_check['level'],
|
||||
'difference': structure_check['difference'],
|
||||
'warnings': structure_check['warnings'],
|
||||
},
|
||||
})
|
||||
if not inventory_lines:
|
||||
raise AppError(
|
||||
code='SHIPPING.INVENTORY_FILE_EMPTY',
|
||||
message='库存文件没有可用于匹配的有效库存数据',
|
||||
http_status=409,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_identity import (
|
||||
assert_inventory_excel_warehouse_identity,
|
||||
)
|
||||
|
||||
assert_inventory_excel_warehouse_identity(
|
||||
path,
|
||||
expected_warehouse_id=str(warehouse_id or ""),
|
||||
operation="manual_upload",
|
||||
)
|
||||
if str(warehouse_id or '').strip():
|
||||
assert_inventory_excel_warehouse_identity(
|
||||
path,
|
||||
expected_warehouse_id=str(warehouse_id or ""),
|
||||
operation="manual_upload",
|
||||
)
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = str(upload.filename or path.name)
|
||||
preview['structure_validation'] = column_meta['structure_validation']
|
||||
except AppError:
|
||||
if path.is_file():
|
||||
try:
|
||||
@@ -230,12 +253,15 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
storage_path=str(path),
|
||||
schema_preview_json=preview,
|
||||
share_mode="task_only",
|
||||
line_count=0,
|
||||
line_count=len(inventory_lines),
|
||||
inventory_lines_json=inventory_lines,
|
||||
field_mapping_json=dict(structure_check['field_mapping']),
|
||||
mapping_source='parsing_profile',
|
||||
mapping_confirmed=True,
|
||||
source_code=source_code,
|
||||
source_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
source_config_version=task.inventory_source_config_version or get_inventory_sources_config_version(),
|
||||
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
|
||||
identity_status="pending",
|
||||
snapshot_status="ready",
|
||||
exported_at=datetime.utcnow(),
|
||||
@@ -387,31 +413,35 @@ def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]:
|
||||
return preview
|
||||
|
||||
|
||||
def parse_linked_inventory_file(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any], Path, ShippingInventoryFile]:
|
||||
"""解析任务 active 库存快照 Excel,并返回解析行、列元数据、文件路径和快照对象。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if not inv_file:
|
||||
raise FileNotFoundError(f"未找到任务 {task.task_no} 的库存快照")
|
||||
def parse_inventory_snapshot_file(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""以快照所属库存站点的已发布解析方案重读文件,禁止正式快照猜列。
|
||||
|
||||
仅供快照复用、动态仓识别和路由证据恢复调用。不存在已发布方案时直接失败,
|
||||
促使管理员修复库存站点配置而不是让运行期静默采用旧规则或 LLM 映射。
|
||||
"""
|
||||
path = Path(inv_file.storage_path)
|
||||
if not path.is_file():
|
||||
raise FileNotFoundError(f"未找到库存快照文件 {inv_file.inventory_file_no}")
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.shipping_notice.inventory_parsing_profile import require_source_profile
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=inv_file.source_code).first()
|
||||
profile = require_source_profile(source)
|
||||
actual_format = path.suffix.lower().lstrip('.')
|
||||
if actual_format != profile.file_format:
|
||||
raise ValidationError(
|
||||
f'Inventory file format {actual_format} does not match parsing profile {profile.file_format}',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
definition = dict(profile.definition_json or {})
|
||||
return parse_inventory_excel_with_meta(
|
||||
path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=header_row_index,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
field_mapping=dict(definition.get('field_mapping') or {}),
|
||||
mapping_source=f"parsing_profile:{profile.profile_code}:v{profile.version}",
|
||||
header_row_index=definition.get('header_row_index'),
|
||||
sheet_name=str(definition.get('sheet_name') or '').strip() or None,
|
||||
)
|
||||
return lines, column_meta, path, inv_file
|
||||
|
||||
|
||||
def apply_inventory_parse_result_to_linked_tasks(
|
||||
|
||||
@@ -1,23 +1,71 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_mapping.py
|
||||
|
||||
用途:标准化库存字段映射,补充匹配规则说明,并校验映射是否完整。
|
||||
依赖:match_rule_desc、标准 `json`/`typing` 能力。
|
||||
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件解析 map_json,再进入库存解析和匹配链路。
|
||||
用途:按用户维护的库存字段 ID 标准化列映射,并校验字段能力是否完整。
|
||||
依赖:ShippingInventoryField、match_rule_desc、标准 `json`/`typing` 能力。
|
||||
逻辑:正式库存链始终保留字段 ID;临时候选也只能引用库存字段目录 ID。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryField
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||||
|
||||
SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty")
|
||||
REQUIRED_SYSTEM_FIELDS = ("part_number", "reservation_id", "available_qty")
|
||||
LEGACY_SYSTEM_FIELDS = ("part_number", "aws_part_number", "reservation_id", "available_qty", "warehouse_id")
|
||||
LEGACY_REQUIRED_FIELDS = ("part_number", "reservation_id", "available_qty")
|
||||
|
||||
|
||||
def _catalog_by_id(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
|
||||
"""读取映射中的库存字段目录记录;非 ID 映射仅保留给临时上传的旧链路。"""
|
||||
try:
|
||||
ids = {int(key) for key in field_mapping}
|
||||
except (TypeError, ValueError):
|
||||
return {}
|
||||
if not ids or any(item <= 0 for item in ids):
|
||||
return {}
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(ids), ShippingInventoryField.status == 'active',
|
||||
).all()
|
||||
return {str(row.id): row for row in rows}
|
||||
|
||||
|
||||
def _uses_catalog_ids(field_mapping: dict[str, Any]) -> bool:
|
||||
"""判断映射键是否为字段目录 ID;纯数字键绝不能回退成旧运行字段。"""
|
||||
if not field_mapping:
|
||||
return False
|
||||
try:
|
||||
return all(int(key) > 0 for key in field_mapping)
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def runtime_field_mapping(field_mapping: dict[str, str]) -> tuple[dict[str, str], dict[str, ShippingInventoryField]]:
|
||||
"""验证“目录 ID → 原始表头”并保留字段 ID,禁止运行期依赖字段名称或内部编码。"""
|
||||
catalog = _catalog_by_id(field_mapping)
|
||||
if _uses_catalog_ids(field_mapping):
|
||||
if len(catalog) != len(field_mapping):
|
||||
return {}, {}
|
||||
return ({str(item.id): str(field_mapping[str(item.id)]).strip() for item in catalog.values()}, catalog)
|
||||
# 临时会话上传尚未绑定库存站点时沿用受控旧格式;正式解析方案不会走该分支。
|
||||
return ({str(key): str(value).strip() for key, value in field_mapping.items()}, {})
|
||||
|
||||
|
||||
def usage_field_ids() -> dict[str, set[str]]:
|
||||
"""按业务用途返回启用字段 ID;程序校验能力角色而不限定字段名称。"""
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.status == 'active',
|
||||
).all()
|
||||
result: dict[str, set[str]] = {}
|
||||
for row in rows:
|
||||
result.setdefault(row.usage_type, set()).add(str(row.id))
|
||||
return result
|
||||
|
||||
|
||||
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
|
||||
"""将 map_json 规范为库存 v2 字段映射;缺内部料号、Reservation 或可用量时返回 None。"""
|
||||
"""规范库存字段目录 ID 到来源栏位的映射;缺必要用途字段时返回 None。"""
|
||||
data: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict):
|
||||
data = raw
|
||||
@@ -38,17 +86,17 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
|
||||
return None
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for key in SYSTEM_FIELDS:
|
||||
for key in LEGACY_SYSTEM_FIELDS:
|
||||
value = inner.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if text:
|
||||
result[key] = text
|
||||
return result if all(field in result for field in REQUIRED_SYSTEM_FIELDS) else None
|
||||
return result if all(field in result for field in LEGACY_REQUIRED_FIELDS) else None
|
||||
|
||||
|
||||
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
|
||||
def _suggest_runtime_field_mapping(headers: list[str]) -> dict[str, str]:
|
||||
"""基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。"""
|
||||
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
|
||||
|
||||
@@ -105,12 +153,41 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
|
||||
if qty:
|
||||
mapping["available_qty"] = qty
|
||||
|
||||
warehouse = pick("warehouse_id", "Warehouse ID", "Warehouse", "Warehouse Code", "WH ID")
|
||||
if warehouse:
|
||||
mapping["warehouse_id"] = warehouse
|
||||
|
||||
return mapping
|
||||
|
||||
|
||||
def suggest_field_mapping(headers: list[str], *, as_catalog: bool = False) -> dict[str, str]:
|
||||
"""按用户字段显示名称确定性推荐表头;正式配置不内置任何字段名称词典。"""
|
||||
if not as_catalog:
|
||||
return _suggest_runtime_field_mapping(headers)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
|
||||
|
||||
rows = ShippingInventoryField.query.filter_by(status='active').all()
|
||||
header_by_name: dict[str, list[str]] = {}
|
||||
for header in headers:
|
||||
normalized = normalise_header(header)
|
||||
if normalized:
|
||||
header_by_name.setdefault(normalized, []).append(str(header).strip())
|
||||
result: dict[str, str] = {}
|
||||
for row in rows:
|
||||
candidates = header_by_name.get(normalise_header(row.display_name), [])
|
||||
if len(candidates) == 1:
|
||||
result[str(row.id)] = candidates[0]
|
||||
return result
|
||||
|
||||
|
||||
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
|
||||
"""映射是否同时包含内部料号、Reservation ID 与可用数量。"""
|
||||
return all(bool(field_mapping.get(field)) for field in REQUIRED_SYSTEM_FIELDS)
|
||||
"""映射是否至少提供一个匹配字段和且仅一个库存数量字段。"""
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
if catalog:
|
||||
mapped = set(runtime_mapping)
|
||||
usages = usage_field_ids()
|
||||
return bool(mapped & usages.get('match_identity', set())) and len(mapped & usages.get('inventory_quantity', set())) == 1
|
||||
return all(bool(runtime_mapping.get(field)) for field in LEGACY_REQUIRED_FIELDS)
|
||||
|
||||
|
||||
def validate_field_mapping_against_headers(
|
||||
@@ -121,16 +198,17 @@ def validate_field_mapping_against_headers(
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_set = {h.lower() for h in norm_headers if h}
|
||||
errors: list[str] = []
|
||||
labels = {
|
||||
"part_number": "part_number",
|
||||
"aws_part_number": "aws_part_number",
|
||||
"reservation_id": "reservation_id",
|
||||
"available_qty": "available_qty",
|
||||
}
|
||||
for key, label in labels.items():
|
||||
name = str(field_mapping.get(key) or "").strip()
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
if not runtime_mapping:
|
||||
return ['库存字段目录中存在已停用或不存在的字段']
|
||||
required_codes = set(LEGACY_REQUIRED_FIELDS)
|
||||
if catalog:
|
||||
usages = usage_field_ids()
|
||||
required_codes = (set(runtime_mapping) & usages.get('match_identity', set())) | (set(runtime_mapping) & usages.get('inventory_quantity', set()))
|
||||
for key, name in runtime_mapping.items():
|
||||
label = catalog.get(key).display_name if key in catalog else key
|
||||
if not name:
|
||||
if key in REQUIRED_SYSTEM_FIELDS:
|
||||
if key in required_codes:
|
||||
errors.append(f"缺少 {label} 列映射")
|
||||
continue
|
||||
if name not in norm_headers and name.lower() not in lower_set:
|
||||
@@ -145,9 +223,7 @@ def resolve_columns_from_field_mapping(
|
||||
headers: list[str],
|
||||
field_mapping: dict[str, str],
|
||||
) -> dict[str, int | None]:
|
||||
"""将显式 field_mapping 转为系统字段 → 列索引映射(保留自动检测的可选列)。"""
|
||||
from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns
|
||||
|
||||
"""将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。"""
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
|
||||
|
||||
@@ -161,19 +237,10 @@ def resolve_columns_from_field_mapping(
|
||||
return norm_headers.index(name)
|
||||
return lower_to_idx.get(name.lower())
|
||||
|
||||
# Keep auto-detected optional columns (e.g. odm_id / qty) even when the
|
||||
# required mapping is provided explicitly by LLM or user.
|
||||
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
|
||||
columns.update({
|
||||
"part_number": idx_for(field_mapping.get("part_number")),
|
||||
"aws_part_number": idx_for(field_mapping.get("aws_part_number")),
|
||||
"reservation_id": idx_for(field_mapping.get("reservation_id")),
|
||||
"available_qty": None,
|
||||
})
|
||||
avail_header = field_mapping.get("available_qty")
|
||||
if avail_header:
|
||||
columns["available_qty"] = idx_for(avail_header)
|
||||
return columns
|
||||
runtime_mapping, _catalog = runtime_field_mapping(field_mapping)
|
||||
if not runtime_mapping:
|
||||
return {}
|
||||
return {field_code: idx_for(header_name) for field_code, header_name in runtime_mapping.items()}
|
||||
|
||||
|
||||
def build_column_meta_from_mapping(
|
||||
@@ -181,10 +248,9 @@ def build_column_meta_from_mapping(
|
||||
field_mapping: dict[str, str],
|
||||
*,
|
||||
mapping_source: str = "rules",
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""由用户/LLM 确认的 field_mapping 构建 column_meta(含 match_rule 与 source_column)。"""
|
||||
"""由规则建议或已发布方案构建 column_meta(含匹配说明与来源栏位)。"""
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
columns = resolve_columns_from_field_mapping(headers, field_mapping)
|
||||
|
||||
def source_column(index: int | None) -> str | None:
|
||||
@@ -193,38 +259,19 @@ def build_column_meta_from_mapping(
|
||||
text = str(headers[index] or "").strip()
|
||||
return text or None
|
||||
|
||||
qty_header = field_mapping.get("available_qty")
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(
|
||||
field_mapping,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
labels = {str(item.id): item.display_name for item in catalog.values()}
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(runtime_mapping)
|
||||
return {
|
||||
"headers": [str(h or "").strip() for h in headers],
|
||||
"mapping_source": mapping_source,
|
||||
"field_mapping": dict(field_mapping),
|
||||
"mapping": {
|
||||
"part_number": {
|
||||
"system_field": "part_number",
|
||||
"label": "Supplier Sku / 内部料号",
|
||||
"source_column": source_column(columns.get("part_number")),
|
||||
},
|
||||
"aws_part_number": {
|
||||
"system_field": "aws_part_number",
|
||||
"label": "AWS Sku / AWS 料号",
|
||||
"source_column": source_column(columns.get("aws_part_number")),
|
||||
},
|
||||
"reservation_id": {
|
||||
"system_field": "reservation_id",
|
||||
"label": "Reservation ID",
|
||||
"source_column": source_column(columns.get("reservation_id")),
|
||||
},
|
||||
"available_qty": {
|
||||
"system_field": "available_qty",
|
||||
"label": "可用数量",
|
||||
"source_column": qty_header or source_column(columns.get("available_qty")),
|
||||
"qty_preference": "available_qty",
|
||||
},
|
||||
field_id: {
|
||||
"inventory_field_id": int(field_id) if field_id.isdigit() else None,
|
||||
"label": labels.get(field_id, field_id),
|
||||
"source_column": source_column(index),
|
||||
}
|
||||
for field_id, index in columns.items()
|
||||
},
|
||||
"match_key": match_key,
|
||||
"match_rule": match_rule,
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_mapping_store.py
|
||||
|
||||
用途:持久化库存字段映射模板,并按客户与表头哈希做查询复用。
|
||||
依赖:db、ShippingInventoryMapping 模型、hashlib/json。
|
||||
逻辑:由 inventory_mapping_workflow 或库存上传链路调用本文件,把用户确认过的映射保存下来供后续同模板复用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime
|
||||
from hashlib import sha256
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryMapping
|
||||
|
||||
|
||||
_GLOBAL_CUSTOMER_CODE = "GLOBAL"
|
||||
|
||||
|
||||
def _customer_key(customer_code: str | None) -> str:
|
||||
key = str(customer_code or "").strip()
|
||||
return key or _GLOBAL_CUSTOMER_CODE
|
||||
|
||||
|
||||
def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str:
|
||||
"""对表头行与 header_row_index 计算 SHA256,用作映射模板去重键。"""
|
||||
norm_headers = [str(h or "").strip() for h in headers]
|
||||
payload = {
|
||||
"header_row_index": int(header_row_index or 1),
|
||||
"headers": norm_headers,
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
return sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None:
|
||||
"""按 customer_code + header_hash 查找已保存的列映射模板。"""
|
||||
customer = _customer_key(customer_code)
|
||||
if not header_hash:
|
||||
return None
|
||||
return ShippingInventoryMapping.query.filter_by(customer_code=customer, header_hash=header_hash).first()
|
||||
|
||||
|
||||
def resolve_inventory_mapping(
|
||||
customer_code: str | None,
|
||||
*,
|
||||
preview: dict[str, Any],
|
||||
) -> dict[str, str] | None:
|
||||
"""从 schema preview 匹配历史映射模板;命中时更新 last_used_at。"""
|
||||
customer = _customer_key(customer_code)
|
||||
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
|
||||
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
|
||||
record = find_inventory_mapping(customer, header_hash)
|
||||
if not record:
|
||||
return None
|
||||
record.last_used_at = datetime.utcnow()
|
||||
if isinstance(record.field_mapping_json, dict) and record.field_mapping_json:
|
||||
return {str(k): str(v) for k, v in record.field_mapping_json.items() if v}
|
||||
return None
|
||||
|
||||
|
||||
def upsert_inventory_mapping(
|
||||
customer_code: str | None,
|
||||
*,
|
||||
preview: dict[str, Any],
|
||||
field_mapping: dict[str, str],
|
||||
) -> ShippingInventoryMapping | None:
|
||||
"""保存或更新客户+表头哈希对应的列映射模板。"""
|
||||
customer = _customer_key(customer_code)
|
||||
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
|
||||
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
|
||||
record = find_inventory_mapping(customer, header_hash)
|
||||
now = datetime.utcnow()
|
||||
if record:
|
||||
record.field_mapping_json = dict(field_mapping)
|
||||
record.headers_json = [str(h or "").strip() for h in headers]
|
||||
record.updated_at = now
|
||||
record.last_used_at = now
|
||||
return record
|
||||
record = ShippingInventoryMapping(
|
||||
customer_code=customer,
|
||||
header_hash=header_hash,
|
||||
headers_json=[str(h or "").strip() for h in headers],
|
||||
field_mapping_json=dict(field_mapping),
|
||||
last_used_at=now,
|
||||
)
|
||||
db.session.add(record)
|
||||
return record
|
||||
@@ -1,275 +1,28 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_mapping_workflow.py
|
||||
|
||||
用途:库存字段对齐确认、自动映射推进与库存载入后的 auto-chain 编排。
|
||||
依赖:inventory_snapshot、inventory_mapping_store、query_service、task_line_store、tool_common、state_machine。
|
||||
逻辑:inventory_workflow / inventory_rpa_workflow 在解析/上传后委托本模块;
|
||||
task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁;
|
||||
订单行对齐预览经 read_task_order_lines 读取。
|
||||
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
|
||||
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
|
||||
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
apply_inventory_parse_result_to_linked_tasks,
|
||||
start_inventory_file_linked_tasks,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
|
||||
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
|
||||
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
|
||||
from app.services.shipping_notice.query_service import serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
auto_mapping_allow_llm,
|
||||
auto_match_enabled,
|
||||
auto_progress_enabled,
|
||||
log_task_event,
|
||||
payload_wants_auto_chain_fallback,
|
||||
set_task_step_progress,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.constants import RS_ALIGN_REVIEW
|
||||
|
||||
|
||||
def mapping_review_enabled() -> bool:
|
||||
"""是否启用库存字段对齐人审(SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW,默认 true)。"""
|
||||
val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW")
|
||||
if val is None:
|
||||
return True
|
||||
return str(val).lower() not in {"0", "false", "no", "off"}
|
||||
|
||||
|
||||
def awaiting_inventory_mapping_confirm(task: ShippingTask) -> bool:
|
||||
"""任务是否停在 align_review 等待用户确认库存列映射。"""
|
||||
return task.review_status == RS_ALIGN_REVIEW
|
||||
|
||||
|
||||
def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""从最近 30 条任务事件中回溯最新的 column_meta。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
events = (
|
||||
ShippingTaskEvent.query.filter_by(task_id=task.id)
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.limit(30)
|
||||
.all()
|
||||
)
|
||||
for event in events:
|
||||
detail = event.detail_json or {}
|
||||
meta = detail.get("column_meta")
|
||||
if isinstance(meta, dict) and meta:
|
||||
return meta
|
||||
return None
|
||||
|
||||
|
||||
def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
"""为当前任务生成 field_alignment 预览(订单行 vs 库存行 + warnings)。"""
|
||||
meta = column_meta or latest_inventory_column_meta(task)
|
||||
return build_field_alignment_preview(
|
||||
task.inventory_lines_json or [],
|
||||
read_task_order_lines(task),
|
||||
column_meta=meta,
|
||||
)
|
||||
|
||||
|
||||
def mapping_confirm_blockers(task: ShippingTask) -> list[str]:
|
||||
"""列映射尚不能自动/人工确认的原因列表(中文)。"""
|
||||
blockers: list[str] = []
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
|
||||
res_source = None
|
||||
if isinstance(inv_mapping.get("reservation_id"), dict):
|
||||
res_source = inv_mapping["reservation_id"].get("source_column")
|
||||
if not str(res_source or "").strip():
|
||||
blockers.append("缺少 Reservation ID 列映射")
|
||||
field_alignment = field_alignment_for_task(task)
|
||||
warnings = field_alignment.get("warnings") if isinstance(field_alignment.get("warnings"), list) else []
|
||||
blockers.extend(str(w) for w in warnings if w)
|
||||
return blockers
|
||||
|
||||
|
||||
def can_auto_advance_mapping(task: ShippingTask) -> bool:
|
||||
"""映射完整且无 blocker 时,auto_progress 可跳过 align_review 人审门禁。"""
|
||||
if not auto_progress_enabled() or not auto_match_enabled():
|
||||
return False
|
||||
if not mapping_review_enabled():
|
||||
return False
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return False
|
||||
if mapping_confirm_blockers(task):
|
||||
return False
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
|
||||
if mapping_source == "llm" and not auto_mapping_allow_llm():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def should_auto_chain_after_mapping(
|
||||
task: ShippingTask,
|
||||
payload: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
"""库存映射完成后是否应自动串联 match_inventory(fallback 或 auto_advance)。"""
|
||||
if payload_wants_auto_chain_fallback(payload):
|
||||
return True
|
||||
return can_auto_advance_mapping(task)
|
||||
|
||||
|
||||
def inventory_mapping_checkpoint_response(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
column_meta: dict[str, Any] | None = None,
|
||||
extra_data: dict[str, Any] | None = None,
|
||||
lang: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
返回 align_review 检查点响应,强制 Agent 停等用户确认字段对齐。
|
||||
【AI 触发时机】:match_inventory 发现仍待映射确认时由内部调用;Agent 禁止主动调用。
|
||||
"""
|
||||
# [STEP 1] 先根据任务和列信息构建字段对齐视图。
|
||||
# 这里要把库存列、订单字段和额外 warning 汇总成用户能直接确认的 message/data。
|
||||
field_alignment = field_alignment_for_task(task, column_meta)
|
||||
extra = extra_data or {}
|
||||
message = format_field_alignment_summary(
|
||||
task_no=task.task_no,
|
||||
field_alignment=field_alignment,
|
||||
inventory_row_count=extra.get("inventory_row_count"),
|
||||
warnings=extra.get("warnings") if isinstance(extra.get("warnings"), list) else None,
|
||||
lang=lang,
|
||||
)
|
||||
data = {
|
||||
**serialize_task_for_tool(task),
|
||||
"field_alignment": field_alignment,
|
||||
**extra,
|
||||
}
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step4_align_confirm",
|
||||
step_title="确认字段对齐",
|
||||
status="needs_human",
|
||||
message="请确认库存字段对齐后再继续匹配",
|
||||
progress_percent=100,
|
||||
current=3,
|
||||
total=3,
|
||||
detail="系统已识别必填列映射,请先人工确认",
|
||||
extra={"field_alignment": field_alignment},
|
||||
)
|
||||
db.session.flush()
|
||||
# [STEP 2] 明确停在人审检查点。
|
||||
# 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=message,
|
||||
data=data,
|
||||
next_required_action=(
|
||||
"向用户原文展示 message(固定 Markdown)后停止本轮;"
|
||||
"用户确认后调用 submit_decision(decision=confirm_inventory_mapping);"
|
||||
"禁止在同一轮调用 match_inventory"
|
||||
),
|
||||
forbidden_next_tools=[
|
||||
"match_inventory",
|
||||
"generate_shipment_excel",
|
||||
"upload_to_freight",
|
||||
],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
|
||||
def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
|
||||
"""auto_progress 路径下自动确认映射并推进 MAPPING_CONFIRMED;成功返回 True。"""
|
||||
# [STEP 1] 先检查是否满足自动确认前提。
|
||||
# 包括开关、当前检查点、阻塞项以及 LLM 映射是否被允许自动接受。
|
||||
if not auto_progress_enabled():
|
||||
return False
|
||||
if not mapping_review_enabled():
|
||||
return False
|
||||
if not awaiting_inventory_mapping_confirm(task):
|
||||
return False
|
||||
if mapping_confirm_blockers(task):
|
||||
return False
|
||||
meta = latest_inventory_column_meta(task) or {}
|
||||
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
|
||||
if mapping_source == "llm" and not auto_mapping_allow_llm():
|
||||
return False
|
||||
|
||||
# [STEP 2] 若映射完整则先落模板,再推进状态机。
|
||||
# 这样相同客户/表头的后续上传可以直接复用人工确认过的映射结果。
|
||||
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
|
||||
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
|
||||
if headers and field_mapping and mapping_is_complete(field_mapping):
|
||||
upsert_inventory_mapping(
|
||||
task.customer_code,
|
||||
preview={
|
||||
"headers": headers,
|
||||
"header_row_index": meta.get("header_row_index") or 1,
|
||||
},
|
||||
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
|
||||
)
|
||||
|
||||
# [STEP 3] 最后把任务推进到 mapping_confirmed,并记录自动确认审计事件。
|
||||
field_alignment = field_alignment_for_task(task)
|
||||
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inv_file.mapping_confirmed = True
|
||||
for link in inv_file.links or []:
|
||||
linked_task = link.task
|
||||
if not link.is_active or not linked_task or linked_task.id == task.id:
|
||||
continue
|
||||
if awaiting_inventory_mapping_confirm(linked_task):
|
||||
apply_task_transition(linked_task, TaskTransition.MAPPING_CONFIRMED)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
"inventory_mapping_auto_confirmed",
|
||||
{
|
||||
"field_alignment": field_alignment,
|
||||
"confirmed_by_task_no": task.task_no,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
if inv_file:
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
return True
|
||||
|
||||
|
||||
def _try_auto_chain_after_inventory_loaded(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Auto: confirm mapping → match → Excel → RPA upload when allowed."""
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
match_completed,
|
||||
match_inventory,
|
||||
try_auto_chain_after_match,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import merge_tool_payload, prepend_tool_message
|
||||
|
||||
if not should_auto_chain_after_mapping(task, payload):
|
||||
return None
|
||||
auto_confirmed = maybe_auto_confirm_inventory_mapping(task)
|
||||
if auto_confirmed:
|
||||
db.session.refresh(task)
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
return None
|
||||
if not auto_match_enabled() or match_completed(task):
|
||||
return None
|
||||
match_result = match_inventory(merge_tool_payload(task, payload))
|
||||
if auto_confirmed:
|
||||
match_result = prepend_tool_message(match_result, "字段对齐已自动确认。")
|
||||
return try_auto_chain_after_match(task, match_result, payload=payload)
|
||||
|
||||
|
||||
def inventory_loaded_response(
|
||||
@@ -279,29 +32,28 @@ def inventory_loaded_response(
|
||||
warnings: list[str] | None = None,
|
||||
column_meta: dict[str, Any] | None = None,
|
||||
source: str,
|
||||
require_mapping_review: bool,
|
||||
event_type: str,
|
||||
chain_payload: dict[str, Any] | None = None,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str | None = None,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。
|
||||
写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。
|
||||
|
||||
Args:
|
||||
require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。
|
||||
chain_payload: 传递给 auto-chain 的原始请求体。
|
||||
commit: False 时仅 flush,供 batch 外层统一提交,避免中途 commit 破坏事务边界。
|
||||
"""
|
||||
def _persist_inventory_loaded() -> None:
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
task: 当前正式发货任务。
|
||||
inventory_lines: 已通过 published Profile 结构校验和类型转换的库存行。
|
||||
warnings: 非阻断解析提示。
|
||||
column_meta: 解析审计元数据,仅用于展示和追溯。
|
||||
source: 库存来源标识。
|
||||
event_type: 库存载入审计事件类型。
|
||||
field_mapping: published Profile 的字段映射快照。
|
||||
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
|
||||
commit: False 时仅 flush,供批量回调维持外层事务边界。
|
||||
|
||||
# [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。
|
||||
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
|
||||
Returns:
|
||||
Tool 标准响应;成功后任务可直接进入库存匹配。
|
||||
"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_tasks: list[ShippingTask] = []
|
||||
if inv_file:
|
||||
@@ -310,84 +62,27 @@ def inventory_loaded_response(
|
||||
inventory_lines,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
mapping_confirmed=False,
|
||||
mapping_confirmed=True,
|
||||
)
|
||||
else:
|
||||
task.inventory_lines_json = inventory_lines
|
||||
field_alignment = field_alignment_for_task(task, column_meta)
|
||||
|
||||
field_alignment = build_field_alignment_preview(
|
||||
inventory_lines,
|
||||
read_task_order_lines(task),
|
||||
column_meta=column_meta,
|
||||
)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="running" if require_mapping_review else "completed",
|
||||
status="completed",
|
||||
message=f"已载入库存 {len(inventory_lines)} 行",
|
||||
progress_percent=100,
|
||||
current=len(inventory_lines),
|
||||
total=len(inventory_lines),
|
||||
detail="库存快照已就绪,正在进入字段对齐阶段" if require_mapping_review else "库存快照已就绪,可进入匹配阶段",
|
||||
detail="库存结构校验与解析已完成,可进入匹配阶段",
|
||||
)
|
||||
|
||||
# [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。
|
||||
# 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。
|
||||
if require_mapping_review and mapping_review_enabled():
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_REVIEW)
|
||||
log_task_event(
|
||||
task,
|
||||
event_type,
|
||||
{
|
||||
"row_count": len(inventory_lines),
|
||||
"warnings": warnings or [],
|
||||
"source": source,
|
||||
"mapping_review": True,
|
||||
"column_meta": column_meta,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
},
|
||||
)
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id == task.id:
|
||||
continue
|
||||
apply_task_transition(linked_task, TaskTransition.INVENTORY_ALIGN_REVIEW)
|
||||
log_task_event(
|
||||
linked_task,
|
||||
event_type,
|
||||
{
|
||||
"row_count": len(inventory_lines),
|
||||
"warnings": warnings or [],
|
||||
"source": source,
|
||||
"mapping_review": True,
|
||||
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
|
||||
"owner_task_no": task.task_no,
|
||||
"column_meta": column_meta,
|
||||
},
|
||||
)
|
||||
_persist_inventory_loaded()
|
||||
if commit:
|
||||
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
|
||||
else:
|
||||
chained = None
|
||||
if chained is not None:
|
||||
return chained
|
||||
lang = None
|
||||
if chain_payload:
|
||||
lang = str(
|
||||
chain_payload.get("lang")
|
||||
or chain_payload.get("locale")
|
||||
or chain_payload.get("language")
|
||||
or ""
|
||||
).strip() or None
|
||||
return inventory_mapping_checkpoint_response(
|
||||
task,
|
||||
column_meta=column_meta,
|
||||
extra_data={
|
||||
"inventory_row_count": len(inventory_lines),
|
||||
"warnings": warnings or [],
|
||||
},
|
||||
lang=lang,
|
||||
)
|
||||
|
||||
# [STEP 3] 无需映射复核时,直接推进到 inventory_ready。
|
||||
# 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id != task.id:
|
||||
@@ -404,7 +99,10 @@ def inventory_loaded_response(
|
||||
"linked_task_nos": [item.task_no for item in linked_tasks],
|
||||
},
|
||||
)
|
||||
_persist_inventory_loaded()
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
if commit and inv_file:
|
||||
start_inventory_file_linked_tasks(inv_file)
|
||||
return tool_response(
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/inventory_parsing_profile.py
|
||||
|
||||
用途:管理可跨库存源复用的版本化库存解析 Profile,并为运行期提供确定性解析定义。
|
||||
依赖:ShippingInventoryParsingProfile、ShippingInventorySource、ShippingOrderField、inventory_mapping。
|
||||
逻辑:管理员保存草稿并发布不可变版本;库存源仅绑定 published Profile,解析链直接使用定义中的列映射与订单字段匹配键。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderField,
|
||||
)
|
||||
|
||||
|
||||
def _catalog_fields(field_mapping: dict[str, Any]) -> dict[str, ShippingInventoryField]:
|
||||
"""解析字段目录 ID 并确认均为可用于新方案的启用库存业务字段。"""
|
||||
field_ids: list[int] = []
|
||||
for raw_id in field_mapping:
|
||||
try:
|
||||
field_id = int(raw_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') from exc
|
||||
if field_id <= 0:
|
||||
raise ValidationError('Parsing profile inventory field is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
field_ids.append(field_id)
|
||||
rows = ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(set(field_ids))).all() if field_ids else []
|
||||
fields = {str(row.id): row for row in rows if row.status == 'active'}
|
||||
if len(fields) != len(set(str(item) for item in field_ids)):
|
||||
raise ValidationError('Parsing profile inventory field is unavailable', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
return fields
|
||||
|
||||
|
||||
def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> set[str]:
|
||||
"""校验解析方案具备匹配与库存数量能力,不限定字段名称。"""
|
||||
match_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'match_identity'}
|
||||
quantity_ids = {field_id for field_id, row in fields.items() if row.usage_type == 'inventory_quantity'}
|
||||
if not match_ids or len(quantity_ids) != 1:
|
||||
raise ValidationError(
|
||||
'Parsing profile requires at least one match field and exactly one inventory quantity field',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
|
||||
)
|
||||
return match_ids | quantity_ids
|
||||
|
||||
|
||||
def _validate_definition(raw: Any) -> dict[str, Any]:
|
||||
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。"""
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
field_mapping = raw.get('field_mapping')
|
||||
if not isinstance(field_mapping, dict) or not field_mapping:
|
||||
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
if any(not str(value or '').strip() for value in field_mapping.values()):
|
||||
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
catalog_fields = _catalog_fields(field_mapping)
|
||||
_required_catalog_field_ids(catalog_fields)
|
||||
match_keys = raw.get('match_keys')
|
||||
if not isinstance(match_keys, list) or not match_keys:
|
||||
raise ValidationError('Parsing profile requires match keys', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
normalized_keys: list[dict[str, str]] = []
|
||||
seen_order_fields: set[str] = set()
|
||||
seen_inventory_fields: set[str] = set()
|
||||
for item in match_keys:
|
||||
field = db.session.get(ShippingOrderField, str(item.get('order_field_id') or '')) if isinstance(item, dict) else None
|
||||
inventory_field = str(item.get('inventory_field_id') or item.get('inventory_field') or '') if isinstance(item, dict) else ''
|
||||
inventory = catalog_fields.get(inventory_field)
|
||||
if (
|
||||
field is None or field.status != 'active' or field.scope != 'line'
|
||||
or inventory is None or inventory.usage_type != 'match_identity'
|
||||
):
|
||||
raise ValidationError('Parsing profile match key is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
if field.id in seen_order_fields or inventory_field in seen_inventory_fields:
|
||||
raise ValidationError('Parsing profile match keys must be unique', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
seen_order_fields.add(field.id)
|
||||
seen_inventory_fields.add(inventory_field)
|
||||
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
|
||||
header_row_index = raw.get('header_row_index')
|
||||
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
|
||||
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
return {
|
||||
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
|
||||
'header_row_index': header_row_index,
|
||||
'field_mapping': {str(int(key)): str(value).strip() for key, value in field_mapping.items()},
|
||||
'match_keys': normalized_keys,
|
||||
}
|
||||
|
||||
|
||||
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
|
||||
"""序列化解析 Profile 管理 DTO。"""
|
||||
return {
|
||||
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
|
||||
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
|
||||
'published_at': profile.published_at.isoformat() if profile.published_at else None,
|
||||
'source_count': len(profile.sources),
|
||||
}
|
||||
|
||||
|
||||
def list_profiles() -> list[dict[str, Any]]:
|
||||
"""列出全部解析 Profile 版本。"""
|
||||
return [payload(item) for item in ShippingInventoryParsingProfile.query.order_by(
|
||||
ShippingInventoryParsingProfile.profile_code, ShippingInventoryParsingProfile.version.desc(),
|
||||
).all()]
|
||||
|
||||
|
||||
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
|
||||
"""创建或更新解析 Profile 草稿;published 版本不可原地修改。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
|
||||
if profile_id and profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile is not None and profile.status != 'draft':
|
||||
raise ConflictError('Published parsing profile is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
code = str(data.get('profile_code') or '').strip().upper()
|
||||
if not code:
|
||||
raise ValidationError('profile_code is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
if profile is not None and code != profile.profile_code:
|
||||
raise ConflictError('Draft profile_code is immutable', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
|
||||
if profile is None:
|
||||
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
|
||||
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
|
||||
db.session.add(profile)
|
||||
profile.display_name = str(data.get('display_name') or code).strip()
|
||||
profile.file_format = str(data.get('file_format') or 'xlsx').lower()
|
||||
if profile.file_format not in {'xls', 'xlsx', 'csv'}:
|
||||
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
definition = _validate_definition(data.get('definition'))
|
||||
if profile.file_format == 'csv' and definition.get('sheet_name'):
|
||||
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
|
||||
profile.definition_json = definition
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布解析 Profile;既有 published 版本继续供已绑定库存源稳定使用。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
published_field_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in order_schema_service.get_published_contract().get('fields', [])
|
||||
}
|
||||
referenced_field_ids = {
|
||||
str(item.get('order_field_id') or '')
|
||||
for item in (profile.definition_json or {}).get('match_keys', [])
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if not referenced_field_ids or not referenced_field_ids <= published_field_ids:
|
||||
raise ValidationError(
|
||||
'Parsing profile match keys must reference the current published order schema',
|
||||
code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
encoded = json.dumps(profile.definition_json, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
profile.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
profile.status = 'published'
|
||||
profile.published_by = actor_id
|
||||
profile.published_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def retire(profile_id: int) -> dict[str, Any]:
|
||||
"""退役无库存源引用的 published Profile,避免使现有 Source 静默失效。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published':
|
||||
raise ConflictError('Only published parsing profile can be retired', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_INVALID')
|
||||
if ShippingInventorySource.query.filter_by(parsing_profile_id=profile.id).count():
|
||||
raise ConflictError('Rebind inventory sources before retiring profile', code='SHIPPING.INVENTORY_PARSING_PROFILE_RETIRE_BLOCKED')
|
||||
profile.status = 'retired'
|
||||
db.session.commit()
|
||||
return payload(profile)
|
||||
|
||||
|
||||
def delete_draft(profile_id: int) -> None:
|
||||
"""删除从未发布的解析 Profile 草稿。"""
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if profile is None:
|
||||
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'draft':
|
||||
raise ConflictError('Only draft parsing profile can be deleted', code='SHIPPING.INVENTORY_PARSING_PROFILE_DELETE_BLOCKED')
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def require_source_profile(source: Any) -> ShippingInventoryParsingProfile:
|
||||
"""读取库存源绑定的 published 解析 Profile;缺失或非发布状态时阻断自动解析。"""
|
||||
profile = getattr(source, 'parsing_profile', None)
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is not published', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
return profile
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_profile_matching.py
|
||||
|
||||
用途:将库存文件结构分析与已发布库存文件解析方案进行确定性比对。
|
||||
依赖:ShippingInventoryParsingProfile、库存结构指纹服务。
|
||||
逻辑:返回完全相同、结构兼容、需要新版本或无匹配;只提供管理员建议,绝不自动绑定库存站点。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import normalise_header
|
||||
|
||||
|
||||
def _profile_headers(profile: ShippingInventoryParsingProfile) -> list[str]:
|
||||
"""读取已发布方案保存的结构表头,缺失时不参与新方案复用推荐。"""
|
||||
structure = profile.structure_definition_json if isinstance(profile.structure_definition_json, dict) else {}
|
||||
return [str(header) for header in structure.get('headers', [])]
|
||||
|
||||
|
||||
def _difference(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> dict[str, list[str]]:
|
||||
"""以业务栏位名称展示新增、缺少和顺序变化,避免只给相似度百分比。"""
|
||||
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
|
||||
observed = [normalise_header(header) for header in structure.get('selected_headers', [])]
|
||||
expected = [normalise_header(header) for header in _profile_headers(profile)]
|
||||
return {
|
||||
'added_columns': [header for header in observed if header and header not in expected],
|
||||
'missing_columns': [header for header in expected if header and header not in observed],
|
||||
'column_order_changed': ['yes'] if set(observed) == set(expected) and observed != expected else [],
|
||||
}
|
||||
|
||||
|
||||
def _core_mapping_matches(analysis: dict[str, Any], profile: ShippingInventoryParsingProfile) -> bool:
|
||||
"""确认既有方案的匹配与数量来源表头仍存在,不依赖字段名称猜测。"""
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
structure = analysis.get('structure') if isinstance(analysis.get('structure'), dict) else {}
|
||||
observed_headers = {normalise_header(header) for header in structure.get('selected_headers', [])}
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
expected = definition.get('field_mapping') if isinstance(definition.get('field_mapping'), dict) else {}
|
||||
expected_runtime, _ = runtime_field_mapping(expected)
|
||||
usages = usage_field_ids()
|
||||
expected_ids = set(expected_runtime)
|
||||
required = expected_ids & (usages.get('match_identity', set()) | usages.get('inventory_quantity', set()))
|
||||
if not (required & usages.get('match_identity', set())) or len(required & usages.get('inventory_quantity', set())) != 1:
|
||||
return False
|
||||
return all(normalise_header(expected_runtime.get(field)) in observed_headers for field in required)
|
||||
|
||||
|
||||
def recommend_profiles(analysis: dict[str, Any]) -> dict[str, Any]:
|
||||
"""查找已发布方案并返回可解释推荐;库存数据内容、文件名和内容 hash 均不参与判断。"""
|
||||
exact = str(analysis.get('exact_structure_fingerprint') or '')
|
||||
compatible = str(analysis.get('compatibility_fingerprint') or '')
|
||||
profiles = ShippingInventoryParsingProfile.query.filter_by(status='published').all()
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for profile in profiles:
|
||||
level = None
|
||||
if exact and profile.exact_structure_fingerprint == exact:
|
||||
level = 'exact'
|
||||
elif _core_mapping_matches(analysis, profile):
|
||||
difference = _difference(analysis, profile)
|
||||
if not difference['missing_columns']:
|
||||
level = 'compatible'
|
||||
if level:
|
||||
candidates.append({
|
||||
'profile_id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
|
||||
'version': profile.version, 'level': level, 'difference': _difference(analysis, profile),
|
||||
'source_count': len(profile.sources),
|
||||
})
|
||||
candidates.sort(key=lambda item: (0 if item['level'] == 'exact' else 1, -item['source_count'], item['profile_code']))
|
||||
result = {'status': candidates[0]['level'] if candidates else 'no_match', 'candidates': candidates}
|
||||
return result
|
||||
@@ -0,0 +1,113 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_routing_engine.py
|
||||
|
||||
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
|
||||
依赖:库存路由模型、routing_facts、routing_operators。
|
||||
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryRoutingRule, ShippingOrderFieldValue, ShippingOrderLine
|
||||
from app.services.shipping_notice.routing_facts import build_routing_facts, read_system_fact
|
||||
from app.services.shipping_notice.routing_operators import matches_operator
|
||||
|
||||
|
||||
ALLOWED_ACTIONS = frozenset({'add_source_candidates', 'exclude_source_candidates', 'require_manual_review'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryRoutingResult:
|
||||
"""路由引擎输出;evidence 可持久化到任务审计快照。"""
|
||||
|
||||
status: str
|
||||
source_codes: tuple[str, ...]
|
||||
matched_rule_ids: tuple[int, ...]
|
||||
evidence: dict[str, Any]
|
||||
|
||||
|
||||
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None,
|
||||
facts: dict[str, dict[str, Any]]) -> Any:
|
||||
"""读取受控系统事实或 Task 当前 Extraction 的动态订单字段值。"""
|
||||
if condition.source_kind == 'system_fact':
|
||||
return read_system_fact(facts, condition.system_fact_key)
|
||||
extraction_id = getattr(task, 'current_order_extraction_id', None)
|
||||
if not extraction_id:
|
||||
return None
|
||||
query = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=int(extraction_id), field_id=condition.order_field_id,
|
||||
)
|
||||
if line is None:
|
||||
value = query.filter(ShippingOrderFieldValue.line_id.is_(None)).first()
|
||||
else:
|
||||
position = int(line.get('_position', 0))
|
||||
value = query.join(ShippingOrderLine, ShippingOrderLine.id == ShippingOrderFieldValue.line_id).filter(
|
||||
ShippingOrderLine.position == position,
|
||||
).first()
|
||||
return value.value_json if value is not None else None
|
||||
|
||||
|
||||
def _rule_matches(rule: ShippingInventoryRoutingRule, *, task: Any, line: dict[str, Any] | None,
|
||||
facts: dict[str, dict[str, Any]]) -> bool:
|
||||
"""判断规则条件按 all/any 语义是否命中。"""
|
||||
results = [
|
||||
matches_operator(_condition_value(condition, task=task, line=line, facts=facts), condition.operator, condition.expected_value_json)
|
||||
for condition in rule.conditions
|
||||
]
|
||||
if not results:
|
||||
return False
|
||||
return all(results) if rule.match_mode == 'all' else any(results)
|
||||
|
||||
|
||||
def evaluate_inventory_source_rules(*, task: Any, line: dict[str, Any] | None = None, now: datetime | None = None) -> InventoryRoutingResult:
|
||||
"""
|
||||
评估已发布规则并返回最高优先级的 Source 候选集合。
|
||||
|
||||
Args:
|
||||
task: 已解析的货代任务。
|
||||
line: 行级规则的订单行;任务级规则传 None。
|
||||
now: 测试可注入的评估时间,默认当前 UTC 时间。
|
||||
|
||||
Returns:
|
||||
InventoryRoutingResult: resolved/unresolved/ambiguous/conflicted 状态及可审计证据。
|
||||
"""
|
||||
moment = now or datetime.utcnow()
|
||||
scope = 'line' if line is not None else 'task'
|
||||
facts = build_routing_facts(task=task, line=line)
|
||||
query = ShippingInventoryRoutingRule.query.filter_by(status='published', scope=scope)
|
||||
rules = [
|
||||
rule for rule in query.order_by(ShippingInventoryRoutingRule.priority.desc(), ShippingInventoryRoutingRule.id.asc()).all()
|
||||
if (rule.effective_from is None or rule.effective_from <= moment)
|
||||
and (rule.effective_to is None or rule.effective_to >= moment)
|
||||
]
|
||||
matched = [rule for rule in rules if _rule_matches(rule, task=task, line=line, facts=facts)]
|
||||
if not matched:
|
||||
return InventoryRoutingResult('unresolved', (), (), {'facts': facts, 'matched_rules': []})
|
||||
priority = matched[0].priority
|
||||
top_rules = [rule for rule in matched if rule.priority == priority]
|
||||
source_codes: set[str] = set()
|
||||
excluded: set[str] = set()
|
||||
manual = False
|
||||
for rule in top_rules:
|
||||
if rule.action_type not in ALLOWED_ACTIONS:
|
||||
return InventoryRoutingResult('conflicted', (), tuple(item.id for item in top_rules), {'reason': 'unsupported_action'})
|
||||
payload = rule.action_payload_json if isinstance(rule.action_payload_json, dict) else {}
|
||||
codes = {str(code or '').strip().upper() for code in payload.get('source_codes', []) if str(code or '').strip()}
|
||||
if rule.action_type == 'add_source_candidates':
|
||||
source_codes.update(codes)
|
||||
elif rule.action_type == 'exclude_source_candidates':
|
||||
excluded.update(codes)
|
||||
else:
|
||||
manual = True
|
||||
source_codes.difference_update(excluded)
|
||||
status = 'conflicted' if manual else ('resolved' if len(source_codes) == 1 else 'ambiguous' if source_codes else 'unresolved')
|
||||
return InventoryRoutingResult(
|
||||
status,
|
||||
tuple(sorted(source_codes)),
|
||||
tuple(rule.id for rule in top_rules),
|
||||
{'facts': facts, 'priority': priority, 'matched_rules': [rule.rule_code for rule in top_rules]},
|
||||
)
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、task_line_store、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory;
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;tools 门面 re-export rpa_report_inventory;
|
||||
Reservation 门禁订单行经 read_task_order_lines 读取。
|
||||
"""
|
||||
|
||||
@@ -23,7 +23,6 @@ from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_RPA_PENDING,
|
||||
@@ -53,14 +52,12 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
confirm_task_inventory_source,
|
||||
inventory_identities_match,
|
||||
is_inventory_source_stable,
|
||||
task_needs_parse_review,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
customer_gate_tool_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import build_rpa_inventory_source
|
||||
from app.services.shipping_notice.query_service import (
|
||||
resolve_task_from_payload,
|
||||
serialize_task_for_tool,
|
||||
@@ -141,21 +138,16 @@ def _try_reuse_inventory_snapshot(
|
||||
优先复用未过期库存快照,避免重复触发 RPA。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
|
||||
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。
|
||||
retry_rpa 必须跳过缓存强制重新导出。
|
||||
"""
|
||||
if mode == "retry_rpa":
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_loaded_response,
|
||||
inventory_mapping_checkpoint_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
|
||||
snapshot = find_latest_ready_snapshot(
|
||||
str(rpa_source.get("source_code") or ""),
|
||||
str(rpa_source.get("site_id") or ""),
|
||||
str(rpa_source.get("warehouse_id") or ""),
|
||||
)
|
||||
if not snapshot:
|
||||
@@ -187,21 +179,19 @@ def _try_reuse_inventory_snapshot(
|
||||
]
|
||||
if cached_lines:
|
||||
task.inventory_lines_json = cached_lines
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
db.session.commit()
|
||||
return inventory_mapping_checkpoint_response(task)
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
cached_lines,
|
||||
column_meta={"source": "snapshot_reuse"},
|
||||
source="snapshot_reuse",
|
||||
require_mapping_review=not snapshot.mapping_confirmed,
|
||||
event_type="inventory_snapshot_reused",
|
||||
)
|
||||
|
||||
path = Path(snapshot.storage_path)
|
||||
if path.is_file():
|
||||
lines, column_meta = ingest_inventory_file(path, move_to=None)
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
|
||||
lines, column_meta = parse_inventory_snapshot_file(snapshot)
|
||||
if lines:
|
||||
snapshot.inventory_lines_json = lines
|
||||
snapshot.line_count = len(lines)
|
||||
@@ -210,7 +200,6 @@ def _try_reuse_inventory_snapshot(
|
||||
lines,
|
||||
column_meta=column_meta,
|
||||
source="snapshot_reuse",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_snapshot_reused",
|
||||
)
|
||||
|
||||
@@ -218,7 +207,7 @@ def _try_reuse_inventory_snapshot(
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message="已关联最新库存快照,正在读取字段映射。",
|
||||
message="已关联最新库存快照,正在读取库存数据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
@@ -331,21 +320,19 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
|
||||
|
||||
def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str, str]:
|
||||
"""从任务正式库存身份推导快照预期三元组。"""
|
||||
def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str]:
|
||||
"""从任务正式库存身份推导快照预期二元组。"""
|
||||
return (
|
||||
str(task.inventory_source_code or "").strip().upper(),
|
||||
str(task.inventory_site_id or "").strip().upper(),
|
||||
str(task.inventory_warehouse_id or "").strip().upper(),
|
||||
)
|
||||
|
||||
|
||||
def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str, str]:
|
||||
"""从 RPA/配置源推导快照预期身份三元组,供回调入库前预检。"""
|
||||
def _expected_snapshot_identity_from_source(source: dict[str, Any]) -> tuple[str, str]:
|
||||
"""从 RPA/配置源推导快照预期身份二元组,供回调入库前预检。"""
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
site = str(source.get("site_id") or "").strip().upper()
|
||||
warehouse = str(source.get("warehouse_id") or "").strip().upper()
|
||||
return code, site, warehouse
|
||||
return code, warehouse
|
||||
|
||||
|
||||
def _rollback_orphan_inventory_snapshot(
|
||||
@@ -748,8 +735,8 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
|
||||
|
||||
def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
成功回调的身份契约:source/site/warehouse/run_no 必须与任务一致。
|
||||
核心逻辑:仅 success 路径调用;skipped/failed 允许 RPA 缺身份字段。
|
||||
成功回调的身份契约:Source 必须与任务一致;fixed Source 的 Warehouse 还须一致。
|
||||
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
|
||||
"""
|
||||
callback_source = str(payload.get("source_code") or "").strip().upper()
|
||||
task_source = str(task.inventory_source_code or "").strip().upper()
|
||||
@@ -768,18 +755,13 @@ def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[st
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
callback_site = str(payload.get("site_id") or "").strip().upper()
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task_source)
|
||||
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
|
||||
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
|
||||
task_site = str(task.inventory_site_id or "").strip().upper()
|
||||
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
|
||||
if not callback_site or callback_site != task_site:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message="RPA 回调 site_id 与任务库存源不一致,已拒绝入库",
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
if not callback_wh or callback_wh != task_wh:
|
||||
if is_fixed and (not callback_wh or callback_wh != task_wh):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
@@ -853,9 +835,9 @@ def _resolve_batch_callback_source(
|
||||
source_code = str(item.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
return None
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_source
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
return get_inventory_source(source_code)
|
||||
return get_database_inventory_source(source_code)
|
||||
|
||||
|
||||
def _batch_snapshot_verify_warehouse_id(
|
||||
@@ -864,6 +846,8 @@ def _batch_snapshot_verify_warehouse_id(
|
||||
item: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
"""推导批量快照入库前须校验的 Excel Warehouse ID。"""
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
|
||||
return None
|
||||
if task:
|
||||
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper()
|
||||
return warehouse_id or None
|
||||
@@ -877,36 +861,21 @@ def _batch_snapshot_verify_warehouse_id(
|
||||
|
||||
def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
校验批量回调 Worker 返回的四字段身份与启用配置一致。
|
||||
核心逻辑:定时/无任务成功项必须显式携带 source/site/warehouse;动态库位源校验 allowed_warehouse_ids。
|
||||
校验批量回调 Worker 返回的 Source/Warehouse 身份与启用配置一致。
|
||||
核心逻辑:定时/无任务成功项必须显式携带 source/warehouse;动态仓接受库存文件返回的 Warehouse。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_sources import (
|
||||
configured_allowed_warehouse_ids,
|
||||
source_uses_dynamic_warehouse_id,
|
||||
)
|
||||
|
||||
callback_source = str(item.get("source_code") or "").strip().upper()
|
||||
callback_site = str(item.get("site_id") or "").strip().upper()
|
||||
callback_wh = str(item.get("warehouse_id") or "").strip().upper()
|
||||
if not callback_source:
|
||||
return "source_code_missing"
|
||||
if not callback_site:
|
||||
return "site_id_missing"
|
||||
if not callback_wh:
|
||||
return "warehouse_id_missing"
|
||||
|
||||
cfg_source = str(source.get("source_code") or "").strip().upper()
|
||||
cfg_site = str(source.get("site_id") or "").strip().upper()
|
||||
cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
|
||||
cfg_wh = str(source.get("fixed_warehouse_id") or source.get("warehouse_id") or "").strip().upper()
|
||||
if callback_source != cfg_source:
|
||||
return "source_code_mismatch"
|
||||
if callback_site != cfg_site:
|
||||
return "site_id_mismatch"
|
||||
|
||||
if source_uses_dynamic_warehouse_id(source):
|
||||
allowed = configured_allowed_warehouse_ids(source)
|
||||
if allowed and callback_wh not in allowed:
|
||||
return "warehouse_id_not_allowed"
|
||||
if str(source.get('warehouse_resolution_mode') or '') == 'inventory_match':
|
||||
return None
|
||||
|
||||
if callback_wh != cfg_wh:
|
||||
@@ -916,10 +885,9 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存 RPA 来源,并在门禁通过后继续触发库存导出。
|
||||
确认当前任务的库存来源,并在门禁通过后等待库存文件可用。
|
||||
|
||||
【AI 触发时机】:当用户在库存源检查点(通常已先完成解析确认)选择 source_code 后调用。
|
||||
兼容:存量任务若仍带 pending_parse_review_after_source,确认源后会回到 parse_review。
|
||||
【AI 触发时机】:当用户完成解析确认并在库存源检查点选择 source_code 后调用。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
|
||||
@@ -963,60 +931,22 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
{
|
||||
"source_code": task.inventory_source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"site_id": task.inventory_site_id,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": confirmed_by or "integration_tool",
|
||||
},
|
||||
)
|
||||
|
||||
# 存量兼容:旧顺序先确认库存源时延后的低置信度解析复核。
|
||||
if task_needs_parse_review(task):
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload.pop("pending_parse_review_after_source", None)
|
||||
task.step_payload_json = step_payload
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
task.current_step = "step2_parse_confirm"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源已确认,请继续确认解析结果。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload.pop("pending_parse_review_after_source", None)
|
||||
task.step_payload_json = step_payload
|
||||
task.current_step = "step3_inventory_prepare"
|
||||
db.session.commit()
|
||||
|
||||
from app.services.shipping_notice.tool_common import auto_rpa_inventory_enabled
|
||||
|
||||
if (not task.inventory_lines_json) and auto_rpa_inventory_enabled():
|
||||
rpa_result = ensure_inventory_via_rpa(task, mode=str(payload.get("mode") or "auto"))
|
||||
rpa_status = str(rpa_result.get("status") or "").strip().lower()
|
||||
if rpa_status in {"running", "ok"}:
|
||||
return rpa_result
|
||||
if rpa_status == "needs_human" and str(task.pending_human_reason or "").strip() == PH_RPA_PENDING:
|
||||
return rpa_result
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="库存源已确认;自动获取库存暂未完成,请稍后重试或手动上传库存文件。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
)
|
||||
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="库存源已确认。",
|
||||
message="库存源已确认;将使用该来源已导出的有效库存文件。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
)
|
||||
@@ -1577,7 +1507,28 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if link is None:
|
||||
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
|
||||
|
||||
lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
|
||||
structure_check = validate_production_inventory_structure(
|
||||
source_code=str(rpa_source['source_code']), path=ingest_path,
|
||||
)
|
||||
lines, column_meta = ingest_inventory_file(
|
||||
ingest_path, move_to=None,
|
||||
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
|
||||
header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'],
|
||||
)
|
||||
column_meta.update({
|
||||
'sheet_name': structure_check['sheet_name'],
|
||||
'header_row_index': structure_check['header_row_index'],
|
||||
'structure_validation': {
|
||||
'level': structure_check['level'], 'difference': structure_check['difference'],
|
||||
'warnings': structure_check['warnings'],
|
||||
},
|
||||
})
|
||||
inv_file.schema_preview_json = {
|
||||
**(inv_file.schema_preview_json or {}),
|
||||
'structure_validation': column_meta['structure_validation'],
|
||||
}
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
@@ -1598,6 +1549,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"origin_file_path": str(path),
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"reused_existing_snapshot": not created_new,
|
||||
"structure_validation": column_meta.get('structure_validation'),
|
||||
},
|
||||
)
|
||||
_mark_inventory_rpa_run_no_consumed(task, run_no)
|
||||
@@ -1606,7 +1558,6 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
lines,
|
||||
column_meta=column_meta,
|
||||
source="rpa_callback",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_rpa_ready",
|
||||
commit=False,
|
||||
)
|
||||
@@ -1753,7 +1704,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
merged_item = _merge_batch_callback_item(payload, item)
|
||||
source_code = str(merged_item.get("source_code") or "").strip().upper()
|
||||
warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper()
|
||||
site_id = str(merged_item.get("site_id") or "").strip().upper()
|
||||
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
|
||||
task_no = str(merged_item.get("task_no") or "").strip()
|
||||
task: ShippingTask | None = None
|
||||
@@ -1762,7 +1712,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if task is None:
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": "task_not_found",
|
||||
@@ -1775,7 +1724,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if gate_resp is not None:
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
|
||||
@@ -1786,7 +1734,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
round_data = round_resp.get("data") if isinstance(round_resp.get("data"), dict) else {}
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": round_data.get("run_no_error") or "run_no_invalid",
|
||||
@@ -1797,7 +1744,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_handle_rpa_inventory_skipped(task, merged_item, runtime, commit=False)
|
||||
skipped.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"skip_reason": merged_item.get("skip_reason") or "skipped",
|
||||
@@ -1807,7 +1753,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error_code": merged_item.get("error_code") or "rpa_export_failed",
|
||||
@@ -1819,7 +1764,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not source:
|
||||
error = {
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"error": "unknown_or_disabled_source",
|
||||
}
|
||||
@@ -1841,7 +1785,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if not path or not path.is_file():
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"error": "file_missing",
|
||||
})
|
||||
@@ -1852,21 +1795,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if gate_resp is not None:
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": gate_resp.get("message") or "inventory_source_gate_blocked",
|
||||
})
|
||||
continue
|
||||
if not inventory_identities_match(
|
||||
task,
|
||||
source_code=str(source.get("source_code") or ""),
|
||||
site_id=str(source.get("site_id") or ""),
|
||||
warehouse_id=str(source.get("warehouse_id") or ""),
|
||||
if (
|
||||
str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
|
||||
and not inventory_identities_match(
|
||||
task,
|
||||
source_code=str(source.get("source_code") or ""),
|
||||
warehouse_id=warehouse_id,
|
||||
)
|
||||
):
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": "inventory_identity_mismatch",
|
||||
@@ -1877,7 +1820,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if identity_error:
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"error": identity_error,
|
||||
})
|
||||
@@ -1916,25 +1858,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
):
|
||||
item_orphan_path = str(inv_file.storage_path)
|
||||
|
||||
from app.services.shipping_notice.inventory_structure_drift import validate_production_inventory_structure
|
||||
|
||||
ingest_path = _snapshot_ingest_path(inv_file)
|
||||
structure_check = validate_production_inventory_structure(
|
||||
source_code=source_code, path=ingest_path,
|
||||
)
|
||||
created_entry = {
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"source_code": inv_file.source_code or source_code,
|
||||
"site_id": inv_file.site_id or merged_item.get("site_id"),
|
||||
"warehouse_id": inv_file.warehouse_id or warehouse_id,
|
||||
"reused_existing_snapshot": not created_new,
|
||||
"structure_validation": {
|
||||
"level": structure_check["level"],
|
||||
"difference": structure_check["difference"],
|
||||
},
|
||||
}
|
||||
created.append(created_entry)
|
||||
if item_orphan_path:
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
|
||||
if task_no and task:
|
||||
if not inventory_identities_match(
|
||||
task,
|
||||
source_code=inv_file.source_code,
|
||||
site_id=inv_file.site_id,
|
||||
warehouse_id=inv_file.warehouse_id,
|
||||
):
|
||||
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
|
||||
link = link_snapshot_to_task(
|
||||
task,
|
||||
inv_file,
|
||||
@@ -1943,15 +1887,26 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
if link is None:
|
||||
raise _RpaCallbackItemAbort("inventory_identity_mismatch")
|
||||
ingest_path = _snapshot_ingest_path(inv_file)
|
||||
lines, column_meta = ingest_inventory_file(ingest_path, move_to=None)
|
||||
lines, column_meta = ingest_inventory_file(
|
||||
ingest_path, move_to=None,
|
||||
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
|
||||
header_row_index=structure_check['header_row_index'], sheet_name=structure_check['sheet_name'],
|
||||
)
|
||||
column_meta.update({
|
||||
'sheet_name': structure_check['sheet_name'],
|
||||
'header_row_index': structure_check['header_row_index'],
|
||||
'structure_validation': created_entry['structure_validation'],
|
||||
})
|
||||
inv_file.schema_preview_json = {
|
||||
**(inv_file.schema_preview_json or {}),
|
||||
'structure_validation': column_meta['structure_validation'],
|
||||
}
|
||||
if lines and task.process_status not in {"uploaded", "completed", "closed", "rejected"}:
|
||||
inventory_loaded_response(
|
||||
task,
|
||||
lines,
|
||||
column_meta=column_meta,
|
||||
source="rpa_batch_callback",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_rpa_ready",
|
||||
commit=False,
|
||||
)
|
||||
@@ -1982,7 +1937,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
created.pop()
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no or None,
|
||||
"error": abort.error,
|
||||
@@ -2000,7 +1954,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
created.pop()
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no,
|
||||
"error": str(exc)[:200] or "batch_ingest_failed",
|
||||
@@ -2009,7 +1962,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
elif raw_status == "skipped":
|
||||
skipped.append({
|
||||
"source_code": source_code,
|
||||
"site_id": merged_item.get("site_id"),
|
||||
"warehouse_id": warehouse_id,
|
||||
"skip_reason": merged_item.get("skip_reason") or "skipped",
|
||||
"message": merged_item.get("message") or merged_item.get("error_message") or "",
|
||||
@@ -2017,7 +1969,6 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
else:
|
||||
failed.append({
|
||||
"source_code": str(source.get("source_code") or source_code),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"error_code": merged_item.get("error_code") or "rpa_export_failed",
|
||||
"error": merged_item.get("error_message"),
|
||||
@@ -2147,13 +2098,16 @@ def _validate_repair_inventory_snapshot(
|
||||
return "snapshot_expired"
|
||||
if not is_inventory_source_stable(task):
|
||||
return "inventory_source_unstable"
|
||||
if not inventory_identities_match(
|
||||
task,
|
||||
source_code=inv_file.source_code,
|
||||
site_id=inv_file.site_id,
|
||||
warehouse_id=inv_file.warehouse_id,
|
||||
):
|
||||
return "inventory_identity_mismatch"
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
if not inventory_identities_match(
|
||||
task,
|
||||
source_code=inv_file.source_code,
|
||||
warehouse_id=inv_file.warehouse_id,
|
||||
):
|
||||
return "inventory_identity_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_snapshot.py
|
||||
|
||||
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
|
||||
依赖:openpyxl、reservation_id、Flask current_app 配置、Path 文件操作。
|
||||
依赖:openpyxl、xlrd、reservation_id、Flask current_app 配置、Path 文件操作。
|
||||
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
|
||||
"""
|
||||
|
||||
@@ -65,6 +65,11 @@ DEFAULT_COLUMN_MAP = {
|
||||
"Qty": "qty",
|
||||
"qty": "qty",
|
||||
"数量": "qty",
|
||||
# Warehouse:动态 Source 必须保留行级 Warehouse,不能只记录整个文件的单一值。
|
||||
"Warehouse ID": "warehouse_id",
|
||||
"Warehouse": "warehouse_id",
|
||||
"Warehouse Code": "warehouse_id",
|
||||
"WH ID": "warehouse_id",
|
||||
# ODM
|
||||
"ODM ID": "odm_id",
|
||||
"ODM Id": "odm_id",
|
||||
@@ -121,7 +126,7 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None:
|
||||
|
||||
|
||||
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
|
||||
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = None
|
||||
idx_part_number = idx_aws_part_number = idx_reservation = idx_available = idx_qty = idx_odm = idx_warehouse = None
|
||||
for i, h in enumerate(headers):
|
||||
mapped = _map_header(h, col_map)
|
||||
if mapped == "part_number" and idx_part_number is None:
|
||||
@@ -136,6 +141,8 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
|
||||
idx_qty = i
|
||||
elif mapped == "odm_id" and idx_odm is None:
|
||||
idx_odm = i
|
||||
elif mapped == "warehouse_id" and idx_warehouse is None:
|
||||
idx_warehouse = i
|
||||
|
||||
# 若 reservation 列未命中,按 AWS 模板常见列名再试
|
||||
if idx_reservation is None:
|
||||
@@ -152,6 +159,7 @@ def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> d
|
||||
"available_qty": idx_available,
|
||||
"qty": idx_qty,
|
||||
"odm_id": idx_odm,
|
||||
"warehouse_id": idx_warehouse,
|
||||
}
|
||||
|
||||
|
||||
@@ -174,7 +182,38 @@ def _normalize_inventory_row(
|
||||
*,
|
||||
default_part_number_index: int | None = None,
|
||||
default_qty_index: int = 1,
|
||||
configured_mapping: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
# Published profiles use inventory field IDs as row keys. Field purpose and
|
||||
# value type come from the user-maintained catalog, never from a fixed code.
|
||||
if configured_mapping and columns and all(str(field_id).isdigit() for field_id in columns):
|
||||
from app.models import ShippingInventoryField
|
||||
|
||||
field_ids = {int(field_id) for field_id in columns if str(field_id).isdigit()}
|
||||
catalog = {
|
||||
str(item.id): item
|
||||
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
|
||||
}
|
||||
parsed = {
|
||||
field_id: _cell(row, index)
|
||||
for field_id, index in columns.items()
|
||||
if index is not None and _cell(row, index) not in (None, '')
|
||||
}
|
||||
match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity']
|
||||
if not any(str(parsed.get(field_id) or '').strip() for field_id in match_fields):
|
||||
return None
|
||||
for field_id, value in list(parsed.items()):
|
||||
field = catalog.get(field_id)
|
||||
if field is None:
|
||||
continue
|
||||
if field.value_type in {'integer', 'decimal'}:
|
||||
parsed[field_id] = _parse_qty(value)
|
||||
elif field.value_type == 'date':
|
||||
parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip()
|
||||
else:
|
||||
parsed[field_id] = str(value).strip()
|
||||
return parsed
|
||||
|
||||
idx_part_number = columns.get("part_number")
|
||||
if idx_part_number is None:
|
||||
idx_part_number = default_part_number_index
|
||||
@@ -227,11 +266,16 @@ def _normalize_inventory_row(
|
||||
odm_id = str(_cell(row, idx_odm) or "").strip()
|
||||
if odm_id:
|
||||
parsed["odm_id"] = odm_id
|
||||
idx_warehouse = columns.get("warehouse_id")
|
||||
if idx_warehouse is not None:
|
||||
warehouse_id = str(_cell(row, idx_warehouse) or "").strip().upper()
|
||||
if warehouse_id:
|
||||
parsed["warehouse_id"] = warehouse_id
|
||||
return parsed
|
||||
|
||||
|
||||
def _score_header_candidate(cells: list[Any]) -> int:
|
||||
"""Score how likely a row is the inventory column header (not a title row)."""
|
||||
"""按通用表格结构给候选表头评分,固定库存词典只作为旧临时链加分项。"""
|
||||
headers = [str(c or "").strip() for c in cells]
|
||||
non_empty = [h for h in headers if h]
|
||||
if len(non_empty) < 2:
|
||||
@@ -244,7 +288,9 @@ def _score_header_candidate(cells: list[Any]) -> int:
|
||||
if mapped:
|
||||
mapped_fields.add(mapped)
|
||||
|
||||
score = len(mapped_fields) * 10
|
||||
text_cells = sum(1 for value in non_empty if isinstance(value, str) and str(value).strip())
|
||||
unique_cells = len({str(value).strip().casefold() for value in non_empty})
|
||||
score = len(non_empty) + text_cells + unique_cells + len(mapped_fields) * 10
|
||||
if "part_number" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
|
||||
score += 30
|
||||
return score
|
||||
@@ -262,8 +308,10 @@ def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40
|
||||
return best_idx if best_score > 0 else 0
|
||||
|
||||
|
||||
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
|
||||
"""Load worksheet or CSV rows; returns (rows, total_row_count_hint)."""
|
||||
def _load_excel_rows(
|
||||
path: Path, *, max_rows: int | None = None, sheet_name: str | None = None,
|
||||
) -> tuple[list[list[Any]], int]:
|
||||
"""Load configured worksheet or CSV rows; returns rows and total row count hint."""
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".csv":
|
||||
from app.services.shipping_notice.inventory_file_identity import load_inventory_csv_rows
|
||||
@@ -275,9 +323,32 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l
|
||||
total = len(rows)
|
||||
return rows, int(total)
|
||||
|
||||
if suffix == ".xls":
|
||||
import xlrd
|
||||
|
||||
book = xlrd.open_workbook(filename=str(path), on_demand=True)
|
||||
try:
|
||||
if sheet_name:
|
||||
try:
|
||||
sheet = book.sheet_by_name(sheet_name)
|
||||
except xlrd.biffh.XLRDError as exc:
|
||||
raise ValueError(f'Inventory worksheet not found: {sheet_name}') from exc
|
||||
else:
|
||||
sheet = book.sheet_by_index(0)
|
||||
row_limit = sheet.nrows if max_rows is None else min(sheet.nrows, max_rows)
|
||||
rows = [
|
||||
[_xls_cell_value(book, sheet.cell(row_index, column_index)) for column_index in range(sheet.ncols)]
|
||||
for row_index in range(row_limit)
|
||||
]
|
||||
return rows, int(sheet.nrows)
|
||||
finally:
|
||||
book.release_resources()
|
||||
|
||||
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
if sheet_name and sheet_name not in wb.sheetnames:
|
||||
raise ValueError(f'Inventory worksheet not found: {sheet_name}')
|
||||
ws = wb[sheet_name] if sheet_name else wb.active
|
||||
rows: list[list[Any]] = []
|
||||
for i, row in enumerate(ws.iter_rows(values_only=True)):
|
||||
if max_rows is not None and i >= max_rows:
|
||||
@@ -289,6 +360,19 @@ def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[l
|
||||
return rows, int(total)
|
||||
|
||||
|
||||
def _xls_cell_value(book: Any, cell: Any) -> Any:
|
||||
"""将 xlrd 单元格值规范为与 openpyxl 接近的 Python 值。"""
|
||||
import xlrd
|
||||
|
||||
if cell.ctype == xlrd.XL_CELL_EMPTY:
|
||||
return None
|
||||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||||
return xlrd.xldate_as_datetime(cell.value, book.datemode)
|
||||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
|
||||
return int(cell.value)
|
||||
return cell.value
|
||||
|
||||
|
||||
def _rows_from_table_text(raw_text: str) -> list[list[str]]:
|
||||
rows: list[list[str]] = []
|
||||
for line in raw_text.splitlines():
|
||||
@@ -315,10 +399,8 @@ def describe_inventory_columns(
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""生成库存列映射与匹配规则的可读描述,供字段对齐人审展示。"""
|
||||
"""根据规则建议或已发布方案生成库存栏位与匹配规则的审计描述。"""
|
||||
if field_mapping:
|
||||
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
|
||||
|
||||
@@ -326,8 +408,6 @@ def describe_inventory_columns(
|
||||
headers,
|
||||
field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
|
||||
@@ -360,11 +440,7 @@ def describe_inventory_columns(
|
||||
if qty_source:
|
||||
inferred_mapping["available_qty"] = qty_source
|
||||
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(
|
||||
inferred_mapping,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
match_rule, match_key, match_rule_source = resolve_match_rule(inferred_mapping)
|
||||
|
||||
return {
|
||||
"headers": [str(h or "").strip() for h in headers],
|
||||
@@ -497,7 +573,9 @@ def parse_inventory_rows(
|
||||
else:
|
||||
col_map = _column_map()
|
||||
columns = _resolve_inventory_columns(headers, col_map)
|
||||
has_header = columns["part_number"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
|
||||
has_header = any(index is not None for index in columns.values()) if field_mapping else (
|
||||
columns.get("part_number") is not None or columns.get("available_qty") is not None or columns.get("qty") is not None
|
||||
)
|
||||
if not has_header and headers and not field_mapping:
|
||||
has_header = any(_map_header(h, _column_map()) for h in headers)
|
||||
|
||||
@@ -505,7 +583,7 @@ def parse_inventory_rows(
|
||||
for row in data_rows:
|
||||
if not row:
|
||||
continue
|
||||
parsed = _normalize_inventory_row(list(row), columns)
|
||||
parsed = _normalize_inventory_row(list(row), columns, configured_mapping=bool(field_mapping))
|
||||
if parsed:
|
||||
lines.append(parsed)
|
||||
return lines
|
||||
@@ -540,7 +618,7 @@ def parse_inventory_text(
|
||||
else:
|
||||
col_map = _column_map()
|
||||
columns = _resolve_inventory_columns(header, col_map)
|
||||
has_header = columns["part_number"] is not None or any(_map_header(h, col_map) for h in header)
|
||||
has_header = columns.get("part_number") is not None or any(_map_header(h, col_map) for h in header)
|
||||
column_meta = describe_inventory_columns(header) if has_header else empty_meta
|
||||
|
||||
data_rows: list[list[Any]] = rows[1:] if has_header else rows
|
||||
@@ -591,7 +669,6 @@ def read_inventory_schema_preview(
|
||||
"aws_part_number": "AWS Sku / AWS 料号(可选)",
|
||||
"reservation_id": "Reservation ID / COM ID(必填)",
|
||||
"available_qty": "可用数量 / Qty Available / Qty",
|
||||
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
|
||||
},
|
||||
"row_count_hint": data_row_count,
|
||||
}
|
||||
@@ -603,15 +680,14 @@ def parse_inventory_excel_with_meta(
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
sheet_name: str | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""
|
||||
解析库存 Excel 并返回标准化行与 column_meta。
|
||||
|
||||
核心逻辑:定位表头行 → describe_inventory_columns → parse_inventory_rows。
|
||||
核心逻辑:选择工作表 → 定位表头行 → describe_inventory_columns → parse_inventory_rows。
|
||||
"""
|
||||
rows, _total = _load_excel_rows(path)
|
||||
rows, _total = _load_excel_rows(path, sheet_name=sheet_name)
|
||||
if not rows:
|
||||
return [], {"headers": [], "mapping": {}, "match_key": ["part_number", "reservation_id"]}
|
||||
|
||||
@@ -640,10 +716,9 @@ def parse_inventory_excel_with_meta(
|
||||
headers,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source if field_mapping else "rules",
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
meta["header_row_index"] = header_idx + 1
|
||||
meta["sheet_name"] = sheet_name
|
||||
return lines, meta
|
||||
|
||||
|
||||
@@ -659,6 +734,8 @@ def ingest_inventory_file(
|
||||
move_to: Path | None = None,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
sheet_name: str | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""
|
||||
解析库存文件并可选择移动至 processed 目录(RPA drop 摄入用)。
|
||||
@@ -670,6 +747,8 @@ def ingest_inventory_file(
|
||||
source_path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=header_row_index,
|
||||
sheet_name=sheet_name,
|
||||
)
|
||||
if move_to:
|
||||
move_to.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -71,33 +71,23 @@ def is_snapshot_fresh(inv_file: ShippingInventoryFile, *, now: datetime | None =
|
||||
|
||||
def find_latest_ready_snapshot(
|
||||
source_code: str | None,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> ShippingInventoryFile | None:
|
||||
"""
|
||||
查找指定 source/site/warehouse 最新 ready 且未过期的库存快照。
|
||||
核心逻辑:库存身份须与任务正式库存源一致;site_id 与 warehouse_id 分别匹配,禁止混用。
|
||||
查找指定 Source 的最新 ready 且未过期库存快照。
|
||||
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
|
||||
"""
|
||||
code = str(source_code or "").strip().upper()
|
||||
site = str(site_id or "").strip().upper()
|
||||
warehouse = str(warehouse_id or "").strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
if not site and not warehouse:
|
||||
return None
|
||||
|
||||
query = ShippingInventoryFile.query.filter_by(
|
||||
source_code=code,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
if site:
|
||||
query = query.filter_by(site_id=site)
|
||||
if warehouse:
|
||||
query = query.filter_by(warehouse_id=warehouse)
|
||||
elif site:
|
||||
query = query.filter(
|
||||
(ShippingInventoryFile.warehouse_id.is_(None)) | (ShippingInventoryFile.warehouse_id == "")
|
||||
)
|
||||
|
||||
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
|
||||
for row in rows:
|
||||
@@ -110,24 +100,21 @@ def find_ready_rpa_inventory_snapshot(
|
||||
*,
|
||||
rpa_run_no: str,
|
||||
source_code: str,
|
||||
site_id: str,
|
||||
warehouse_id: str,
|
||||
) -> ShippingInventoryFile | None:
|
||||
"""
|
||||
按 RPA 轮次 + 四字段身份查找已入库 ready 快照。
|
||||
按 RPA 轮次 + Source/Warehouse 身份查找已入库 ready 快照。
|
||||
核心逻辑:定时 finalize 重试或并发回调时复用同一快照,避免重复落盘。
|
||||
"""
|
||||
run_no = str(rpa_run_no or "").strip()
|
||||
code = str(source_code or "").strip().upper()
|
||||
site = str(site_id or "").strip().upper()
|
||||
warehouse = str(warehouse_id or "").strip().upper()
|
||||
if not run_no or not code or not site or not warehouse:
|
||||
if not run_no or not code or not warehouse:
|
||||
return None
|
||||
return (
|
||||
ShippingInventoryFile.query.filter_by(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
snapshot_status=_SNAPSHOT_STATUS_READY,
|
||||
)
|
||||
@@ -162,13 +149,11 @@ def get_or_create_rpa_inventory_snapshot(
|
||||
|
||||
run_no = str(rpa_run_no or "").strip()
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
site = str(source.get("site_id") or "").strip().upper()
|
||||
warehouse = str(verify_warehouse_id or source.get("warehouse_id") or "").strip().upper()
|
||||
if run_no and code and site and warehouse:
|
||||
if run_no and code and warehouse:
|
||||
existing = find_ready_rpa_inventory_snapshot(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
)
|
||||
if existing:
|
||||
@@ -202,11 +187,10 @@ def get_or_create_rpa_inventory_snapshot(
|
||||
from app.services.shipping_notice.inventory_file_store import delete_inventory_storage_path
|
||||
|
||||
delete_inventory_storage_path(orphan_storage_path)
|
||||
if run_no and code and site and warehouse:
|
||||
if run_no and code and warehouse:
|
||||
existing = find_ready_rpa_inventory_snapshot(
|
||||
rpa_run_no=run_no,
|
||||
source_code=code,
|
||||
site_id=site,
|
||||
warehouse_id=warehouse,
|
||||
)
|
||||
if existing:
|
||||
@@ -291,12 +275,11 @@ def create_inventory_snapshot_from_rpa(
|
||||
exported_at = datetime.utcnow()
|
||||
inventory_file_no = generate_inventory_file_no()
|
||||
source_code = str(source.get("source_code") or "").strip().upper()
|
||||
configured_site_id = str(source.get("site_id") or "").strip().upper()
|
||||
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
runtime_identity_applied = bool(source.get("_runtime_identity_applied"))
|
||||
excel_warehouse_id = ""
|
||||
warehouse_id = export_warehouse_id
|
||||
warehouse_code = warehouse_id or configured_site_id
|
||||
warehouse_code = warehouse_id
|
||||
excel_verified = False
|
||||
|
||||
if success:
|
||||
@@ -334,7 +317,7 @@ def create_inventory_snapshot_from_rpa(
|
||||
snapshot_status = _SNAPSHOT_STATUS_FAILED
|
||||
storage_path = str(path) if path and path.is_file() else ""
|
||||
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_sources_config_version
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
@@ -345,10 +328,10 @@ def create_inventory_snapshot_from_rpa(
|
||||
schema_preview_json=preview,
|
||||
share_mode=share_mode or ("task_only" if trigger_type in {"on_demand", "manual_upload"} else "warehouse_pool"),
|
||||
line_count=0,
|
||||
# 动态 Source 的文件可含多个 Warehouse;具体 Warehouse 在 link 时从库存行解析。
|
||||
warehouse_id=warehouse_id or None,
|
||||
warehouse_code=warehouse_code or None,
|
||||
site_id=configured_site_id or None,
|
||||
source_config_version=get_inventory_sources_config_version(),
|
||||
source_config_version=inventory_sources_runtime_version(),
|
||||
identity_status="pending" if success else "unknown",
|
||||
source_code=source_code or None,
|
||||
source_type=str(source.get("connector_type") or "").strip() or None,
|
||||
@@ -361,7 +344,6 @@ def create_inventory_snapshot_from_rpa(
|
||||
"query": source.get("query"),
|
||||
"navigation": source.get("navigation"),
|
||||
"parameters": source.get("parameters"),
|
||||
"site_id": configured_site_id or None,
|
||||
"export_warehouse_id": export_warehouse_id,
|
||||
"excel_warehouse_id": excel_warehouse_id or None,
|
||||
"warehouse_id_source": (
|
||||
@@ -419,6 +401,32 @@ def link_snapshot_to_task(
|
||||
if not is_snapshot_fresh(inv_file):
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
if source is None:
|
||||
return None
|
||||
resolved_warehouse_id = inv_file.warehouse_id
|
||||
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
|
||||
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
|
||||
|
||||
lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines and Path(inv_file.storage_path).is_file():
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
|
||||
lines, _column_meta = parse_inventory_snapshot_file(inv_file)
|
||||
inv_file.inventory_lines_json = lines
|
||||
inv_file.line_count = len(lines)
|
||||
resolution = resolve_dynamic_warehouse(
|
||||
task=task,
|
||||
inventory_lines=lines,
|
||||
fallback_warehouse_id=inv_file.warehouse_id,
|
||||
)
|
||||
if not resolution.warehouse_id:
|
||||
inv_file.identity_status = resolution.reason
|
||||
return None
|
||||
resolved_warehouse_id = resolution.warehouse_id
|
||||
|
||||
age_seconds: int | None = None
|
||||
if inv_file.exported_at:
|
||||
age_seconds = max(int((datetime.utcnow() - inv_file.exported_at).total_seconds()), 0)
|
||||
@@ -428,25 +436,27 @@ def link_snapshot_to_task(
|
||||
identity_ok = inventory_identities_match(
|
||||
task,
|
||||
source_code=inv_file.source_code,
|
||||
site_id=inv_file.site_id,
|
||||
warehouse_id=inv_file.warehouse_id,
|
||||
warehouse_id=resolved_warehouse_id,
|
||||
)
|
||||
inv_file.identity_status = "verified" if identity_ok else "mismatch"
|
||||
if not identity_ok:
|
||||
return None
|
||||
|
||||
# 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。
|
||||
if not task.inventory_warehouse_id:
|
||||
task.inventory_warehouse_id = resolved_warehouse_id
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file, role=role)
|
||||
link.link_reason = reason
|
||||
link.matched_warehouse_id = inv_file.warehouse_id
|
||||
link.matched_warehouse_id = resolved_warehouse_id
|
||||
link.matched_source_code = inv_file.source_code
|
||||
link.matched_site_id = inv_file.site_id
|
||||
link.identity_check_status = "verified" if identity_ok else "mismatch"
|
||||
link.identity_checked_at = datetime.utcnow()
|
||||
link.snapshot_age_seconds = age_seconds
|
||||
link.audit_payload_json = {
|
||||
**(audit_payload or {}),
|
||||
"source_code": inv_file.source_code,
|
||||
"warehouse_id": inv_file.warehouse_id,
|
||||
"warehouse_id": resolved_warehouse_id,
|
||||
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
|
||||
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
@@ -461,6 +471,7 @@ def link_snapshot_to_task(
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"link_reason": reason,
|
||||
"snapshot_age_seconds": age_seconds,
|
||||
"warehouse_id": resolved_warehouse_id,
|
||||
**(audit_payload or {}),
|
||||
},
|
||||
)
|
||||
@@ -484,7 +495,7 @@ def serialize_inventory_snapshot_link(task: ShippingTask) -> dict[str, Any] | No
|
||||
return {
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"source_code": inv_file.source_code,
|
||||
"warehouse_id": inv_file.warehouse_id,
|
||||
"warehouse_id": link.matched_warehouse_id or inv_file.warehouse_id,
|
||||
"warehouse_code": inv_file.warehouse_code,
|
||||
"exported_at": inv_file.exported_at.isoformat() if inv_file.exported_at else None,
|
||||
"expires_at": inv_file.expires_at.isoformat() if inv_file.expires_at else None,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_sources、models.ShippingTask、core.errors。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。
|
||||
逻辑:parse_notice 先裁决线索;解析确认通过后未稳定才进入 inventory_source_review;
|
||||
RPA/库存/匹配/导出统一经本模块硬门禁,禁止散落判断。
|
||||
"""
|
||||
@@ -14,15 +14,18 @@ from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_source_identity import identity_matches_config
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
confirm_inventory_source_by_code,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
resolve_ambiguous_source_from_ready_snapshots,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import get_inventory_source, get_inventory_sources_config_version
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed"})
|
||||
@@ -40,9 +43,9 @@ INVENTORY_SOURCE_ERROR_CODES = {
|
||||
|
||||
|
||||
def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
"""任务上记录的库存源配置版本须与当前 YAML 版本一致。"""
|
||||
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
current = get_inventory_sources_config_version()
|
||||
current = inventory_sources_runtime_version()
|
||||
if not stored:
|
||||
return False
|
||||
return stored == current
|
||||
@@ -51,7 +54,7 @@ def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
|
||||
核心逻辑:独立字段齐全、配置版本一致、与启用配置身份一致;status 须为 resolved 或 user_confirmed。
|
||||
核心逻辑:Source、Driver 与数据库配置一致即可稳定;动态 Warehouse 在库存行匹配后再确定。
|
||||
"""
|
||||
status = str(task.inventory_source_status or "").strip()
|
||||
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
@@ -64,22 +67,16 @@ def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
connector_type = str(task.inventory_connector_type or "").strip()
|
||||
if not connector_type:
|
||||
return False
|
||||
source = get_inventory_source(code)
|
||||
source = get_database_inventory_source(code)
|
||||
if not source:
|
||||
return False
|
||||
if connector_type != str(source.get("connector_type") or "").strip():
|
||||
return False
|
||||
|
||||
site_id = str(task.inventory_site_id or "").strip().upper()
|
||||
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
|
||||
if not site_id or not task_wh:
|
||||
return False
|
||||
if not identity_matches_config(
|
||||
source,
|
||||
site_id=site_id,
|
||||
warehouse_id=task_wh,
|
||||
context=extract_routing_context(task),
|
||||
):
|
||||
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
|
||||
fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper()
|
||||
task_warehouse = str(task.inventory_warehouse_id or '').strip().upper()
|
||||
if mode == 'fixed' and task_warehouse != fixed_warehouse:
|
||||
return False
|
||||
|
||||
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
|
||||
@@ -105,7 +102,7 @@ def inventory_source_config_changed(task: ShippingTask) -> bool:
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
if not stored:
|
||||
return bool(str(task.inventory_source_status or "").strip())
|
||||
return stored != get_inventory_sources_config_version()
|
||||
return stored != inventory_sources_runtime_version()
|
||||
|
||||
|
||||
def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
|
||||
@@ -136,7 +133,6 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic
|
||||
method=str(task.inventory_source_method or "").strip() or None,
|
||||
source_code=str(task.inventory_source_code or "").strip().upper() or None,
|
||||
connector_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
site_id=str(task.inventory_site_id or "").strip().upper() or None,
|
||||
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
config_version=str(task.inventory_source_config_version or "").strip() or None,
|
||||
routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
|
||||
@@ -162,12 +158,11 @@ def apply_inventory_source_adjudication(
|
||||
|
||||
task.inventory_source_status = adjudication.status
|
||||
task.inventory_source_method = adjudication.method or None
|
||||
task.inventory_source_config_version = adjudication.config_version or get_inventory_sources_config_version()
|
||||
task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version()
|
||||
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_connector_type = adjudication.connector_type
|
||||
task.inventory_site_id = adjudication.site_id
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
|
||||
task.inventory_source_confirmed_by = confirmed_by_user_id
|
||||
@@ -175,7 +170,6 @@ def apply_inventory_source_adjudication(
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
task.inventory_site_id = None
|
||||
task.inventory_warehouse_id = None
|
||||
payload = dict(task.step_payload_json or {})
|
||||
payload.pop("rpa_inventory_source", None)
|
||||
@@ -194,9 +188,9 @@ def apply_inventory_source_adjudication(
|
||||
"routing_fingerprint": fingerprint,
|
||||
}
|
||||
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
|
||||
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
|
||||
rpa_source = build_task_rpa_inventory_source(task)
|
||||
rpa_source = task_rpa_inventory_source(task)
|
||||
if rpa_source:
|
||||
payload["rpa_inventory_source"] = rpa_source
|
||||
else:
|
||||
@@ -222,6 +216,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
|
||||
return _adjudication_from_stable_task(task)
|
||||
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
# Multiple routing candidates may be resolved only from already-exported
|
||||
# snapshots; this never starts RPA or uses inventory quantity as a signal.
|
||||
adjudication = resolve_ambiguous_source_from_ready_snapshots(task, adjudication)
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and adjudication.status == "resolved"
|
||||
@@ -234,7 +231,6 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
|
||||
method="user_confirmed",
|
||||
source_code=adjudication.source_code,
|
||||
connector_type=adjudication.connector_type,
|
||||
site_id=adjudication.site_id,
|
||||
warehouse_id=adjudication.warehouse_id,
|
||||
config_version=adjudication.config_version,
|
||||
routing_fingerprint=adjudication.routing_fingerprint,
|
||||
@@ -247,35 +243,17 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
|
||||
return adjudication
|
||||
|
||||
|
||||
def task_needs_parse_review(task: ShippingTask) -> bool:
|
||||
"""
|
||||
判断任务是否仍需完成低置信度解析人工确认。
|
||||
|
||||
核心逻辑:仅认显式标记——review/pending 为 parse_review / low_confidence,
|
||||
或存量 pending_parse_review_after_source。禁止仅凭 parse_confidence 兜底,
|
||||
否则「解析已确认 → 再确认库存源」会被误判回解析复核。
|
||||
"""
|
||||
from app.services.shipping_notice.constants import PH_LOW_CONF, RS_PARSE_REVIEW
|
||||
|
||||
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
|
||||
return True
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
return bool(payload.get("pending_parse_review_after_source"))
|
||||
|
||||
|
||||
def transition_task_to_inventory_source_review(
|
||||
task: ShippingTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
error_message: str | None = None,
|
||||
mark_pending_parse_review: bool = False,
|
||||
) -> None:
|
||||
"""
|
||||
将任务持久化到库存源人工复核检查点,并写入候选裁决信息。
|
||||
|
||||
核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。
|
||||
mark_pending_parse_review 仅用于存量/兼容路径(旧顺序先源后解析);
|
||||
新路径应先完成 parse_review,再进入本检查点,通常不传 True。
|
||||
解析复核必须在进入本检查点前完成,不保存延后复核标记。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
|
||||
@@ -294,8 +272,6 @@ def transition_task_to_inventory_source_review(
|
||||
"config_version": adjudication.config_version,
|
||||
"routing_fingerprint": adjudication.routing_fingerprint,
|
||||
}
|
||||
if mark_pending_parse_review:
|
||||
payload["pending_parse_review_after_source"] = True
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
@@ -304,16 +280,11 @@ def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceA
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
|
||||
|
||||
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
|
||||
核心逻辑:新业务顺序是先解析后库存源;仅当仍检测到待解析复核(含存量延后标记)时,
|
||||
才写入 pending_parse_review_after_source 以兼容旧任务。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源确认。
|
||||
"""
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
if not is_inventory_source_stable(task):
|
||||
transition_task_to_inventory_source_review(
|
||||
task,
|
||||
adjudication,
|
||||
mark_pending_parse_review=task_needs_parse_review(task),
|
||||
)
|
||||
transition_task_to_inventory_source_review(task, adjudication)
|
||||
return adjudication
|
||||
|
||||
|
||||
@@ -372,7 +343,6 @@ def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
|
||||
"""返回任务当前正式库存身份,供库存文件绑定与匹配校验。"""
|
||||
return {
|
||||
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
|
||||
"inventory_site_id": str(task.inventory_site_id or "").strip().upper() or None,
|
||||
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
}
|
||||
|
||||
@@ -381,10 +351,9 @@ def inventory_identities_match(
|
||||
task: ShippingTask,
|
||||
*,
|
||||
source_code: str | None,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None,
|
||||
) -> bool:
|
||||
"""校验库存文件/链接身份与任务正式库存源是否完全一致。"""
|
||||
"""校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。"""
|
||||
identity = task_inventory_identity(task)
|
||||
if not is_inventory_source_stable(task):
|
||||
return False
|
||||
@@ -392,11 +361,8 @@ def inventory_identities_match(
|
||||
if expected_code != identity["inventory_source_code"]:
|
||||
return False
|
||||
|
||||
file_site = str(site_id or "").strip().upper()
|
||||
file_wh = str(warehouse_id or "").strip().upper()
|
||||
if not file_site or file_site != (identity["inventory_site_id"] or ""):
|
||||
if not file_wh:
|
||||
return False
|
||||
if not file_wh or file_wh != (identity["inventory_warehouse_id"] or ""):
|
||||
return False
|
||||
|
||||
return True
|
||||
expected = identity['inventory_warehouse_id']
|
||||
return not expected or expected == file_wh
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_identity.py
|
||||
|
||||
用途:从库存源配置与订单路由上下文解析正式库存身份(source/site/warehouse)。
|
||||
依赖:无业务模块反向依赖;normalize/match 工具在本文件内定义。
|
||||
逻辑:裁决、门禁、RPA 与迁移回填统一调用本模块,禁止散落身份推导。
|
||||
用途:校验库存源与 Warehouse 的两段式身份。
|
||||
依赖:无业务模块反向依赖。
|
||||
逻辑:路由阶段只确定 Source;fixed Source 立即确定 Warehouse,inventory_match Source 在库存行匹配后确定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,143 +14,52 @@ from typing import Any
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
text = str(value or "").strip().upper()
|
||||
if not text:
|
||||
return ""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", text).strip()
|
||||
"""将文本归一为可比较的路由 token。"""
|
||||
return re.sub(r"[^A-Z0-9]+", " ", str(value or "").strip().upper()).strip()
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
"""别名按词元匹配,避免短 token 误命中更长编码。"""
|
||||
return _alias_token_match(normalize_destination(candidate), alias)
|
||||
"""按完整词元匹配别名,避免短码误命中。"""
|
||||
normalized = normalize_destination(alias)
|
||||
return bool(normalized) and (normalize_destination(candidate) == normalized or normalized in normalize_destination(candidate).split())
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ResolvedInventoryIdentity:
|
||||
"""稳定库存源四元组中的站点/库位解析结果。"""
|
||||
"""已确定的 Source 与可选 Warehouse 身份。"""
|
||||
|
||||
source_code: str
|
||||
connector_type: str
|
||||
site_id: str
|
||||
warehouse_id: str
|
||||
warehouse_id: str | None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryIdentityResolution:
|
||||
"""身份解析结果;失败时 reason 说明原因,ambiguous 时带 warehouse 候选。"""
|
||||
"""身份解析结果;动态 Warehouse 在路由阶段可合法为空。"""
|
||||
|
||||
ok: bool
|
||||
identity: ResolvedInventoryIdentity | None = None
|
||||
reason: str = ""
|
||||
warehouse_candidates: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def _alias_token_match(candidate: str, alias: str) -> bool:
|
||||
"""库位别名按词元精确匹配,禁止短别名误命中长编码。"""
|
||||
alias_norm = normalize_destination(alias)
|
||||
if not alias_norm:
|
||||
def resolve_inventory_source_identity(source: dict[str, Any], _context: dict[str, Any]) -> InventoryIdentityResolution:
|
||||
"""解析 Source;仅 fixed 模式从配置直接提供 Warehouse。"""
|
||||
code = str(source.get('source_code') or '').strip().upper()
|
||||
connector = str(source.get('connector_type') or '').strip().lower()
|
||||
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
|
||||
if not code or connector not in {'dbs', 'crane'} or mode not in {'fixed', 'inventory_match'}:
|
||||
return InventoryIdentityResolution(False, reason='source_incomplete')
|
||||
warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper() or None
|
||||
if mode == 'fixed' and not warehouse:
|
||||
return InventoryIdentityResolution(False, reason='fixed_warehouse_missing')
|
||||
return InventoryIdentityResolution(True, ResolvedInventoryIdentity(code, connector, warehouse))
|
||||
|
||||
|
||||
def identity_matches_config(source: dict[str, Any], *, warehouse_id: str | None, context: dict[str, Any] | None = None) -> bool:
|
||||
"""验证任务 Warehouse 与 Source 策略一致;动态仓由已匹配库存行决定。"""
|
||||
resolution = resolve_inventory_source_identity(source, context or {})
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return False
|
||||
if candidate == alias_norm:
|
||||
return True
|
||||
return alias_norm in candidate.split()
|
||||
|
||||
|
||||
def _resolve_crane_warehouse_id(source: dict[str, Any], context: dict[str, Any]) -> InventoryIdentityResolution:
|
||||
"""Crane 库位由订单线索与 match_aliases 唯一命中决定。"""
|
||||
aliases = [str(alias).strip() for alias in (source.get("match_aliases") or []) if str(alias).strip()]
|
||||
if not aliases:
|
||||
return InventoryIdentityResolution(ok=False, reason="crane_aliases_missing")
|
||||
|
||||
destination_candidates = list(context.get("destination_candidates") or [])
|
||||
hint = normalize_destination(context.get("warehouse_hint"))
|
||||
if hint:
|
||||
destination_candidates.append(hint)
|
||||
|
||||
matched: list[str] = []
|
||||
for candidate in destination_candidates:
|
||||
candidate_norm = normalize_destination(candidate)
|
||||
if not candidate_norm:
|
||||
continue
|
||||
for alias in aliases:
|
||||
if _alias_token_match(candidate_norm, alias):
|
||||
token = str(alias).strip().upper()
|
||||
if token and token not in matched:
|
||||
matched.append(token)
|
||||
|
||||
if len(matched) == 1:
|
||||
site_id = str(source.get("site_id") or "CRANE").strip().upper()
|
||||
return InventoryIdentityResolution(
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=str(source.get("source_code") or "").strip().upper(),
|
||||
connector_type=str(source.get("connector_type") or "").strip(),
|
||||
site_id=site_id,
|
||||
warehouse_id=matched[0],
|
||||
),
|
||||
)
|
||||
if len(matched) > 1:
|
||||
return InventoryIdentityResolution(
|
||||
ok=False,
|
||||
reason="crane_warehouse_ambiguous",
|
||||
warehouse_candidates=tuple(matched),
|
||||
)
|
||||
return InventoryIdentityResolution(ok=False, reason="crane_warehouse_unresolved")
|
||||
|
||||
|
||||
def resolve_inventory_source_identity(
|
||||
source: dict[str, Any],
|
||||
context: dict[str, Any],
|
||||
) -> InventoryIdentityResolution:
|
||||
"""
|
||||
解析库存源在订单上下文下的正式 site_id / warehouse_id。
|
||||
核心逻辑:DSV 使用配置显式声明;Crane 通过别名唯一命中推导库位。
|
||||
"""
|
||||
source_code = str(source.get("source_code") or "").strip().upper()
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if not source_code or not connector_type:
|
||||
return InventoryIdentityResolution(ok=False, reason="source_incomplete")
|
||||
|
||||
if connector_type == "crane_footprint":
|
||||
return _resolve_crane_warehouse_id(source, context)
|
||||
|
||||
site_id = str(source.get("site_id") or "").strip().upper()
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
if not site_id or not warehouse_id:
|
||||
return InventoryIdentityResolution(ok=False, reason="identity_incomplete")
|
||||
return InventoryIdentityResolution(
|
||||
ok=True,
|
||||
identity=ResolvedInventoryIdentity(
|
||||
source_code=source_code,
|
||||
connector_type=connector_type,
|
||||
site_id=site_id,
|
||||
warehouse_id=warehouse_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def identity_matches_config(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
site_id: str | None,
|
||||
warehouse_id: str | None,
|
||||
context: dict[str, Any] | None = None,
|
||||
) -> bool:
|
||||
"""校验任务身份与配置一致;Crane 额外要求库位与当前路由上下文唯一解析结果一致。"""
|
||||
cfg_site = str(source.get("site_id") or "").strip().upper()
|
||||
cfg_wh = str(source.get("warehouse_id") or "").strip().upper()
|
||||
task_site = str(site_id or "").strip().upper()
|
||||
task_wh = str(warehouse_id or "").strip().upper()
|
||||
if not task_site or not task_wh:
|
||||
return False
|
||||
if cfg_site and task_site != cfg_site:
|
||||
return False
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if connector_type == "crane_footprint":
|
||||
if context is None:
|
||||
return False
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return False
|
||||
return resolution.identity.warehouse_id == task_wh
|
||||
return bool(cfg_wh) and task_wh == cfg_wh
|
||||
expected = resolution.identity.warehouse_id
|
||||
actual = str(warehouse_id or '').strip().upper() or None
|
||||
return bool(actual) and (expected is None or expected == actual)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_repository.py
|
||||
|
||||
用途:提供库存源主数据的最小一致性校验和受控读取入口。
|
||||
依赖:models.ShippingInventorySource/ShippingRpaProfile、core.errors.ValidationError。
|
||||
逻辑:管理服务保存 Source 前调用本模块校验 Source 与 Profile 的 Driver 一致;后续库存路由、排程与手动刷新统一复用读取入口。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile
|
||||
|
||||
|
||||
def validate_source_profile(source: ShippingInventorySource, profile: ShippingRpaProfile) -> None:
|
||||
"""
|
||||
校验库存源引用的 RPA Profile 与其 Driver 类型一致。
|
||||
|
||||
Args:
|
||||
source: 待保存的库存源;connector_type 只能为 dbs 或 crane。
|
||||
profile: Source 绑定的 RPA Profile。
|
||||
|
||||
Raises:
|
||||
ValidationError: Source/Profile Driver 不一致或出现未知 Driver。
|
||||
"""
|
||||
source_type = str(source.connector_type or '').strip().lower()
|
||||
profile_type = str(profile.connector_type or '').strip().lower()
|
||||
if source_type not in {'dbs', 'crane'} or profile_type not in {'dbs', 'crane'}:
|
||||
raise ValidationError('Unsupported inventory connector type', code='SHIPPING.INVENTORY_CONNECTOR_INVALID')
|
||||
if source_type != profile_type:
|
||||
raise ValidationError(
|
||||
'Inventory Source connector_type must match its RPA Profile',
|
||||
code='SHIPPING.INVENTORY_PROFILE_CONNECTOR_MISMATCH',
|
||||
)
|
||||
|
||||
|
||||
def get_database_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None:
|
||||
"""
|
||||
按业务编码读取数据库库存源及其非敏感 RPA 配置。
|
||||
|
||||
Args:
|
||||
source_code: 稳定库存源编码。
|
||||
enabled_only: 为 True 时仅返回启用 Source 和 Profile。
|
||||
|
||||
Returns:
|
||||
dict | None: 不含任何凭据密文/明文的 Source、Profile 与操作配置快照。
|
||||
"""
|
||||
code = str(source_code or '').strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=code).first()
|
||||
if source is None or (enabled_only and not source.enabled):
|
||||
return None
|
||||
profile = source.rpa_profile
|
||||
if profile is None or (enabled_only and not profile.enabled):
|
||||
return None
|
||||
login_config = dict(profile.login_config_json or {'auth_mode': 'password'})
|
||||
if login_config.get('auth_mode') != 'password':
|
||||
return None
|
||||
# Source owns report navigation and business query values. Driver behavior is
|
||||
# code/template-owned and never travels through a login connection profile.
|
||||
source_navigation = dict(source.report_path_json or {}) if source.connector_type == 'dbs' else {}
|
||||
return {
|
||||
'source_code': source.source_code,
|
||||
'display_name': source.display_name,
|
||||
'connector_type': source.connector_type,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
# Worker 兼容字段:fixed Source 可直接作为导出目标;动态 Source 保持为空。
|
||||
'warehouse_id': source.fixed_warehouse_id,
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
|
||||
'config_version': source.config_version,
|
||||
'parsing_profile_id': source.parsing_profile_id,
|
||||
'excel_template_id': source.excel_template_id,
|
||||
'report_path_json': dict(source.report_path_json or {}),
|
||||
'query_parameters_json': list(source.query_parameters_json or []),
|
||||
'match_aliases_json': list(source.match_aliases_json or []),
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
|
||||
'navigation': source_navigation,
|
||||
'parameters': list(source.query_parameters_json or []),
|
||||
'query': {},
|
||||
'login_url': profile.login_url,
|
||||
'login_config': login_config,
|
||||
}
|
||||
|
||||
|
||||
def get_rpa_trigger_inventory_source(source_code: str, *, enabled_only: bool = True) -> dict | None:
|
||||
"""构造仅投递给 RPA worker 的 Source 快照;配置测试可显式读取停用站点。"""
|
||||
source_config = get_database_inventory_source(source_code, enabled_only=enabled_only)
|
||||
if source_config is None:
|
||||
return None
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_config['source_code']).first()
|
||||
profile = source.rpa_profile if source else None
|
||||
if profile is None or (enabled_only and not profile.enabled):
|
||||
return None
|
||||
result = dict(source_config)
|
||||
result['credential_envelope'] = {
|
||||
'username_ciphertext': profile.username_ciphertext,
|
||||
'password_ciphertext': profile.password_ciphertext,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def list_database_inventory_sources(*, enabled_only: bool = True) -> list[dict]:
|
||||
"""列出数据库库存源的非敏感运行时快照,供路由和排程按 Source 选择。"""
|
||||
query = ShippingInventorySource.query.order_by(ShippingInventorySource.source_code)
|
||||
if enabled_only:
|
||||
query = query.filter_by(enabled=True)
|
||||
result = []
|
||||
for source in query.all():
|
||||
item = get_database_inventory_source(source.source_code, enabled_only=enabled_only)
|
||||
if item:
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
|
||||
def inventory_sources_runtime_version() -> str:
|
||||
"""计算启用库存源与其 Profile 配置的稳定版本,用于任务路由失效判断。"""
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
rows = []
|
||||
for source in ShippingInventorySource.query.order_by(ShippingInventorySource.source_code).all():
|
||||
profile = source.rpa_profile
|
||||
rows.append({
|
||||
'source_code': source.source_code,
|
||||
'source_version': source.config_version,
|
||||
'source_enabled': bool(source.enabled),
|
||||
'profile_code': profile.profile_code if profile else None,
|
||||
'profile_version': profile.config_version if profile else None,
|
||||
'profile_enabled': bool(profile.enabled) if profile else False,
|
||||
'source_config': {
|
||||
'connector_type': source.connector_type,
|
||||
'warehouse_resolution_mode': source.warehouse_resolution_mode,
|
||||
'fixed_warehouse_id': source.fixed_warehouse_id,
|
||||
'report_path_json': source.report_path_json or {},
|
||||
'query_parameters_json': source.query_parameters_json or [],
|
||||
'match_aliases_json': source.match_aliases_json or [],
|
||||
'snapshot_ttl_seconds': source.snapshot_ttl_seconds,
|
||||
},
|
||||
'profile_config': {
|
||||
'login_url': profile.login_url if profile else None,
|
||||
'login_config': profile.login_config_json if profile else None,
|
||||
},
|
||||
})
|
||||
payload = json.dumps(rows, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(payload.encode('ascii')).hexdigest()[:16]
|
||||
@@ -1,42 +1,38 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_source_rules.py
|
||||
|
||||
用途:根据发货通知路由线索对库存源做确定性裁决。
|
||||
依赖:inventory_sources、ShippingTask 目的地字段、task_line_store、step_payload_json。
|
||||
逻辑:Dify/LLM 只提供行级可选路由线索;本模块负责唯一性判断、冲突检测与人工确认复核;
|
||||
订单行路由线索经 read_task_order_lines 读取。
|
||||
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
|
||||
依赖:inventory_routing_engine、inventory_source_repository、task_line_store。
|
||||
逻辑:规则只决定 Source;fixed Warehouse 由 Source 给出,inventory_match Warehouse 延后到库存行匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass, field, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.inventory_source_identity import (
|
||||
normalize_destination,
|
||||
resolve_inventory_source_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_sources import (
|
||||
build_rpa_inventory_source,
|
||||
get_inventory_source,
|
||||
get_inventory_sources_config_version,
|
||||
list_inventory_sources,
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
list_database_inventory_sources,
|
||||
)
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventorySourceAdjudication:
|
||||
"""库存源裁决结构化结果。"""
|
||||
"""库存源裁决结果;Warehouse 在动态模式下可为空。"""
|
||||
|
||||
status: str
|
||||
method: str | None = None
|
||||
source_code: str | None = None
|
||||
connector_type: str | None = None
|
||||
site_id: str | None = None
|
||||
warehouse_id: str | None = None
|
||||
config_version: str | None = None
|
||||
routing_fingerprint: str | None = None
|
||||
@@ -44,501 +40,230 @@ class InventorySourceAdjudication:
|
||||
destination_candidates: list[str] = field(default_factory=list)
|
||||
evidence: list[dict[str, Any]] = field(default_factory=list)
|
||||
conflicts: list[str] = field(default_factory=list)
|
||||
reason: str = ""
|
||||
reason: str = ''
|
||||
|
||||
|
||||
# Backward-compatible alias
|
||||
InventorySourceResolution = InventorySourceAdjudication
|
||||
|
||||
|
||||
def compute_routing_fingerprint(context: dict[str, Any]) -> str:
|
||||
"""
|
||||
根据标准化路由上下文与配置版本生成可比较指纹。
|
||||
核心逻辑:相同输入与相同配置版本下指纹必须稳定,用于判断人工确认是否失效。
|
||||
"""
|
||||
normalized = {
|
||||
"destination_code": str(context.get("destination_code") or "").strip().upper(),
|
||||
"destination_city": str(context.get("destination_city") or "").strip().upper(),
|
||||
"destination_country": str(context.get("destination_country") or "").strip().upper(),
|
||||
"warehouse_hint": str(context.get("warehouse_hint") or "").strip().upper(),
|
||||
"customer_code": str(context.get("customer_code") or "").strip().upper(),
|
||||
"customer_name": str(context.get("customer_name") or "").strip().upper(),
|
||||
"order_type": str(context.get("order_type") or "").strip().upper(),
|
||||
"config_version": get_inventory_sources_config_version(),
|
||||
"destination_candidates": sorted(
|
||||
str(item).strip().upper()
|
||||
for item in (context.get("destination_candidates") or [])
|
||||
if str(item).strip()
|
||||
),
|
||||
}
|
||||
digest = hashlib.sha256(json.dumps(normalized, sort_keys=True, ensure_ascii=False).encode("utf-8"))
|
||||
return digest.hexdigest()[:32]
|
||||
|
||||
|
||||
def normalize_destination(value: Any) -> str:
|
||||
"""将 Dify/单据中的目的地线索标准化成可匹配 token。"""
|
||||
from app.services.shipping_notice.inventory_source_identity import normalize_destination as _normalize
|
||||
|
||||
return _normalize(value)
|
||||
|
||||
|
||||
def _matches_alias(candidate: str, alias: str) -> bool:
|
||||
from app.services.shipping_notice.inventory_source_identity import _matches_alias as _match
|
||||
|
||||
return _match(candidate, alias)
|
||||
|
||||
|
||||
def _append_candidate(candidates: list[str], value: Any) -> None:
|
||||
text = normalize_destination(value)
|
||||
if text and text not in candidates:
|
||||
candidates.append(text)
|
||||
|
||||
|
||||
def _extract_destination_object(candidates: list[str], value: Any) -> None:
|
||||
if not isinstance(value, dict):
|
||||
_append_candidate(candidates, value)
|
||||
return
|
||||
for key in ("port_code", "city", "country", "warehouse_hint", "ship_to_location", "raw_text", "destination_code"):
|
||||
_append_candidate(candidates, value.get(key))
|
||||
|
||||
|
||||
def extract_destination_candidates(task: ShippingTask) -> list[str]:
|
||||
"""
|
||||
从任务解析结果提取目的地/港口/仓库候选。
|
||||
【AI 触发时机】:订单解析后由裁决服务调用,行级 inventory_source_hint 与目的地字段都作为候选证据。
|
||||
|
||||
核心逻辑:只读取 orders[].lines[].inventory_source_hint,禁止使用 Task.source_type;
|
||||
Task.source_type 表示 PDF/manual 等接入来源,不是库存源路由证据。
|
||||
Args:
|
||||
task: 待裁决库存源的发货任务。
|
||||
Returns:
|
||||
去重并标准化后的 match_aliases 候选。
|
||||
"""
|
||||
candidates: list[str] = []
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
for item in payload.get("destination_candidates") or []:
|
||||
_append_candidate(candidates, item)
|
||||
_extract_destination_object(candidates, payload.get("destination"))
|
||||
_append_candidate(candidates, task.ship_to)
|
||||
_append_candidate(candidates, task.destination_code)
|
||||
_append_candidate(candidates, task.destination_city)
|
||||
_append_candidate(candidates, task.destination_country)
|
||||
_append_candidate(candidates, task.warehouse_hint)
|
||||
for line in read_task_order_lines(task):
|
||||
_extract_destination_object(candidates, line.get("destination"))
|
||||
for key in ("destination_port", "destination_city", "destination_country", "warehouse_hint", "ship_to", "raw_text"):
|
||||
_append_candidate(candidates, line.get(key))
|
||||
_append_candidate(candidates, line.get("inventory_source_hint"))
|
||||
return candidates
|
||||
|
||||
|
||||
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
|
||||
"""将任务解析结果标准化为库存路由上下文。"""
|
||||
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
destination = payload.get("destination") if isinstance(payload.get("destination"), dict) else {}
|
||||
return {
|
||||
"destination_code": task.destination_code or destination.get("port_code") or destination.get("destination_code"),
|
||||
"destination_city": task.destination_city or destination.get("city"),
|
||||
"destination_country": task.destination_country or destination.get("country"),
|
||||
"warehouse_hint": task.warehouse_hint or destination.get("warehouse_hint"),
|
||||
"customer_code": task.customer_code,
|
||||
"customer_name": task.customer_name,
|
||||
"order_type": payload.get("order_type"),
|
||||
"destination_candidates": extract_destination_candidates(task),
|
||||
'destination_code': task.destination_code,
|
||||
'destination_city': task.destination_city,
|
||||
'destination_country': task.destination_country,
|
||||
'warehouse_hint': task.warehouse_hint,
|
||||
'customer_code': task.customer_code,
|
||||
'customer_name': task.customer_name,
|
||||
'order_type': payload.get('order_type'),
|
||||
'destination_candidates': [],
|
||||
}
|
||||
|
||||
|
||||
def _candidate_summary(source: dict[str, Any], *, score: int = 0, matched_by: str | None = None) -> dict[str, Any]:
|
||||
"""人工确认候选项展示字段;前端必须提交 source_code。"""
|
||||
def compute_routing_fingerprint(context: dict[str, Any]) -> str:
|
||||
"""按路由事实和数据库配置版本生成稳定指纹。"""
|
||||
payload = {'context': context, 'config_version': inventory_sources_runtime_version()}
|
||||
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=True, default=str).encode('ascii')).hexdigest()[:32]
|
||||
|
||||
|
||||
def _candidate(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构造不泄露凭据的人工确认候选。"""
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"display_name": source.get("display_name"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"match_score": score,
|
||||
"matched_by": matched_by,
|
||||
'source_code': source['source_code'],
|
||||
'display_name': source['display_name'],
|
||||
'connector_type': source['connector_type'],
|
||||
'warehouse_resolution_mode': source['warehouse_resolution_mode'],
|
||||
'fixed_warehouse_id': source['fixed_warehouse_id'],
|
||||
}
|
||||
|
||||
|
||||
def _normalize_token_list(values: Any) -> list[str]:
|
||||
if not isinstance(values, list):
|
||||
return []
|
||||
return [normalize_destination(item) for item in values if normalize_destination(item)]
|
||||
|
||||
|
||||
def _all_enabled_source_candidates() -> list[dict[str, Any]]:
|
||||
"""返回全部启用库存源候选项,供未命中时人工选择。"""
|
||||
return [
|
||||
_candidate_summary(source)
|
||||
for source in list_inventory_sources()
|
||||
if source.get("enabled", True) is not False
|
||||
]
|
||||
|
||||
|
||||
def _source_matches_destination(source: dict[str, Any], destination_candidates: list[str]) -> bool:
|
||||
"""判断库存源别名是否与订单目的地线索有交集。"""
|
||||
aliases = list(source.get("match_aliases") or [])
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
aliases.extend(_normalize_token_list(match_cfg.get("aliases")))
|
||||
if not aliases:
|
||||
return False
|
||||
return any(_matches_alias(candidate, alias) for candidate in destination_candidates for alias in aliases)
|
||||
|
||||
|
||||
def _source_field_excluded(source: dict[str, Any], context: dict[str, Any]) -> bool:
|
||||
"""显式 match 规则已声明但订单字段未命中时,排除该库存源。"""
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if allowed and field_value:
|
||||
if not (
|
||||
field_value in allowed
|
||||
or any(field_value in item or item in field_value for item in allowed)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _detect_rule_conflicts(
|
||||
matches: list[tuple[int, dict[str, Any], list[dict[str, Any]]]],
|
||||
context: dict[str, Any],
|
||||
) -> list[str]:
|
||||
"""多候选同分时,检测不同来源对同一订单字段给出互斥规则命中。"""
|
||||
conflicts: list[str] = []
|
||||
field_hits: dict[str, set[str]] = {}
|
||||
for _, source, _ in matches:
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if not allowed or not field_value:
|
||||
continue
|
||||
hits = {
|
||||
item
|
||||
for item in allowed
|
||||
if field_value in item or item in field_value or field_value == item
|
||||
}
|
||||
if hits:
|
||||
field_hits.setdefault(field_name, set()).update(hits)
|
||||
for field_name, hits in field_hits.items():
|
||||
if len(hits) > 1:
|
||||
conflicts.append(f"{field_name}_rule_conflict")
|
||||
return conflicts
|
||||
|
||||
|
||||
def _source_match_score(source: dict[str, Any], context: dict[str, Any], destination_candidates: list[str]) -> tuple[int, list[dict[str, Any]]]:
|
||||
"""按配置 match 规则与 match_aliases 计算命中分数与证据。"""
|
||||
score = 0
|
||||
evidence: list[dict[str, Any]] = []
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
|
||||
for field_name, cfg_key in (
|
||||
("destination_code", "destination_codes"),
|
||||
("customer_code", "customers"),
|
||||
("order_type", "order_types"),
|
||||
("warehouse_hint", "warehouse_hints"),
|
||||
):
|
||||
field_value = normalize_destination(context.get(field_name))
|
||||
allowed = _normalize_token_list(match_cfg.get(cfg_key))
|
||||
if allowed and field_value:
|
||||
if field_value in allowed or any(field_value in item or item in field_value for item in allowed):
|
||||
score += 10
|
||||
evidence.append({"field": field_name, "value": field_value, "rule": cfg_key})
|
||||
|
||||
aliases = list(source.get("match_aliases") or []) + _normalize_token_list(match_cfg.get("aliases"))
|
||||
for candidate in destination_candidates:
|
||||
for alias in aliases:
|
||||
if _matches_alias(candidate, alias):
|
||||
score += 5
|
||||
evidence.append({"field": "destination_candidate", "value": candidate, "alias": alias})
|
||||
break
|
||||
|
||||
priority = int(source.get("priority") or 0)
|
||||
if score > 0 and priority:
|
||||
score += min(priority // 10, 5)
|
||||
return score, evidence
|
||||
|
||||
|
||||
def _stable_from_source(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
method: str,
|
||||
evidence: list[dict[str, Any]],
|
||||
context: dict[str, Any],
|
||||
) -> InventorySourceAdjudication:
|
||||
"""仅在四元组身份可完整解析时返回 resolved。"""
|
||||
def _from_source(*, status: str, source: dict[str, Any], method: str, context: dict[str, Any], evidence: list[dict[str, Any]] | None = None) -> InventorySourceAdjudication:
|
||||
"""由数据库 Source 生成 resolved/user_confirmed 裁决。"""
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
config_version = get_inventory_sources_config_version()
|
||||
fingerprint = compute_routing_fingerprint(context)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
if not resolution.ok or not resolution.identity:
|
||||
if resolution.reason == "crane_warehouse_ambiguous":
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
method=method,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=evidence,
|
||||
reason=resolution.reason,
|
||||
)
|
||||
status = "invalid" if resolution.reason in {"source_incomplete", "crane_aliases_missing"} else "unresolved"
|
||||
return InventorySourceAdjudication(
|
||||
status=status,
|
||||
method=method,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=evidence,
|
||||
conflicts=[resolution.reason] if resolution.reason else [],
|
||||
reason=resolution.reason or "identity_incomplete",
|
||||
)
|
||||
return InventorySourceAdjudication('invalid', reason=resolution.reason, config_version=inventory_sources_runtime_version())
|
||||
identity = resolution.identity
|
||||
return InventorySourceAdjudication(
|
||||
status="resolved",
|
||||
status=status,
|
||||
method=method,
|
||||
source_code=identity.source_code,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=config_version,
|
||||
routing_fingerprint=fingerprint,
|
||||
candidates=[_candidate_summary(source, score=100, matched_by=method)],
|
||||
destination_candidates=destination_candidates,
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(source)],
|
||||
evidence=evidence or [],
|
||||
)
|
||||
|
||||
|
||||
def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication:
|
||||
"""将规则引擎候选集转换为可执行或待人工确认的裁决。"""
|
||||
sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))]
|
||||
evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}]
|
||||
if result.status == 'resolved' and len(sources) == 1:
|
||||
return _from_source(status='resolved', source=sources[0], method='rule', context=context, evidence=evidence)
|
||||
return InventorySourceAdjudication(
|
||||
status=result.status,
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())],
|
||||
evidence=evidence,
|
||||
reason='routing_rule_' + result.status,
|
||||
)
|
||||
|
||||
|
||||
def _snapshot_match_key(row: dict[str, Any]) -> tuple[str, str] | None:
|
||||
"""构造库存快照与订单共用的 Reservation ID + Part Number 匹配键。"""
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
part_number = str(row.get('part_number') or '').strip().upper()
|
||||
reservation_id = validated_reservation_id(row.get('reservation_id'))
|
||||
return (part_number, reservation_id) if part_number and reservation_id else None
|
||||
|
||||
|
||||
def resolve_ambiguous_source_from_ready_snapshots(
|
||||
task: ShippingTask,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用已有有效快照从多个规则候选中确定唯一库存源,绝不比较库存数量或触发 RPA。
|
||||
|
||||
仅当规则已经给出明确的多个 Source 候选时执行。每个候选只检查其最新有效快照是否
|
||||
覆盖订单全部 ``reservation_id + part_number`` 键;恰好一个候选命中才自动确定 Source。
|
||||
快照缺失、多个候选命中或订单缺少匹配键时保留原人工确认状态。
|
||||
"""
|
||||
if adjudication.status != 'ambiguous':
|
||||
return adjudication
|
||||
|
||||
candidate_codes = {
|
||||
str(item.get('source_code') or '').strip().upper()
|
||||
for item in adjudication.candidates
|
||||
if isinstance(item, dict) and str(item.get('source_code') or '').strip()
|
||||
}
|
||||
order_keys = {
|
||||
key for row in read_task_order_lines(task)
|
||||
if isinstance(row, dict) and (key := _snapshot_match_key(row))
|
||||
}
|
||||
if not candidate_codes or not order_keys:
|
||||
return adjudication
|
||||
|
||||
# A partial or malformed order cannot be silently routed from a file.
|
||||
if len(order_keys) != len(read_task_order_lines(task)):
|
||||
return adjudication
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
|
||||
|
||||
matched: list[tuple[dict[str, Any], Any]] = []
|
||||
checked: list[dict[str, Any]] = []
|
||||
for source_code in sorted(candidate_codes):
|
||||
source = get_database_inventory_source(source_code)
|
||||
if source is None:
|
||||
continue
|
||||
warehouse_id = source.get('fixed_warehouse_id') if source.get('warehouse_resolution_mode') == 'fixed' else None
|
||||
snapshot = find_latest_ready_snapshot(source_code, warehouse_id)
|
||||
if snapshot is None:
|
||||
checked.append({'source_code': source_code, 'snapshot': 'missing'})
|
||||
continue
|
||||
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
if not lines:
|
||||
try:
|
||||
lines, _column_meta = parse_inventory_snapshot_file(snapshot)
|
||||
except (OSError, ValueError):
|
||||
lines = []
|
||||
inventory_keys = {
|
||||
key for row in lines
|
||||
if isinstance(row, dict) and (key := _snapshot_match_key(row))
|
||||
}
|
||||
is_match = order_keys.issubset(inventory_keys)
|
||||
checked.append({
|
||||
'source_code': source_code,
|
||||
'inventory_file_no': snapshot.inventory_file_no,
|
||||
'matched': is_match,
|
||||
})
|
||||
if is_match:
|
||||
matched.append((source, snapshot))
|
||||
|
||||
evidence = [*(adjudication.evidence or []), {
|
||||
'snapshot_candidate_check': checked,
|
||||
'match_key': ['reservation_id', 'part_number'],
|
||||
'selection_basis': 'unique_exact_key_coverage',
|
||||
}]
|
||||
if len(matched) != 1:
|
||||
return replace(adjudication, evidence=evidence)
|
||||
|
||||
source, snapshot = matched[0]
|
||||
resolution = resolve_inventory_source_identity(source, extract_routing_context(task))
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return replace(adjudication, evidence=evidence)
|
||||
identity = resolution.identity
|
||||
return InventorySourceAdjudication(
|
||||
status='resolved',
|
||||
method='snapshot_match',
|
||||
source_code=identity.source_code,
|
||||
connector_type=identity.connector_type,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
|
||||
candidates=adjudication.candidates,
|
||||
destination_candidates=adjudication.destination_candidates,
|
||||
evidence=evidence,
|
||||
reason=f'unique_ready_snapshot:{snapshot.inventory_file_no}',
|
||||
)
|
||||
|
||||
|
||||
def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""
|
||||
根据任务路由上下文与配置规则做确定性库存源裁决。
|
||||
核心逻辑:相同输入与相同配置必须产生相同结果;区分未命中、多命中、冲突与配置无效。
|
||||
"""
|
||||
"""先评估任务级规则,再在所有订单行一致时接受行级规则结果。"""
|
||||
context = extract_routing_context(task)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
config_version = get_inventory_sources_config_version()
|
||||
|
||||
scored: list[tuple[int, dict[str, Any], list[dict[str, Any]]]] = []
|
||||
for source in list_inventory_sources():
|
||||
if _source_field_excluded(source, context):
|
||||
continue
|
||||
connector_type = str(source.get("connector_type") or "").strip()
|
||||
if connector_type == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip()
|
||||
or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
continue
|
||||
score, evidence = _source_match_score(source, context, destination_candidates)
|
||||
if score > 0:
|
||||
scored.append((score, source, evidence))
|
||||
|
||||
if not scored:
|
||||
# Fallback: legacy match_aliases only
|
||||
matched_codes: list[str] = []
|
||||
alias_evidence: dict[str, list[dict[str, Any]]] = {}
|
||||
for candidate in destination_candidates:
|
||||
for source in list_inventory_sources():
|
||||
aliases = source.get("match_aliases") or []
|
||||
if any(_matches_alias(candidate, alias) for alias in aliases):
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
if code and code not in matched_codes:
|
||||
matched_codes.append(code)
|
||||
alias_evidence.setdefault(code, []).append(
|
||||
{"field": "destination_candidate", "value": candidate, "alias_only": True}
|
||||
)
|
||||
if len(matched_codes) == 1:
|
||||
source = get_inventory_source(matched_codes[0])
|
||||
if source:
|
||||
return _stable_from_source(
|
||||
source,
|
||||
method="rule_exact",
|
||||
evidence=alias_evidence.get(matched_codes[0], []),
|
||||
context=context,
|
||||
)
|
||||
if len(matched_codes) > 1:
|
||||
candidates = [
|
||||
_candidate_summary(src, matched_by="rule_exact")
|
||||
for code in matched_codes
|
||||
for src in [get_inventory_source(code)]
|
||||
if src
|
||||
]
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[item for ev in alias_evidence.values() for item in ev],
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
task_result = evaluate_inventory_source_rules(task=task)
|
||||
if task_result.status != 'unresolved':
|
||||
return _result_to_adjudication(task_result, context)
|
||||
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in read_task_order_lines(task)]
|
||||
resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1}
|
||||
if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results):
|
||||
return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context)
|
||||
if len(resolved_codes) > 1:
|
||||
return InventorySourceAdjudication(
|
||||
status="unresolved",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=_all_enabled_source_candidates(),
|
||||
destination_candidates=destination_candidates,
|
||||
reason="no_route_rule_matched",
|
||||
'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes],
|
||||
reason='line_rules_resolve_different_sources',
|
||||
)
|
||||
|
||||
scored.sort(key=lambda item: (-item[0], str(item[1].get("source_code") or "")))
|
||||
top_score = scored[0][0]
|
||||
top_matches = [item for item in scored if item[0] == top_score]
|
||||
|
||||
if len(top_matches) == 1:
|
||||
_, source, evidence = top_matches[0]
|
||||
method = "rule_combined" if len(evidence) > 1 else "rule_exact"
|
||||
return _stable_from_source(source, method=method, evidence=evidence, context=context)
|
||||
|
||||
conflicts = _detect_rule_conflicts(top_matches, context)
|
||||
if conflicts:
|
||||
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
|
||||
return InventorySourceAdjudication(
|
||||
status="conflicted",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[ev for _, _, ev in top_matches for ev in ev],
|
||||
conflicts=conflicts,
|
||||
reason="matched_conflicting_rules",
|
||||
)
|
||||
|
||||
candidates = [_candidate_summary(item[1], score=item[0], matched_by="rule_combined") for item in top_matches]
|
||||
return InventorySourceAdjudication(
|
||||
status="ambiguous",
|
||||
config_version=config_version,
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=candidates,
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[ev for _, _, ev in top_matches for ev in ev],
|
||||
reason="matched_multiple_sources",
|
||||
)
|
||||
return _result_to_adjudication(task_result, context)
|
||||
|
||||
|
||||
def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用户只提交 source_code;站点与库位从配置生成。用户最终选择优先于自动裁决。
|
||||
【AI 触发时机】:用户在 inventory_source_review 检查点选择正式库存源后调用。
|
||||
"""
|
||||
"""人工从已启用数据库 Source 中选择来源;不要求预先确定动态 Warehouse。"""
|
||||
context = extract_routing_context(task)
|
||||
destination_candidates = context.get("destination_candidates") or []
|
||||
code = str(source_code or "").strip().upper()
|
||||
source = get_inventory_source(code)
|
||||
if not source or source.get("enabled", True) is False:
|
||||
source = get_database_inventory_source(source_code)
|
||||
if not source:
|
||||
return InventorySourceAdjudication(
|
||||
status="invalid",
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=_all_enabled_source_candidates(),
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=["source_code_not_found"],
|
||||
reason="source_code_not_found",
|
||||
'invalid', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(item) for item in list_database_inventory_sources()], reason='source_code_not_found',
|
||||
)
|
||||
if str(source.get("connector_type") or "").strip() == "dsv360" and (
|
||||
not str(source.get("site_id") or "").strip() or not str(source.get("warehouse_id") or "").strip()
|
||||
):
|
||||
return InventorySourceAdjudication(
|
||||
status="invalid",
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source)],
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=["identity_incomplete_in_config"],
|
||||
reason="identity_incomplete_in_config",
|
||||
)
|
||||
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
status = "ambiguous" if resolution.reason == "crane_warehouse_ambiguous" else "invalid"
|
||||
return InventorySourceAdjudication(
|
||||
status=status,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source)],
|
||||
destination_candidates=destination_candidates,
|
||||
conflicts=[resolution.reason] if resolution.reason else [],
|
||||
reason=resolution.reason or "identity_incomplete",
|
||||
)
|
||||
|
||||
identity = resolution.identity
|
||||
return InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate_summary(source, matched_by="user_confirmed")],
|
||||
destination_candidates=destination_candidates,
|
||||
evidence=[{"field": "user_selection", "value": code}],
|
||||
)
|
||||
return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context)
|
||||
|
||||
|
||||
# Backward-compatible wrappers
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
"""兼容旧调用点:委托 adjudicate_inventory_source。"""
|
||||
"""兼容调用名,委托当前通用规则裁决。"""
|
||||
return adjudicate_inventory_source(task)
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""读取任务当前运行时 RPA source(静态配置 + 任务动态库位)。"""
|
||||
from app.services.shipping_notice.inventory_sources import build_task_rpa_inventory_source
|
||||
|
||||
return build_task_rpa_inventory_source(task)
|
||||
"""按任务 Source 从数据库读取 RPA 配置;动态仓由回调库存文件确定。"""
|
||||
return get_database_inventory_source(task.inventory_source_code)
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(
|
||||
task: ShippingTask,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
resolution: InventorySourceAdjudication | None = None,
|
||||
) -> None:
|
||||
"""把已确认库存源写入独立字段与 step_payload_json。"""
|
||||
def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
"""兼容旧入口,将确认结果委托库存源门禁持久化。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
if resolution:
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
return
|
||||
code = str(source.get("source_code") or "").strip().upper()
|
||||
cfg = get_inventory_source(code)
|
||||
if not cfg:
|
||||
return
|
||||
context = extract_routing_context(task)
|
||||
resolution = resolve_inventory_source_identity(cfg, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return
|
||||
identity = resolution.identity
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=identity.source_code,
|
||||
connector_type=identity.connector_type,
|
||||
site_id=identity.site_id,
|
||||
warehouse_id=identity.warehouse_id,
|
||||
config_version=get_inventory_sources_config_version(),
|
||||
routing_fingerprint=compute_routing_fingerprint(context),
|
||||
)
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
selected = resolution or confirm_inventory_source_by_code(task, str(source.get('source_code') or ''))
|
||||
apply_inventory_source_adjudication(task, selected)
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
|
||||
"""库存源无法唯一命中时写入候选项;委托 apply_inventory_source_adjudication。"""
|
||||
"""兼容旧入口,写入待人工确认的 Source 候选。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
@@ -1,457 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_sources.py
|
||||
|
||||
用途:从 YAML/JSON 配置加载发货通知库存 RPA 源,并构造写入 trigger 的标准 rpa_inventory_source。
|
||||
依赖:Flask current_app、pathlib、PyYAML/json;inventory_source_rules / inventory_rpa_workflow 调用本模块。
|
||||
逻辑:新增 Warehouse 只改 backend/config/shipping_inventory_sources.yaml,不改 Python。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import yaml
|
||||
from flask import current_app
|
||||
|
||||
_VALID_CONNECTOR_TYPES = {
|
||||
"dsv360": "dsv360",
|
||||
"crane_footprint": "crane_footprint",
|
||||
}
|
||||
_VALID_PARAMETER_MODES = frozenset({"single", "multi_text", "multi_select"})
|
||||
_CONFIG_CACHE: dict[str, Any] | None = None
|
||||
_CONFIG_PATH: str | None = None
|
||||
_CONFIG_RAW_DIGEST: str | None = None
|
||||
|
||||
|
||||
def _canonical_source_for_digest(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""提取参与版本哈希的语义字段,忽略注释/空白等文件层噪声。"""
|
||||
match_cfg = source.get("match") if isinstance(source.get("match"), dict) else {}
|
||||
return {
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"warehouse_resolution": source.get("warehouse_resolution"),
|
||||
"enabled": source.get("enabled", True),
|
||||
"priority": source.get("priority", 0),
|
||||
"entry_url": source.get("entry_url"),
|
||||
"display_name": source.get("display_name"),
|
||||
"match_aliases": sorted(source.get("match_aliases") or []),
|
||||
"allowed_warehouse_ids": sorted(source.get("allowed_warehouse_ids") or []),
|
||||
"match": {
|
||||
key: sorted(value) if isinstance(value, list) else value
|
||||
for key, value in sorted(match_cfg.items())
|
||||
},
|
||||
"navigation": source.get("navigation"),
|
||||
"parameters": source.get("parameters"),
|
||||
"export": source.get("export"),
|
||||
}
|
||||
|
||||
|
||||
def _normalized_config_digest(sources: dict[str, dict[str, Any]]) -> str:
|
||||
"""基于规范化结构计算配置内容哈希。"""
|
||||
import hashlib
|
||||
|
||||
canonical = [_canonical_source_for_digest(sources[code]) for code in sorted(sources)]
|
||||
payload = json.dumps(canonical, sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
|
||||
|
||||
|
||||
def _config_content_version(payload: dict[str, Any], sources: dict[str, dict[str, Any]]) -> str:
|
||||
"""配置版本 = 声明版本 + 规范化结构哈希。"""
|
||||
digest = _normalized_config_digest(sources)
|
||||
declared = str(payload.get("version") or "1").strip()
|
||||
return f"{declared}-{digest}"
|
||||
|
||||
|
||||
class InventorySourceConfigError(ValueError):
|
||||
"""库存源配置校验失败。"""
|
||||
|
||||
|
||||
def _config_path() -> Path:
|
||||
"""解析库存源配置文件路径;优先 Flask config,其次默认 backend/config。"""
|
||||
raw = str(current_app.config.get("SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG") or "").strip()
|
||||
if raw:
|
||||
path = Path(raw)
|
||||
if not path.is_absolute():
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
path = Path(resolve_backend_relative_path(raw, path))
|
||||
return path
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
|
||||
default = Path(__file__).resolve().parents[3] / "config" / "shipping_inventory_sources.yaml"
|
||||
return Path(resolve_backend_relative_path(None, default))
|
||||
|
||||
|
||||
def _parse_config_payload(path: Path) -> dict[str, Any]:
|
||||
"""
|
||||
按文件后缀解析库存源配置(默认 YAML;测试夹具仍可用 .json)。
|
||||
Raises:
|
||||
InventorySourceConfigError: 后缀不支持或解析失败
|
||||
"""
|
||||
text = path.read_text(encoding="utf-8")
|
||||
suffix = path.suffix.lower()
|
||||
try:
|
||||
if suffix in {".yaml", ".yml"}:
|
||||
payload = yaml.safe_load(text)
|
||||
elif suffix == ".json":
|
||||
payload = json.loads(text)
|
||||
else:
|
||||
raise InventorySourceConfigError(
|
||||
f"unsupported inventory sources config format: {path.suffix} (use .yaml, .yml, or .json)"
|
||||
)
|
||||
except (yaml.YAMLError, json.JSONDecodeError) as exc:
|
||||
raise InventorySourceConfigError(f"failed to parse inventory sources config: {path}: {exc}") from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise InventorySourceConfigError("inventory sources config root must be a mapping")
|
||||
return payload
|
||||
|
||||
|
||||
def _join_parameter_values(parameter: dict[str, Any]) -> str | None:
|
||||
"""将 multi_text 参数值按 joiner 拼接为单字符串。"""
|
||||
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
|
||||
if not values:
|
||||
return None
|
||||
joiner = str(parameter.get("joiner") or ",")
|
||||
return joiner.join(values)
|
||||
|
||||
|
||||
def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
从 navigation + parameters 构造 worker 兼容的 query 字段。
|
||||
核心逻辑:保留 DSV/Crane worker 现有读取口径,同时支持新版 parameters 驱动。
|
||||
"""
|
||||
navigation = dict(source.get("navigation") or {})
|
||||
query: dict[str, Any] = {}
|
||||
connector_type = str(source.get("connector_type") or "").strip().lower()
|
||||
|
||||
if connector_type == "dsv360":
|
||||
for key in ("program_group", "program_label", "report_group", "report_name"):
|
||||
if navigation.get(key):
|
||||
query[key] = navigation[key]
|
||||
elif connector_type == "crane_footprint":
|
||||
if navigation.get("report_name"):
|
||||
query["report_name"] = navigation["report_name"]
|
||||
query["project_code"] = navigation.get("project_code")
|
||||
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip()
|
||||
if warehouse_id:
|
||||
query["warehouse_code"] = warehouse_id
|
||||
|
||||
for parameter in source.get("parameters") or []:
|
||||
if not isinstance(parameter, dict):
|
||||
continue
|
||||
name = str(parameter.get("name") or "").strip()
|
||||
mode = str(parameter.get("mode") or "single").strip().lower()
|
||||
if mode == "multi_text":
|
||||
joined = _join_parameter_values(parameter)
|
||||
if not joined:
|
||||
continue
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = joined
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = joined
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = joined
|
||||
continue
|
||||
values = [str(item).strip() for item in (parameter.get("values") or []) if str(item).strip()]
|
||||
if not values:
|
||||
continue
|
||||
value = values[0]
|
||||
if name.lower() == "owner":
|
||||
query["owner_code"] = value
|
||||
elif name.lower() == "putawayzone":
|
||||
query["putaway_zone"] = value
|
||||
elif name.lower() == "warehouse":
|
||||
query["warehouse_code"] = value
|
||||
elif name.lower() == "project":
|
||||
query["project_code"] = value
|
||||
|
||||
return query
|
||||
|
||||
|
||||
def effective_warehouse_id(source: dict[str, Any]) -> str:
|
||||
"""返回配置中显式声明的 warehouse_id;禁止用 site_id 回填。"""
|
||||
return str(source.get("warehouse_id") or "").strip().upper()
|
||||
|
||||
|
||||
def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str, Any]:
|
||||
"""校验并规范化单条库存源配置。"""
|
||||
source_code = str(raw.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
raise InventorySourceConfigError("source_code is required")
|
||||
if source_code in seen_codes:
|
||||
raise InventorySourceConfigError(f"duplicate source_code: {source_code}")
|
||||
seen_codes.add(source_code)
|
||||
|
||||
connector_type = str(raw.get("connector_type") or "").strip().lower()
|
||||
if connector_type not in _VALID_CONNECTOR_TYPES:
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: connector_type must be dsv360 or crane_footprint"
|
||||
)
|
||||
|
||||
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
|
||||
site_id = str(raw.get("site_id") or "").strip().upper()
|
||||
if connector_type == "dsv360":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
|
||||
if not warehouse_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required for dsv360")
|
||||
elif connector_type == "crane_footprint":
|
||||
if not site_id:
|
||||
raise InventorySourceConfigError(f"{source_code}: site_id is required for crane_footprint")
|
||||
aliases = [str(alias).strip() for alias in (raw.get("match_aliases") or []) if str(alias).strip()]
|
||||
if not aliases:
|
||||
raise InventorySourceConfigError(f"{source_code}: match_aliases is required for crane_footprint")
|
||||
allowed_warehouse_ids = [
|
||||
str(item).strip()
|
||||
for item in (raw.get("allowed_warehouse_ids") or [])
|
||||
if str(item).strip()
|
||||
]
|
||||
if not allowed_warehouse_ids:
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: allowed_warehouse_ids is required for crane_footprint"
|
||||
)
|
||||
warehouse_resolution = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
|
||||
if warehouse_resolution != "alias_match":
|
||||
raise InventorySourceConfigError(
|
||||
f"{source_code}: warehouse_resolution must be alias_match for crane_footprint"
|
||||
)
|
||||
parameters: list[dict[str, Any]] = []
|
||||
for item in raw.get("parameters") or []:
|
||||
if not isinstance(item, dict):
|
||||
raise InventorySourceConfigError(f"{source_code}: parameters[] must be objects")
|
||||
mode = str(item.get("mode") or "single").strip().lower()
|
||||
if mode not in _VALID_PARAMETER_MODES:
|
||||
raise InventorySourceConfigError(f"{source_code}: invalid parameter mode {mode}")
|
||||
required = bool(item.get("required", False))
|
||||
values = [str(v).strip() for v in (item.get("values") or []) if str(v).strip()]
|
||||
if required and not values:
|
||||
raise InventorySourceConfigError(f"{source_code}: required parameter {item.get('name')} has no values")
|
||||
parameters.append({**item, "mode": mode, "values": values})
|
||||
|
||||
normalized = {
|
||||
"source_code": source_code,
|
||||
"connector_type": _VALID_CONNECTOR_TYPES[connector_type],
|
||||
"site_id": site_id,
|
||||
"display_name": str(raw.get("display_name") or source_code).strip(),
|
||||
"enabled": bool(raw.get("enabled", True)),
|
||||
"priority": int(raw.get("priority") or 0),
|
||||
"entry_url": str(raw.get("entry_url") or "").strip(),
|
||||
"warehouse_id": warehouse_id,
|
||||
"navigation": dict(raw.get("navigation") or {}),
|
||||
"parameters": parameters,
|
||||
"match_aliases": [
|
||||
str(alias).strip()
|
||||
for alias in (raw.get("match_aliases") or [])
|
||||
if str(alias).strip()
|
||||
],
|
||||
}
|
||||
if connector_type == "crane_footprint":
|
||||
normalized["warehouse_resolution"] = str(raw.get("warehouse_resolution") or "alias_match").strip().lower()
|
||||
normalized["allowed_warehouse_ids"] = allowed_warehouse_ids
|
||||
match_cfg = raw.get("match")
|
||||
if isinstance(match_cfg, dict) and match_cfg:
|
||||
normalized["match"] = {
|
||||
"destination_codes": [str(v).strip() for v in (match_cfg.get("destination_codes") or []) if str(v).strip()],
|
||||
"customers": [str(v).strip() for v in (match_cfg.get("customers") or []) if str(v).strip()],
|
||||
"order_types": [str(v).strip() for v in (match_cfg.get("order_types") or []) if str(v).strip()],
|
||||
"warehouse_hints": [str(v).strip() for v in (match_cfg.get("warehouse_hints") or []) if str(v).strip()],
|
||||
"aliases": [str(v).strip() for v in (match_cfg.get("aliases") or []) if str(v).strip()],
|
||||
}
|
||||
if connector_type == "crane_footprint" and raw.get("export"):
|
||||
normalized["export"] = dict(raw.get("export") or {})
|
||||
normalized["query"] = _build_legacy_query(normalized)
|
||||
return normalized
|
||||
|
||||
|
||||
def _load_config(*, force_reload: bool = False) -> dict[str, Any]:
|
||||
"""加载并缓存 YAML/JSON 配置;路径或文件内容变化时刷新(不依赖 mtime 单独命中)。"""
|
||||
import hashlib
|
||||
|
||||
global _CONFIG_CACHE, _CONFIG_PATH, _CONFIG_RAW_DIGEST
|
||||
path = _config_path()
|
||||
if not path.is_file():
|
||||
raise InventorySourceConfigError(f"inventory sources config not found: {path}")
|
||||
|
||||
path_str = str(path.resolve())
|
||||
raw_digest = hashlib.sha256(path.read_bytes()).hexdigest()[:16]
|
||||
if (
|
||||
_CONFIG_CACHE is not None
|
||||
and not force_reload
|
||||
and _CONFIG_PATH == path_str
|
||||
and _CONFIG_RAW_DIGEST == raw_digest
|
||||
):
|
||||
return _CONFIG_CACHE
|
||||
|
||||
payload = _parse_config_payload(path)
|
||||
sources_raw = payload.get("sources")
|
||||
if not isinstance(sources_raw, list):
|
||||
raise InventorySourceConfigError("sources must be a list")
|
||||
|
||||
seen_codes: set[str] = set()
|
||||
sources: dict[str, dict[str, Any]] = {}
|
||||
for item in sources_raw:
|
||||
if not isinstance(item, dict):
|
||||
raise InventorySourceConfigError("each source must be an object")
|
||||
normalized = _validate_source(item, seen_codes=seen_codes)
|
||||
sources[normalized["source_code"]] = normalized
|
||||
|
||||
_CONFIG_CACHE = {
|
||||
"version": _config_content_version(payload, sources),
|
||||
"sources": sources,
|
||||
"path": path_str,
|
||||
"raw_digest": raw_digest,
|
||||
}
|
||||
_CONFIG_PATH = path_str
|
||||
_CONFIG_RAW_DIGEST = raw_digest
|
||||
return _CONFIG_CACHE
|
||||
|
||||
|
||||
def get_inventory_sources_config_version() -> str:
|
||||
"""返回当前加载的库存源配置版本字符串。"""
|
||||
return str(_load_config().get("version") or "1")
|
||||
|
||||
|
||||
def reload_inventory_sources_config() -> dict[str, Any]:
|
||||
"""强制重新加载库存源配置(管理/测试用)。"""
|
||||
return _load_config(force_reload=True)
|
||||
|
||||
|
||||
def get_inventory_source(source_code: str | None) -> dict[str, Any] | None:
|
||||
"""按 source_code 返回启用的库存源配置副本。"""
|
||||
code = str(source_code or "").strip().upper()
|
||||
if not code:
|
||||
return None
|
||||
source = _load_config()["sources"].get(code)
|
||||
if not source or not source.get("enabled", True):
|
||||
return None
|
||||
return deepcopy(source)
|
||||
|
||||
|
||||
def source_uses_dynamic_warehouse_id(source: dict[str, Any] | None) -> bool:
|
||||
"""判断库存源是否采用运行时动态库位(如 CRANE alias_match)。"""
|
||||
if not source:
|
||||
return False
|
||||
if str(source.get("warehouse_id") or "").strip():
|
||||
return False
|
||||
resolution = str(source.get("warehouse_resolution") or "").strip().lower()
|
||||
return resolution in {"alias_match", "dynamic", "runtime"}
|
||||
|
||||
|
||||
def configured_warehouse_aliases(source: dict[str, Any] | None) -> set[str]:
|
||||
"""返回配置中的路由匹配别名集合(大写),供订单目的地裁决使用。"""
|
||||
if not source:
|
||||
return set()
|
||||
return {
|
||||
str(alias).strip().upper()
|
||||
for alias in (source.get("match_aliases") or [])
|
||||
if str(alias).strip()
|
||||
}
|
||||
|
||||
|
||||
def configured_allowed_warehouse_ids(source: dict[str, Any] | None) -> set[str]:
|
||||
"""
|
||||
返回 Worker 回调允许落库的库位 ID 集合(大写)。
|
||||
核心逻辑:优先读 allowed_warehouse_ids;静态源回退 warehouse_id;与 match_aliases 解耦。
|
||||
"""
|
||||
if not source:
|
||||
return set()
|
||||
allowed = source.get("allowed_warehouse_ids")
|
||||
if allowed:
|
||||
return {str(item).strip().upper() for item in allowed if str(item).strip()}
|
||||
# fallback for static DSV 等源
|
||||
warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
|
||||
if warehouse_id:
|
||||
return {warehouse_id}
|
||||
return set()
|
||||
|
||||
|
||||
def list_inventory_sources(*, enabled_only: bool = True) -> list[dict[str, Any]]:
|
||||
"""返回库存源配置副本,供人工检查点展示候选项。"""
|
||||
sources = _load_config()["sources"].values()
|
||||
if enabled_only:
|
||||
sources = [item for item in sources if item.get("enabled", True)]
|
||||
return [deepcopy(item) for item in sources]
|
||||
|
||||
|
||||
def build_rpa_inventory_source(
|
||||
source_code: str | None,
|
||||
*,
|
||||
query_override: dict[str, Any] | None = None,
|
||||
site_id: str | None = None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 RPA trigger 使用的 rpa_inventory_source。
|
||||
【AI 触发时机】:HXOPS 已确定库存源后,写 RPA trigger 或确认人工选择时调用。
|
||||
"""
|
||||
source = get_inventory_source(source_code)
|
||||
if not source:
|
||||
return None
|
||||
if query_override:
|
||||
query = dict(source.get("query") or {})
|
||||
for key, value in query_override.items():
|
||||
if value is not None and str(value).strip():
|
||||
query[key] = value
|
||||
source["query"] = query
|
||||
return merge_runtime_inventory_identity(source, site_id=site_id, warehouse_id=warehouse_id)
|
||||
|
||||
|
||||
def merge_runtime_inventory_identity(
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
site_id: str | None = None,
|
||||
warehouse_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将任务已解析的 site/warehouse 合并进 RPA source,并同步 query.warehouse_code。
|
||||
核心逻辑:Crane 动态库位、DSV 子仓均通过本函数进入 trigger/回调/快照复用。
|
||||
"""
|
||||
merged = deepcopy(source)
|
||||
site = str(site_id or merged.get("site_id") or "").strip().upper()
|
||||
warehouse = str(warehouse_id or merged.get("warehouse_id") or "").strip().upper()
|
||||
if site:
|
||||
merged["site_id"] = site
|
||||
if warehouse:
|
||||
merged["warehouse_id"] = warehouse
|
||||
merged["_runtime_identity_applied"] = True
|
||||
query = dict(merged.get("query") or {})
|
||||
query["warehouse_code"] = warehouse
|
||||
merged["query"] = query
|
||||
connector_type = str(merged.get("connector_type") or "").strip()
|
||||
if connector_type == "crane_footprint":
|
||||
navigation = dict(merged.get("navigation") or {})
|
||||
navigation["project_code"] = warehouse
|
||||
merged["navigation"] = navigation
|
||||
query["project_code"] = warehouse
|
||||
merged["query"] = query
|
||||
return merged
|
||||
|
||||
|
||||
def build_task_rpa_inventory_source(task: "ShippingTask") -> dict[str, Any] | None:
|
||||
"""
|
||||
基于任务正式库存身份构造运行时 RPA source(配置 + 动态库位)。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa、RPA 回调、快照复用统一调用。
|
||||
"""
|
||||
from app.models import ShippingTask
|
||||
|
||||
if not isinstance(task, ShippingTask):
|
||||
return None
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
code = str(task.inventory_source_code or "").strip().upper()
|
||||
site_id = str(task.inventory_site_id or "").strip().upper() or None
|
||||
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper() or None
|
||||
if not code:
|
||||
legacy = payload.get("rpa_inventory_source")
|
||||
if isinstance(legacy, dict) and legacy.get("source_code"):
|
||||
return merge_runtime_inventory_identity(legacy, site_id=site_id, warehouse_id=warehouse_id)
|
||||
return None
|
||||
base = get_inventory_source(code)
|
||||
if not base:
|
||||
return None
|
||||
return merge_runtime_inventory_identity(base, site_id=site_id, warehouse_id=warehouse_id)
|
||||
@@ -0,0 +1,426 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_analysis.py
|
||||
|
||||
用途:安全分析库存样本文件的工作表、表头、列统计和字段建议。
|
||||
依赖:openpyxl、inventory_snapshot 的受控表头词典、库存解析 Profile 服务、结构分析 ORM 模型。
|
||||
逻辑:管理端上传 .xls/.xlsx/.csv 样本后调用本服务生成后端权威分析记录;后续 RPA 测试与运行期漂移检查复用同一分析契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import hashlib
|
||||
import re
|
||||
import shutil
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import load_workbook
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
structure_definition,
|
||||
)
|
||||
|
||||
MAX_UPLOAD_BYTES = 20 * 1024 * 1024
|
||||
MAX_SCAN_ROWS = 40
|
||||
MAX_SAMPLE_ROWS = 5
|
||||
MAX_COLUMNS = 200
|
||||
_SOURCE_KINDS = {'sample_upload', 'configuration_test', 'production_snapshot', 'temporary_conversation'}
|
||||
|
||||
|
||||
def _has_required_suggestions(mapping: dict[str, str]) -> bool:
|
||||
"""确认自动建议至少覆盖一个匹配字段和一个库存数量字段。"""
|
||||
rows = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.status == 'active', ShippingInventoryField.id.in_([
|
||||
int(field_id) for field_id in mapping if str(field_id).isdigit()
|
||||
]),
|
||||
).all() if mapping else []
|
||||
usages = {row.usage_type for row in rows}
|
||||
return 'match_identity' in usages and 'inventory_quantity' in usages
|
||||
|
||||
|
||||
def _analysis_root() -> Path:
|
||||
"""返回库存结构分析样本的受控托管目录。"""
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
|
||||
return _storage_root() / 'inventory_structure_analyses'
|
||||
|
||||
|
||||
def _safe_filename(value: str) -> str:
|
||||
"""清理上传文件名,避免分析样本路径包含目录穿越字符。"""
|
||||
return re.sub(r'[^A-Za-z0-9._-]+', '_', Path(str(value or '')).name) or 'inventory.xlsx'
|
||||
|
||||
|
||||
def _normalise_header(value: Any) -> str:
|
||||
"""规范表头展示文本;结构指纹阶段会在此基础上做更严格标准化。"""
|
||||
return re.sub(r'\s+', ' ', str(value or '').replace('\u3000', ' ').strip())
|
||||
|
||||
|
||||
def _value_type(values: list[Any]) -> str:
|
||||
"""依据非空样本推断列类型,只供管理员确认,不能取代字段映射。"""
|
||||
non_empty = [value for value in values if value not in (None, '')]
|
||||
if not non_empty:
|
||||
return 'empty'
|
||||
numeric_count = 0
|
||||
date_count = 0
|
||||
for value in non_empty:
|
||||
if hasattr(value, 'year') and hasattr(value, 'month'):
|
||||
date_count += 1
|
||||
continue
|
||||
try:
|
||||
float(str(value).replace(',', '').strip())
|
||||
numeric_count += 1
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if date_count == len(non_empty):
|
||||
return 'date'
|
||||
if numeric_count == len(non_empty):
|
||||
return 'number'
|
||||
return 'text'
|
||||
|
||||
|
||||
def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]:
|
||||
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
|
||||
suggestions = suggest_field_mapping(headers, as_catalog=True)
|
||||
catalog = {
|
||||
str(item.id): item for item in ShippingInventoryField.query.filter_by(status='active').all()
|
||||
}
|
||||
reverse_suggestions = {header: catalog[field_id].display_name for field_id, header in suggestions.items() if field_id in catalog}
|
||||
duplicates = Counter(header for header in headers if header)
|
||||
rows_total = len(sample_rows)
|
||||
columns: list[dict[str, Any]] = []
|
||||
for index, header in enumerate(headers, start=1):
|
||||
values = [row[index - 1] if len(row) >= index else None for row in sample_rows]
|
||||
non_empty = [value for value in values if value not in (None, '')]
|
||||
columns.append({
|
||||
'index': index,
|
||||
'header': header,
|
||||
'sample_values': [str(value)[:120] for value in non_empty[:MAX_SAMPLE_ROWS]],
|
||||
'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1,
|
||||
'inferred_type': _value_type(non_empty),
|
||||
'duplicate': bool(header and duplicates[header] > 1),
|
||||
'suggested_inventory_field': reverse_suggestions.get(header),
|
||||
})
|
||||
return columns
|
||||
|
||||
|
||||
def _workbook_structure(path: Path, *, legacy_xls: bool = False) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""读取 xlsx 或旧 xls 的所有工作表并选择最可能的库存表头。"""
|
||||
if legacy_xls:
|
||||
import xlrd
|
||||
|
||||
book = xlrd.open_workbook(filename=str(path), on_demand=True)
|
||||
worksheets = [
|
||||
(
|
||||
str(book.sheet_by_index(index).name),
|
||||
[
|
||||
[
|
||||
_xls_cell_value(book, book.sheet_by_index(index).cell(row_index, column_index))
|
||||
for column_index in range(book.sheet_by_index(index).ncols)
|
||||
]
|
||||
for row_index in range(min(MAX_SCAN_ROWS, book.sheet_by_index(index).nrows))
|
||||
],
|
||||
book.sheet_by_index(index).nrows,
|
||||
book.sheet_by_index(index).ncols,
|
||||
)
|
||||
for index in range(book.nsheets)
|
||||
]
|
||||
try:
|
||||
return _build_workbook_structure(worksheets)
|
||||
finally:
|
||||
book.release_resources()
|
||||
|
||||
workbook = load_workbook(path, read_only=True, data_only=True)
|
||||
try:
|
||||
worksheets = []
|
||||
for worksheet in workbook.worksheets:
|
||||
rows = [list(row) for _, row in zip(range(MAX_SCAN_ROWS), worksheet.iter_rows(values_only=True))]
|
||||
worksheets.append((worksheet.title, rows, worksheet.max_row or 0, worksheet.max_column or 0))
|
||||
return _build_workbook_structure(worksheets)
|
||||
finally:
|
||||
workbook.close()
|
||||
|
||||
|
||||
def _build_workbook_structure(
|
||||
worksheets: list[tuple[str, list[list[Any]], int, int]],
|
||||
) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""将任意 Excel 行迭代结果归一为统一的库存结构分析输出。"""
|
||||
sheets: list[dict[str, Any]] = []
|
||||
candidates: list[dict[str, Any]] = []
|
||||
warnings: list[str] = []
|
||||
for sheet_name, rows, row_count, column_count in worksheets:
|
||||
if len(rows) and max(len(row) for row in rows) > MAX_COLUMNS:
|
||||
warnings.append(f'工作表“{sheet_name}”栏位数超过分析上限,仅可人工处理')
|
||||
continue
|
||||
header_index = find_inventory_header_row_index(rows)
|
||||
headers = [_normalise_header(value) for value in (rows[header_index] if rows else [])]
|
||||
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS] if rows else []
|
||||
suggested = suggest_field_mapping(headers, as_catalog=True)
|
||||
score = len(suggested) * 10 + (30 if _has_required_suggestions(suggested) else 0)
|
||||
candidate = {
|
||||
'sheet_name': sheet_name,
|
||||
'header_row_index': header_index + 1,
|
||||
'headers': headers,
|
||||
'columns': _column_summary(headers, samples),
|
||||
'sample_row_count': len(samples),
|
||||
'row_count_hint': row_count,
|
||||
'score': score,
|
||||
}
|
||||
sheets.append({'sheet_name': sheet_name, 'row_count_hint': row_count, 'column_count': column_count})
|
||||
if headers:
|
||||
candidates.append(candidate)
|
||||
if not candidates:
|
||||
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
selected = max(candidates, key=lambda item: (item['score'], item['sample_row_count']))
|
||||
structure = {
|
||||
'sheets': sheets,
|
||||
'candidates': candidates,
|
||||
'selected_sheet_name': selected['sheet_name'],
|
||||
'selected_header_row_index': selected['header_row_index'],
|
||||
'selected_headers': selected['headers'],
|
||||
'selected_columns': selected['columns'],
|
||||
}
|
||||
mapping = suggest_field_mapping(selected['headers'], as_catalog=True)
|
||||
summary = {
|
||||
'candidate_count': len(candidates),
|
||||
'sample_row_count': selected['sample_row_count'],
|
||||
'valid_inventory_field_suggestions': len(mapping),
|
||||
'has_required_suggestions': _has_required_suggestions(mapping),
|
||||
}
|
||||
return structure, mapping, summary, warnings
|
||||
|
||||
|
||||
def _xlsx_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""读取 xlsx 工作簿的结构摘要。"""
|
||||
return _workbook_structure(path)
|
||||
|
||||
|
||||
def _xls_cell_value(book: Any, cell: Any) -> Any:
|
||||
"""将 xlrd 单元格值转换为与 openpyxl 接近的 Python 值。"""
|
||||
import xlrd
|
||||
|
||||
if cell.ctype == xlrd.XL_CELL_EMPTY:
|
||||
return None
|
||||
if cell.ctype == xlrd.XL_CELL_DATE:
|
||||
return xlrd.xldate_as_datetime(cell.value, book.datemode)
|
||||
if cell.ctype == xlrd.XL_CELL_NUMBER and float(cell.value).is_integer():
|
||||
return int(cell.value)
|
||||
return cell.value
|
||||
|
||||
|
||||
def _xls_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""读取旧 .xls 工作簿结构;与 xlsx 产出完全相同的分析契约。"""
|
||||
return _workbook_structure(path, legacy_xls=True)
|
||||
|
||||
|
||||
def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""读取 CSV 样本,使用与 Excel 一致的表头和列统计逻辑。"""
|
||||
try:
|
||||
with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as handle:
|
||||
rows = [row for _, row in zip(range(MAX_SCAN_ROWS), csv.reader(handle))]
|
||||
except OSError as exc:
|
||||
raise ValidationError('Inventory CSV cannot be read', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
if not rows:
|
||||
raise ValidationError('Inventory file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
header_index = find_inventory_header_row_index(rows)
|
||||
headers = [_normalise_header(value) for value in rows[header_index]]
|
||||
samples = rows[header_index + 1:header_index + 1 + MAX_SAMPLE_ROWS]
|
||||
mapping = suggest_field_mapping(headers, as_catalog=True)
|
||||
candidate = {
|
||||
'sheet_name': None,
|
||||
'header_row_index': header_index + 1,
|
||||
'headers': headers,
|
||||
'columns': _column_summary(headers, samples),
|
||||
'sample_row_count': len(samples),
|
||||
'row_count_hint': len(rows),
|
||||
'score': len(mapping) * 10 + (30 if _has_required_suggestions(mapping) else 0),
|
||||
}
|
||||
return {
|
||||
'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None,
|
||||
'selected_header_row_index': header_index + 1, 'selected_headers': headers,
|
||||
'selected_columns': candidate['columns'],
|
||||
}, mapping, {
|
||||
'candidate_count': 1, 'sample_row_count': len(samples),
|
||||
'valid_inventory_field_suggestions': len(mapping),
|
||||
'has_required_suggestions': _has_required_suggestions(mapping),
|
||||
}, []
|
||||
|
||||
|
||||
def _analyse_path(path: Path, suffix: str) -> tuple[dict[str, Any], dict[str, str], dict[str, Any], list[str]]:
|
||||
"""按受控文件格式分派结构分析,禁止根据内容猜测不支持的格式。"""
|
||||
if suffix == '.xlsx':
|
||||
return _xlsx_structure(path)
|
||||
if suffix == '.xls':
|
||||
return _xls_structure(path)
|
||||
if suffix == '.csv':
|
||||
return _csv_structure(path)
|
||||
raise ValidationError('Inventory file format is unsupported', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
|
||||
|
||||
def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
|
||||
"""输出管理端需要的分析结果,不暴露服务器存储路径。"""
|
||||
return {
|
||||
'id': item.id,
|
||||
'source_kind': item.source_kind,
|
||||
'source_file_name': item.source_file_name,
|
||||
'file_checksum': item.file_checksum,
|
||||
'file_format': item.file_format,
|
||||
'analysis_status': item.analysis_status,
|
||||
'structure': item.structure_json or {},
|
||||
'suggested_mapping': item.suggested_mapping_json or {},
|
||||
'validation_summary': item.validation_summary_json or {},
|
||||
'warnings': item.warning_json or [],
|
||||
'match_result': item.match_result_json or {},
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""上传并分析管理员选择的库存样本文件,创建后端权威分析记录。"""
|
||||
if upload is None or not str(upload.filename or '').strip():
|
||||
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
|
||||
suffix = resolve_inventory_upload_suffix(str(upload.filename))
|
||||
raw = upload.stream.read(MAX_UPLOAD_BYTES + 1)
|
||||
if len(raw) > MAX_UPLOAD_BYTES:
|
||||
raise ValidationError('Inventory sample file is too large', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_TOO_LARGE')
|
||||
if not raw:
|
||||
raise ValidationError('Inventory sample file is empty', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
|
||||
analysis_dir = _analysis_root() / uuid.uuid4().hex
|
||||
analysis_dir.mkdir(parents=True, exist_ok=False)
|
||||
path = analysis_dir / f'sample{suffix}'
|
||||
try:
|
||||
path.write_bytes(raw)
|
||||
structure, suggested, summary, warnings = _analyse_path(path, suffix)
|
||||
except ValidationError:
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise
|
||||
except Exception as exc:
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise ValidationError('Inventory sample file cannot be analysed', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') from exc
|
||||
selected_headers = structure.get('selected_headers', [])
|
||||
selected_definition = structure_definition(
|
||||
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
|
||||
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
|
||||
)
|
||||
item = ShippingInventoryStructureAnalysis(
|
||||
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=str(path),
|
||||
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
|
||||
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
|
||||
warning_json=warnings, created_by=actor_id,
|
||||
exact_structure_fingerprint=exact_fingerprint(selected_definition),
|
||||
compatibility_fingerprint=compatibility_fingerprint(
|
||||
definition=selected_definition, field_mapping=suggested, match_keys=[],
|
||||
),
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
|
||||
item.match_result_json = recommend_profiles({
|
||||
'structure': structure,
|
||||
'suggested_mapping': suggested,
|
||||
'exact_structure_fingerprint': item.exact_structure_fingerprint,
|
||||
'compatibility_fingerprint': item.compatibility_fingerprint,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_analysis(item)
|
||||
|
||||
|
||||
def get_analysis(analysis_id: int) -> dict[str, Any]:
|
||||
"""读取既有结构分析,供管理员选择工作表、表头和来源栏位。"""
|
||||
item = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if item is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
return serialize_analysis(item)
|
||||
|
||||
|
||||
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if analysis is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
|
||||
header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index')
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') == sheet_name and item.get('header_row_index') == header_row_index), None)
|
||||
if candidate is None and sheet_name is None:
|
||||
candidate = next((item for item in candidates if isinstance(item, dict) and item.get('sheet_name') is None and item.get('header_row_index') == header_row_index), None)
|
||||
if not isinstance(candidate, dict):
|
||||
raise ValidationError('Selected worksheet or header row is not in the analysis', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
headers = {str(value).strip() for value in candidate.get('headers', []) if str(value).strip()}
|
||||
mapping = data.get('field_mapping') if isinstance(data.get('field_mapping'), dict) else analysis.suggested_mapping_json or {}
|
||||
if any(str(value or '').strip() not in headers for value in mapping.values()):
|
||||
raise ValidationError('Parsing field mapping must use analysed headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
duplicates = {
|
||||
str(column.get('header') or '').strip()
|
||||
for column in candidate.get('columns', [])
|
||||
if isinstance(column, dict) and column.get('duplicate')
|
||||
}
|
||||
if any(str(value or '').strip() in duplicates for value in mapping.values()):
|
||||
raise ValidationError('Parsing field mapping cannot use duplicate headers', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
|
||||
saved = inventory_parsing_profile.save_draft({
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
'file_format': analysis.file_format,
|
||||
'definition': {
|
||||
'sheet_name': sheet_name,
|
||||
'header_row_index': header_row_index,
|
||||
'field_mapping': mapping,
|
||||
'match_keys': data.get('match_keys'),
|
||||
},
|
||||
}, actor_id=actor_id, profile_id=data.get('profile_id'))
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, saved['id'])
|
||||
selected_definition = structure_definition(
|
||||
file_format=analysis.file_format, sheet_name=sheet_name, header_row_index=header_row_index,
|
||||
headers=[str(value) for value in candidate.get('headers', [])],
|
||||
)
|
||||
profile.structure_definition_json = selected_definition
|
||||
profile.exact_structure_fingerprint = exact_fingerprint(selected_definition)
|
||||
profile.compatibility_fingerprint = compatibility_fingerprint(
|
||||
definition=selected_definition, field_mapping=mapping,
|
||||
match_keys=data.get('match_keys') if isinstance(data.get('match_keys'), list) else [],
|
||||
)
|
||||
profile.fingerprint_version = selected_definition['fingerprint_version']
|
||||
db.session.commit()
|
||||
return inventory_parsing_profile.payload(profile)
|
||||
|
||||
|
||||
def adopt_published_profile(analysis_id: int, profile_id: int) -> dict[str, Any]:
|
||||
"""确认分析结果采用指定已发布方案;只记录确认,不自动绑定任何库存站点。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
|
||||
if analysis is None:
|
||||
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if profile is None or profile.status != 'published':
|
||||
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
|
||||
match = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
|
||||
candidate_ids = {int(item.get('profile_id')) for item in match.get('candidates', []) if isinstance(item, dict) and item.get('profile_id')}
|
||||
same_test_structure = bool(
|
||||
analysis.exact_structure_fingerprint
|
||||
and analysis.exact_structure_fingerprint == profile.exact_structure_fingerprint
|
||||
)
|
||||
if profile_id not in candidate_ids and not same_test_structure:
|
||||
raise ValidationError('Profile is not a compatible recommendation', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_SELECTION_INVALID')
|
||||
analysis.match_result_json = {
|
||||
**match,
|
||||
'adopted_profile_id': profile.id,
|
||||
'adopted_profile_checksum': profile.checksum,
|
||||
}
|
||||
db.session.commit()
|
||||
return serialize_analysis(analysis)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_drift.py
|
||||
|
||||
用途:在正式库存文件入库前核验其结构是否仍符合库存站点已绑定的解析方案。
|
||||
依赖:库存源/解析方案模型、库存结构分析和方案复用服务。
|
||||
逻辑:RPA 与后续人工受控入库复用本服务;一致文件可继续解析,核心栏位变化必须阻断,绝不回退至猜列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingInventorySource
|
||||
|
||||
|
||||
def validate_production_inventory_structure(*, source_code: str, path: Path) -> dict[str, Any]:
|
||||
"""核验正式库存文件结构并返回已绑定方案的确定性解析参数。
|
||||
|
||||
Args:
|
||||
source_code: 已启用库存站点编码,必须绑定已发布解析方案。
|
||||
path: RPA 下载的库存文件,必须是受控 xls/xlsx/csv 格式且存在。
|
||||
|
||||
Returns:
|
||||
包含 mapping、sheet_name、header_row_index 和可展示差异的字典。
|
||||
|
||||
Raises:
|
||||
ConflictError: 文件结构缺关键栏位、格式不一致或与已绑定方案不兼容时抛出。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=str(source_code or '').strip().upper()).first()
|
||||
profile = source.parsing_profile if source is not None else None
|
||||
if source is None or not source.enabled or profile is None or profile.status != 'published':
|
||||
raise ConflictError('Inventory source parsing profile is unavailable', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import exact_fingerprint, structure_definition
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
|
||||
suffix = resolve_inventory_upload_suffix(path.name)
|
||||
actual_format = suffix.lstrip('.')
|
||||
if actual_format != profile.file_format:
|
||||
raise ConflictError('Inventory file format changed', code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED')
|
||||
structure, suggested, _summary, warnings = _analyse_path(path, suffix)
|
||||
configured = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
expected_sheet = configured.get('sheet_name')
|
||||
expected_header_row = configured.get('header_row_index')
|
||||
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
|
||||
selected = next((item for item in candidates if isinstance(item, dict)
|
||||
and item.get('sheet_name') == expected_sheet
|
||||
and item.get('header_row_index') == expected_header_row), None)
|
||||
if selected is None:
|
||||
raise ConflictError(
|
||||
'Configured inventory worksheet or header row is unavailable',
|
||||
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
|
||||
details={'source_code': source.source_code, 'profile_id': profile.id},
|
||||
)
|
||||
# Compare the configured worksheet rather than the analyser's best guess.
|
||||
structure = {**structure, 'selected_sheet_name': selected['sheet_name'],
|
||||
'selected_header_row_index': selected['header_row_index'],
|
||||
'selected_headers': selected.get('headers', []), 'selected_columns': selected.get('columns', [])}
|
||||
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
|
||||
|
||||
suggested = suggest_field_mapping(structure['selected_headers'], as_catalog=True)
|
||||
definition = structure_definition(
|
||||
file_format=actual_format, sheet_name=structure.get('selected_sheet_name'),
|
||||
header_row_index=structure.get('selected_header_row_index') or 1,
|
||||
headers=structure.get('selected_headers', []),
|
||||
)
|
||||
analysis = {
|
||||
'structure': structure,
|
||||
'suggested_mapping': suggested,
|
||||
'exact_structure_fingerprint': exact_fingerprint(definition),
|
||||
'compatibility_fingerprint': '',
|
||||
}
|
||||
recommendation = recommend_profiles(analysis)
|
||||
candidate = next((item for item in recommendation.get('candidates', []) if item.get('profile_id') == profile.id), None)
|
||||
if candidate is None:
|
||||
raise ConflictError(
|
||||
'Inventory file structure is incompatible with the bound parsing profile',
|
||||
code='SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED',
|
||||
details={'source_code': source.source_code, 'profile_id': profile.id, 'warnings': warnings},
|
||||
)
|
||||
return {
|
||||
'field_mapping': dict(configured.get('field_mapping') or {}),
|
||||
'sheet_name': configured.get('sheet_name'),
|
||||
'header_row_index': configured.get('header_row_index'),
|
||||
'level': candidate.get('level'),
|
||||
'difference': candidate.get('difference') or {},
|
||||
'warnings': warnings,
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_structure_fingerprint.py
|
||||
|
||||
用途:为库存文件结构和解析定义生成稳定、可审计的指纹。
|
||||
依赖:标准 hashlib/json/unicodedata;输入来自 inventory_structure_analysis 与 inventory_parsing_profile。
|
||||
逻辑:精确指纹判断文件布局相同;兼容指纹只保留核心栏位,用于推荐而非自动绑定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any
|
||||
|
||||
|
||||
FINGERPRINT_VERSION = 'inventory-structure-v1'
|
||||
def normalise_header(value: Any) -> str:
|
||||
"""将表头统一为可比文本,处理全半角、大小写、空白和常见分隔符。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip().lower()
|
||||
text = re.sub(r'[\s_\-./\\]+', ' ', text)
|
||||
return re.sub(r'\s+', ' ', text).strip()
|
||||
|
||||
|
||||
def _digest(payload: dict[str, Any]) -> str:
|
||||
"""对排序后的确定性结构内容生成 SHA-256,不含库存业务数据。"""
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def structure_definition(*, file_format: str, sheet_name: str | None, header_row_index: int, headers: list[str]) -> dict[str, Any]:
|
||||
"""提取文件客观结构;列顺序和重复列保留,确保完全相同判断严格。"""
|
||||
return {
|
||||
'fingerprint_version': FINGERPRINT_VERSION,
|
||||
'file_format': str(file_format).lower(),
|
||||
'sheet_name': str(sheet_name or ''),
|
||||
'header_row_index': int(header_row_index),
|
||||
'headers': [normalise_header(header) for header in headers],
|
||||
}
|
||||
|
||||
|
||||
def exact_fingerprint(definition: dict[str, Any]) -> str:
|
||||
"""生成完整文件结构指纹,用于准确识别相同库存模板布局。"""
|
||||
return _digest(definition)
|
||||
|
||||
|
||||
def compatibility_fingerprint(*, definition: dict[str, Any], field_mapping: dict[str, str], match_keys: list[dict[str, Any]]) -> str:
|
||||
"""按匹配与数量用途生成兼容指纹,忽略普通导出列但保留用户字段 ID。"""
|
||||
from app.services.shipping_notice.inventory_mapping import runtime_field_mapping, usage_field_ids
|
||||
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
usages = usage_field_ids()
|
||||
capability_ids = usages.get('match_identity', set()) | usages.get('inventory_quantity', set())
|
||||
core_mapping = {
|
||||
field_id: normalise_header(runtime_mapping.get(field_id))
|
||||
for field_id in sorted(capability_ids)
|
||||
if field_id in catalog and runtime_mapping.get(field_id)
|
||||
}
|
||||
return _digest({
|
||||
'fingerprint_version': FINGERPRINT_VERSION,
|
||||
'file_format': definition.get('file_format'),
|
||||
'core_mapping': core_mapping,
|
||||
'match_keys': sorted([
|
||||
{
|
||||
'order_field_id': str(item.get('order_field_id') or ''),
|
||||
'inventory_field_id': str(item.get('inventory_field_id') or item.get('inventory_field') or ''),
|
||||
}
|
||||
for item in match_keys if isinstance(item, dict)
|
||||
], key=lambda item: (item['order_field_id'], item['inventory_field_id'])),
|
||||
})
|
||||
@@ -0,0 +1,553 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_temporary_session.py
|
||||
|
||||
用途:处理对话上传库存候选文件的身份初检与临时会话状态。
|
||||
依赖:ChatSession、FileAsset、库存结构分析、库存站点模型、FileAsset 私有存储服务。
|
||||
逻辑:Dify 先用统一运行态上下文创建会话;后端验证文件归属并分析结构,
|
||||
仅返回脱敏表头预览和候选站点,不创建生产库存快照或修改库存站点配置。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import copy
|
||||
import math
|
||||
import shutil
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingInventoryStructureAnalysis,
|
||||
ShippingTemporaryInventorySession,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryParsingProfile,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
|
||||
from app.services.shipping_notice.inventory_structure_analysis import (
|
||||
MAX_UPLOAD_BYTES,
|
||||
_analyse_path,
|
||||
_analysis_root,
|
||||
_safe_filename,
|
||||
serialize_analysis,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_structure_fingerprint import (
|
||||
compatibility_fingerprint,
|
||||
exact_fingerprint,
|
||||
structure_definition,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import (
|
||||
mapping_is_complete,
|
||||
runtime_field_mapping,
|
||||
suggest_field_mapping,
|
||||
validate_field_mapping_against_headers,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import parse_inventory_excel_with_meta
|
||||
|
||||
_CONTEXT_PATHS = ['agent_code', 'platform.session_id']
|
||||
_TTL_HOURS = 24
|
||||
def _runtime_session(raw_context: str | dict[str, Any]) -> ChatSession:
|
||||
"""从 Dify 运行态上下文解析货代会话,并以本地会话反查用户身份。"""
|
||||
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
|
||||
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
|
||||
if str(values.get('agent_code') or '') != 'shipping_notice':
|
||||
raise ForbiddenError('Current context is not shipping notice', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
|
||||
session_id = str(values.get('platform.session_id') or '').strip()
|
||||
session = (
|
||||
db.session.query(ChatSession)
|
||||
.join(Agent, Agent.id == ChatSession.agent_id)
|
||||
.filter(ChatSession.session_id == session_id, Agent.agent_code == 'shipping_notice')
|
||||
.one_or_none()
|
||||
)
|
||||
if session is None:
|
||||
raise NotFoundError('Shipping chat session not found', code='SHIPPING.TEMP_INVENTORY_CONTEXT_INVALID')
|
||||
return session
|
||||
|
||||
|
||||
def _session_no() -> str:
|
||||
"""生成临时库存会话编号;编号仅用于审计和 Tool 引用,不承载业务单号语义。"""
|
||||
return f'TIS-{datetime.utcnow().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
|
||||
|
||||
|
||||
def _serialize(item: ShippingTemporaryInventorySession) -> dict[str, Any]:
|
||||
"""输出 Dify 和工作台可消费的临时会话,不泄露对象存储路径和完整库存行。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
return {
|
||||
'session_no': item.session_no,
|
||||
'status': item.status,
|
||||
'file_classification_status': item.file_classification_status,
|
||||
'classification_reason': item.classification_reason,
|
||||
'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None,
|
||||
'available_inventory_fields': _available_inventory_fields(),
|
||||
'mapping_suggestion': _mapping_suggestion(item),
|
||||
'confirmed_usage': _confirmed_usage(item),
|
||||
'expires_at': item.expires_at.isoformat() if item.expires_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _available_inventory_fields() -> list[dict[str, Any]]:
|
||||
"""返回 Dify 可建议的库存业务字段目录,不暴露稳定内部字段编码。"""
|
||||
return [{
|
||||
'id': item.id,
|
||||
'display_name': item.display_name,
|
||||
'description': item.description or '',
|
||||
'value_type': item.value_type,
|
||||
'usage_type': item.usage_type,
|
||||
} for item in ShippingInventoryField.query.filter_by(status='active').order_by(
|
||||
ShippingInventoryField.sort_order, ShippingInventoryField.id,
|
||||
).all()]
|
||||
|
||||
|
||||
def _mapping_suggestion(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
|
||||
"""提取已保存的候选映射;未建议时返回空,不伪造可运行的映射。"""
|
||||
result = item.result_json if isinstance(item.result_json, dict) else {}
|
||||
value = result.get('mapping_suggestion')
|
||||
return value if isinstance(value, dict) else None
|
||||
|
||||
|
||||
def _confirmed_usage(item: ShippingTemporaryInventorySession) -> dict[str, Any] | None:
|
||||
"""输出已确认的临时使用摘要,不返回库存行或文件内部路径。"""
|
||||
result = item.result_json if isinstance(item.result_json, dict) else {}
|
||||
value = result.get('confirmed_usage')
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
return {
|
||||
'usage_scope': 'conversation',
|
||||
'mapping_origin': value.get('mapping_origin'),
|
||||
'profile_id': value.get('profile_id'),
|
||||
'quality': value.get('quality'),
|
||||
'confirmed_at': value.get('confirmed_at'),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_dify_analysis_preview(analysis: ShippingInventoryStructureAnalysis) -> dict[str, Any]:
|
||||
"""返回给 Dify 的库存结构预览,移除所有样例值以避免暴露库存明细。"""
|
||||
preview = copy.deepcopy(serialize_analysis(analysis))
|
||||
structure = preview.get('structure')
|
||||
if not isinstance(structure, dict):
|
||||
return preview
|
||||
for candidate in structure.get('candidates') or []:
|
||||
if not isinstance(candidate, dict):
|
||||
continue
|
||||
for column in candidate.get('columns') or []:
|
||||
if isinstance(column, dict):
|
||||
column.pop('sample_values', None)
|
||||
for column in structure.get('selected_columns') or []:
|
||||
if isinstance(column, dict):
|
||||
column.pop('sample_values', None)
|
||||
return preview
|
||||
|
||||
|
||||
def _persist_analysis(*, asset: FileAsset, owner_id: int) -> ShippingInventoryStructureAnalysis:
|
||||
"""对私有文件资产执行受控结构分析,仅保留结构、有限样例及字段建议。"""
|
||||
if int(asset.file_size or 0) > MAX_UPLOAD_BYTES:
|
||||
raise ValidationError(
|
||||
'Temporary inventory file is too large',
|
||||
code='SHIPPING.TEMP_INVENTORY_FILE_TOO_LARGE',
|
||||
)
|
||||
suffix = resolve_inventory_upload_suffix(asset.original_filename)
|
||||
raw = read_asset_bytes(asset)
|
||||
analysis_dir = _analysis_root() / uuid.uuid4().hex
|
||||
analysis_dir.mkdir(parents=True, exist_ok=False)
|
||||
path = analysis_dir / f'conversation{suffix}'
|
||||
try:
|
||||
path.write_bytes(raw)
|
||||
structure, suggested_catalog, summary, warnings = _analyse_path(path, suffix)
|
||||
except ValidationError:
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise
|
||||
except Exception as exc:
|
||||
shutil.rmtree(analysis_dir, ignore_errors=True)
|
||||
raise ValidationError(
|
||||
'Temporary inventory file cannot be analysed',
|
||||
code='SHIPPING.TEMP_INVENTORY_ANALYSIS_INVALID',
|
||||
) from exc
|
||||
# 临时会话与正式配置一致地保留目录字段 ID,不生成固定运行字段名称。
|
||||
suggested, _catalog = runtime_field_mapping(suggested_catalog)
|
||||
definition = structure_definition(
|
||||
file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'),
|
||||
header_row_index=structure.get('selected_header_row_index') or 1,
|
||||
headers=structure.get('selected_headers', []),
|
||||
)
|
||||
analysis = ShippingInventoryStructureAnalysis(
|
||||
source_kind='temporary_conversation', source_file_name=_safe_filename(asset.original_filename),
|
||||
storage_path=str(path), file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'),
|
||||
analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
|
||||
validation_summary_json=summary, warning_json=warnings, created_by=owner_id,
|
||||
exact_structure_fingerprint=exact_fingerprint(definition),
|
||||
compatibility_fingerprint=compatibility_fingerprint(
|
||||
definition=definition, field_mapping=suggested, match_keys=[],
|
||||
),
|
||||
)
|
||||
db.session.add(analysis)
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
|
||||
|
||||
analysis.match_result_json = recommend_profiles({
|
||||
'structure': structure,
|
||||
'suggested_mapping': suggested,
|
||||
'exact_structure_fingerprint': analysis.exact_structure_fingerprint,
|
||||
'compatibility_fingerprint': analysis.compatibility_fingerprint,
|
||||
})
|
||||
return analysis
|
||||
|
||||
|
||||
def _classify(analysis: ShippingInventoryStructureAnalysis) -> tuple[str, str]:
|
||||
"""在用户已明确声明库存文件后,仅按通用表格结构判断是否可进入候选映射。"""
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
headers = structure.get('selected_headers') if isinstance(structure.get('selected_headers'), list) else []
|
||||
columns = structure.get('selected_columns') if isinstance(structure.get('selected_columns'), list) else []
|
||||
has_sample_values = any(
|
||||
isinstance(column, dict) and bool(column.get('sample_values')) for column in columns
|
||||
)
|
||||
if len([item for item in headers if str(item).strip()]) >= 2 and columns and has_sample_values:
|
||||
return 'inventory_candidate', '已识别可维护的表格结构,待确认库存字段映射后才能使用。'
|
||||
return 'not_inventory', '文件缺少可确认的表头或数据行,不能作为库存候选。'
|
||||
|
||||
|
||||
def create_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
创建对话库存候选会话并执行后端结构初检。
|
||||
|
||||
【AI 触发时机】:用户在货代对话中明确说明上传的 .xls/.xlsx/.csv 是库存文件时调用。
|
||||
核心逻辑:通过 agent_runtime_context 反查真实会话和用户,验证 FileAsset 所有权,分析受控副本;
|
||||
不创建库存快照、不绑定库存站点、不执行订单匹配。
|
||||
|
||||
Args:
|
||||
payload: 必须含 agent_runtime_context 与 asset_no;asset_no 必须属于当前会话用户。
|
||||
|
||||
Returns:
|
||||
临时会话编号、分类结论和脱敏结构分析。
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
asset_no = str(payload.get('asset_no') or '').strip().upper()
|
||||
if not asset_no:
|
||||
raise ValidationError('Temporary inventory asset is required', code='SHIPPING.TEMP_INVENTORY_ASSET_REQUIRED')
|
||||
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).one_or_none()
|
||||
if asset is None or int(asset.owner_user_id) != int(session.user_id):
|
||||
raise NotFoundError('Temporary inventory asset not found', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_FOUND')
|
||||
if str(asset.upload_status or '') != 'ready':
|
||||
raise ConflictError('Temporary inventory asset is not ready', code='SHIPPING.TEMP_INVENTORY_ASSET_NOT_READY')
|
||||
try:
|
||||
resolve_inventory_upload_suffix(asset.original_filename)
|
||||
except Exception as exc:
|
||||
raise ValidationError('Temporary inventory only supports xls, xlsx or csv', code='SHIPPING.TEMP_INVENTORY_FILE_TYPE_INVALID') from exc
|
||||
|
||||
active = ShippingTemporaryInventorySession.query.filter(
|
||||
ShippingTemporaryInventorySession.user_id == session.user_id,
|
||||
ShippingTemporaryInventorySession.conversation_id == session.session_id,
|
||||
ShippingTemporaryInventorySession.asset_id == asset.id,
|
||||
ShippingTemporaryInventorySession.status.in_([
|
||||
'created', 'awaiting_profile_confirmation', 'awaiting_mapping_suggestion',
|
||||
'awaiting_mapping_confirmation',
|
||||
]),
|
||||
ShippingTemporaryInventorySession.expires_at > datetime.utcnow(),
|
||||
).order_by(ShippingTemporaryInventorySession.id.desc()).first()
|
||||
if active:
|
||||
return _serialize(active)
|
||||
|
||||
analysis = _persist_analysis(asset=asset, owner_id=int(session.user_id))
|
||||
classification, reason = _classify(analysis)
|
||||
expires_at = datetime.utcnow() + timedelta(hours=_TTL_HOURS)
|
||||
# 临时会话和上传资产在同一有效期内存活,避免清理任务提前删除仍待确认的文件。
|
||||
if asset.expires_at is None or asset.expires_at < expires_at:
|
||||
asset.expires_at = expires_at
|
||||
match_result = analysis.match_result_json if isinstance(analysis.match_result_json, dict) else {}
|
||||
has_exact_profile = classification == 'inventory_candidate' and str(match_result.get('status') or '') == 'exact'
|
||||
item = ShippingTemporaryInventorySession(
|
||||
session_no=_session_no(), user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
asset_id=int(asset.id), analysis_id=analysis.id, declared_intent='inventory_candidate',
|
||||
file_classification_status=classification,
|
||||
status=(
|
||||
'awaiting_profile_confirmation' if has_exact_profile
|
||||
else ('awaiting_mapping_suggestion' if classification == 'inventory_candidate' else 'rejected')
|
||||
),
|
||||
classification_reason=reason,
|
||||
candidate_source_ids_json=[],
|
||||
result_json={}, expires_at=expires_at,
|
||||
)
|
||||
db.session.add(item)
|
||||
db.session.commit()
|
||||
return _serialize(item)
|
||||
|
||||
|
||||
def get_temporary_inventory_session(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
查询临时库存会话的脱敏分析状态。
|
||||
|
||||
【AI 触发时机】:创建临时库存会话后,需要读取结构预览、方案候选或后端分类结论时调用。
|
||||
Args:
|
||||
payload: 必须含 agent_runtime_context 与 temporary_session_no。
|
||||
Returns:
|
||||
仅属于当前会话用户的临时会话投影。
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
if item.expires_at <= datetime.utcnow() and item.status not in {'rejected', 'expired'}:
|
||||
item.status = 'expired'
|
||||
db.session.commit()
|
||||
return _serialize(item)
|
||||
|
||||
|
||||
def submit_temporary_inventory_mapping_suggestion(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
保存 Dify 给出的临时库存映射建议,但不使其进入正式库存运行链路。
|
||||
|
||||
【AI 触发时机】:仅当临时会话没有可直接复用的 published 方案,且 LLM 已基于真实表头和字段目录给出候选时调用。
|
||||
核心逻辑:校验当前会话、字段目录 ID、真实来源表头、重复映射和匹配/数量能力;只保存待用户确认的建议。
|
||||
|
||||
Args:
|
||||
payload: 必须含 agent_runtime_context、temporary_session_no 与 field_mapping(库存字段目录 ID 到真实表头)。
|
||||
|
||||
Returns:
|
||||
更新后的临时会话投影;不含发布、库存站点绑定或订单匹配结果。
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
if item.status != 'awaiting_mapping_suggestion':
|
||||
raise ConflictError('Temporary inventory session cannot accept a mapping suggestion', code='SHIPPING.TEMP_INVENTORY_MAPPING_STATE_INVALID')
|
||||
raw_mapping = payload.get('field_mapping')
|
||||
if not isinstance(raw_mapping, dict) or not raw_mapping:
|
||||
raise ValidationError('Temporary inventory mapping suggestion is required', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
|
||||
mapping = {
|
||||
str(field_id).strip(): str(header).strip()
|
||||
for field_id, header in raw_mapping.items()
|
||||
if str(field_id).strip() and str(header).strip()
|
||||
}
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
structure = analysis.structure_json if analysis and isinstance(analysis.structure_json, dict) else {}
|
||||
headers = [str(header).strip() for header in structure.get('selected_headers', []) if str(header).strip()]
|
||||
if not headers or len(mapping) != len(raw_mapping) or len(set(mapping.values())) != len(mapping):
|
||||
raise ValidationError('Temporary inventory mapping suggestion is invalid', code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID')
|
||||
errors = validate_field_mapping_against_headers(headers, mapping)
|
||||
if errors or not mapping_is_complete(mapping):
|
||||
raise ValidationError(
|
||||
'Temporary inventory mapping suggestion is incomplete or invalid',
|
||||
code='SHIPPING.TEMP_INVENTORY_MAPPING_INVALID', details={'errors': errors},
|
||||
)
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
'mapping_suggestion': {'field_mapping': mapping, 'origin': 'dify_candidate'},
|
||||
}
|
||||
item.status = 'awaiting_mapping_confirmation'
|
||||
db.session.commit()
|
||||
return _serialize(item)
|
||||
|
||||
|
||||
def _select_confirmed_mapping(
|
||||
item: ShippingTemporaryInventorySession,
|
||||
*,
|
||||
selected_profile_id: Any,
|
||||
) -> tuple[dict[str, str], str, int | None]:
|
||||
"""按会话状态选择 exact 已发布方案或已校验建议,禁止请求直接传映射覆盖。"""
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
if item.status == 'awaiting_profile_confirmation':
|
||||
try:
|
||||
profile_id = int(selected_profile_id)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('A published parsing profile must be selected', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID') from exc
|
||||
candidates = (analysis.match_result_json or {}).get('candidates', []) if isinstance(analysis.match_result_json, dict) else []
|
||||
exact_ids = {
|
||||
int(candidate.get('profile_id'))
|
||||
for candidate in candidates if isinstance(candidate, dict)
|
||||
and str(candidate.get('level') or '') == 'exact'
|
||||
and str(candidate.get('profile_id') or '').isdigit()
|
||||
}
|
||||
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
|
||||
if profile is None or profile.status != 'published' or profile_id not in exact_ids:
|
||||
raise ValidationError('Selected parsing profile is not an exact published candidate', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
return dict((profile.definition_json or {}).get('field_mapping') or {}), f'published_profile:{profile.profile_code}:v{profile.version}', profile.id
|
||||
if item.status == 'awaiting_mapping_confirmation':
|
||||
suggestion = _mapping_suggestion(item) or {}
|
||||
mapping = suggestion.get('field_mapping') if isinstance(suggestion.get('field_mapping'), dict) else {}
|
||||
if not mapping:
|
||||
raise ConflictError('Temporary inventory mapping suggestion is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
return dict(mapping), 'dify_candidate', None
|
||||
raise ConflictError('Temporary inventory session cannot be confirmed', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
|
||||
|
||||
def _quality_report(lines: list[dict[str, Any]], field_mapping: dict[str, str]) -> dict[str, Any]:
|
||||
"""按字段目录用途验证临时解析行;旧编码仅保留给无目录映射的受控内部调用。"""
|
||||
runtime_mapping, catalog = runtime_field_mapping(field_mapping)
|
||||
if catalog:
|
||||
match_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'match_identity']
|
||||
quantity_fields = [field_id for field_id, item in catalog.items() if item.usage_type == 'inventory_quantity']
|
||||
else:
|
||||
match_fields = ['part_number', 'reservation_id']
|
||||
quantity_fields = ['available_qty']
|
||||
invalid_rows = 0
|
||||
for line in lines:
|
||||
try:
|
||||
quantities = [line.get(field_id) for field_id in quantity_fields]
|
||||
quantity_valid = len(quantities) == 1 and math.isfinite(float(quantities[0])) and float(quantities[0]) >= 0
|
||||
except (TypeError, ValueError):
|
||||
quantity_valid = False
|
||||
identities_valid = bool(match_fields) and all(str(line.get(field_id) or '').strip() for field_id in match_fields)
|
||||
if not identities_valid or not quantity_valid:
|
||||
invalid_rows += 1
|
||||
return {
|
||||
'parsed_line_count': len(lines),
|
||||
'valid_line_count': len(lines) - invalid_rows,
|
||||
'invalid_line_count': invalid_rows,
|
||||
'passed': bool(lines) and invalid_rows == 0,
|
||||
}
|
||||
|
||||
|
||||
def confirm_temporary_inventory_use(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
经用户明确确认后,锁定当前会话临时库存文件的确定性解析定义与质量结果。
|
||||
|
||||
【AI 触发时机】:仅在用户明确确认“本次使用此库存文件/方案”后调用,Dify 不得自行确认。
|
||||
核心逻辑:选择 exact published 方案或已校验映射,重新解析受控原文件并执行质量门禁;
|
||||
只写临时会话审计,不创建 ShippingInventoryFile、不修改库存站点、不回填任务库存行、不执行匹配。
|
||||
|
||||
Args:
|
||||
payload: 必须含 agent_runtime_context、temporary_session_no;exact 方案需 selected_profile_id。
|
||||
|
||||
Returns:
|
||||
已确认临时使用会话的安全投影,含质量摘要但不含库存行。
|
||||
"""
|
||||
session = _runtime_session(payload.get('agent_runtime_context'))
|
||||
session_no = str(payload.get('temporary_session_no') or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(
|
||||
session_no=session_no, user_id=int(session.user_id), conversation_id=session.session_id,
|
||||
).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
if item.expires_at <= datetime.utcnow():
|
||||
item.status = 'expired'
|
||||
db.session.commit()
|
||||
raise ConflictError('Temporary inventory session has expired', code='SHIPPING.TEMP_INVENTORY_SESSION_EXPIRED')
|
||||
mapping, mapping_origin, profile_id = _select_confirmed_mapping(item, selected_profile_id=payload.get('selected_profile_id'))
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_CONFIRMATION_INVALID')
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
try:
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
Path(analysis.storage_path), field_mapping=mapping, mapping_source=mapping_origin,
|
||||
header_row_index=structure.get('selected_header_row_index'), sheet_name=structure.get('selected_sheet_name'),
|
||||
)
|
||||
except Exception as exc:
|
||||
raise ValidationError('Temporary inventory file cannot pass deterministic parsing', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID') from exc
|
||||
quality = _quality_report(lines, mapping)
|
||||
if not quality['passed']:
|
||||
raise ValidationError('Temporary inventory file does not meet quality requirements', code='SHIPPING.TEMP_INVENTORY_QUALITY_INVALID', details={'quality': quality})
|
||||
item.task_id = None
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
'confirmed_usage': {
|
||||
'usage_scope': 'conversation',
|
||||
'mapping_origin': mapping_origin, 'profile_id': profile_id, 'field_mapping': mapping,
|
||||
'column_meta': column_meta, 'quality': quality, 'file_checksum': analysis.file_checksum,
|
||||
'confirmed_at': datetime.utcnow().isoformat(),
|
||||
},
|
||||
}
|
||||
item.status = 'confirmed_for_temporary_use'
|
||||
db.session.commit()
|
||||
return _serialize(item)
|
||||
|
||||
|
||||
def list_confirmed_temporary_inventory_sessions(*, limit: int = 100) -> list[dict[str, Any]]:
|
||||
"""返回管理员可沉淀为解析方案草稿的已确认临时会话,不暴露库存行或对象存储路径。"""
|
||||
rows = ShippingTemporaryInventorySession.query.filter_by(
|
||||
status='confirmed_for_temporary_use',
|
||||
).order_by(ShippingTemporaryInventorySession.updated_at.desc()).limit(max(1, min(int(limit or 100), 200))).all()
|
||||
result: list[dict[str, Any]] = []
|
||||
for item in rows:
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
confirmed = _confirmed_usage(item)
|
||||
result.append({
|
||||
'session_no': item.session_no,
|
||||
'analysis_id': item.analysis_id,
|
||||
'source_file_name': analysis.source_file_name if analysis else None,
|
||||
'file_format': analysis.file_format if analysis else None,
|
||||
'analysis': _serialize_dify_analysis_preview(analysis) if analysis else None,
|
||||
'confirmed_usage': confirmed,
|
||||
'locked_mapping': ((item.result_json or {}).get('confirmed_usage', {}).get('field_mapping', {}) if isinstance(item.result_json, dict) else {}),
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
'expires_at': item.expires_at.isoformat() if item.expires_at else None,
|
||||
'promoted_profile_draft_id': ((item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def create_parsing_profile_draft_from_temporary_session(
|
||||
session_no: str,
|
||||
data: dict[str, Any],
|
||||
*,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员把已确认临时库存会话沉淀为库存文件解析方案草稿。
|
||||
|
||||
核心逻辑:只接受已通过确定性质量校验的临时会话,强制复用其锁定映射和结构;
|
||||
管理员仍需维护方案编码、显示名称和订单匹配键。创建结果始终是 draft,不能绕过原有发布/站点启用门禁。
|
||||
|
||||
Args:
|
||||
session_no: 已确认的临时库存会话编号。
|
||||
data: 管理员填写的 profile_code、display_name、match_keys;字段映射由后端忽略客户端输入并锁定会话版本。
|
||||
actor_id: 当前管理员用户 ID。
|
||||
|
||||
Returns:
|
||||
新建的库存文件解析方案草稿。
|
||||
"""
|
||||
normalized_no = str(session_no or '').strip().upper()
|
||||
item = ShippingTemporaryInventorySession.query.filter_by(session_no=normalized_no).one_or_none()
|
||||
if item is None:
|
||||
raise NotFoundError('Temporary inventory session not found', code='SHIPPING.TEMP_INVENTORY_SESSION_NOT_FOUND')
|
||||
if item.status != 'confirmed_for_temporary_use':
|
||||
raise ConflictError('Temporary inventory session is not confirmed', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
confirmed = (item.result_json or {}).get('confirmed_usage') if isinstance(item.result_json, dict) else None
|
||||
if not isinstance(confirmed, dict) or not isinstance(confirmed.get('field_mapping'), dict):
|
||||
raise ConflictError('Temporary inventory confirmation is incomplete', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
existing_draft_id = (item.result_json or {}).get('promoted_profile_draft_id') if isinstance(item.result_json, dict) else None
|
||||
if existing_draft_id:
|
||||
existing_draft = db.session.get(ShippingInventoryParsingProfile, existing_draft_id)
|
||||
if existing_draft is not None:
|
||||
from app.services.shipping_notice.inventory_parsing_profile import payload as profile_payload
|
||||
|
||||
return profile_payload(existing_draft)
|
||||
analysis = db.session.get(ShippingInventoryStructureAnalysis, item.analysis_id) if item.analysis_id else None
|
||||
if analysis is None:
|
||||
raise ConflictError('Temporary inventory analysis is missing', code='SHIPPING.TEMP_INVENTORY_PROMOTION_INVALID')
|
||||
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
|
||||
payload = {
|
||||
'profile_code': data.get('profile_code'),
|
||||
'display_name': data.get('display_name'),
|
||||
'sheet_name': structure.get('selected_sheet_name'),
|
||||
'header_row_index': structure.get('selected_header_row_index'),
|
||||
'field_mapping': confirmed['field_mapping'],
|
||||
'match_keys': data.get('match_keys'),
|
||||
}
|
||||
from app.services.shipping_notice import inventory_structure_analysis
|
||||
|
||||
draft = inventory_structure_analysis.create_profile_draft(analysis.id, payload, actor_id=actor_id)
|
||||
item.result_json = {
|
||||
**(item.result_json if isinstance(item.result_json, dict) else {}),
|
||||
'promoted_profile_draft_id': draft['id'],
|
||||
'promoted_at': datetime.utcnow().isoformat(),
|
||||
'promoted_by': actor_id,
|
||||
}
|
||||
db.session.commit()
|
||||
return draft
|
||||
@@ -22,12 +22,7 @@ from werkzeug.datastructures import FileStorage
|
||||
from app.models import ShippingInventoryFile, ShippingTask
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
read_inventory_schema_preview,
|
||||
)
|
||||
|
||||
_TASK_INVENTORY_SUFFIXES = (".xlsx", ".csv")
|
||||
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
|
||||
_TASK_INVENTORY_MARKER = ".current_inventory"
|
||||
_TASK_INVENTORY_VERSION_PREFIX = "inventory_"
|
||||
|
||||
@@ -214,7 +209,7 @@ def _task_inventory_upload_dir(task_no: str) -> Path:
|
||||
def task_inventory_upload_path(task_no: str, *, suffix: str | None = None) -> Path:
|
||||
"""
|
||||
任务级库存附件标准落盘路径(默认 inventory.xlsx)。
|
||||
suffix 仅允许 .xlsx / .csv,用于 RPA 回调保留源文件格式。
|
||||
suffix 仅允许 .xls / .xlsx / .csv,用于 RPA 回调保留源文件格式。
|
||||
"""
|
||||
normalized = (suffix or ".xlsx").lower()
|
||||
if normalized not in _TASK_INVENTORY_SUFFIXES:
|
||||
@@ -261,8 +256,8 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
|
||||
"""保存 werkzeug FileStorage 库存上传并返回落盘路径。"""
|
||||
suffix = ".xlsx"
|
||||
filename = str(getattr(upload, "filename", "") or "").lower()
|
||||
if filename.endswith(".csv"):
|
||||
suffix = ".csv"
|
||||
if filename.endswith((".xls", ".csv")):
|
||||
suffix = Path(filename).suffix
|
||||
staging_dir = _task_inventory_upload_dir(task_no) / ".staging"
|
||||
staging_dir.mkdir(parents=True, exist_ok=True)
|
||||
staging = staging_dir / f"manual_upload_{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}{suffix}"
|
||||
@@ -278,8 +273,8 @@ def save_task_inventory_local_file(task_no: str, source_path: str | Path) -> Pat
|
||||
保存本地已存在的库存文件到任务标准库存目录。
|
||||
【AI 触发时机】:当 RPA 或其他后台流程已经拿到本地 Excel,需要把它正式纳入系统托管目录时调用。
|
||||
|
||||
核心逻辑:校验 source_path 存在后,统一复制到 inventory_uploads/{task_no}/inventory.xlsx,
|
||||
让 RPA 下载与人工上传共用同一套任务级库存附件路径。
|
||||
核心逻辑:校验 source_path 存在后,按源文件格式复制到版本化任务附件路径,
|
||||
让 RPA 下载与人工上传共用同一套任务级库存附件路径,并保留 .xls/.xlsx/.csv 格式。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号,禁止为空。
|
||||
@@ -314,7 +309,7 @@ def stage_task_inventory_callback_file(
|
||||
) -> Path:
|
||||
"""
|
||||
将 RPA 回调文件复制到本轮唯一 staging 路径,避免在校验前覆盖任务正式附件。
|
||||
核心逻辑:落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}.xlsx。
|
||||
核心逻辑:按源文件格式落盘至 inventory_uploads/{task_no}/.staging/rpa_callback_{token}{suffix}。
|
||||
|
||||
Args:
|
||||
task_no: 发货任务号。
|
||||
@@ -393,47 +388,3 @@ def delete_staged_task_inventory_file(staging_path: str | Path | None) -> None:
|
||||
path.parent.rmdir()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
|
||||
"""读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。"""
|
||||
path = resolve_task_inventory_upload_path(task_no)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
preview = read_inventory_schema_preview(path)
|
||||
preview["upload_filename"] = path.name
|
||||
return preview
|
||||
|
||||
|
||||
def parse_uploaded_task_inventory(
|
||||
task_no: str,
|
||||
*,
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str = "rules",
|
||||
header_row_index: int | None = None,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any], Path]:
|
||||
"""
|
||||
解析已上传的任务库存 Excel。
|
||||
|
||||
Returns:
|
||||
tuple: (inventory_lines, column_meta, 文件路径)。
|
||||
"""
|
||||
path = resolve_task_inventory_upload_path(task_no)
|
||||
if path is None:
|
||||
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
|
||||
lines, column_meta = parse_inventory_excel_with_meta(
|
||||
path,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=header_row_index,
|
||||
llm_match_rule=llm_match_rule,
|
||||
llm_match_key=llm_match_key,
|
||||
)
|
||||
return lines, column_meta, path
|
||||
|
||||
|
||||
def has_uploaded_task_inventory(task_no: str) -> bool:
|
||||
"""任务是否已有落盘的库存附件(.xlsx 或 .csv)。"""
|
||||
return resolve_task_inventory_upload_path(task_no) is not None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_warehouse_resolution.py
|
||||
|
||||
用途:按库存解析方案的匹配关系,从订单行与库存行确定动态 Warehouse。
|
||||
依赖:ShippingInventoryField/Source、动态订单字段投影、task_line_store。
|
||||
逻辑:仅在 inventory_match Source 链接库存快照时调用;字段 ID 和用途决定匹配及仓库取值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryField, ShippingInventorySource
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WarehouseResolution:
|
||||
"""动态 Warehouse 决策结果;不唯一或缺失时不可继续链接。"""
|
||||
|
||||
warehouse_id: str | None
|
||||
reason: str = ''
|
||||
|
||||
|
||||
def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
|
||||
"""按配置字段 ID 构造大小写不敏感的精确匹配键。"""
|
||||
values = tuple(str(row.get(field) or '').strip().casefold() for field in fields)
|
||||
return values if values and all(values) else None
|
||||
|
||||
|
||||
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution:
|
||||
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
|
||||
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
|
||||
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
|
||||
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys if isinstance(item, dict)]
|
||||
mapped_ids = {
|
||||
int(field_id) for field_id in (definition.get('field_mapping') or {})
|
||||
if str(field_id).isdigit()
|
||||
} if isinstance(definition, dict) else set()
|
||||
warehouse_fields = ShippingInventoryField.query.filter(
|
||||
ShippingInventoryField.id.in_(mapped_ids), ShippingInventoryField.status == 'active',
|
||||
ShippingInventoryField.usage_type == 'warehouse_identity',
|
||||
).all() if mapped_ids else []
|
||||
if not order_fields or len(order_fields) != len(inventory_fields) or len(warehouse_fields) != 1:
|
||||
return WarehouseResolution(None, 'warehouse_configuration_invalid')
|
||||
|
||||
warehouse_field_id = str(warehouse_fields[0].id)
|
||||
rows_by_key: dict[tuple[str, ...], set[str]] = {}
|
||||
fallback = str(fallback_warehouse_id or '').strip().upper()
|
||||
for row in inventory_lines:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
key = _key(row, inventory_fields)
|
||||
warehouse = str(row.get(warehouse_field_id) or fallback).strip().upper()
|
||||
if key and warehouse:
|
||||
rows_by_key.setdefault(key, set()).add(warehouse)
|
||||
|
||||
warehouses: set[str] = set()
|
||||
_header_values, order_lines = order_field_id_values(task)
|
||||
for order_line in order_lines:
|
||||
key = _key(order_line, order_fields)
|
||||
if not key or not rows_by_key.get(key):
|
||||
return WarehouseResolution(None, 'warehouse_not_found_for_order_line')
|
||||
warehouses.update(rows_by_key[key])
|
||||
if len(warehouses) != 1:
|
||||
return WarehouseResolution(None, 'warehouse_ambiguous' if warehouses else 'warehouse_not_found')
|
||||
return WarehouseResolution(next(iter(warehouses)))
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_workflow.py
|
||||
|
||||
用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。
|
||||
依赖:customer_identity_gate、reservation_gate、inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine、task_line_store。
|
||||
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain;
|
||||
Reservation 门禁订单行经 read_task_order_lines 读取。
|
||||
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
|
||||
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、task_line_store。
|
||||
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,43 +15,12 @@ from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
AUTO_MAP,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_UPLOAD_REQ,
|
||||
SUGGEST_OK,
|
||||
payload_map_json,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping import (
|
||||
mapping_is_complete,
|
||||
normalize_field_mapping,
|
||||
validate_field_mapping_against_headers,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_store import (
|
||||
resolve_inventory_mapping,
|
||||
upsert_inventory_mapping,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_loaded_response,
|
||||
inventory_mapping_checkpoint_response,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
has_uploaded_inventory_file,
|
||||
parse_linked_inventory_file,
|
||||
read_linked_inventory_schema_preview,
|
||||
save_batch_inventory_upload,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_snapshot import parse_inventory_text
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
has_uploaded_task_inventory,
|
||||
inventory_text_max_chars,
|
||||
parse_uploaded_task_inventory,
|
||||
read_task_inventory_schema_preview,
|
||||
save_task_inventory_upload,
|
||||
)
|
||||
from app.services.shipping_notice.match_rule_desc import extract_mapping_payload_extras
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
resolve_task_from_payload,
|
||||
@@ -89,43 +57,6 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]:
|
||||
raw = payload_map_json(payload)
|
||||
field_mapping = normalize_field_mapping(raw)
|
||||
if field_mapping:
|
||||
return field_mapping, "llm"
|
||||
return None, "rules"
|
||||
|
||||
|
||||
def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
|
||||
data: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict):
|
||||
data = raw
|
||||
elif isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
data = parsed
|
||||
except json.JSONDecodeError:
|
||||
data = None
|
||||
if not data:
|
||||
return {}
|
||||
|
||||
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
|
||||
if not isinstance(inner, dict):
|
||||
return {}
|
||||
|
||||
result: dict[str, str] = {}
|
||||
for key in ("part_number", "aws_part_number", "reservation_id", "available_qty"):
|
||||
value = inner.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
text = str(value).strip()
|
||||
if text:
|
||||
result[key] = text
|
||||
return result
|
||||
|
||||
|
||||
def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存入口统一检查订单侧 Reservation ID。
|
||||
@@ -192,312 +123,8 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang:
|
||||
return None
|
||||
|
||||
|
||||
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Parse inventory from uploaded file, chat text, or structured JSON."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="parse_inventory", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
# [STEP 1] 先归一化库存输入来源与映射提示。
|
||||
# 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。
|
||||
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
|
||||
"1",
|
||||
"true",
|
||||
"yes",
|
||||
}
|
||||
raw_text = str(payload.get("raw_inventory_text") or "").strip()
|
||||
inventory_lines = parse_inventory_lines(payload)
|
||||
warnings: list[str] = []
|
||||
column_meta: dict[str, Any] | None = None
|
||||
source = "parse"
|
||||
field_mapping, mapping_source = _resolve_inventory_field_mapping(payload)
|
||||
mapping_extras = extract_mapping_payload_extras(payload_map_json(payload))
|
||||
if mapping_extras.get("match_rule"):
|
||||
mapping_source = "llm"
|
||||
|
||||
# [STEP 2] 按来源解析库存内容。
|
||||
# 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。
|
||||
has_uploaded_file = has_uploaded_inventory_file(task) or has_uploaded_task_inventory(task.task_no)
|
||||
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_file):
|
||||
if not has_uploaded_file:
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
else:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
source = "uploaded_file"
|
||||
warnings.append(f"parsed from uploaded file: {path.name}")
|
||||
elif not inventory_lines:
|
||||
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
|
||||
if structured and isinstance(structured.get("lines"), list):
|
||||
inventory_lines = structured["lines"]
|
||||
source = "structured"
|
||||
elif raw_text:
|
||||
max_chars = inventory_text_max_chars()
|
||||
if len(raw_text) > max_chars:
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_text_too_large",
|
||||
{"chars": len(raw_text), "max_chars": max_chars},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.text_too_large", lang=lang).format(
|
||||
chars=len(raw_text),
|
||||
max_chars=max_chars,
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
next_required_action=t("workflow.inventory.upload_then_parse", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
inventory_lines, warnings, column_meta = parse_inventory_text(
|
||||
raw_text,
|
||||
field_mapping=field_mapping,
|
||||
)
|
||||
|
||||
# [STEP 3] 对解析失败和成功分别进入下一阶段。
|
||||
# 失败时停在人审检查点;成功时统一委托 inventory_loaded_response 进入字段对齐/自动串联。
|
||||
if not inventory_lines:
|
||||
log_task_event(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.parse_failed", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "warnings": warnings},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
)
|
||||
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
inventory_lines,
|
||||
warnings=warnings,
|
||||
column_meta=column_meta,
|
||||
source=source,
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_parsed",
|
||||
chain_payload=payload,
|
||||
)
|
||||
|
||||
|
||||
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Return headers + sample rows for LLM column mapping (small payload)."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="get_inventory_schema_preview", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.uploaded_file_missing", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
try:
|
||||
if has_uploaded_inventory_file(task):
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
else:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=t("workflow.inventory.preview_ready", lang=lang),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
checkpoint=CP_MAP_INFER,
|
||||
next_required_action=t("workflow.inventory.preview_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
)
|
||||
|
||||
|
||||
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
|
||||
lang = resolve_lang(payload)
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang=lang))
|
||||
|
||||
gate_resp = _inventory_source_gate_response(task, operation="apply_inventory_mapping", lang=lang)
|
||||
if gate_resp is not None:
|
||||
return gate_resp
|
||||
|
||||
# [STEP 1] 先校验上传文件与 schema preview 是否存在。
|
||||
# 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。
|
||||
if not has_uploaded_inventory_file(task) and not has_uploaded_task_inventory(task.task_no):
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=t("workflow.inventory.uploaded_file_missing_short", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
try:
|
||||
if has_uploaded_inventory_file(task):
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
else:
|
||||
preview = read_task_inventory_schema_preview(task.task_no)
|
||||
except OSError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.preview_read_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
raw = payload_map_json(payload)
|
||||
|
||||
# [STEP 2] 汇总映射候选来源。
|
||||
# direct/partial 来自本次 map_json,template/suggested 来自历史模板和表头预判,按完整度决定优先级。
|
||||
direct = normalize_field_mapping(raw)
|
||||
partial = _extract_partial_inventory_field_mapping(raw)
|
||||
template: dict[str, str] = {}
|
||||
if task.customer_code:
|
||||
resolved = resolve_inventory_mapping(task.customer_code, preview=preview)
|
||||
if isinstance(resolved, dict):
|
||||
template = {k: str(v).strip() for k, v in resolved.items() if str(v or "").strip()}
|
||||
|
||||
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
|
||||
suggested = {k: str(v).strip() for k, v in suggested.items() if str(v or "").strip()}
|
||||
|
||||
base: dict[str, str] = {}
|
||||
if mapping_is_complete(template):
|
||||
base = template
|
||||
elif mapping_is_complete(suggested):
|
||||
base = suggested
|
||||
else:
|
||||
base = {**template, **suggested}
|
||||
|
||||
field_mapping = direct or {**base, **partial}
|
||||
mapping_extras = extract_mapping_payload_extras(raw)
|
||||
if direct or partial or mapping_extras.get("match_rule"):
|
||||
mapping_source = "llm"
|
||||
else:
|
||||
mapping_source = "rules"
|
||||
if not mapping_is_complete(field_mapping):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.mapping_invalid", lang=lang),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"schema_preview": preview,
|
||||
"suggested_mapping": suggested,
|
||||
"template_mapping": template if template else None,
|
||||
"received_mapping": partial or None,
|
||||
},
|
||||
)
|
||||
|
||||
# [STEP 3] 确认映射与真实表头一致,再解析整份上传文件。
|
||||
# 只有列名校验通过后才允许落地库存明细,避免错误映射污染后续匹配链路。
|
||||
mapping_errors = validate_field_mapping_against_headers(
|
||||
preview.get("headers") or [],
|
||||
field_mapping,
|
||||
)
|
||||
if mapping_errors:
|
||||
header_row = preview.get("header_row_index") or 1
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.mapping_header_mismatch", lang=lang).format(
|
||||
row=header_row,
|
||||
errors=" ".join(mapping_errors),
|
||||
),
|
||||
data={**serialize_task_for_tool(task), "schema_preview": preview},
|
||||
)
|
||||
|
||||
try:
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=preview.get("header_row_index"),
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
else:
|
||||
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
|
||||
task.task_no,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
header_row_index=preview.get("header_row_index"),
|
||||
llm_match_rule=mapping_extras.get("match_rule"),
|
||||
llm_match_key=mapping_extras.get("match_key"),
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
return tool_response(status="failed", task_id=task.task_no, message=str(exc))
|
||||
except OSError as exc:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.inventory.parse_failed_detail", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
|
||||
upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping)
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
inventory_lines,
|
||||
warnings=warnings,
|
||||
column_meta=column_meta,
|
||||
source="uploaded_file_mapping",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_mapping_applied",
|
||||
chain_payload=payload,
|
||||
field_mapping=field_mapping,
|
||||
mapping_source=mapping_source,
|
||||
)
|
||||
|
||||
|
||||
def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
|
||||
"""按任务库存站点的 published Profile 保存并确定性解析人工库存文件。"""
|
||||
task = get_task_by_ref(str(task_id or ""))
|
||||
if not task:
|
||||
return tool_response(status="failed", message=t("workflow.inventory.task_not_found", lang="zh"))
|
||||
@@ -522,7 +149,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
filename = str(upload.filename or "").strip()
|
||||
if not filename.lower().endswith((".xlsx", ".csv")):
|
||||
if not filename.lower().endswith((".xls", ".xlsx", ".csv")):
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task_id=task.task_no,
|
||||
@@ -541,14 +168,20 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
)
|
||||
db.session.flush()
|
||||
inv_file = save_batch_inventory_upload(task, upload)
|
||||
preview = read_linked_inventory_schema_preview(task)
|
||||
inventory_lines = [
|
||||
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
|
||||
]
|
||||
preview = dict(inv_file.schema_preview_json or {})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
message = str(exc.message or "库存上传被拒绝")
|
||||
if exc.code == 'SHIPPING.INVENTORY_STRUCTURE_DRIFT_BLOCKED':
|
||||
message = '库存文件结构与该库存站点已发布的解析方案不一致,请重新导出正确文件或由管理员发布新方案。'
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
task_id=task.task_no,
|
||||
message=str(exc.message or "库存上传被拒绝"),
|
||||
message=message,
|
||||
data=serialize_task_for_tool(task),
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -560,39 +193,18 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
message=t("workflow.inventory.save_failed", lang=lang).format(error=exc),
|
||||
)
|
||||
|
||||
template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview)
|
||||
if template_mapping and mapping_is_complete(template_mapping):
|
||||
try:
|
||||
inventory_lines, column_meta, path, _inv_file = parse_linked_inventory_file(
|
||||
task,
|
||||
field_mapping=template_mapping,
|
||||
mapping_source="template",
|
||||
)
|
||||
if inventory_lines:
|
||||
warnings = [f"parsed from template mapping: {path.name}"]
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
inventory_lines,
|
||||
warnings=warnings,
|
||||
column_meta=column_meta,
|
||||
source="uploaded_file_template",
|
||||
require_mapping_review=True,
|
||||
event_type="inventory_template_mapping_used",
|
||||
field_mapping=template_mapping,
|
||||
mapping_source="template",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
|
||||
suggested_clean = {k: str(v).strip() for k, v in suggested.items() if str(v).strip()}
|
||||
suggested_complete = mapping_is_complete(suggested_clean)
|
||||
auto_map = (
|
||||
json.dumps(suggested_clean, ensure_ascii=False) if suggested_complete else None
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.MAP_INFER)
|
||||
log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
|
||||
structure_validation = preview.get('structure_validation') if isinstance(
|
||||
preview.get('structure_validation'), dict
|
||||
) else {}
|
||||
column_meta = {
|
||||
'structure_validation': structure_validation,
|
||||
}
|
||||
log_task_event(task, "inventory_file_uploaded", {
|
||||
"filename": filename,
|
||||
"headers": preview.get("headers"),
|
||||
"structure_validation": structure_validation,
|
||||
"parser_contract": "published_profile",
|
||||
})
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_snapshot_created",
|
||||
@@ -602,33 +214,15 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
"batch_no": task.batch.batch_no if task.batch else None,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
upload_message = t("workflow.inventory.uploaded", lang=lang)
|
||||
if suggested_complete:
|
||||
upload_message += t("workflow.inventory.uploaded_suggested_complete", lang=lang)
|
||||
else:
|
||||
upload_message += t("workflow.inventory.uploaded_need_llm", lang=lang)
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message=upload_message,
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"batch_no": task.batch.batch_no if task.batch else None,
|
||||
"batch": serialize_batch_for_tool(task.batch) if task.batch else None,
|
||||
"schema_preview": preview,
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
"linked_task_nos": [
|
||||
link.task.task_no
|
||||
for link in (inv_file.links or [])
|
||||
if link.is_active and link.task
|
||||
],
|
||||
SUGGEST_OK: suggested_complete,
|
||||
AUTO_MAP: auto_map,
|
||||
},
|
||||
next_required_action=t("workflow.inventory.apply_mapping_next", lang=lang),
|
||||
forbidden_next_tools=["match_inventory"],
|
||||
return inventory_loaded_response(
|
||||
task,
|
||||
inventory_lines,
|
||||
warnings=list(structure_validation.get('warnings') or []),
|
||||
column_meta=column_meta,
|
||||
source='manual_upload_published_profile',
|
||||
event_type='inventory_manual_upload_ready',
|
||||
field_mapping=dict(inv_file.field_mapping_json or {}),
|
||||
mapping_source='parsing_profile',
|
||||
)
|
||||
|
||||
|
||||
@@ -652,23 +246,31 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task,
|
||||
inventory_lines,
|
||||
source="manual_json",
|
||||
require_mapping_review=False,
|
||||
event_type="inventory_uploaded",
|
||||
)
|
||||
|
||||
# [STEP 2] 如果允许自动模式,就优先交给 RPA 获取库存。
|
||||
# auto / retry_rpa 都属于“先尝试系统拉取库存”,避免不必要地要求用户手工上传。
|
||||
if mode == "retry_rpa" or mode == "auto":
|
||||
# [STEP 2] 正常流程只复用已完成的库存快照,绝不隐式触发 RPA。
|
||||
# 库存导出由独立排程生产;用户明确选择 retry_rpa 才允许本任务发起刷新。
|
||||
if mode == "retry_rpa":
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
|
||||
return ensure_inventory_via_rpa(task, mode=mode)
|
||||
|
||||
# [STEP 3] 最后处理已有快照与彻底缺库存两种兜底分支。
|
||||
if mode == "auto":
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
|
||||
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
|
||||
|
||||
reused = _try_reuse_inventory_snapshot(
|
||||
task,
|
||||
task_rpa_inventory_source(task) or {},
|
||||
mode=mode,
|
||||
)
|
||||
if reused is not None:
|
||||
return reused
|
||||
|
||||
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
|
||||
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
|
||||
if task.inventory_lines_json:
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_READY)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
@@ -679,6 +281,15 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message=t("workflow.inventory.unavailable", lang=lang),
|
||||
progress_percent=0,
|
||||
detail=t("workflow.inventory.unavailable", lang=lang),
|
||||
)
|
||||
log_task_event(task, "inventory_missing", {})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/match.py
|
||||
|
||||
用途:执行订单行与库存行的匹配、缺货判断与匹配结果汇总。
|
||||
依赖:shipping_notice.i18n、reservation_id 归一化工具、标准聚合逻辑。
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用本文件,把通知订单行与库存快照比对后返回匹配状态和缺货明细。
|
||||
用途:按解析方案配置的字段关系执行库存匹配、缺货判断与结果汇总。
|
||||
依赖:shipping_notice.i18n、动态订单字段投影、标准聚合逻辑。
|
||||
逻辑:由 fulfillment_workflow 传入订单字段 ID、库存字段 ID 和数量字段 ID,字段名称不参与匹配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,69 +11,56 @@ from __future__ import annotations
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def _norm(value: Any) -> str:
|
||||
return str(value or "").strip()
|
||||
|
||||
|
||||
def _norm_reservation(value: Any) -> str:
|
||||
return validated_reservation_id(value)
|
||||
def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
|
||||
"""按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。"""
|
||||
values = tuple(_norm(row.get(field)).casefold() for field in fields)
|
||||
return values if values and all(values) else None
|
||||
|
||||
|
||||
def _line_key(part_number: str, reservation_id: str | None) -> tuple[str, str]:
|
||||
"""构造内部料号与 Reservation 的库存定位键。"""
|
||||
return (_norm(part_number), _norm_reservation(reservation_id))
|
||||
|
||||
|
||||
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
|
||||
"""按库存 part_number 与 reservation_id 汇总 available_qty。"""
|
||||
totals: dict[tuple[str, str], float] = {}
|
||||
def _aggregate_inventory(
|
||||
inventory_lines: list[dict[str, Any]], *, match_fields: list[str], quantity_field: str,
|
||||
) -> dict[tuple[str, ...], float]:
|
||||
"""按用户配置的库存匹配字段组合汇总唯一数量字段。"""
|
||||
totals: dict[tuple[str, ...], float] = {}
|
||||
for row in inventory_lines:
|
||||
part_number = _norm(row.get("part_number"))
|
||||
if not part_number:
|
||||
continue
|
||||
reservation_id = _norm_reservation(row.get("reservation_id"))
|
||||
if not reservation_id:
|
||||
key = _line_key(row, match_fields)
|
||||
if key is None:
|
||||
continue
|
||||
try:
|
||||
qty = float(row.get("available_qty") or 0)
|
||||
qty = float(row.get(quantity_field) or 0)
|
||||
except (TypeError, ValueError):
|
||||
qty = 0.0
|
||||
key = _line_key(part_number, reservation_id)
|
||||
totals[key] = totals.get(key, 0.0) + qty
|
||||
return totals
|
||||
|
||||
|
||||
def _available_for_notice_line(
|
||||
part_number: str,
|
||||
reservation_id: str | None,
|
||||
inv_totals: dict[tuple[str, str], float],
|
||||
) -> float:
|
||||
part_number_normalized = _norm(part_number)
|
||||
rid = _norm_reservation(reservation_id)
|
||||
if not rid:
|
||||
return 0.0
|
||||
return inv_totals.get((part_number_normalized, rid), 0.0)
|
||||
|
||||
|
||||
def match_notice_lines(
|
||||
notice_lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
*,
|
||||
match_keys: list[dict[str, str]],
|
||||
quantity_field_id: str,
|
||||
progress_callback: Callable[[int, int], None] | None = None,
|
||||
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
|
||||
"""
|
||||
将订单行与库存行按 (part_number, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
|
||||
按订单字段 ID 到库存字段 ID 的配置关系匹配,计算 fulfillable/partial/unfulfillable。
|
||||
|
||||
核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。
|
||||
|
||||
Returns:
|
||||
tuple: (match_status, line_results, shortage_json)。
|
||||
"""
|
||||
# [STEP 1] 库存 Supplier Sku 已规范为 part_number,与订单内部料号直接配对。
|
||||
inv_totals = _aggregate_inventory(inventory_lines)
|
||||
order_fields = [str(item.get('order_field_id') or '') for item in match_keys]
|
||||
inventory_fields = [str(item.get('inventory_field_id') or '') for item in match_keys]
|
||||
if not order_fields or any(not item for item in order_fields + inventory_fields) or not quantity_field_id:
|
||||
raise ValueError('库存解析方案缺少有效的匹配字段或库存数量字段')
|
||||
inv_totals = _aggregate_inventory(
|
||||
inventory_lines, match_fields=inventory_fields, quantity_field=quantity_field_id,
|
||||
)
|
||||
|
||||
line_results: list[dict[str, Any]] = []
|
||||
shortages: list[dict[str, Any]] = []
|
||||
@@ -83,14 +70,13 @@ def match_notice_lines(
|
||||
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
|
||||
total_lines = len(notice_lines)
|
||||
for index, line in enumerate(notice_lines, start=1):
|
||||
part_number = _norm(line.get("part_number"))
|
||||
reservation_id = _norm_reservation(line.get("reservation_id")) or None
|
||||
order_key = _line_key(line, order_fields)
|
||||
try:
|
||||
required = float(line.get("qty") or 0)
|
||||
required = float(line.get("__required_qty") or 0)
|
||||
except (TypeError, ValueError):
|
||||
required = 0.0
|
||||
|
||||
available = _available_for_notice_line(part_number, reservation_id, inv_totals)
|
||||
available = inv_totals.get(order_key, 0.0) if order_key is not None else 0.0
|
||||
if available >= required:
|
||||
line_status = "ok"
|
||||
shortage = 0.0
|
||||
@@ -104,8 +90,11 @@ def match_notice_lines(
|
||||
has_shortage = True
|
||||
|
||||
result = {
|
||||
"part_number": part_number,
|
||||
"reservation_id": reservation_id or "",
|
||||
"part_number": _norm(line.get("__display_part_number")),
|
||||
"reservation_id": _norm(line.get("__display_reservation_id")),
|
||||
"order_match_values": {
|
||||
order_field: line.get(order_field) for order_field in order_fields
|
||||
},
|
||||
"required_qty": required,
|
||||
"available_qty": available,
|
||||
"shortage_qty": shortage,
|
||||
|
||||
@@ -1,65 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/match_rule_desc.py
|
||||
|
||||
用途:解析 map_json 中的匹配规则扩展字段,并生成用户可读的匹配规则说明。
|
||||
依赖:标准 `json` 解析与 `typing` 工具。
|
||||
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用本文件,把匹配规则和附加说明渲染成展示文案。
|
||||
用途:根据已确认的库存栏位映射生成用户可读的匹配规则说明。
|
||||
依赖:标准类型能力。
|
||||
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用,说明订单字段与库存栏位的确定性对应关系。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _payload_root(raw: Any) -> dict[str, Any] | None:
|
||||
data: dict[str, Any] | None = None
|
||||
if isinstance(raw, dict):
|
||||
data = raw
|
||||
elif isinstance(raw, str) and raw.strip():
|
||||
import json
|
||||
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
if isinstance(parsed, dict):
|
||||
data = parsed
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
return data
|
||||
|
||||
|
||||
def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
|
||||
"""从 map_json 读取 match_rule / match_key 等 LLM 扩展字段(非列名映射)。"""
|
||||
data = _payload_root(raw)
|
||||
if not data:
|
||||
return {}
|
||||
|
||||
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
|
||||
if not isinstance(inner, dict):
|
||||
inner = data
|
||||
|
||||
match_rule = str(
|
||||
data.get("match_rule")
|
||||
or data.get("matching_rule")
|
||||
or inner.get("match_rule")
|
||||
or inner.get("matching_rule")
|
||||
or ""
|
||||
).strip()
|
||||
|
||||
match_key_raw = data.get("match_key") or inner.get("match_key")
|
||||
match_key: list[str] | None = None
|
||||
if isinstance(match_key_raw, list):
|
||||
match_key = [str(k).strip() for k in match_key_raw if str(k).strip()]
|
||||
elif isinstance(match_key_raw, str) and match_key_raw.strip():
|
||||
match_key = [part.strip() for part in match_key_raw.split(",") if part.strip()]
|
||||
|
||||
extras: dict[str, Any] = {}
|
||||
if match_rule:
|
||||
extras["match_rule"] = match_rule
|
||||
if match_key:
|
||||
extras["match_key"] = match_key
|
||||
return extras
|
||||
|
||||
|
||||
def infer_match_key(field_mapping: dict[str, str]) -> list[str]:
|
||||
"""根据库存列映射推断业务匹配键列表(默认 part_number + reservation_id)。"""
|
||||
keys = ["part_number"]
|
||||
@@ -73,7 +21,7 @@ def build_match_rule_fallback(
|
||||
*,
|
||||
match_key: list[str] | None = None,
|
||||
) -> str:
|
||||
"""LLM 未提供 match_rule 时,根据列映射动态生成中文规则说明。"""
|
||||
"""根据已确认的栏位映射动态生成中文规则说明。"""
|
||||
part_number_col = str(field_mapping.get("part_number") or "Supplier Sku").strip() or "Supplier Sku"
|
||||
qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量"
|
||||
keys = match_key or infer_match_key(field_mapping)
|
||||
@@ -92,12 +40,7 @@ def build_match_rule_fallback(
|
||||
|
||||
def resolve_match_rule(
|
||||
field_mapping: dict[str, str],
|
||||
*,
|
||||
llm_match_rule: str | None = None,
|
||||
llm_match_key: list[str] | None = None,
|
||||
) -> tuple[str, list[str], str]:
|
||||
"""返回 (match_rule, match_key, match_rule_source);优先 LLM 规则,否则 fallback。"""
|
||||
keys = llm_match_key or infer_match_key(field_mapping)
|
||||
if llm_match_rule and str(llm_match_rule).strip():
|
||||
return str(llm_match_rule).strip(), keys, "llm"
|
||||
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "fallback"
|
||||
"""返回由已确认栏位映射生成的匹配说明、匹配键及规则来源。"""
|
||||
keys = infer_match_key(field_mapping)
|
||||
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "configured_mapping"
|
||||
@@ -10,9 +10,6 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.constants import MAP_JSON
|
||||
|
||||
|
||||
def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]:
|
||||
prop: dict[str, Any] = {"type": "string", "description": description}
|
||||
if enum:
|
||||
@@ -77,6 +74,30 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
)
|
||||
observation_schema = {
|
||||
"type": "object",
|
||||
"required": ["value", "document_id", "quote"],
|
||||
"properties": {
|
||||
"value": {"description": "从证据原文提取的字段值,类型必须符合动态字段契约"},
|
||||
"document_id": _int_prop("证据来源 Document ID,必须来自抽取上下文"),
|
||||
"quote": _str_prop("证据原文中的逐字引用,HXOPS 将验证其确实存在"),
|
||||
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
}
|
||||
extracted_field_schema = {
|
||||
"type": "object",
|
||||
"required": ["field_id", "observations"],
|
||||
"properties": {
|
||||
"field_id": _str_prop("动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称"),
|
||||
"observations": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": observation_schema,
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
@@ -107,7 +128,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
required=["agent_runtime_context"],
|
||||
description=(
|
||||
"仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,"
|
||||
"并返回 input_snapshot_hash、documents 与固定输出契约;禁止让 LLM 传 user_id。"
|
||||
"并返回 input_snapshot_hash、documents 与当前 published 动态 Schema 契约;禁止让 LLM 传 user_id。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_order_extraction": _post_op(
|
||||
@@ -123,61 +144,43 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema_version_id",
|
||||
"schema_checksum",
|
||||
"source_intake_no",
|
||||
"primary_document_id",
|
||||
"classification",
|
||||
"classification_confidence",
|
||||
"field_confidence",
|
||||
"header_fields",
|
||||
"lines",
|
||||
"evidence",
|
||||
],
|
||||
"properties": {
|
||||
"source_intake_no": _str_prop("来源 Intake 编号,必须来自上下文"),
|
||||
"schema_version_id": _int_prop("context.contract.schema_version_id,必须原样回传"),
|
||||
"schema_checksum": _str_prop("context.contract.checksum,必须原样回传"),
|
||||
"primary_document_id": _int_prop("主来源 Document ID,必须来自上下文"),
|
||||
"candidate_key_hint": _str_prop("可选稳定订单标识,如 PO/订单号;不得使用随机值"),
|
||||
"classification": _str_prop("仅 shipping_request 可自动建单", enum=["shipping_request", "non_shipping_request", "uncertain"]),
|
||||
"classification_confidence": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"field_confidence": {
|
||||
"type": "object",
|
||||
"required": ["part_number", "qty"],
|
||||
"properties": {
|
||||
"part_number": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"qty": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
},
|
||||
"header_fields": {
|
||||
"type": "array",
|
||||
"description": "Header scope 动态字段;仅可使用 context.contract.fields 中的稳定 field_id",
|
||||
"items": extracted_field_schema,
|
||||
},
|
||||
"po_number": _str_prop("可为空的 PO/订单号"),
|
||||
"lines": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["part_number", "qty"],
|
||||
"required": ["fields"],
|
||||
"properties": {
|
||||
"part_number": _str_prop("内部料号/主匹配料号"),
|
||||
"qty": {"type": "number", "exclusiveMinimum": 0},
|
||||
"reservation_id": _str_prop("可为空,缺失时 Task 停在补字段门禁"),
|
||||
"inventory_source_hint": _str_prop(
|
||||
"可选库存来源提示;仅在原文有可靠证据时填写,"
|
||||
"不代表任务通知来源或已确认的库存连接器类型"
|
||||
),
|
||||
"customer_part_number": _str_prop("可选客户料号"),
|
||||
"aws_part_number": _str_prop("可选 AWS 料号"),
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"description": "Line scope 动态字段;每项含 field_id 与 observations[]",
|
||||
"items": extracted_field_schema,
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
"evidence": {
|
||||
"type": "array",
|
||||
"description": "至少分别提供内部料号与 Qty 原文证据,元素含 field 与非空 quote",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["field", "quote"],
|
||||
"properties": {
|
||||
"field": _str_prop("证据字段,如 lines[0].part_number 或 lines[0].qty"),
|
||||
"quote": _str_prop("原文片段,禁止改写"),
|
||||
"document_id": _int_prop("证据来源 Document ID"),
|
||||
},
|
||||
},
|
||||
},
|
||||
"conflicts": {
|
||||
"type": "array",
|
||||
"items": {"type": "object", "additionalProperties": True},
|
||||
@@ -189,13 +192,73 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["agent_runtime_context", "input_snapshot_hash", "orders"],
|
||||
description=(
|
||||
"只接受 get_order_extraction_context 的同一快照。HXOPS 仅在分类、内部料号/Qty 置信度及原文证据均达标,"
|
||||
"且无阻断冲突/修订决策时自动建单;Reservation ID 允许缺失,"
|
||||
"订单行 inventory_source_hint 是可选路由线索并独立持久化。"
|
||||
"只接受同一快照和同一 Schema checksum。Dify 必须逐字段返回稳定 field_id 与 observations[];"
|
||||
"每个 Observation 包含 value、document_id、逐字 quote 和可选 confidence。"
|
||||
"HXOPS 验证原文、执行类型/validator/证据策略与跨 Document 裁决后,才按 field_code 投影给下游。"
|
||||
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
|
||||
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
|
||||
),
|
||||
),
|
||||
"/tools/create_temporary_inventory_session": _post_op(
|
||||
"create_temporary_inventory_session",
|
||||
"创建对话上传库存文件的临时分析会话",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"asset_no": _str_prop("当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv"),
|
||||
},
|
||||
required=["agent_runtime_context", "asset_no"],
|
||||
description=(
|
||||
"仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。"
|
||||
"后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、"
|
||||
"不会绑定库存站点、不会执行库存匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/get_temporary_inventory_session": _post_op(
|
||||
"get_temporary_inventory_session",
|
||||
"读取临时库存文件的脱敏结构分析和方案候选",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("create_temporary_inventory_session 返回的临时会话编号"),
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no"],
|
||||
description=(
|
||||
"返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。"
|
||||
"Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_temporary_inventory_mapping_suggestion": _post_op(
|
||||
"submit_temporary_inventory_mapping_suggestion",
|
||||
"保存对话临时库存的候选字段映射",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("临时库存会话编号"),
|
||||
"field_mapping": {
|
||||
"type": "object",
|
||||
"description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头",
|
||||
"additionalProperties": {"type": "string"},
|
||||
},
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no", "field_mapping"],
|
||||
description=(
|
||||
"仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性,"
|
||||
"只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/confirm_temporary_inventory_use": _post_op(
|
||||
"confirm_temporary_inventory_use",
|
||||
"确认当前对话临时库存文件使用",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("临时库存会话编号"),
|
||||
"selected_profile_id": _int_prop("仅 exact 已发布方案候选时由用户选择的方案 ID"),
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no"],
|
||||
description=(
|
||||
"仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;"
|
||||
"只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、"
|
||||
"写入任务库存行或执行库存匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/parse_notice": _post_op(
|
||||
"parse_notice",
|
||||
"解析发货通知文本",
|
||||
@@ -267,38 +330,18 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
required=["task_id", "line_index"],
|
||||
),
|
||||
"/tools/get_inventory_schema_preview": _post_op(
|
||||
"get_inventory_schema_preview",
|
||||
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
|
||||
{"task_id": task_id},
|
||||
required=["task_id"],
|
||||
),
|
||||
"/tools/apply_inventory_mapping": _post_op(
|
||||
"apply_inventory_mapping",
|
||||
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认,后续主流程由后台任务续跑",
|
||||
{
|
||||
"task_id": task_id,
|
||||
MAP_JSON: _str_prop(
|
||||
"Dify Tool 参数使用 JSON 字符串,内容含 part_number/reservation_id/available_qty,"
|
||||
"可选 aws_part_number;"
|
||||
"可选 match_rule(LLM 自然语言匹配说明)与 match_key(匹配键列表)。"
|
||||
),
|
||||
},
|
||||
required=["task_id", MAP_JSON],
|
||||
),
|
||||
"/tools/confirm_inventory_source": _post_op(
|
||||
"confirm_inventory_source",
|
||||
"在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"source_code": _str_prop(
|
||||
"启用配置中的库存源编码,如 DSV360_AWSDU、CRANE;"
|
||||
"站点 site_id 与库位 warehouse_id 由后端根据配置与订单路由解析,禁止前端直传"
|
||||
"启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传"
|
||||
),
|
||||
},
|
||||
required=["task_id", "source_code"],
|
||||
description=(
|
||||
"库存连接器门禁:稳定身份须同时具备 source_code、connector_type、site_id、warehouse_id,"
|
||||
"库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id,"
|
||||
"且 routing_fingerprint 与当前配置版本一致。"
|
||||
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
|
||||
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
|
||||
@@ -324,8 +367,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||
"decision": _str_prop(
|
||||
"confirm=确认继续;reject=驳回;retry_rpa=重新获取库存(清理旧库存解析状态并重新触发 RPA);rematch=重新匹配;reparse=重新解析;"
|
||||
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
|
||||
"confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析",
|
||||
enum=[
|
||||
"confirm",
|
||||
"confirm_parse",
|
||||
@@ -333,9 +375,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"retry_rpa",
|
||||
"rematch",
|
||||
"reparse",
|
||||
"confirm_inventory_mapping",
|
||||
"correct_inventory_mapping",
|
||||
"reparse_inventory",
|
||||
],
|
||||
),
|
||||
"comment": _str_prop("备注(可选)"),
|
||||
@@ -358,7 +397,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
},
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_connector_type、inventory_site_id、"
|
||||
"返回 inventory_source_code、inventory_connector_type、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
"user_confirmed|invalid|conflicted)、inventory_source_method、"
|
||||
"inventory_source_config_version、inventory_routing_fingerprint、"
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_customer_matching.py
|
||||
|
||||
用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。
|
||||
依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。
|
||||
逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import normalize_customer_name
|
||||
|
||||
ROLE_FIELDS = {
|
||||
'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'},
|
||||
'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'},
|
||||
}
|
||||
|
||||
|
||||
def _normalized_code(value: Any) -> str:
|
||||
"""规范外部客户/站点编码,保留业务符号并统一大小写。"""
|
||||
return str(value or '').strip().upper()
|
||||
|
||||
|
||||
def _customer_candidates(raw_name: str) -> list[dict[str, Any]]:
|
||||
"""按标准名称和 approved 名称别名返回稳定去重的启用客户候选。"""
|
||||
normalized = normalize_customer_name(raw_name)
|
||||
if not normalized:
|
||||
return []
|
||||
customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
|
||||
matched: dict[int, dict[str, Any]] = {}
|
||||
for customer in customers:
|
||||
if normalize_customer_name(customer.standard_name) == normalized:
|
||||
matched[customer.id] = {
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'matched_by': ['standard_name'],
|
||||
}
|
||||
aliases = db.session.query(ShippingCustomerIdentifier).filter_by(
|
||||
identifier_type='name_alias', normalized_value=normalized, status='approved',
|
||||
).all()
|
||||
active_by_id = {customer.id: customer for customer in customers}
|
||||
for alias in aliases:
|
||||
customer = active_by_id.get(int(alias.customer_id))
|
||||
if customer is None:
|
||||
continue
|
||||
candidate = matched.setdefault(customer.id, {
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'matched_by': [],
|
||||
})
|
||||
if 'name_alias' not in candidate['matched_by']:
|
||||
candidate['matched_by'].append('name_alias')
|
||||
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id']))
|
||||
|
||||
|
||||
def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
|
||||
"""优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。"""
|
||||
code = _normalized_code(external_code)
|
||||
source = _normalized_code(source_system)
|
||||
if code and source:
|
||||
refs = db.session.query(ShippingCustomerExternalRef).filter_by(
|
||||
source_system=source, legacy_customer_key=code,
|
||||
).all()
|
||||
candidates = []
|
||||
for ref in refs:
|
||||
customer = db.session.get(ShippingCustomer, int(ref.customer_id))
|
||||
if customer and customer.status == 'active':
|
||||
candidates.append({
|
||||
'customer_id': customer.id, 'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code, 'site_id': None, 'site_name': None,
|
||||
'site_code': None, 'matched_by': ['external_customer_code'],
|
||||
})
|
||||
if candidates:
|
||||
return candidates
|
||||
return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)]
|
||||
|
||||
|
||||
def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
|
||||
"""优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。"""
|
||||
code = _normalized_code(external_code)
|
||||
source = _normalized_code(source_system)
|
||||
sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all()
|
||||
matched: dict[int, dict[str, Any]] = {}
|
||||
matched_site_ids: dict[int, str] = {}
|
||||
if code:
|
||||
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
|
||||
identifier_type='external_code', source_system=source, normalized_value=code, status='approved',
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
matched_site_ids[int(identifier.site_id)] = 'external_site_code'
|
||||
for site in sites:
|
||||
if _normalized_code(site.site_code) == code:
|
||||
matched_site_ids[site.id] = 'site_code'
|
||||
if not matched_site_ids:
|
||||
normalized = normalize_customer_name(raw_name) if raw_name else ''
|
||||
for site in sites:
|
||||
if normalized and normalize_customer_name(site.site_name) == normalized:
|
||||
matched_site_ids[site.id] = 'site_name'
|
||||
if normalized:
|
||||
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
|
||||
identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved',
|
||||
).all()
|
||||
for identifier in identifiers:
|
||||
matched_site_ids[int(identifier.site_id)] = 'site_name_alias'
|
||||
by_id = {site.id: site for site in sites}
|
||||
for site_id, matched_by in matched_site_ids.items():
|
||||
site = by_id.get(site_id)
|
||||
customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None
|
||||
if site is None or customer is None or customer.status != 'active':
|
||||
continue
|
||||
matched[site.id] = {
|
||||
'customer_id': customer.id, 'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name,
|
||||
'site_code': site.site_code, 'matched_by': [matched_by],
|
||||
}
|
||||
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id']))
|
||||
|
||||
|
||||
def refresh_order_customer_matches(
|
||||
extraction: ShippingOrderExtraction,
|
||||
header: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。
|
||||
|
||||
Args:
|
||||
extraction: 已持久化的动态订单解析记录。
|
||||
header: 已通过证据裁决的订单头字段投影。
|
||||
Returns:
|
||||
两种角色的匹配摘要;客户简称只来自客户主数据快照。
|
||||
"""
|
||||
results: list[dict[str, Any]] = []
|
||||
for role, fields in ROLE_FIELDS.items():
|
||||
raw_name = str(header.get(fields['name']) or '').strip()
|
||||
external_code = _normalized_code(header.get(fields['code']))
|
||||
source_system = _normalized_code(header.get(fields['source']))
|
||||
candidates = (
|
||||
_bill_to_candidates(raw_name, external_code, source_system)
|
||||
if role == 'bill_to'
|
||||
else _ship_to_candidates(raw_name, external_code, source_system)
|
||||
)
|
||||
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
|
||||
extraction_id=extraction.id, role=role,
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role)
|
||||
db.session.add(row)
|
||||
row.raw_name = raw_name or None
|
||||
row.normalized_name = normalize_customer_name(raw_name) if raw_name else None
|
||||
row.source_system = source_system or None
|
||||
row.external_code = external_code or None
|
||||
row.candidates_json = candidates
|
||||
if len(candidates) == 1:
|
||||
candidate = candidates[0]
|
||||
row.status = 'unique_candidate'
|
||||
row.customer_id = int(candidate['customer_id'])
|
||||
row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None
|
||||
row.customer_name_snapshot = str(candidate['standard_name'])
|
||||
row.customer_short_code_snapshot = str(candidate['short_code'])
|
||||
row.resolution_method = str(candidate['matched_by'][0])
|
||||
else:
|
||||
row.status = 'ambiguous' if candidates else 'unmatched'
|
||||
row.customer_id = None
|
||||
row.site_id = None
|
||||
row.customer_name_snapshot = None
|
||||
row.customer_short_code_snapshot = None
|
||||
row.resolution_method = None
|
||||
row.confirmed_by_id = None
|
||||
row.confirmed_at = None
|
||||
row.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
results.append(serialize_order_customer_match(row))
|
||||
return results
|
||||
|
||||
|
||||
def confirm_order_customer_match(
|
||||
extraction_id: int,
|
||||
*,
|
||||
role: str,
|
||||
customer_id: int,
|
||||
site_id: int | None = None,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""人工确认某个订单客户角色;Ship-to 必须同时选择所属客户的启用站点。"""
|
||||
if role not in ROLE_FIELDS:
|
||||
raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID')
|
||||
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
|
||||
extraction_id=extraction_id, role=role,
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND')
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
if customer.status != 'active':
|
||||
raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE')
|
||||
selected_site = None
|
||||
if role == 'ship_to':
|
||||
selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None
|
||||
if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active':
|
||||
raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID')
|
||||
row.status = 'confirmed'
|
||||
row.customer_id = customer.id
|
||||
row.site_id = selected_site.id if selected_site else None
|
||||
row.customer_name_snapshot = customer.standard_name
|
||||
row.customer_short_code_snapshot = customer.short_code
|
||||
row.resolution_method = 'manual'
|
||||
row.confirmed_by_id = actor_id
|
||||
row.confirmed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return serialize_order_customer_match(row)
|
||||
|
||||
|
||||
def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]:
|
||||
"""输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。"""
|
||||
return {
|
||||
'id': row.id,
|
||||
'extraction_id': row.extraction_id,
|
||||
'role': row.role,
|
||||
'raw_name': row.raw_name,
|
||||
'status': row.status,
|
||||
'customer_id': row.customer_id,
|
||||
'site_id': row.site_id,
|
||||
'source_system': row.source_system,
|
||||
'external_code': row.external_code,
|
||||
'standard_name': row.customer_name_snapshot,
|
||||
'short_code': row.customer_short_code_snapshot,
|
||||
'candidates': list(row.candidates_json or []),
|
||||
'resolution_method': row.resolution_method,
|
||||
}
|
||||
@@ -27,6 +27,8 @@ from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingTask,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
@@ -42,16 +44,7 @@ from app.services.shipping_notice.duplicate_detection import (
|
||||
detect_duplicates_for_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
from app.services.shipping_notice.order_extraction_evidence import (
|
||||
adjudicate_order_reservations,
|
||||
verify_reservation_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.field_adjudication import (
|
||||
adjudicate_order_fields,
|
||||
merge_observation_history,
|
||||
trusted_required_fields,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
|
||||
|
||||
_CONTEXT_PATHS = [
|
||||
'agent_code',
|
||||
@@ -120,9 +113,15 @@ def _load_intakes(
|
||||
for row in rows:
|
||||
if row.conversation_id and row.conversation_id != session.session_id:
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话')
|
||||
if row.parse_status == 'consumed' or row.consumed_at is not None:
|
||||
if allow_consumed:
|
||||
continue
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED',
|
||||
message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果',
|
||||
)
|
||||
ready = row.parse_status == 'parsed' and row.consumed_at is None
|
||||
replayable = allow_consumed and row.parse_status == 'consumed'
|
||||
if not ready and not replayable:
|
||||
if not ready:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
|
||||
if row.conversation_id is None:
|
||||
row.conversation_id = session.session_id
|
||||
@@ -276,7 +275,13 @@ def start_order_extraction(
|
||||
now = datetime.utcnow()
|
||||
intake_ids: list[int] = []
|
||||
for intake in intakes:
|
||||
if intake.parse_status != 'parsed' or intake.consumed_at is not None:
|
||||
if intake.parse_status == 'consumed' or intake.consumed_at is not None:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED',
|
||||
message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果',
|
||||
)
|
||||
if intake.parse_status != 'parsed':
|
||||
db.session.rollback()
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
|
||||
if intake.conversation_id and intake.conversation_id != session_value:
|
||||
@@ -686,13 +691,7 @@ def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
row.intake_no: dict(row.structured_result_json or {}).get('rule_hints') or {}
|
||||
for row in intakes
|
||||
},
|
||||
'contract': {
|
||||
'required_order_fields': ['source_intake_no', 'primary_document_id', 'classification', 'lines'],
|
||||
'auto_create_required_line_fields': ['part_number', 'qty'],
|
||||
'required_process_line_fields': ['reservation_id'],
|
||||
'optional_routing_line_fields': ['inventory_source_hint'],
|
||||
'allowed_missing_process_fields': ['reservation_id'],
|
||||
},
|
||||
'contract': dify_contract(published_version()),
|
||||
}
|
||||
|
||||
|
||||
@@ -900,52 +899,32 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
document_non_shipping_indexes[int(document.id)].append(index)
|
||||
continue
|
||||
|
||||
summary = dict(raw_order)
|
||||
summary.pop('evidence', None)
|
||||
summary.pop('field_confidence', None)
|
||||
summary.pop('classification_confidence', None)
|
||||
summary.pop('candidate_key_hint', None)
|
||||
summary.pop('classification', None)
|
||||
summary.pop('source_intake_no', None)
|
||||
summary.pop('primary_document_id', None)
|
||||
field_confidence = raw_order.get('field_confidence') if isinstance(raw_order.get('field_confidence'), dict) else {}
|
||||
field_adjudication = adjudicate_order_fields(
|
||||
summary,
|
||||
dynamic = persist_dynamic_order(
|
||||
raw_order=raw_order,
|
||||
intake_id=int(intake.id),
|
||||
snapshot_hash=current_snapshot,
|
||||
documents=owned_docs,
|
||||
field_confidence=field_confidence,
|
||||
actor_id=int(session.user_id),
|
||||
)
|
||||
normalized = field_adjudication['summary']
|
||||
blocking_conflicts.extend(field_adjudication['conflicts'])
|
||||
assessment = assess_candidate_business_summary(normalized)
|
||||
normalized, backend_conflicts = adjudicate_order_reservations(
|
||||
assessment['normalized_summary'],
|
||||
documents=owned_docs,
|
||||
)
|
||||
assessment = assess_candidate_business_summary(normalized)
|
||||
summary = {**dynamic['header'], 'lines': dynamic['lines']}
|
||||
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
|
||||
if summary.get('bill_to_customer'):
|
||||
summary['customer_name'] = summary['bill_to_customer']
|
||||
if dynamic['blocked_fields']:
|
||||
blocking_conflicts.extend([
|
||||
{
|
||||
'field': item.get('field_code'),
|
||||
'severity': 'blocking',
|
||||
'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate',
|
||||
}
|
||||
for item in dynamic['decisions']
|
||||
if item.get('status') not in {'accepted', 'corroborated'}
|
||||
] or [{
|
||||
'field': ','.join(dynamic['blocked_fields']), 'severity': 'blocking',
|
||||
'reason': 'dynamic_schema_required_or_evidence_gate',
|
||||
}])
|
||||
assessment = assess_candidate_business_summary(summary)
|
||||
normalized = assessment['normalized_summary']
|
||||
blocking_conflicts.extend(backend_conflicts)
|
||||
# [STEP] 证据核验对齐裁决后的行值,门禁比较 (line_index, reservation_id) pair,
|
||||
# 避免仅比 index 时把被裁决改写过的 Reservation 误判为已核验。
|
||||
order_for_evidence = dict(raw_order)
|
||||
order_for_evidence['lines'] = list(normalized.get('lines') or [])
|
||||
verified_reservation_evidence = verify_reservation_evidence(
|
||||
order_for_evidence,
|
||||
documents=owned_docs,
|
||||
)
|
||||
reservation_pairs = {
|
||||
(line_index, reservation_id)
|
||||
for line_index, line in enumerate(normalized.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
for reservation_id in [validated_reservation_id(line.get('reservation_id'))]
|
||||
if reservation_id
|
||||
}
|
||||
verified_reservation_pairs = {
|
||||
(int(item['line_index']), validated_reservation_id(item.get('reservation_id')))
|
||||
for item in verified_reservation_evidence
|
||||
if str(item.get('line_index', '')).isdigit()
|
||||
and validated_reservation_id(item.get('reservation_id'))
|
||||
}
|
||||
reasons: list[str] = []
|
||||
if classification != 'shipping_request':
|
||||
reasons.append('not_shipping_request')
|
||||
@@ -953,10 +932,8 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
reasons.append('missing_or_invalid_part_number_qty')
|
||||
if classification_confidence < class_threshold:
|
||||
reasons.append('low_classification_confidence')
|
||||
if not trusted_required_fields(field_adjudication):
|
||||
reasons.append('untrusted_part_number_qty_adjudication')
|
||||
if reservation_pairs - verified_reservation_pairs:
|
||||
reasons.append('unverified_reservation_evidence')
|
||||
if dynamic['blocked_fields']:
|
||||
reasons.append('dynamic_schema_gate')
|
||||
if blocking_conflicts:
|
||||
reasons.append('blocking_conflict')
|
||||
|
||||
@@ -978,32 +955,13 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
candidate_key=candidate_key,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
previous_structured = (
|
||||
candidate.structured_result_json
|
||||
if isinstance(candidate.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
previous_extraction = (
|
||||
previous_structured.get('extraction')
|
||||
if isinstance(previous_structured.get('extraction'), dict)
|
||||
else {}
|
||||
)
|
||||
previous_adjudication = (
|
||||
previous_extraction.get('field_adjudication')
|
||||
if isinstance(previous_extraction.get('field_adjudication'), dict)
|
||||
else {}
|
||||
)
|
||||
observation_history = merge_observation_history(
|
||||
previous_adjudication.get('observation_history') or previous_adjudication.get('observations'),
|
||||
field_adjudication['observations'],
|
||||
)
|
||||
candidate.primary_document_id = int(document.id)
|
||||
candidate.source_order_index = index
|
||||
candidate.extraction_source = 'dify_chatflow'
|
||||
candidate.classification_confidence = classification_confidence
|
||||
candidate.field_confidence_json = dict(field_confidence)
|
||||
candidate.field_confidence_json = {}
|
||||
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
|
||||
candidate.evidence_json = [item for item in (raw_order.get('evidence') or []) if isinstance(item, dict)]
|
||||
candidate.evidence_json = list(dynamic['observations'])
|
||||
candidate.po_number = str(normalized.get('po_number') or '').strip() or None
|
||||
candidate.confidence = classification_confidence
|
||||
candidate.conflicts_json = blocking_conflicts
|
||||
@@ -1024,19 +982,36 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'request_id': request_id,
|
||||
'classification': classification,
|
||||
'classification_confidence': classification_confidence,
|
||||
'field_confidence': field_confidence,
|
||||
'field_confidence': {},
|
||||
'field_adjudication': {
|
||||
'schema_version': field_adjudication['schema_version'],
|
||||
'observations': field_adjudication['observations'],
|
||||
'observation_history': observation_history,
|
||||
'decisions': field_adjudication['decisions'],
|
||||
'conflicts': field_adjudication['conflicts'],
|
||||
'schema_version_id': int(dynamic['extraction'].schema_version_id),
|
||||
'extraction_id': int(dynamic['extraction'].id),
|
||||
'observations': dynamic['observations'],
|
||||
'decisions': dynamic['decisions'],
|
||||
'conflicts': blocking_conflicts,
|
||||
},
|
||||
'customer_matches': dynamic['customer_matches'],
|
||||
'missing_required_fields': assessment['missing_required_fields'],
|
||||
'missing_process_fields': assessment['missing_process_fields'],
|
||||
'process_issues': assessment['process_issues'],
|
||||
'auto_create_reasons': reasons,
|
||||
'verified_reservation_evidence': verified_reservation_evidence,
|
||||
'verified_reservation_evidence': [
|
||||
{
|
||||
'line_index': int(item.get('line_position') or 0),
|
||||
'reservation_id': item.get('value'),
|
||||
'document_id': next(
|
||||
(
|
||||
observation.get('document_id')
|
||||
for observation in dynamic['observations']
|
||||
if observation.get('id') in set(item.get('observation_ids') or [])
|
||||
),
|
||||
None,
|
||||
),
|
||||
}
|
||||
for item in dynamic['decisions']
|
||||
if item.get('status') in {'accepted', 'corroborated'}
|
||||
and item.get('field_code') == 'reservation_id'
|
||||
],
|
||||
},
|
||||
}
|
||||
duplicate = detect_duplicates_for_candidate(
|
||||
@@ -1135,6 +1110,21 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
candidate_nos=auto_candidate_nos,
|
||||
create_idempotency_key=idem,
|
||||
)
|
||||
# [STEP 4A] Candidate 被创建或打开到 Task 后,回填当前动态订单真相版本。
|
||||
for candidate in auto_candidates:
|
||||
if candidate.consumed_task_id is None:
|
||||
continue
|
||||
extraction_data = (
|
||||
candidate.structured_result_json.get('extraction', {}).get('field_adjudication', {})
|
||||
if isinstance(candidate.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
extraction_id = extraction_data.get('extraction_id') if isinstance(extraction_data, dict) else None
|
||||
task = db.session.get(ShippingTask, int(candidate.consumed_task_id))
|
||||
if task is not None and str(extraction_id or '').isdigit():
|
||||
task.current_order_extraction_id = int(extraction_id)
|
||||
db.session.get(ShippingOrderExtraction, int(extraction_id)).task_id = int(task.id)
|
||||
db.session.commit()
|
||||
else:
|
||||
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
|
||||
if not pending:
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/__init__.py
|
||||
|
||||
用途:货代订单唯一 Schema 领域服务入口。
|
||||
依赖:registry、service。
|
||||
逻辑:管理 API 和后续订单抽取链从本包读取受控字段能力与已发布契约。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.order_schema.service import get_published_contract
|
||||
|
||||
__all__ = ['get_published_contract']
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/diff.py
|
||||
|
||||
用途:计算订单 Schema 版本定义之间可直接展示的语义化字段差异。
|
||||
依赖:无数据库依赖,仅处理 version definition JSON。
|
||||
逻辑:以稳定 field_id 配对字段;集合属性与顺序分别比较,避免字段重命名被误判为删除和新增。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
_SCALAR_KEYS = (
|
||||
'field_code', 'scope', 'value_type', 'enabled', 'display_name', 'description',
|
||||
'required', 'normalizer_key', 'relation_role', 'comparator_key',
|
||||
'extraction_instruction', 'sequence',
|
||||
)
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options')
|
||||
_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source')
|
||||
|
||||
|
||||
def _field_map(definition: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
"""按稳定 field_id 索引字段,忽略不完整的历史快照条目。"""
|
||||
return {
|
||||
str(field['field_id']): field
|
||||
for field in (definition or {}).get('fields', [])
|
||||
if isinstance(field, dict) and field.get('field_id') is not None
|
||||
}
|
||||
|
||||
|
||||
def _set_change(key: str, before: Any, after: Any) -> dict[str, Any] | None:
|
||||
"""比较无序字符串集合,并显式返回新增、移除和原始值以便界面呈现。"""
|
||||
before_items = list(before or [])
|
||||
after_items = list(after or [])
|
||||
before_set = set(before_items)
|
||||
after_set = set(after_items)
|
||||
if before_set == after_set and before_items == after_items:
|
||||
return None
|
||||
return {
|
||||
'key': key,
|
||||
'kind': 'set',
|
||||
'before': before_items,
|
||||
'after': after_items,
|
||||
'added': sorted(after_set - before_set),
|
||||
'removed': sorted(before_set - after_set),
|
||||
'order_changed': before_set == after_set and before_items != after_items,
|
||||
}
|
||||
|
||||
|
||||
def _field_changes(before: dict[str, Any], after: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""返回同一字段的属性级变更,证据策略按子属性而非整个对象展示。"""
|
||||
changes: list[dict[str, Any]] = []
|
||||
for key in _SCALAR_KEYS:
|
||||
if before.get(key) != after.get(key):
|
||||
changes.append({'key': key, 'kind': 'value', 'before': before.get(key), 'after': after.get(key)})
|
||||
for key in _SET_KEYS:
|
||||
change = _set_change(key, before.get(key), after.get(key))
|
||||
if change:
|
||||
changes.append(change)
|
||||
before_policy = before.get('evidence_policy') or {}
|
||||
after_policy = after.get('evidence_policy') or {}
|
||||
for key in _EVIDENCE_POLICY_KEYS:
|
||||
qualified_key = f'evidence_policy.{key}'
|
||||
if key == 'source_precedence':
|
||||
change = _set_change(qualified_key, before_policy.get(key), after_policy.get(key))
|
||||
if change:
|
||||
changes.append(change)
|
||||
elif before_policy.get(key) != after_policy.get(key):
|
||||
changes.append({
|
||||
'key': qualified_key,
|
||||
'kind': 'value',
|
||||
'before': before_policy.get(key),
|
||||
'after': after_policy.get(key),
|
||||
})
|
||||
return changes
|
||||
|
||||
|
||||
def compare_definitions(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
计算两个 Schema 定义的字段级差异。
|
||||
|
||||
Args:
|
||||
before: 作为基线的完整版本 definition。
|
||||
after: 用来比较的完整版本 definition。
|
||||
Returns:
|
||||
包含新增、移除、修改和未变字段及属性变更列表的稳定 JSON 结构。
|
||||
"""
|
||||
before_fields = _field_map(before)
|
||||
after_fields = _field_map(after)
|
||||
field_ids = sorted(set(before_fields) | set(after_fields))
|
||||
fields: list[dict[str, Any]] = []
|
||||
counts = {'added': 0, 'removed': 0, 'modified': 0, 'unchanged': 0}
|
||||
for field_id in field_ids:
|
||||
previous = before_fields.get(field_id)
|
||||
current = after_fields.get(field_id)
|
||||
if previous is None:
|
||||
change_type = 'added'
|
||||
changes: list[dict[str, Any]] = []
|
||||
elif current is None:
|
||||
change_type = 'removed'
|
||||
changes = []
|
||||
else:
|
||||
changes = _field_changes(previous, current)
|
||||
change_type = 'modified' if changes else 'unchanged'
|
||||
counts[change_type] += 1
|
||||
fields.append({
|
||||
'field_id': field_id,
|
||||
'change_type': change_type,
|
||||
'before': previous,
|
||||
'after': current,
|
||||
'changes': changes,
|
||||
})
|
||||
return {'summary': counts, 'fields': fields}
|
||||
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/registry.py
|
||||
|
||||
用途:维护订单字段类型、规范化器、校验器、比较器和证据策略白名单。
|
||||
依赖:无。
|
||||
逻辑:管理员配置只能引用本模块声明的安全能力;运行期解析器在后续阶段复用同一目录。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
FIELD_TYPES = {'string', 'decimal', 'integer', 'date', 'boolean', 'enum'}
|
||||
FIELD_SCOPES = {'header', 'line'}
|
||||
NORMALIZERS = {
|
||||
'trim', 'uppercase_trim', 'lowercase_trim', 'decimal', 'integer', 'iso_date',
|
||||
'boolean', 'reservation_id',
|
||||
}
|
||||
VALIDATORS = {
|
||||
'non_empty', 'positive_decimal', 'non_negative_decimal', 'positive_integer',
|
||||
'reservation_id', 'atomic_part_number', 'iso_date',
|
||||
}
|
||||
COMPARATORS = {'normalized_text', 'case_insensitive_text', 'decimal', 'integer', 'date', 'boolean', 'reservation_id'}
|
||||
RELATION_ROLES = {None, 'primary_link', 'secondary_link', 'line_match'}
|
||||
SOURCE_TYPES = {
|
||||
'attachment_table', 'attachment_text', 'email_body_table', 'email_body_text',
|
||||
'backend_table', 'dify_llm',
|
||||
}
|
||||
CONFLICT_POLICIES = {'block', 'review', 'prefer_attachment', 'prefer_email'}
|
||||
TYPE_NORMALIZERS = {
|
||||
'string': {'trim', 'uppercase_trim', 'lowercase_trim', 'reservation_id'},
|
||||
'decimal': {'decimal'},
|
||||
'integer': {'integer'},
|
||||
'date': {'iso_date'},
|
||||
'boolean': {'boolean'},
|
||||
'enum': {'trim', 'uppercase_trim', 'lowercase_trim'},
|
||||
}
|
||||
TYPE_COMPARATORS = {
|
||||
'string': {'normalized_text', 'case_insensitive_text', 'reservation_id'},
|
||||
'decimal': {'decimal'},
|
||||
'integer': {'integer'},
|
||||
'date': {'date'},
|
||||
'boolean': {'boolean'},
|
||||
'enum': {'normalized_text', 'case_insensitive_text'},
|
||||
}
|
||||
TYPE_VALIDATORS = {
|
||||
'string': {'non_empty', 'reservation_id', 'atomic_part_number'},
|
||||
'decimal': {'non_empty', 'positive_decimal', 'non_negative_decimal'},
|
||||
'integer': {'non_empty', 'positive_integer'},
|
||||
'date': {'non_empty', 'iso_date'},
|
||||
'boolean': set(),
|
||||
'enum': {'non_empty'},
|
||||
}
|
||||
ADMIN_HIDDEN_RULES = {'reservation_id'}
|
||||
|
||||
|
||||
def _admin_rules(values: set[str]) -> list[str]:
|
||||
"""隐藏字段专用的内部兼容规则,避免管理员将其误用到普通文本字段。"""
|
||||
return sorted(values - ADMIN_HIDDEN_RULES)
|
||||
|
||||
|
||||
def catalog() -> dict[str, list[str] | dict[str, list[str]]]:
|
||||
"""返回管理端字段编辑器可选目录及按字段类型收窄后的兼容矩阵。"""
|
||||
return {
|
||||
'field_types': sorted(FIELD_TYPES),
|
||||
'field_scopes': sorted(FIELD_SCOPES),
|
||||
'normalizers': _admin_rules(NORMALIZERS),
|
||||
'validators': _admin_rules(VALIDATORS),
|
||||
'comparators': _admin_rules(COMPARATORS),
|
||||
'relation_roles': sorted(item for item in RELATION_ROLES if item),
|
||||
'source_types': sorted(SOURCE_TYPES),
|
||||
'conflict_policies': sorted(CONFLICT_POLICIES),
|
||||
'type_normalizers': {key: _admin_rules(value) for key, value in TYPE_NORMALIZERS.items()},
|
||||
'type_validators': {key: _admin_rules(value) for key, value in TYPE_VALIDATORS.items()},
|
||||
'type_comparators': {key: _admin_rules(value) for key, value in TYPE_COMPARATORS.items()},
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
|
||||
依赖:订单 Schema 动态模型、ShippingNoticeDocument、registry、订单客户匹配服务。
|
||||
逻辑:提交时先验证原文证据和字段规则,再以已裁决订单头匹配 Bill-to/Ship-to 客户主数据并输出业务投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.notice_lines import parse_notice_table_text
|
||||
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def published_version() -> ShippingOrderSchemaVersion:
|
||||
"""读取当前唯一 published 订单 Schema;未发布时阻断解析。"""
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').first()
|
||||
if version is None:
|
||||
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
|
||||
return version
|
||||
|
||||
|
||||
def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
"""编译 Dify 动态抽取契约;仅输出发布快照中 enabled 的字段。"""
|
||||
fields = [
|
||||
dict(item) for item in (version.definition_json or {}).get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
]
|
||||
return {
|
||||
'schema_version_id': int(version.id),
|
||||
'schema_version': int(version.version),
|
||||
'checksum': version.checksum,
|
||||
'fields': fields,
|
||||
'submission_contract': {
|
||||
'field': {'field_id': '<stable uuid>', 'observations': '<one or more observation objects>'},
|
||||
'observation': {
|
||||
'value': '<typed candidate value>',
|
||||
'document_id': '<id from documents[]>',
|
||||
'quote': '<verbatim source quote>',
|
||||
'confidence': '<optional 0..1>',
|
||||
},
|
||||
'order': {'header_fields': '<field[]>', 'lines': [{'fields': '<field[]>'}]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _json_value(value: Any) -> Any:
|
||||
"""将 Decimal/date 转为 JSON 可安全持久化的标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return format(value, 'f')
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _input_snapshot(*, intake_id: int, snapshot_hash: str, documents: list[ShippingNoticeDocument]) -> dict[str, Any]:
|
||||
"""冻结本次裁决使用的文档文本和指纹,供管理员重建输入证据而不回读可变 Document。"""
|
||||
return {
|
||||
'intake_id': intake_id,
|
||||
'snapshot_hash': snapshot_hash,
|
||||
'documents': [
|
||||
{
|
||||
'id': int(document.id),
|
||||
'filename': document.filename,
|
||||
'document_type': document.document_type,
|
||||
'content_hash': document.content_hash,
|
||||
'extracted_text': document.extracted_text,
|
||||
}
|
||||
for document in documents
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _normalize(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""按发布字段类型与 normalizer 规范化候选值。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
value_type = str(config['value_type'])
|
||||
normalizer = str(config.get('normalizer_key') or 'trim')
|
||||
try:
|
||||
if value_type == 'decimal':
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
if value_type == 'integer':
|
||||
return int(str(value).replace(',', '').strip())
|
||||
if value_type == 'date':
|
||||
return date.fromisoformat(str(value).strip())
|
||||
if value_type == 'boolean':
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
lowered = str(value).strip().lower()
|
||||
if lowered in {'true', '1', 'yes', 'y'}:
|
||||
return True
|
||||
if lowered in {'false', '0', 'no', 'n'}:
|
||||
return False
|
||||
raise ValueError('invalid boolean')
|
||||
except (InvalidOperation, ValueError, TypeError) as exc:
|
||||
raise ValidationError(
|
||||
'Dynamic field value type is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT'
|
||||
) from exc
|
||||
text = str(value).strip()
|
||||
if normalizer == 'uppercase_trim':
|
||||
text = text.upper()
|
||||
elif normalizer == 'lowercase_trim':
|
||||
text = text.lower()
|
||||
if normalizer == 'reservation_id':
|
||||
text = validated_reservation_id(text) or ''
|
||||
if value_type == 'enum' and text not in set(config.get('enum_options') or []):
|
||||
raise ValidationError('Dynamic enum value is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
return text or None
|
||||
|
||||
|
||||
def _validate(value: Any, config: dict[str, Any]) -> bool:
|
||||
"""执行发布契约中受控 validator;返回值决定字段是否可被接受。"""
|
||||
for key in config.get('validator_keys') or []:
|
||||
if key == 'non_empty' and value in (None, ''):
|
||||
return False
|
||||
if key in {'positive_decimal', 'positive_integer'} and Decimal(str(value)) <= 0:
|
||||
return False
|
||||
if key == 'non_negative_decimal' and Decimal(str(value)) < 0:
|
||||
return False
|
||||
if key == 'reservation_id' and not validated_reservation_id(value):
|
||||
return False
|
||||
if key == 'atomic_part_number' and '/' in str(value):
|
||||
return False
|
||||
if key == 'iso_date' and not isinstance(value, date):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _source_type(document: ShippingNoticeDocument) -> str:
|
||||
"""把 Document 技术类型映射为 Schema 证据来源类型。"""
|
||||
return 'email_body_text' if document.document_type == 'body' else 'attachment_text'
|
||||
|
||||
|
||||
def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
"""验证动态 Observation 的字段值、Document 归属、逐字 quote 与值包含关系。"""
|
||||
items = raw.get('observations') if isinstance(raw.get('observations'), list) else []
|
||||
verified: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict) or not str(item.get('document_id') or '').isdigit():
|
||||
continue
|
||||
document = documents.get(int(item['document_id']))
|
||||
value = _normalize(item.get('value'), config)
|
||||
quote = str(item.get('quote') or '').strip()
|
||||
if document is None or value is None or not _validate(value, config):
|
||||
continue
|
||||
if not quote or quote not in str(document.extracted_text or ''):
|
||||
continue
|
||||
if str(_json_value(value)).upper() not in quote.upper():
|
||||
continue
|
||||
try:
|
||||
confidence = max(0.0, min(float(item.get('confidence')), 1.0))
|
||||
except (TypeError, ValueError):
|
||||
confidence = 0.0
|
||||
verified.append({
|
||||
'value': value,
|
||||
'document': document,
|
||||
'quote': quote,
|
||||
'confidence': confidence,
|
||||
'source_type': _source_type(document),
|
||||
})
|
||||
return verified
|
||||
|
||||
|
||||
def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]:
|
||||
"""按一致性、来源优先级和冲突策略选择字段值。"""
|
||||
if not observations:
|
||||
return None, 'missing', 'evidence_missing'
|
||||
groups: dict[str, list[dict[str, Any]]] = {}
|
||||
for item in observations:
|
||||
groups.setdefault(str(_json_value(item['value'])), []).append(item)
|
||||
policy = dict(config.get('evidence_policy') or {})
|
||||
if len(groups) == 1:
|
||||
value = observations[0]['value']
|
||||
distinct_documents = {int(item['document'].id) for item in observations}
|
||||
if not policy.get('allow_single_source', True) and len(distinct_documents) < 2:
|
||||
return value, 'needs_review', 'cross_document_evidence_required'
|
||||
return value, 'corroborated' if len(distinct_documents) > 1 else 'accepted', None
|
||||
|
||||
conflict_policy = str(policy.get('conflict_policy') or 'block')
|
||||
preferred = {
|
||||
'prefer_attachment': {'attachment_text', 'attachment_table'},
|
||||
'prefer_email': {'email_body_text', 'email_body_table'},
|
||||
}.get(conflict_policy)
|
||||
if preferred:
|
||||
hits = [item for item in observations if item['source_type'] in preferred]
|
||||
preferred_values = {str(_json_value(item['value'])) for item in hits}
|
||||
if len(preferred_values) == 1:
|
||||
return hits[0]['value'], 'accepted', f'{conflict_policy}_resolved'
|
||||
return observations[0]['value'], 'blocked' if conflict_policy == 'block' else 'needs_review', 'cross_source_conflict'
|
||||
|
||||
|
||||
def _persist_field(*, extraction: ShippingOrderExtraction, line_id: int | None, raw: dict[str, Any],
|
||||
config: dict[str, Any], documents: dict[int, ShippingNoticeDocument],
|
||||
backend_candidates: list[dict[str, Any]]) -> tuple[Any, str, list[dict[str, Any]], dict[str, Any]]:
|
||||
"""持久化字段全部 Observation、最终 Decision 和可查询类型化 Value。"""
|
||||
candidates = _verified_observations(raw, config, documents)
|
||||
candidates.extend(backend_candidates)
|
||||
observation_rows: list[ShippingOrderFieldObservation] = []
|
||||
for item in candidates:
|
||||
row = ShippingOrderFieldObservation(
|
||||
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'],
|
||||
source_document_id=int(item['document'].id), source_type=item['source_type'],
|
||||
extractor=item.get('extractor') or 'dify_dynamic_schema', raw_value_json=_json_value(item['value']),
|
||||
normalized_value_json=_json_value(item['value']), evidence_quote=item['quote'],
|
||||
confidence=Decimal(str(item['confidence'])), evidence_verified=True,
|
||||
)
|
||||
db.session.add(row)
|
||||
observation_rows.append(row)
|
||||
db.session.flush()
|
||||
value, status, reason = _choose_value(candidates, config)
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_status=status,
|
||||
selected_observation_id=observation_rows[0].id if observation_rows else None,
|
||||
supporting_observation_ids_json=[int(item.id) for item in observation_rows],
|
||||
resolved_value_json=_json_value(value), reason_code=reason,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None and status in {'accepted', 'corroborated'}:
|
||||
value_type = str(config['value_type'])
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line_id, field_id=config['field_id'], decision_id=decision.id,
|
||||
value_text=str(value) if value_type in {'string', 'enum'} else None,
|
||||
value_decimal=value if value_type == 'decimal' else None,
|
||||
value_integer=value if value_type == 'integer' else None,
|
||||
value_date=value if value_type == 'date' else None,
|
||||
value_boolean=value if value_type == 'boolean' else None,
|
||||
value_json=_json_value(value),
|
||||
))
|
||||
observations = [{
|
||||
'id': int(item.id), 'field_id': config['field_id'], 'line_id': line_id,
|
||||
'source_type': item.source_type, 'document_id': item.source_document_id,
|
||||
'value': item.normalized_value_json, 'evidence_verified': bool(item.evidence_verified),
|
||||
} for item in observation_rows]
|
||||
decision_payload = {
|
||||
'id': int(decision.id), 'field_id': config['field_id'], 'field_code': config['field_code'], 'line_id': line_id,
|
||||
'status': status, 'value': _json_value(value), 'reason_code': reason,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
}
|
||||
return value, status, observations, decision_payload
|
||||
|
||||
|
||||
def _backend_rows(documents: list[ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
"""从 EML/PDF Document 保留列边界的文本生成后端表格观察原料。"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
for document in documents:
|
||||
for position, raw in enumerate(parse_notice_table_text(str(document.extracted_text or ''))):
|
||||
if isinstance(raw, dict):
|
||||
rows.append({**raw, '_document': document, '_position': position})
|
||||
return rows
|
||||
|
||||
|
||||
def _associated_backend_rows(raw_fields: list[Any], configs: dict[str, dict[str, Any]],
|
||||
rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""使用当前动态行任一稳定字段值关联后端表格行,避免按行号或目标字段自证。"""
|
||||
signatures: list[tuple[str, str]] = []
|
||||
for raw in raw_fields:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
config = configs.get(str(raw.get('field_id') or ''))
|
||||
if config is None:
|
||||
continue
|
||||
for item in raw.get('observations') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = _normalize(item.get('value'), config)
|
||||
if value is not None:
|
||||
signatures.append((str(config['field_code']), str(_json_value(value))))
|
||||
matched = [
|
||||
row for row in rows
|
||||
if any(
|
||||
row.get(code) not in (None, '')
|
||||
and str(_json_value(_normalize(row.get(code), configs[next(
|
||||
field_id for field_id, item in configs.items() if item['field_code'] == code
|
||||
)]))) == value
|
||||
for code, value in signatures
|
||||
if any(item['field_code'] == code for item in configs.values())
|
||||
)
|
||||
]
|
||||
return matched
|
||||
|
||||
|
||||
def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从已关联后端表格行读取当前字段候选,用于一致或冲突裁决。"""
|
||||
if not rows:
|
||||
return []
|
||||
code = str(config['field_code'])
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
if row.get(code) in (None, ''):
|
||||
continue
|
||||
value = _normalize(row.get(code), config)
|
||||
if value is None or not _validate(value, config):
|
||||
continue
|
||||
result.append({
|
||||
'value': value, 'document': row['_document'], 'quote': None, 'confidence': 0.9,
|
||||
'source_type': 'backend_table', 'extractor': 'backend_table',
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot_hash: str,
|
||||
documents: list[ShippingNoticeDocument], actor_id: int | None) -> dict[str, Any]:
|
||||
"""裁决并保存一个动态订单,返回 field_code 下游投影与阻断字段。"""
|
||||
version = published_version()
|
||||
supplied_version = raw_order.get('schema_version_id')
|
||||
supplied_checksum = str(raw_order.get('schema_checksum') or '')
|
||||
if supplied_version != int(version.id) or supplied_checksum != str(version.checksum or ''):
|
||||
raise ConflictError('Order schema changed', code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED')
|
||||
configs = {
|
||||
str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake_id, schema_version_id=version.id, input_snapshot_hash=snapshot_hash,
|
||||
input_snapshot_json=_input_snapshot(
|
||||
intake_id=intake_id, snapshot_hash=snapshot_hash, documents=documents,
|
||||
),
|
||||
status='extracting', raw_llm_output_json=raw_order, created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
document_map = {int(item.id): item for item in documents}
|
||||
header: dict[str, Any] = {}
|
||||
line_projections: list[dict[str, Any]] = []
|
||||
blocked: list[str] = []
|
||||
observations: list[dict[str, Any]] = []
|
||||
decisions: list[dict[str, Any]] = []
|
||||
backend_rows = _backend_rows(documents)
|
||||
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
|
||||
(None, None, 'header', raw_order.get('header_fields') or [], header)
|
||||
]
|
||||
for position, raw_line in enumerate(raw_order.get('lines') or []):
|
||||
if not isinstance(raw_line, dict):
|
||||
raise ValidationError('Dynamic order line must be an object', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
projection: dict[str, Any] = {}
|
||||
line_projections.append(projection)
|
||||
groups.append((line.id, position, 'line', raw_line.get('fields') or [], projection))
|
||||
|
||||
# [STEP 1] 只接受发布契约内且 scope 正确的稳定字段 ID。
|
||||
seen: set[tuple[int | None, str]] = set()
|
||||
for line_id, position, scope, raw_fields, projection in groups:
|
||||
if not isinstance(raw_fields, list):
|
||||
raise ValidationError('Dynamic fields must be arrays', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
associated_rows = _associated_backend_rows(raw_fields, configs, backend_rows) if position is not None else []
|
||||
for raw in raw_fields:
|
||||
field_id = str(raw.get('field_id') or '') if isinstance(raw, dict) else ''
|
||||
config = configs.get(field_id)
|
||||
if config is None or config.get('scope') != scope or (line_id, field_id) in seen:
|
||||
raise ValidationError('Dynamic field identity or scope is invalid', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
seen.add((line_id, field_id))
|
||||
value, status, field_observations, decision = _persist_field(
|
||||
extraction=extraction, line_id=line_id, raw=raw, config=config, documents=document_map,
|
||||
backend_candidates=_backend_candidates(config, rows=associated_rows),
|
||||
)
|
||||
observations.extend(field_observations)
|
||||
decision['line_position'] = position
|
||||
decisions.append(decision)
|
||||
if value is not None:
|
||||
projection[str(config['field_code'])] = _json_value(value)
|
||||
if status not in {'accepted', 'corroborated'}:
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
# [STEP 2] 未提交字段也必须形成 missing Decision,保证每个 Schema 字段都有可审计结果。
|
||||
for config in configs.values():
|
||||
field_id = str(config['field_id'])
|
||||
if config.get('scope') != scope or (line_id, field_id) in seen:
|
||||
continue
|
||||
_value, status, field_observations, decision = _persist_field(
|
||||
extraction=extraction, line_id=line_id, raw={}, config=config, documents=document_map,
|
||||
backend_candidates=_backend_candidates(config, rows=associated_rows),
|
||||
)
|
||||
decision['line_position'] = position
|
||||
observations.extend(field_observations)
|
||||
decisions.append(decision)
|
||||
if config.get('required') and status not in {'accepted', 'corroborated'}:
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
# [STEP 3] Required 按 Header/每一 Line 检查,缺值和冲突都阻断自动建单。
|
||||
for config in configs.values():
|
||||
if not config.get('required'):
|
||||
continue
|
||||
code = str(config['field_code'])
|
||||
if config['scope'] == 'header' and code not in header:
|
||||
blocked.append(code)
|
||||
if config['scope'] == 'line' and (not line_projections or any(code not in line for line in line_projections)):
|
||||
blocked.append(code)
|
||||
extraction.normalized_result_json = {'header': header, 'lines': line_projections}
|
||||
extraction.validation_result_json = {'blocked_fields': sorted(set(blocked))}
|
||||
extraction.status = 'needs_review' if blocked else 'accepted'
|
||||
extraction.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
customer_matches = refresh_order_customer_matches(extraction, header)
|
||||
return {
|
||||
'extraction': extraction,
|
||||
'header': header,
|
||||
'lines': line_projections,
|
||||
'blocked_fields': sorted(set(blocked)),
|
||||
'observations': observations,
|
||||
'decisions': decisions,
|
||||
'customer_matches': customer_matches,
|
||||
}
|
||||
@@ -0,0 +1,876 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/service.py
|
||||
|
||||
用途:管理唯一订单 Schema、稳定字段目录、不可变版本和追加式配置审计。
|
||||
依赖:db、订单 Schema 模型、registry、统一 AppError。
|
||||
逻辑:草稿与发布版本统一读写 definition_json;乐观锁阻止覆盖;发布冻结快照并追加审计事件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.registry import (
|
||||
COMPARATORS,
|
||||
CONFLICT_POLICIES,
|
||||
FIELD_SCOPES,
|
||||
FIELD_TYPES,
|
||||
NORMALIZERS,
|
||||
RELATION_ROLES,
|
||||
SOURCE_TYPES,
|
||||
TYPE_COMPARATORS,
|
||||
TYPE_NORMALIZERS,
|
||||
TYPE_VALIDATORS,
|
||||
VALIDATORS,
|
||||
catalog,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
|
||||
SCHEMA_CODE = 'SHIPPING_ORDER'
|
||||
FIELD_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
EVIDENCE_KEYS = {'required', 'source_precedence', 'conflict_policy', 'allow_single_source'}
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""将可空时间转换为 API 使用的 ISO 字符串。"""
|
||||
return value.isoformat() if value else None
|
||||
|
||||
|
||||
def _schema() -> ShippingOrderSchema | None:
|
||||
"""读取唯一逻辑订单 Schema;不存在时返回 None。"""
|
||||
return ShippingOrderSchema.query.filter_by(schema_code=SCHEMA_CODE).first()
|
||||
|
||||
|
||||
def _require_schema() -> ShippingOrderSchema:
|
||||
"""读取唯一订单 Schema,不存在时抛出领域 404。"""
|
||||
row = _schema()
|
||||
if row is None:
|
||||
raise NotFoundError('Shipping order schema not found', code='SHIPPING.ORDER_SCHEMA_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _field_payload(field: ShippingOrderField) -> dict[str, Any]:
|
||||
"""序列化稳定字段身份,不混入具体版本的显示和抽取规则。"""
|
||||
return {
|
||||
'id': field.id,
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'status': field.status,
|
||||
'published_once': bool(field.published_once),
|
||||
'created_at': _iso(field.created_at),
|
||||
'updated_at': _iso(field.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _copy_json(value: Any) -> Any:
|
||||
"""复制 JSON 兼容数据,避免 ORM 可变对象被后续修改污染审计快照。"""
|
||||
return json.loads(json.dumps(value, ensure_ascii=True))
|
||||
|
||||
|
||||
def _definition(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
"""返回版本完整定义副本;草稿和发布版本均以此字段作为唯一配置真相。"""
|
||||
return _copy_json(version.definition_json or {'schema_code': SCHEMA_CODE, 'version': version.version, 'fields': []})
|
||||
|
||||
|
||||
def _enabled_fields(definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""筛选当前版本实际生效字段,供发布门禁和 Dify 运行契约复用。"""
|
||||
return [dict(item) for item in definition.get('fields') or [] if item.get('enabled', True)]
|
||||
|
||||
|
||||
def _audit_summary(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""生成阶段一审计摘要;阶段三在此基础上提供完整字段级语义差异。"""
|
||||
before_fields = {str(item.get('field_id')): item for item in (before or {}).get('fields', [])}
|
||||
after_fields = {str(item.get('field_id')): item for item in (after or {}).get('fields', [])}
|
||||
return {
|
||||
'before_field_count': len(before_fields),
|
||||
'after_field_count': len(after_fields),
|
||||
'added_field_ids': sorted(set(after_fields) - set(before_fields)),
|
||||
'removed_field_ids': sorted(set(before_fields) - set(after_fields)),
|
||||
'changed_field_ids': sorted(
|
||||
field_id for field_id in set(before_fields) & set(after_fields)
|
||||
if before_fields[field_id] != after_fields[field_id]
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _write_audit(
|
||||
*, schema_id: int, version_id: int | None, event_type: str, actor_id: int | None,
|
||||
request_id: str | None, before: dict[str, Any] | None, after: dict[str, Any] | None,
|
||||
) -> None:
|
||||
"""追加配置审计事件;调用方与业务变更共用同一数据库事务。"""
|
||||
db.session.add(ShippingOrderSchemaAuditEvent(
|
||||
schema_id=schema_id,
|
||||
version_id=version_id,
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
before_snapshot_json=_copy_json(before) if before is not None else None,
|
||||
after_snapshot_json=_copy_json(after) if after is not None else None,
|
||||
change_summary_json=_audit_summary(before, after),
|
||||
request_id=request_id,
|
||||
))
|
||||
|
||||
|
||||
def _version_payload(
|
||||
version: ShippingOrderSchemaVersion, *, include_definition: bool = True,
|
||||
actors: dict[int, User] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""序列化 Schema 版本;列表可省略完整快照,详情始终读取不可分叉的 definition_json。"""
|
||||
definition = _definition(version)
|
||||
|
||||
def actor_payload(user_id: int | None) -> dict[str, Any] | None:
|
||||
"""返回版本操作者的安全展示信息,避免历史页面暴露用户敏感字段。"""
|
||||
user = actors.get(user_id) if actors and user_id else (db.session.get(User, user_id) if user_id else None)
|
||||
if user is None:
|
||||
return None
|
||||
return {'id': user.id, 'display_name': user.real_name or user.username}
|
||||
|
||||
payload = {
|
||||
'id': version.id,
|
||||
'version': version.version,
|
||||
'status': version.status,
|
||||
'checksum': version.checksum,
|
||||
'lock_version': version.lock_version,
|
||||
'change_note': version.change_note,
|
||||
'source_version_id': version.source_version_id,
|
||||
'published_at': _iso(version.published_at),
|
||||
'retired_at': _iso(version.retired_at),
|
||||
'created_at': _iso(version.created_at),
|
||||
'updated_at': _iso(version.updated_at),
|
||||
'created_by': actor_payload(version.created_by_id),
|
||||
'published_by': actor_payload(version.published_by_id),
|
||||
'field_count': sum(1 for item in definition.get('fields') or [] if item.get('enabled', True)),
|
||||
}
|
||||
if include_definition:
|
||||
payload['definition'] = definition
|
||||
return payload
|
||||
|
||||
|
||||
def get_state() -> dict[str, Any]:
|
||||
"""返回编辑工作区所需当前草稿/发布版本,历史版本由分页接口按需读取。"""
|
||||
schema = _schema()
|
||||
if schema is None:
|
||||
return {'schema': None, 'fields': [], 'versions': [], 'catalog': catalog()}
|
||||
return {
|
||||
'schema': {
|
||||
'id': schema.id,
|
||||
'schema_code': schema.schema_code,
|
||||
'display_name': schema.display_name,
|
||||
'description': schema.description,
|
||||
'status': schema.status,
|
||||
},
|
||||
# Retired fields remain available to historical records, not the current configuration workspace.
|
||||
'fields': [_field_payload(item) for item in ShippingOrderField.query.filter_by(
|
||||
schema_id=schema.id, status='active',
|
||||
).order_by(ShippingOrderField.field_code).all()],
|
||||
'versions': [
|
||||
_version_payload(item)
|
||||
for item in reversed(schema.versions)
|
||||
if item.status in {'draft', 'published'}
|
||||
],
|
||||
'catalog': catalog(),
|
||||
}
|
||||
|
||||
|
||||
def list_versions(
|
||||
*, page: int = 1, page_size: int = 20, version_number: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""分页返回 Schema 版本概要;可按业务版本号精确定位历史链接。"""
|
||||
schema = _require_schema()
|
||||
safe_page = max(page, 1)
|
||||
safe_page_size = min(max(page_size, 1), 100)
|
||||
query = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id)
|
||||
if version_number is not None:
|
||||
query = query.filter(ShippingOrderSchemaVersion.version == version_number)
|
||||
total = query.count()
|
||||
rows = query.order_by(ShippingOrderSchemaVersion.version.desc()).offset(
|
||||
(safe_page - 1) * safe_page_size
|
||||
).limit(safe_page_size).all()
|
||||
actor_ids = {
|
||||
actor_id for row in rows for actor_id in (row.created_by_id, row.published_by_id) if actor_id is not None
|
||||
}
|
||||
actors = {user.id: user for user in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {}
|
||||
return {
|
||||
'items': [_version_payload(item, include_definition=False, actors=actors) for item in rows],
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'total': total,
|
||||
}
|
||||
|
||||
|
||||
def get_version_detail(version_id: int) -> dict[str, Any]:
|
||||
"""返回指定版本的完整不可变快照;不存在或跨 Schema 时拒绝访问。"""
|
||||
schema = _require_schema()
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.schema_id != schema.id:
|
||||
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
|
||||
return _version_payload(version)
|
||||
|
||||
|
||||
def _require_version(version_id: int, *, schema: ShippingOrderSchema | None = None) -> ShippingOrderSchemaVersion:
|
||||
"""读取属于唯一订单 Schema 的版本,防止 ID 被用于访问其他未来 Schema。"""
|
||||
owner = schema or _require_schema()
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.schema_id != owner.id:
|
||||
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
|
||||
return version
|
||||
|
||||
|
||||
def get_version_diff(version_id: int, *, against_version_id: int) -> dict[str, Any]:
|
||||
"""比较任意两个订单 Schema 版本;字段重命名依靠 field_id 保持为一次修改。"""
|
||||
schema = _require_schema()
|
||||
version = _require_version(version_id, schema=schema)
|
||||
against = _require_version(against_version_id, schema=schema)
|
||||
return {
|
||||
'base_version': _version_payload(version),
|
||||
'compare_version': _version_payload(against),
|
||||
**compare_definitions(_definition(version), _definition(against)),
|
||||
}
|
||||
|
||||
|
||||
def _audit_event_payload(
|
||||
event: ShippingOrderSchemaAuditEvent, *, actors: dict[int, User], versions: dict[int, ShippingOrderSchemaVersion],
|
||||
) -> dict[str, Any]:
|
||||
"""序列化审计时间线的最小安全字段,不暴露完整配置快照或用户敏感信息。"""
|
||||
actor = actors.get(event.actor_id) if event.actor_id else None
|
||||
version = versions.get(event.version_id) if event.version_id else None
|
||||
return {
|
||||
'id': event.id,
|
||||
'event_type': event.event_type,
|
||||
'version': {'id': version.id, 'version': version.version} if version else None,
|
||||
'actor': {'id': actor.id, 'display_name': actor.real_name or actor.username} if actor else None,
|
||||
'change_summary': _copy_json(event.change_summary_json or {}),
|
||||
'request_id': event.request_id,
|
||||
'created_at': _iso(event.created_at),
|
||||
}
|
||||
|
||||
|
||||
def list_audit_events(*, page: int = 1, page_size: int = 20, version_id: int | None = None) -> dict[str, Any]:
|
||||
"""分页读取只追加的 Schema 审计时间线,可按版本过滤且批量加载操作者。"""
|
||||
schema = _require_schema()
|
||||
safe_page = max(page, 1)
|
||||
safe_page_size = min(max(page_size, 1), 100)
|
||||
query = ShippingOrderSchemaAuditEvent.query.filter_by(schema_id=schema.id)
|
||||
if version_id is not None:
|
||||
_require_version(version_id, schema=schema)
|
||||
query = query.filter(ShippingOrderSchemaAuditEvent.version_id == version_id)
|
||||
total = query.count()
|
||||
rows = query.order_by(
|
||||
ShippingOrderSchemaAuditEvent.created_at.desc(), ShippingOrderSchemaAuditEvent.id.desc(),
|
||||
).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
|
||||
actor_ids = {item.actor_id for item in rows if item.actor_id is not None}
|
||||
version_ids = {item.version_id for item in rows if item.version_id is not None}
|
||||
actors = {item.id: item for item in User.query.filter(User.id.in_(actor_ids)).all()} if actor_ids else {}
|
||||
versions = {
|
||||
item.id: item for item in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.id.in_(version_ids)
|
||||
).all()
|
||||
} if version_ids else {}
|
||||
return {
|
||||
'items': [_audit_event_payload(item, actors=actors, versions=versions) for item in rows],
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'total': total,
|
||||
}
|
||||
|
||||
|
||||
def _extraction_summary(extraction: ShippingOrderExtraction) -> dict[str, Any]:
|
||||
"""序列化版本使用记录概要,不返回原始 LLM 和证据正文以控制历史列表体积。"""
|
||||
return {
|
||||
'id': extraction.id,
|
||||
'task_id': extraction.task_id,
|
||||
'intake_id': extraction.intake_id,
|
||||
'status': extraction.status,
|
||||
'input_snapshot_hash': extraction.input_snapshot_hash,
|
||||
'created_at': _iso(extraction.created_at),
|
||||
'updated_at': _iso(extraction.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def get_version_usage(version_id: int, *, page: int = 1, page_size: int = 20) -> dict[str, Any]:
|
||||
"""统计并分页读取实际使用指定 Schema 版本的解析记录,供发布影响评估和审计追溯。"""
|
||||
schema = _require_schema()
|
||||
version = _require_version(version_id, schema=schema)
|
||||
safe_page = max(page, 1)
|
||||
safe_page_size = min(max(page_size, 1), 100)
|
||||
query = ShippingOrderExtraction.query.filter_by(schema_version_id=version.id)
|
||||
total = query.count()
|
||||
status_counts = {
|
||||
status: count for status, count in db.session.query(
|
||||
ShippingOrderExtraction.status, func.count(ShippingOrderExtraction.id),
|
||||
).filter_by(schema_version_id=version.id).group_by(ShippingOrderExtraction.status).all()
|
||||
}
|
||||
first_used_at, last_used_at = db.session.query(
|
||||
func.min(ShippingOrderExtraction.created_at), func.max(ShippingOrderExtraction.created_at),
|
||||
).filter_by(schema_version_id=version.id).one()
|
||||
rows = query.order_by(
|
||||
ShippingOrderExtraction.created_at.desc(), ShippingOrderExtraction.id.desc(),
|
||||
).offset((safe_page - 1) * safe_page_size).limit(safe_page_size).all()
|
||||
return {
|
||||
'version': _version_payload(version, include_definition=False),
|
||||
'summary': {
|
||||
'total': total,
|
||||
'status_counts': status_counts,
|
||||
'first_used_at': _iso(first_used_at),
|
||||
'last_used_at': _iso(last_used_at),
|
||||
},
|
||||
'items': [_extraction_summary(row) for row in rows],
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'total': total,
|
||||
}
|
||||
|
||||
|
||||
def _field_identity_map(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
|
||||
"""从提取时锁定的 Schema 快照读取字段身份,避免后续目录重命名污染运行审计。"""
|
||||
return {
|
||||
str(item['field_id']): item for item in _definition(version).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
|
||||
|
||||
def _extraction_value(value: ShippingOrderFieldValue) -> Any:
|
||||
"""返回运行时已保存的统一 JSON 值,避免读取已失效的类型字段组合。"""
|
||||
return _copy_json(value.value_json)
|
||||
|
||||
|
||||
def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
|
||||
"""返回单次订单解析的完整只读审计链:冻结输入、LLM 候选、裁决和证据。"""
|
||||
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
|
||||
if extraction is None:
|
||||
raise NotFoundError('Shipping order extraction not found', code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND')
|
||||
schema = _require_schema()
|
||||
version = _require_version(extraction.schema_version_id, schema=schema)
|
||||
identities = _field_identity_map(version)
|
||||
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
|
||||
observations = ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).order_by(
|
||||
ShippingOrderFieldObservation.id,
|
||||
).all()
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).order_by(
|
||||
ShippingOrderFieldDecision.id,
|
||||
).all()
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).order_by(
|
||||
ShippingOrderFieldValue.id,
|
||||
).all()
|
||||
|
||||
def identity(field_id: str) -> dict[str, Any]:
|
||||
field = identities.get(field_id, {})
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field.get('field_code'),
|
||||
'display_name': field.get('display_name'),
|
||||
'scope': field.get('scope'),
|
||||
'value_type': field.get('value_type'),
|
||||
}
|
||||
|
||||
return {
|
||||
'extraction': _extraction_summary(extraction),
|
||||
'schema_version': _version_payload(version),
|
||||
'input_snapshot': (
|
||||
_copy_json(extraction.input_snapshot_json) | {'snapshot_available': True}
|
||||
if extraction.input_snapshot_json else {
|
||||
'snapshot_hash': extraction.input_snapshot_hash,
|
||||
'documents': [],
|
||||
'snapshot_available': False,
|
||||
}
|
||||
),
|
||||
'raw_llm_output': _copy_json(extraction.raw_llm_output_json),
|
||||
'normalized_result': _copy_json(extraction.normalized_result_json),
|
||||
'validation_result': _copy_json(extraction.validation_result_json),
|
||||
'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines],
|
||||
'observations': [
|
||||
identity(row.field_id) | {
|
||||
'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id,
|
||||
'source_type': row.source_type, 'extractor': row.extractor,
|
||||
'raw_value': _copy_json(row.raw_value_json), 'normalized_value': _copy_json(row.normalized_value_json),
|
||||
'evidence_quote': row.evidence_quote, 'confidence': str(row.confidence) if row.confidence is not None else None,
|
||||
'evidence_verified': bool(row.evidence_verified), 'created_at': _iso(row.created_at),
|
||||
}
|
||||
for row in observations
|
||||
],
|
||||
'decisions': [
|
||||
identity(row.field_id) | {
|
||||
'id': row.id, 'line_id': row.line_id, 'decision_status': row.decision_status,
|
||||
'selected_observation_id': row.selected_observation_id,
|
||||
'supporting_observation_ids': list(row.supporting_observation_ids_json or []),
|
||||
'resolved_value': _copy_json(row.resolved_value_json), 'reason_code': row.reason_code,
|
||||
'decided_at': _iso(row.decided_at),
|
||||
}
|
||||
for row in decisions
|
||||
],
|
||||
'field_values': [
|
||||
identity(row.field_id) | {
|
||||
'id': row.id, 'line_id': row.line_id, 'decision_id': row.decision_id,
|
||||
'value': _extraction_value(row), 'created_at': _iso(row.created_at),
|
||||
}
|
||||
for row in values
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def initialize_schema(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""初始化全局唯一订单 Schema;重复初始化明确拒绝。"""
|
||||
if ShippingOrderSchema.query.count():
|
||||
raise ConflictError('Only one shipping order schema is allowed', code='SHIPPING.ORDER_SCHEMA_EXISTS')
|
||||
display_name = str(data.get('display_name') or '').strip()
|
||||
if not display_name:
|
||||
raise ValidationError('display_name is required', details={'field': 'display_name'})
|
||||
schema = ShippingOrderSchema(
|
||||
schema_code=SCHEMA_CODE,
|
||||
display_name=display_name,
|
||||
description=str(data.get('description') or '').strip() or None,
|
||||
created_by_id=actor_id,
|
||||
updated_by_id=actor_id,
|
||||
)
|
||||
db.session.add(schema)
|
||||
db.session.commit()
|
||||
return get_state()
|
||||
|
||||
|
||||
def save_field(
|
||||
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建或更新稳定字段;系统标识可重命名,首次发布后仍锁定 scope 和 type。"""
|
||||
schema = _require_schema()
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if field_id and (field is None or field.schema_id != schema.id):
|
||||
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
|
||||
code = str(data.get('field_code') or '').strip().lower()
|
||||
scope = str(data.get('scope') or '').strip().lower()
|
||||
value_type = str(data.get('value_type') or '').strip().lower()
|
||||
if not FIELD_CODE_RE.fullmatch(code):
|
||||
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES:
|
||||
raise ValidationError('scope or value_type is invalid', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
if field and field.published_once and (field.scope, field.value_type) != (scope, value_type):
|
||||
raise ConflictError('Published field scope and type are immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
previous_code = field.field_code if field else None
|
||||
field = field or ShippingOrderField(
|
||||
schema_id=schema.id,
|
||||
field_code=code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
field.field_code = code
|
||||
field.scope = scope
|
||||
field.value_type = value_type
|
||||
if not field_id:
|
||||
db.session.add(field)
|
||||
try:
|
||||
db.session.flush()
|
||||
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').first()
|
||||
before = _definition(draft) if draft else None
|
||||
if draft and previous_code != code:
|
||||
definition = _definition(draft)
|
||||
for item in definition.get('fields') or []:
|
||||
if str(item.get('field_id')) == field.id:
|
||||
item['field_code'] = code
|
||||
draft.definition_json = definition
|
||||
draft.lock_version += 1
|
||||
_write_audit(
|
||||
schema_id=schema.id, version_id=draft.id if draft else None, event_type='field_saved',
|
||||
actor_id=actor_id, request_id=request_id, before=before,
|
||||
after=_definition(draft) if draft else None,
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('field_code already exists', code='SHIPPING.ORDER_FIELD_CONFLICT') from exc
|
||||
return _field_payload(field)
|
||||
|
||||
|
||||
def retire_field(
|
||||
field_id: str, *, actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""退役无运行配置引用的稳定字段;历史 Extraction/Schema 版本可继续审计。"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None or field.schema_id != _require_schema().id:
|
||||
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
|
||||
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first()
|
||||
if draft and any(str(item.get('field_id')) == field.id for item in _definition(draft).get('fields') or []):
|
||||
raise ConflictError('Field is referenced by a draft schema version', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
|
||||
if _field_runtime_references(field.id):
|
||||
raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
|
||||
field.status = 'retired'
|
||||
_write_audit(
|
||||
schema_id=field.schema_id, version_id=None, event_type='field_retired', actor_id=actor_id,
|
||||
request_id=request_id, before={'field': _field_payload(field) | {'status': 'active'}},
|
||||
after={'field': _field_payload(field)},
|
||||
)
|
||||
db.session.commit()
|
||||
return _field_payload(field)
|
||||
|
||||
|
||||
def delete_field(
|
||||
field_id: str, *, actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
删除当前配置不再需要的字段。
|
||||
|
||||
未发布且没有业务/下游引用时物理删除;已进入历史 Schema 或解析记录时仅归档。
|
||||
草稿中的字段配置和字段目录在同一事务内变更,避免删除失败却提前改坏草稿。
|
||||
"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None or field.schema_id != _require_schema().id:
|
||||
raise NotFoundError('Shipping order field not found', code='SHIPPING.ORDER_FIELD_NOT_FOUND')
|
||||
if _field_runtime_references(field.id):
|
||||
raise ConflictError('Field is referenced by downstream runtime configuration', code='SHIPPING.ORDER_FIELD_RETIRE_BLOCKED')
|
||||
|
||||
historical_schema_reference = any(
|
||||
any(str(item.get('field_id')) == field.id for item in _definition(version).get('fields') or [])
|
||||
for version in ShippingOrderSchemaVersion.query.filter(
|
||||
ShippingOrderSchemaVersion.schema_id == field.schema_id,
|
||||
ShippingOrderSchemaVersion.status.in_(['published', 'retired']),
|
||||
).all()
|
||||
)
|
||||
extraction_reference = any((
|
||||
db.session.query(ShippingOrderFieldObservation.id).filter_by(field_id=field.id).first(),
|
||||
db.session.query(ShippingOrderFieldDecision.id).filter_by(field_id=field.id).first(),
|
||||
db.session.query(ShippingOrderFieldValue.id).filter_by(field_id=field.id).first(),
|
||||
))
|
||||
|
||||
draft = ShippingOrderSchemaVersion.query.filter_by(schema_id=field.schema_id, status='draft').first()
|
||||
before = _definition(draft) if draft else None
|
||||
if draft:
|
||||
definition = _definition(draft)
|
||||
definition['fields'] = [
|
||||
item for item in definition.get('fields') or [] if str(item.get('field_id')) != field.id
|
||||
]
|
||||
draft.definition_json = definition
|
||||
draft.lock_version += 1
|
||||
|
||||
if field.published_once or historical_schema_reference or extraction_reference:
|
||||
field.status = 'retired'
|
||||
action = 'archived'
|
||||
else:
|
||||
db.session.delete(field)
|
||||
action = 'deleted'
|
||||
_write_audit(
|
||||
schema_id=field.schema_id, version_id=draft.id if draft else None, event_type='field_deleted',
|
||||
actor_id=actor_id, request_id=request_id, before=before,
|
||||
after=_definition(draft) if draft else None,
|
||||
)
|
||||
db.session.commit()
|
||||
return {'field_id': field_id, 'action': action}
|
||||
|
||||
|
||||
def _field_runtime_references(field_id: str) -> list[str]:
|
||||
"""返回字段仍被哪些可运行下游配置引用,供退役与 Schema 发布共用。"""
|
||||
from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile,
|
||||
ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
)
|
||||
references: list[str] = []
|
||||
if db.session.query(ShippingInventoryRoutingRuleCondition).join(ShippingInventoryRoutingRule).filter(
|
||||
ShippingInventoryRoutingRuleCondition.order_field_id == field_id,
|
||||
ShippingInventoryRoutingRule.status.in_(['draft', 'published']),
|
||||
).count():
|
||||
references.append('inventory_routing_rule')
|
||||
parsing_reference = any(
|
||||
any(str(item.get('order_field_id') or '') == field_id for item in (profile.definition_json or {}).get('match_keys', []))
|
||||
for profile in ShippingInventoryParsingProfile.query.filter(
|
||||
ShippingInventoryParsingProfile.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
)
|
||||
if parsing_reference:
|
||||
references.append('inventory_parsing_profile')
|
||||
template_reference = any(
|
||||
any(
|
||||
item.get('source_kind') == 'order_field' and str(item.get('source_key') or '') == field_id
|
||||
for item in (template.definition_json or {}).get('mappings', [])
|
||||
)
|
||||
for template in ShippingExcelTemplate.query.filter(
|
||||
ShippingExcelTemplate.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
)
|
||||
if template_reference:
|
||||
references.append('excel_template')
|
||||
return references
|
||||
|
||||
|
||||
def create_draft(
|
||||
data: dict[str, Any], *, actor_id: int | None, request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建下一版本草稿;从指定版本复制完整定义并记录来源和审计事件。"""
|
||||
schema = _require_schema()
|
||||
source_id = data.get('copy_from_version_id')
|
||||
if source_id is not None and (not str(source_id).isdigit() or int(source_id) < 1):
|
||||
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
source = db.session.get(ShippingOrderSchemaVersion, int(source_id)) if source_id is not None else None
|
||||
if source_id is not None and source is None:
|
||||
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if source is not None and source.schema_id != schema.id:
|
||||
raise ValidationError('copy_from_version_id is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if source is not None and source.status not in {'published', 'retired'}:
|
||||
raise ValidationError('copy_from_version_id must be immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='draft').count():
|
||||
raise ConflictError('A draft schema version already exists', code='SHIPPING.ORDER_SCHEMA_DRAFT_EXISTS')
|
||||
next_version = int(db.session.query(func.max(ShippingOrderSchemaVersion.version)).filter_by(schema_id=schema.id).scalar() or 0) + 1
|
||||
definition = _definition(source) if source else {
|
||||
'schema_code': schema.schema_code, 'version': next_version, 'fields': [],
|
||||
}
|
||||
definition['version'] = next_version
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=next_version,
|
||||
status='draft',
|
||||
definition_json=definition,
|
||||
source_version_id=source.id if source else None,
|
||||
change_note=str(data.get('change_note') or '').strip() or None,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
_write_audit(
|
||||
schema_id=schema.id, version_id=version.id,
|
||||
event_type='cloned' if source else 'draft_created', actor_id=actor_id,
|
||||
request_id=request_id, before=_definition(source) if source else None, after=definition,
|
||||
)
|
||||
db.session.commit()
|
||||
return _version_payload(version)
|
||||
|
||||
|
||||
def _string_list(value: Any, *, field: str) -> list[str]:
|
||||
"""规范化去重字符串列表,非法结构抛出字段级校验错误。"""
|
||||
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.ORDER_SCHEMA_VERSION_INVALID')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
normalized = item.strip()
|
||||
if normalized and normalized not in result:
|
||||
result.append(normalized)
|
||||
return result
|
||||
|
||||
|
||||
def _evidence_policy(value: Any) -> dict[str, Any]:
|
||||
"""校验证据策略,仅允许受控来源、冲突策略和布尔开关。"""
|
||||
if not isinstance(value, dict) or set(value) - EVIDENCE_KEYS:
|
||||
raise ValidationError('evidence_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
sources = _string_list(value.get('source_precedence', []), field='source_precedence')
|
||||
if set(sources) - SOURCE_TYPES:
|
||||
raise ValidationError('source_precedence contains unsupported source', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
conflict_policy = str(value.get('conflict_policy') or 'block').strip()
|
||||
if conflict_policy not in CONFLICT_POLICIES:
|
||||
raise ValidationError('conflict_policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
required = value.get('required', True)
|
||||
allow_single = value.get('allow_single_source', True)
|
||||
if not isinstance(required, bool) or not isinstance(allow_single, bool):
|
||||
raise ValidationError('evidence policy flags must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
return {
|
||||
'required': required,
|
||||
'source_precedence': sources,
|
||||
'conflict_policy': conflict_policy,
|
||||
'allow_single_source': allow_single,
|
||||
}
|
||||
|
||||
|
||||
def save_draft(
|
||||
version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""校验并整体替换草稿定义;expected_lock_version 不匹配时拒绝覆盖。"""
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.schema_id != _require_schema().id:
|
||||
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
|
||||
if version.status != 'draft':
|
||||
raise ConflictError('Published schema version is immutable', code='SHIPPING.ORDER_SCHEMA_VERSION_IMMUTABLE')
|
||||
expected_lock_version = data.get('expected_lock_version')
|
||||
if not isinstance(expected_lock_version, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED',
|
||||
details={'field': 'expected_lock_version'},
|
||||
)
|
||||
if expected_lock_version != version.lock_version:
|
||||
raise ConflictError(
|
||||
'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT',
|
||||
details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version},
|
||||
)
|
||||
configs = data.get('fields')
|
||||
if not isinstance(configs, list):
|
||||
raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
before = _definition(version)
|
||||
active_fields = {
|
||||
item.id: item for item in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all()
|
||||
}
|
||||
seen: set[str] = set()
|
||||
normalized_fields: list[dict[str, Any]] = []
|
||||
for sequence, raw in enumerate(configs, start=1):
|
||||
if not isinstance(raw, dict) or str(raw.get('field_id') or '') not in active_fields:
|
||||
raise ValidationError('field_id is invalid or retired', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
field_id = str(raw['field_id'])
|
||||
if field_id in seen:
|
||||
raise ValidationError('field_id must be unique in a version', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
seen.add(field_id)
|
||||
field = active_fields[field_id]
|
||||
enabled = raw.get('enabled', True)
|
||||
display_name = str(raw.get('display_name') or '').strip()
|
||||
normalizer = str(raw.get('normalizer_key') or 'trim').strip()
|
||||
comparator = str(raw.get('comparator_key') or 'normalized_text').strip()
|
||||
validators = _string_list(raw.get('validator_keys', []), field='validator_keys')
|
||||
aliases = _string_list(raw.get('aliases', []), field='aliases')
|
||||
enum_options = _string_list(raw.get('enum_options', []), field='enum_options')
|
||||
relation_role = str(raw.get('relation_role') or '').strip() or None
|
||||
required = raw.get('required', False)
|
||||
if not isinstance(enabled, bool) or not isinstance(required, bool):
|
||||
raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS:
|
||||
raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if set(validators) - VALIDATORS or relation_role not in RELATION_ROLES:
|
||||
raise ValidationError('field validator or relation role is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if normalizer not in TYPE_NORMALIZERS[field.value_type]:
|
||||
raise ValidationError('normalizer is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if comparator not in TYPE_COMPARATORS[field.value_type]:
|
||||
raise ValidationError('comparator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if set(validators) - TYPE_VALIDATORS[field.value_type]:
|
||||
raise ValidationError('validator is incompatible with field type', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if field.value_type == 'enum' and not enum_options:
|
||||
raise ValidationError('enum field requires enum_options', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if field.value_type != 'enum' and enum_options:
|
||||
raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
normalized_fields.append({
|
||||
'field_id': field_id,
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'enabled': enabled,
|
||||
'display_name': display_name,
|
||||
'description': str(raw.get('description') or '').strip() or None,
|
||||
'required': required,
|
||||
'aliases': aliases,
|
||||
'normalizer_key': normalizer,
|
||||
'validator_keys': validators,
|
||||
'enum_options': enum_options,
|
||||
'evidence_policy': _evidence_policy(raw.get('evidence_policy', {})),
|
||||
'relation_role': relation_role,
|
||||
'comparator_key': comparator,
|
||||
'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None,
|
||||
'sequence': sequence,
|
||||
})
|
||||
after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields}
|
||||
version.definition_json = after
|
||||
version.lock_version += 1
|
||||
version.change_note = str(data.get('change_note') or version.change_note or '').strip() or None
|
||||
_write_audit(
|
||||
schema_id=version.schema_id, version_id=version.id, event_type='draft_saved', actor_id=actor_id,
|
||||
request_id=request_id, before=before, after=after,
|
||||
)
|
||||
db.session.commit()
|
||||
return _version_payload(version)
|
||||
|
||||
|
||||
def publish(
|
||||
version_id: int, *, actor_id: int | None, expected_lock_version: int | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""发布指定锁版本的草稿,生成不可变 checksum 并退役上一发布版本。"""
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.schema_id != _require_schema().id:
|
||||
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
|
||||
if version.status != 'draft':
|
||||
raise ConflictError('Only draft schema version can be published', code='SHIPPING.ORDER_SCHEMA_PUBLISH_INVALID')
|
||||
if not isinstance(expected_lock_version, int):
|
||||
raise ValidationError(
|
||||
'expected_lock_version is required', code='SHIPPING.ORDER_SCHEMA_LOCK_VERSION_REQUIRED',
|
||||
details={'field': 'expected_lock_version'},
|
||||
)
|
||||
if expected_lock_version != version.lock_version:
|
||||
raise ConflictError(
|
||||
'Schema draft was changed by another user', code='SHIPPING.ORDER_SCHEMA_VERSION_CONFLICT',
|
||||
details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version},
|
||||
)
|
||||
definition = _definition(version)
|
||||
enabled_configs = _enabled_fields(definition)
|
||||
if not enabled_configs:
|
||||
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
included_field_ids = {str(config.get('field_id')) for config in enabled_configs}
|
||||
referenced_omissions: dict[str, list[str]] = {}
|
||||
for field in ShippingOrderField.query.filter_by(schema_id=version.schema_id, status='active').all():
|
||||
if field.id in included_field_ids:
|
||||
continue
|
||||
references = _field_runtime_references(field.id)
|
||||
if references:
|
||||
referenced_omissions[field.id] = references
|
||||
if referenced_omissions:
|
||||
raise ConflictError(
|
||||
'Schema version omits fields referenced by downstream runtime configuration',
|
||||
code='SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
|
||||
details={'fields': referenced_omissions},
|
||||
)
|
||||
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
now = datetime.utcnow()
|
||||
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
|
||||
if previous is not None:
|
||||
previous.status = 'retired'
|
||||
previous.retired_at = now
|
||||
db.session.flush()
|
||||
for config in enabled_configs:
|
||||
field = db.session.get(ShippingOrderField, str(config.get('field_id')))
|
||||
if field is not None:
|
||||
field.published_once = True
|
||||
version.checksum = hashlib.sha256(encoded).hexdigest()
|
||||
version.status = 'published'
|
||||
version.published_by_id = actor_id
|
||||
version.published_at = now
|
||||
_write_audit(
|
||||
schema_id=version.schema_id, version_id=version.id, event_type='published', actor_id=actor_id,
|
||||
request_id=request_id, before=definition, after=definition,
|
||||
)
|
||||
db.session.commit()
|
||||
return _version_payload(version)
|
||||
|
||||
|
||||
def delete_draft(
|
||||
version_id: int, *, actor_id: int | None = None, request_id: str | None = None,
|
||||
) -> None:
|
||||
"""删除错误草稿并保留删除前快照审计;发布和退役版本不可删除。"""
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
if version is None or version.schema_id != _require_schema().id:
|
||||
raise NotFoundError('Shipping order schema version not found', code='SHIPPING.ORDER_SCHEMA_VERSION_NOT_FOUND')
|
||||
if version.status != 'draft':
|
||||
raise ConflictError('Only draft schema version can be deleted', code='SHIPPING.ORDER_SCHEMA_VERSION_DELETE_BLOCKED')
|
||||
_write_audit(
|
||||
schema_id=version.schema_id, version_id=None, event_type='draft_deleted', actor_id=actor_id,
|
||||
request_id=request_id, before=_definition(version), after=None,
|
||||
)
|
||||
db.session.delete(version)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def get_published_contract() -> dict[str, Any]:
|
||||
"""返回当前发布订单字段契约,供阶段 2 的 Dify 输入编译器使用。"""
|
||||
schema = _require_schema()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(schema_id=schema.id, status='published').first()
|
||||
if version is None:
|
||||
raise ConflictError('No published shipping order schema', code='SHIPPING.ORDER_SCHEMA_NOT_PUBLISHED')
|
||||
return {
|
||||
'schema_version_id': version.id,
|
||||
'schema_code': schema.schema_code,
|
||||
'version': version.version,
|
||||
'checksum': version.checksum,
|
||||
'fields': _enabled_fields(_definition(version)),
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
"""
|
||||
services/shipping_notice/progress_workflow.py
|
||||
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
|
||||
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、tool_response。
|
||||
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
|
||||
"""
|
||||
|
||||
@@ -16,7 +16,6 @@ from app.services.shipping_notice import fulfillment_workflow
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_RSV_REQ,
|
||||
@@ -27,25 +26,20 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
is_inventory_source_stable,
|
||||
ensure_inventory_source_review_state,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import (
|
||||
awaiting_inventory_mapping_confirm,
|
||||
inventory_mapping_checkpoint_response,
|
||||
maybe_auto_confirm_inventory_mapping,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory
|
||||
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress
|
||||
from app.services.shipping_notice.state_machine import resolve_task_ui_state
|
||||
from app.services.shipping_notice.tool_common import auto_progress_enabled
|
||||
from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
|
||||
|
||||
|
||||
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
按任务当前状态自动串联解析确认、库存准备、字段映射与履约动作。
|
||||
按任务当前状态自动串联解析确认、正式库存准备与履约动作。
|
||||
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
|
||||
|
||||
核心逻辑:先检查解析是否需要人工确认,再保证库存已就绪、字段映射已确认,最后委托 fulfillment workflow 继续推进。
|
||||
核心逻辑:先检查解析是否需要人工确认,再保证正式库存已按 published Profile 就绪,最后委托 fulfillment workflow 继续推进。
|
||||
Args:
|
||||
payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。
|
||||
|
||||
@@ -135,30 +129,8 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
# [STEP 2] 保证库存已经就绪。
|
||||
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
|
||||
# 正常任务仅复用排程或手动刷新已导出的文件;这里不得隐式触发 RPA。
|
||||
if not task.inventory_lines_json:
|
||||
if not auto_rpa_inventory_enabled():
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step3_inventory_prepare",
|
||||
step_title="获取库存",
|
||||
status="needs_human",
|
||||
message="未开启自动 RPA 获取库存",
|
||||
progress_percent=100,
|
||||
current=0,
|
||||
total=1,
|
||||
detail="请手动上传货代库存 Excel,或开启自动 RPA 后重试。",
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="未开启自动 RPA 获取库存。请手动上传货代库存 Excel。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
|
||||
if lang:
|
||||
@@ -168,24 +140,11 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
steps.append("触发 RPA 库存导出")
|
||||
return inv
|
||||
if inv.get("status") != "ok":
|
||||
if maybe_auto_confirm_inventory_mapping(task):
|
||||
steps.append("自动确认字段对齐")
|
||||
else:
|
||||
return inv
|
||||
return inv
|
||||
else:
|
||||
steps.append("载入库存")
|
||||
|
||||
# [STEP 3] 尝试自动完成字段映射确认。
|
||||
# 当系统已经拿到足够可靠的列映射时,直接确认可减少一次人工往返。
|
||||
if maybe_auto_confirm_inventory_mapping(task):
|
||||
steps.append("自动确认字段对齐")
|
||||
|
||||
# [STEP 4] 如果映射仍需人工确认,则停在检查点,把确认动作交还给用户或 Agent。
|
||||
if awaiting_inventory_mapping_confirm(task):
|
||||
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
|
||||
return inventory_mapping_checkpoint_response(task, lang=lang or None)
|
||||
|
||||
# [STEP 5] 库存与映射都就绪后,再进入履约侧自动推进。
|
||||
# [STEP 3] 库存就绪后进入履约侧自动推进。
|
||||
# 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。
|
||||
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
|
||||
if fulfillment_result is not None:
|
||||
|
||||
@@ -188,21 +188,29 @@ def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None:
|
||||
|
||||
|
||||
def resolve_task_export_download(task: ShippingTask | None) -> tuple[Path, str] | None:
|
||||
"""解析任务导出文件路径;文件不存在或路径无效时返回 None。"""
|
||||
"""解析任务当前 ready Artifact;文件不存在或校验元数据无效时返回 None。"""
|
||||
if not task or not task.export_file_path:
|
||||
return None
|
||||
path = Path(task.export_file_path)
|
||||
from app.models import ShippingExportArtifact
|
||||
artifact = ShippingExportArtifact.query.filter_by(
|
||||
task_id=task.id, status='ready', file_path=task.export_file_path,
|
||||
).order_by(
|
||||
ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(),
|
||||
).first()
|
||||
if artifact is None:
|
||||
return None
|
||||
path = Path(artifact.file_path)
|
||||
if not path.is_file():
|
||||
return None
|
||||
return path, task.export_file_name or path.name
|
||||
return path, artifact.file_name or path.name
|
||||
|
||||
|
||||
def task_export_error_message(task: ShippingTask | None) -> str:
|
||||
"""导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。"""
|
||||
if not task or not task.export_file_path:
|
||||
if not task or task.id is None or not task.export_file_path:
|
||||
return "export file not found"
|
||||
path = Path(task.export_file_path)
|
||||
if not path.is_file():
|
||||
resolved = resolve_task_export_download(task)
|
||||
if resolved is None:
|
||||
return "export file missing on disk"
|
||||
return ""
|
||||
|
||||
@@ -536,7 +544,6 @@ def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str,
|
||||
"warehouse_hint": task.warehouse_hint,
|
||||
"inventory_source_code": task.inventory_source_code,
|
||||
"inventory_connector_type": task.inventory_connector_type,
|
||||
"inventory_site_id": task.inventory_site_id,
|
||||
"inventory_warehouse_id": task.inventory_warehouse_id,
|
||||
"inventory_source_status": task.inventory_source_status,
|
||||
"inventory_source_method": task.inventory_source_method,
|
||||
@@ -727,7 +734,7 @@ def list_tasks_for_user(
|
||||
process_status: str | None = None,
|
||||
limit: int = 100,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""列出用户可见任务摘要,可按 batch_no / process_status 过滤。"""
|
||||
"""列出用户可见任务摘要,可按批次或工作台用户态状态过滤。"""
|
||||
q = ShippingTask.query.filter(
|
||||
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
|
||||
)
|
||||
@@ -737,7 +744,13 @@ def list_tasks_for_user(
|
||||
return []
|
||||
q = q.filter(ShippingTask.batch_id == batch.id)
|
||||
if process_status:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
if process_status == "shortage_review":
|
||||
q = q.filter(
|
||||
(ShippingTask.review_status == "shortage_review")
|
||||
| (ShippingTask.pending_human_reason.in_(("shortage", "shortage_review")))
|
||||
)
|
||||
else:
|
||||
q = q.filter(ShippingTask.process_status == process_status)
|
||||
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
|
||||
return [serialize_task_summary(c) for c in rows]
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@ _ACTION_EVENT_MAP: dict[str, _ActionEventMeta] = {
|
||||
"decision_rejected": _ActionEventMeta("reject", "用户已驳回 {task_no}", 40),
|
||||
"focus_switched": _ActionEventMeta("switch_focus", "用户已切换 focus 到 {task_no}", 35),
|
||||
"focus_auto_switched": _ActionEventMeta("auto_focus", "系统自动聚焦到 {task_no}", 10),
|
||||
"inventory_mapping_confirmed": _ActionEventMeta("confirm_inventory_mapping", "用户已确认 {task_no} 库存映射", 30),
|
||||
"inventory_source_confirmed": _ActionEventMeta("confirm_inventory_source", "用户已确认 {task_no} 库存源", 30),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
services/shipping_notice/routing_facts.py
|
||||
|
||||
用途:构造库存源路由规则可读取的受控业务事实。
|
||||
依赖:无 ORM 写入依赖;调用方传入已完成解析和标准化的任务/订单行数据。
|
||||
逻辑:规则引擎只能通过本模块的白名单读取事实,避免管理端规则访问任意模型字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
ALLOWED_SYSTEM_FACT_KEYS = frozenset({
|
||||
'task.customer_code', 'task.destination_country', 'task.destination_city', 'task.destination_port',
|
||||
'task.warehouse_hint', 'task.order_type', 'task.sender_email', 'task.sender_domain',
|
||||
'line.reservation_id', 'line.part_number', 'line.customer_part_number', 'line.aws_part_number',
|
||||
'line.inventory_source_hint',
|
||||
})
|
||||
|
||||
|
||||
def build_routing_facts(*, task: Any, line: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
将任务和订单行投影为路由规则可读取的稳定事实。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 或提供同名属性的对象。
|
||||
line: 单条规范订单行;任务级规则传 None。
|
||||
|
||||
Returns:
|
||||
dict: 使用 task/line 两层命名空间的只读事实字典。
|
||||
"""
|
||||
line_data = dict(line or {})
|
||||
sender_email = str(getattr(task, 'sender_email', '') or '').strip().lower()
|
||||
sender_domain = sender_email.rsplit('@', 1)[-1] if '@' in sender_email else ''
|
||||
return {
|
||||
'task': {
|
||||
'customer_code': str(getattr(task, 'customer_code', '') or '').strip().upper(),
|
||||
'destination_country': str(getattr(task, 'destination_country', '') or '').strip().upper(),
|
||||
'destination_city': str(getattr(task, 'destination_city', '') or '').strip().upper(),
|
||||
'destination_port': str(getattr(task, 'destination_code', '') or '').strip().upper(),
|
||||
'warehouse_hint': str(getattr(task, 'warehouse_hint', '') or '').strip().upper(),
|
||||
'order_type': str(getattr(task, 'order_type', '') or '').strip().upper(),
|
||||
'sender_email': sender_email,
|
||||
'sender_domain': sender_domain,
|
||||
},
|
||||
'line': {
|
||||
key: str(line_data.get(key) or '').strip().upper()
|
||||
for key in ('reservation_id', 'part_number', 'customer_part_number', 'aws_part_number', 'inventory_source_hint')
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def read_system_fact(facts: dict[str, dict[str, Any]], fact_path: str) -> Any:
|
||||
"""
|
||||
读取白名单路由事实。
|
||||
|
||||
Raises:
|
||||
KeyError: 规则引用未注册字段时抛出,调用方应拒绝发布或执行该规则。
|
||||
"""
|
||||
if fact_path not in ALLOWED_SYSTEM_FACT_KEYS:
|
||||
raise KeyError(f'Unsupported routing fact: {fact_path}')
|
||||
namespace, field = fact_path.split('.', 1)
|
||||
return facts.get(namespace, {}).get(field)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
services/shipping_notice/routing_operators.py
|
||||
|
||||
用途:执行库存源路由规则允许的比较操作。
|
||||
依赖:无业务服务依赖;由 inventory_routing_engine 调用。
|
||||
逻辑:操作符白名单限制规则表达能力,避免管理员配置任意代码、SQL 或正则执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
ALLOWED_OPERATORS = frozenset({
|
||||
'equals', 'not_equals', 'in', 'not_in', 'prefix', 'suffix', 'contains',
|
||||
'numeric_length', 'string_length', 'is_empty', 'is_not_empty',
|
||||
})
|
||||
|
||||
|
||||
def matches_operator(actual: Any, operator: str, expected: Any = None) -> bool:
|
||||
"""
|
||||
按受控操作符匹配一个标准化事实值。
|
||||
|
||||
Args:
|
||||
actual: 路由事实值。
|
||||
operator: 白名单操作符。
|
||||
expected: 规则期望值;空值判断操作符不使用该参数。
|
||||
|
||||
Returns:
|
||||
bool: 当前条件是否命中。
|
||||
|
||||
Raises:
|
||||
ValueError: 操作符未注册或期望值格式不合法。
|
||||
"""
|
||||
if operator not in ALLOWED_OPERATORS:
|
||||
raise ValueError(f'Unsupported routing operator: {operator}')
|
||||
value = str(actual or '').strip()
|
||||
if operator == 'is_empty':
|
||||
return not value
|
||||
if operator == 'is_not_empty':
|
||||
return bool(value)
|
||||
if operator in {'in', 'not_in'}:
|
||||
if not isinstance(expected, list):
|
||||
raise ValueError(f'{operator} expects a list')
|
||||
result = value in {str(item or '').strip().upper() for item in expected}
|
||||
return not result if operator == 'not_in' else result
|
||||
expected_text = str(expected or '').strip().upper()
|
||||
if operator == 'equals':
|
||||
return value.upper() == expected_text
|
||||
if operator == 'not_equals':
|
||||
return value.upper() != expected_text
|
||||
if operator == 'prefix':
|
||||
return value.upper().startswith(expected_text)
|
||||
if operator == 'suffix':
|
||||
return value.upper().endswith(expected_text)
|
||||
if operator == 'contains':
|
||||
return expected_text in value.upper()
|
||||
if operator == 'numeric_length':
|
||||
return value.isdigit() and len(value) == int(expected)
|
||||
if operator == 'string_length':
|
||||
return len(value) == int(expected)
|
||||
raise ValueError(f'Unsupported routing operator: {operator}')
|
||||
@@ -9,7 +9,6 @@ services/shipping_notice/rpa.py
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -35,7 +34,7 @@ def rpa_runtime_mode(runtime: dict[str, Any] | None = None) -> dict[str, str | b
|
||||
mode = str(runtime.get("mode") or runtime.get("rpa_mode") or "").strip().lower()
|
||||
if mode in {"browser", "mock"}:
|
||||
return _runtime_summary(mode)
|
||||
raw = str(os.getenv("FREIGHT_RPA_MOCK", current_app.config.get("FREIGHT_RPA_MOCK", "false")) or "false").strip().lower()
|
||||
raw = str(current_app.config.get("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false") or "false").strip().lower()
|
||||
return _runtime_summary("mock" if raw in {"1", "true", "yes", "on"} else "browser")
|
||||
|
||||
|
||||
@@ -47,8 +46,8 @@ def _path(key: str) -> Path | None:
|
||||
|
||||
|
||||
def inventory_drop_dir() -> Path | None:
|
||||
"""RPA 库存 Excel 落盘目录(FREIGHT_INVENTORY_DROP_DIR)。"""
|
||||
return _path("FREIGHT_INVENTORY_DROP_DIR")
|
||||
"""RPA 库存 Excel 落盘目录(SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR)。"""
|
||||
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR")
|
||||
|
||||
|
||||
def inventory_processed_dir() -> Path | None:
|
||||
@@ -61,17 +60,17 @@ def inventory_processed_dir() -> Path | None:
|
||||
|
||||
def inventory_trigger_dir() -> Path | None:
|
||||
"""RPA 库存导出触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
|
||||
return _path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR")
|
||||
|
||||
|
||||
def upload_queue_dir() -> Path | None:
|
||||
"""货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。"""
|
||||
return _path("FREIGHT_UPLOAD_QUEUE_DIR")
|
||||
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR")
|
||||
|
||||
|
||||
def upload_trigger_dir() -> Path | None:
|
||||
"""RPA 货代上传触发 JSON 目录。"""
|
||||
return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
|
||||
return _path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR")
|
||||
|
||||
|
||||
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
|
||||
@@ -129,15 +128,27 @@ def write_inventory_export_batch_trigger(
|
||||
for source in sources:
|
||||
if not isinstance(source, dict) or not source.get("source_code"):
|
||||
continue
|
||||
# 调用方只持有非敏感快照;写 trigger 前在服务端按 Source 补入 Profile 密文。
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
configuration_test = str((payload or {}).get('trigger_type') or '') == 'configuration_test'
|
||||
trigger_source = get_rpa_trigger_inventory_source(
|
||||
str(source["source_code"]), enabled_only=not configuration_test,
|
||||
) or source
|
||||
source = {**source, **trigger_source}
|
||||
business_connector = str(source.get("connector_type") or "").strip().lower()
|
||||
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
|
||||
inventory_sources.append({
|
||||
"source_code": source.get("source_code"),
|
||||
"connector_type": source.get("connector_type"),
|
||||
"site_id": source.get("site_id"),
|
||||
"warehouse_id": source.get("warehouse_id"),
|
||||
"entry_url": source.get("entry_url"),
|
||||
"connector_type": business_connector,
|
||||
"worker_connector_type": worker_connector,
|
||||
"rpa_profile_code": source.get("rpa_profile_code"),
|
||||
"warehouse_id": source.get("fixed_warehouse_id") or source.get("warehouse_id"),
|
||||
"login_url": source.get("login_url"),
|
||||
"entry_url": source.get("login_url"),
|
||||
"navigation": source.get("navigation") or {},
|
||||
"parameters": source.get("parameters") or [],
|
||||
"query": source.get("query") or {},
|
||||
"credential_envelope": source.get("credential_envelope") or {},
|
||||
})
|
||||
if not inventory_sources:
|
||||
return None
|
||||
@@ -176,6 +187,16 @@ def write_inventory_export_trigger_for_task(
|
||||
|
||||
核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。
|
||||
"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source_code = str(rpa_source.get('source_code') or '').strip()
|
||||
rpa_source = get_rpa_trigger_inventory_source(source_code) or rpa_source
|
||||
# Legacy 单票 trigger 与 batch trigger 必须共享 worker 输入契约。
|
||||
rpa_source = dict(rpa_source)
|
||||
business_connector = str(rpa_source.get('connector_type') or '').strip().lower()
|
||||
rpa_source.setdefault('worker_connector_type', {'dbs': 'dsv360', 'crane': 'crane_footprint'}.get(business_connector, business_connector))
|
||||
rpa_source.setdefault('entry_url', rpa_source.get('login_url'))
|
||||
rpa_source.setdefault('credential_envelope', {})
|
||||
body = dict(payload or {})
|
||||
if inventory_rpa_batch_enabled():
|
||||
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
|
||||
|
||||
@@ -77,6 +77,8 @@ def _build_refs(
|
||||
run_purpose: str | None,
|
||||
intake_nos: list[str] | None = None,
|
||||
capability: str | None = None,
|
||||
temporary_inventory_asset_no: str | None = None,
|
||||
temporary_inventory_session_no: str | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""
|
||||
构建新版 agent_runtime_context.refs。
|
||||
@@ -111,6 +113,12 @@ def _build_refs(
|
||||
refs["intake_nos"] = json.dumps(normalized_intakes, ensure_ascii=False, separators=(",", ":"))
|
||||
if _clean_text(capability):
|
||||
refs["capability"] = _clean_text(capability)
|
||||
asset_no = _clean_text(temporary_inventory_asset_no).upper()
|
||||
if asset_no:
|
||||
refs["temporary_inventory_asset_no"] = asset_no
|
||||
session_no = _clean_text(temporary_inventory_session_no).upper()
|
||||
if session_no:
|
||||
refs["temporary_inventory_session_no"] = session_no
|
||||
return refs
|
||||
|
||||
|
||||
@@ -208,6 +216,8 @@ def build_shipping_runtime_context(
|
||||
run_purpose: str | None = None,
|
||||
intake_nos: list[str] | None = None,
|
||||
capability: str | None = None,
|
||||
temporary_inventory_asset_no: str | None = None,
|
||||
temporary_inventory_session_no: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构建货代发货通知 Agent 的 agent_runtime_context。
|
||||
@@ -226,6 +236,8 @@ def build_shipping_runtime_context(
|
||||
run_purpose: 本次 Dify run 的目的,如 parse_notice。
|
||||
intake_nos: 尚未建 Task 时的 Intake 编号集合。
|
||||
capability: 当前固定画布能力。
|
||||
temporary_inventory_asset_no: 本轮对话临时库存文件资产编号;仅供 Dify 调用受控 Tool。
|
||||
temporary_inventory_session_no: 已创建的临时库存会话编号。
|
||||
|
||||
Returns:
|
||||
agent_runtime_context 字典;session_id 为空时返回空 dict。
|
||||
@@ -253,6 +265,8 @@ def build_shipping_runtime_context(
|
||||
run_purpose=run_purpose,
|
||||
intake_nos=intake_nos,
|
||||
capability=capability,
|
||||
temporary_inventory_asset_no=temporary_inventory_asset_no,
|
||||
temporary_inventory_session_no=temporary_inventory_session_no,
|
||||
),
|
||||
domain=domain,
|
||||
reference_context=reference_context,
|
||||
|
||||
@@ -21,13 +21,11 @@ from typing import Any
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.task_line_store import read_task_order_lines
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_ALIGN_REVIEW,
|
||||
CP_EXPORT_READY,
|
||||
CP_EXPORT_GENERATED,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_CUSTOMER_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_READY_EXPORT,
|
||||
@@ -39,11 +37,9 @@ from app.services.shipping_notice.constants import (
|
||||
CP_UPLOAD_FAILED,
|
||||
CP_UPLOAD_REQ,
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_ALIGN_REVIEW,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_LOW_CONF,
|
||||
PH_MAP_INFER,
|
||||
PH_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
@@ -51,7 +47,6 @@ from app.services.shipping_notice.constants import (
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RPA_FAILED,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_ALIGN_REVIEW,
|
||||
RS_CONFIRMED,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_REJECTED,
|
||||
@@ -72,20 +67,12 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
|
||||
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
|
||||
"replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"},
|
||||
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
|
||||
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
|
||||
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
|
||||
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
|
||||
"retry_rpa": {"label": "重新获取库存", "message": "重新获取库存", "variant": "secondary"},
|
||||
"confirm_inventory_source": {"label": "确认库存源", "message": "确认库存查询来源", "variant": "primary"},
|
||||
"confirm_customer": {"label": "确认客户", "message": "选择并确认标准客户", "variant": "primary"},
|
||||
"retry_resolve_inventory_source": {"label": "重新判断", "message": "重新判断库存查询来源", "variant": "secondary"},
|
||||
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
|
||||
"upload_inventory_file": {
|
||||
"label": "选择库存文件",
|
||||
"message": "我要上传库存 Excel",
|
||||
"variant": "secondary",
|
||||
},
|
||||
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
|
||||
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
|
||||
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
|
||||
@@ -94,16 +81,6 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
"message": "已在货代系统手工上传完成",
|
||||
"variant": "primary",
|
||||
},
|
||||
"paste_inventory_json": {
|
||||
"label": "粘贴库存",
|
||||
"message": "我粘贴库存小表",
|
||||
"variant": "secondary",
|
||||
},
|
||||
"edit_inventory_mapping": {
|
||||
"label": "修改映射",
|
||||
"message": "修改库存列映射",
|
||||
"variant": "primary",
|
||||
},
|
||||
"match_inventory": {
|
||||
"label": "匹配库存",
|
||||
"message": "匹配库存",
|
||||
@@ -115,28 +92,14 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
|
||||
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
|
||||
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
|
||||
CP_CUSTOMER_REVIEW: ("confirm_customer",),
|
||||
CP_ALIGN_REVIEW: (
|
||||
"confirm_inventory_mapping",
|
||||
"correct_inventory_mapping",
|
||||
"reparse_inventory",
|
||||
"retry_rpa",
|
||||
"reject",
|
||||
),
|
||||
CP_MAP_INFER: (
|
||||
"edit_inventory_mapping",
|
||||
"upload_inventory_file",
|
||||
"paste_inventory_json",
|
||||
"retry_rpa",
|
||||
),
|
||||
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
|
||||
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa"),
|
||||
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa"),
|
||||
CP_INVENTORY_SOURCE_REVIEW: (
|
||||
"confirm_inventory_source",
|
||||
"retry_resolve_inventory_source",
|
||||
"upload_inventory_file",
|
||||
),
|
||||
CP_RSV_REQ: ("replace_notice_file", "reparse", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("reparse_inventory", "rematch", "reject"),
|
||||
RS_SHORTAGE_REVIEW: ("retry_rpa", "rematch", "reject"),
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
|
||||
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
|
||||
@@ -154,7 +117,7 @@ ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
|
||||
|
||||
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
|
||||
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
|
||||
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file")
|
||||
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("upload_inventory_file", "retry_rpa")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -211,7 +174,7 @@ def inventory_source_action_buttons(task: ShippingTask) -> list[dict[str, str]]:
|
||||
"variant": "primary",
|
||||
"source_code": source_code,
|
||||
},
|
||||
*build_action_buttons(["retry_resolve_inventory_source", "upload_inventory_file"]),
|
||||
*build_action_buttons(["retry_resolve_inventory_source"]),
|
||||
]
|
||||
return build_action_buttons(list(CHECKPOINT_REGISTRY[CP_INVENTORY_SOURCE_REVIEW]))
|
||||
|
||||
@@ -347,16 +310,6 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
|
||||
)
|
||||
|
||||
# [STEP 5] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。
|
||||
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_ALIGN_REVIEW,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
|
||||
)
|
||||
if reason == PH_MAP_INFER:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_MAP_INFER,
|
||||
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
|
||||
)
|
||||
if reason == PH_INV_UNAVAIL:
|
||||
return TaskUiState(
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
@@ -454,8 +407,6 @@ class TaskTransition(StrEnum):
|
||||
PARSED = "parsed"
|
||||
PARSE_NEEDS_REVIEW = "parse_needs_review"
|
||||
INVENTORY_READY = "inventory_ready"
|
||||
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
|
||||
MAP_INFER = "map_infer"
|
||||
RPA_EXHAUSTED = "rpa_exhausted"
|
||||
RPA_PENDING = "rpa_pending"
|
||||
INV_UNAVAIL = "inv_unavail"
|
||||
@@ -467,11 +418,6 @@ class TaskTransition(StrEnum):
|
||||
CLOSED = "closed"
|
||||
CONFIRM_PARSE = "confirm_parse"
|
||||
CONFIRM_MATCHED = "confirm_matched"
|
||||
ALIGN_REVIEW_HOLD = "align_review_hold"
|
||||
MAPPING_CONFIRMED = "mapping_confirmed"
|
||||
CORRECT_MAPPING = "correct_mapping"
|
||||
REPARSE_INVENTORY = "reparse_inventory"
|
||||
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
|
||||
NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
|
||||
REMATCH_REQUESTED = "rematch_requested"
|
||||
WAITING_UPLOAD = "waiting_upload"
|
||||
@@ -497,17 +443,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
pending_human_reason=None,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
|
||||
process_status="inventory_ready",
|
||||
review_status=RS_ALIGN_REVIEW,
|
||||
pending_human_reason=PH_ALIGN_REVIEW,
|
||||
clear_error_message=True,
|
||||
),
|
||||
TaskTransition.MAP_INFER: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_MAP_INFER,
|
||||
),
|
||||
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
@@ -563,28 +498,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
|
||||
review_status=RS_CONFIRMED,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec(
|
||||
review_status=RS_ALIGN_REVIEW,
|
||||
pending_human_reason=PH_ALIGN_REVIEW,
|
||||
),
|
||||
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
|
||||
process_status="waiting_inventory",
|
||||
review_status=None,
|
||||
pending_human_reason=PH_MAP_INFER,
|
||||
),
|
||||
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
|
||||
process_status="parsed",
|
||||
review_status=None,
|
||||
pending_human_reason=None,
|
||||
),
|
||||
TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec(
|
||||
process_status="pending_review",
|
||||
review_status=None,
|
||||
|
||||
@@ -44,6 +44,26 @@ def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
|
||||
return parsed
|
||||
|
||||
|
||||
def cfg_float(
|
||||
key: str,
|
||||
default: float = 0.0,
|
||||
*,
|
||||
min_value: float | None = None,
|
||||
max_value: float | None = None,
|
||||
) -> float:
|
||||
"""读取 Flask config 浮点值,并在异常配置时回退到安全默认值。"""
|
||||
val = current_app.config.get(key)
|
||||
try:
|
||||
parsed = float(default if val is None else val)
|
||||
except (TypeError, ValueError):
|
||||
parsed = default
|
||||
if min_value is not None:
|
||||
parsed = max(parsed, min_value)
|
||||
if max_value is not None:
|
||||
parsed = min(parsed, max_value)
|
||||
return parsed
|
||||
|
||||
|
||||
def auto_progress_enabled() -> bool:
|
||||
"""是否启用 auto_progress 自动推进(SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED)。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
|
||||
|
||||
@@ -65,15 +65,40 @@ confirm_customer = customer_identity_gate.confirm_customer
|
||||
|
||||
# 库存阶段
|
||||
ensure_inventory = inventory_workflow.ensure_inventory
|
||||
parse_inventory = inventory_workflow.parse_inventory
|
||||
get_inventory_schema_preview = inventory_workflow.get_inventory_schema_preview
|
||||
apply_inventory_mapping = inventory_workflow.apply_inventory_mapping
|
||||
upload_inventory_file = inventory_workflow.upload_inventory_file
|
||||
rpa_report_inventory = inventory_rpa_workflow.rpa_report_inventory
|
||||
rpa_report_inventory_batch = inventory_rpa_workflow.rpa_report_inventory_batch
|
||||
repair_task_inventory_attachment = inventory_rpa_workflow.repair_task_inventory_attachment
|
||||
confirm_inventory_source = inventory_rpa_workflow.confirm_inventory_source
|
||||
|
||||
|
||||
def create_temporary_inventory_session(payload: dict):
|
||||
"""创建对话上传库存候选会话;仅供 Dify 临时库存固定分支调用。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import create_temporary_inventory_session as _create
|
||||
|
||||
return _create(payload)
|
||||
|
||||
|
||||
def get_temporary_inventory_session(payload: dict):
|
||||
"""读取临时库存候选会话的脱敏结构预览;仅供 Dify 固定分支调用。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import get_temporary_inventory_session as _get
|
||||
|
||||
return _get(payload)
|
||||
|
||||
|
||||
def submit_temporary_inventory_mapping_suggestion(payload: dict):
|
||||
"""保存 Dify 临时库存映射候选;后端校验后仍须由用户确认。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import submit_temporary_inventory_mapping_suggestion as _submit
|
||||
|
||||
return _submit(payload)
|
||||
|
||||
|
||||
def confirm_temporary_inventory_use(payload: dict):
|
||||
"""确认当前会话临时库存使用并执行后端确定性质量校验。"""
|
||||
from app.services.shipping_notice.inventory_temporary_session import confirm_temporary_inventory_use as _confirm
|
||||
|
||||
return _confirm(payload)
|
||||
|
||||
# 履约阶段
|
||||
match_inventory = fulfillment_workflow.match_inventory
|
||||
generate_excel = fulfillment_workflow.generate_excel
|
||||
|
||||
@@ -13,12 +13,10 @@ from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_ALIGN_REVIEW,
|
||||
CP_COMPLETED,
|
||||
CP_EXPORT_READY,
|
||||
CP_INVENTORY_PENDING,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_MAP_INFER,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_PARSE_REVIEW,
|
||||
CP_READY_EXPORT,
|
||||
@@ -31,13 +29,11 @@ from app.services.shipping_notice.constants import (
|
||||
CP_WAITING_UPLOAD,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_MAP_INFER,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
PH_RSV_REQ,
|
||||
PH_SHORTAGE,
|
||||
PH_UPLOAD_RPA_PENDING,
|
||||
RS_ALIGN_REVIEW,
|
||||
RS_PARSE_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
)
|
||||
@@ -59,7 +55,7 @@ WORKFLOW_STEPS: tuple[dict[str, str], ...] = (
|
||||
{"id": "shipping-step-1", "code": "notice_submit", "label": "提交通知"},
|
||||
{"id": "shipping-step-2", "code": "parse_confirm", "label": "确认解析"},
|
||||
{"id": "shipping-step-3", "code": "inventory_prepare", "label": "获取库存"},
|
||||
{"id": "shipping-step-4", "code": "align_confirm", "label": "确认字段对齐"},
|
||||
{"id": "shipping-step-4", "code": "align_confirm", "label": "校验库存"},
|
||||
{"id": "shipping-step-5", "code": "match_inventory", "label": "匹配库存"},
|
||||
{"id": "shipping-step-6", "code": "generate_file", "label": "生成发货文件"},
|
||||
{"id": "shipping-step-7", "code": "upload_freight", "label": "上传货代"},
|
||||
@@ -86,7 +82,6 @@ _BLOCKED_CHECKPOINTS = {
|
||||
CP_PARSE_REVIEW,
|
||||
CP_RSV_REQ,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_ALIGN_REVIEW,
|
||||
RS_SHORTAGE_REVIEW,
|
||||
CP_NOTICE_TEXT_EXTRACTION_FAILED,
|
||||
CP_UPLOAD_REQ,
|
||||
@@ -119,12 +114,9 @@ def _derive_current_step_index(task: ShippingTask) -> int:
|
||||
return 4
|
||||
if review_status == RS_SHORTAGE_REVIEW or pending_reason == PH_SHORTAGE:
|
||||
return 4
|
||||
if review_status == RS_ALIGN_REVIEW or pending_reason == CP_ALIGN_REVIEW:
|
||||
return 3
|
||||
if process_status == "inventory_ready" or match_status:
|
||||
return 4
|
||||
if process_status == "waiting_inventory" or pending_reason in {
|
||||
PH_MAP_INFER,
|
||||
PH_RPA_PENDING,
|
||||
PH_INV_UNAVAIL,
|
||||
PH_RPA_EXHAUSTED,
|
||||
@@ -232,7 +224,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
|
||||
|
||||
核心逻辑:解析复核、RSV 缺失、库存源门禁、parse warnings 可能并发;
|
||||
以前仅透出 error_message(多为库存源),导致其它解析问题被吞掉。
|
||||
新顺序为先解析复核再库存源;存量 pending_parse_review_after_source 仍提示延后复核。
|
||||
"""
|
||||
checkpoint_value = str(checkpoint or "").strip()
|
||||
if checkpoint_value not in _PARSE_STAGE_CHECKPOINTS:
|
||||
@@ -277,12 +268,6 @@ def _collect_parse_stage_issues(task: ShippingTask, checkpoint: str | None) -> l
|
||||
if isinstance(item, dict):
|
||||
_append_unique_issue(issues, _parse_validation_issue_text(item))
|
||||
|
||||
# 存量兼容:旧顺序「先库存源后解析」延后的低置信度提示。
|
||||
if payload.get("pending_parse_review_after_source") or (
|
||||
checkpoint_value == CP_INVENTORY_SOURCE_REVIEW and task.review_status == RS_PARSE_REVIEW
|
||||
):
|
||||
_append_unique_issue(issues, "解析置信度不足,确认库存源后仍需复核解析结果。")
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
@@ -295,8 +280,6 @@ def _build_task_summary(task: ShippingTask, checkpoint: str | None) -> dict[str,
|
||||
CP_UPLOAD_REQ: "当前需要提供库存数据或重试库存获取。",
|
||||
CP_INVENTORY_PENDING: "发货通知已就绪,等待库存数据。",
|
||||
CP_INVENTORY_SOURCE_REVIEW: "库存源尚未确定,请先选择正式库存源。",
|
||||
CP_MAP_INFER: "库存列映射需要确认或重新选择。",
|
||||
CP_ALIGN_REVIEW: "库存字段对齐需要人工确认。",
|
||||
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
|
||||
CP_READY_MATCH: "库存已就绪,可以继续执行匹配。",
|
||||
CP_READY_EXPORT: "库存匹配已满足发货条件,可以生成发货文件。",
|
||||
|
||||
Loaded 100 of 320 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user