Merge branch 'hugo-shipping-notice' into dev
This commit is contained in:
commit
0e4e581f9a
89 files changed
+7559
-816
No files matched your search
@@ -29,7 +29,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
inventory_source_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
|
||||
# 收料不设独立启停:是否运行统一由库存站点 enabled 与本配置是否存在决定。
|
||||
# 收料文件解析规则(purpose='movement');定死领域字段端点。空则无法解析收料文件。
|
||||
parsing_profile_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_inventory_parsing_profiles.id'), nullable=True, index=True,
|
||||
@@ -40,10 +40,7 @@ class ShippingReceiptReportConfig(Base):
|
||||
query_parameters_json: Mapped[list[dict[str, Any]]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# DBS 可包含多个 Warehouse;Crane 固定 Inbound Details,保留空数组。
|
||||
warehouse_ids_json: Mapped[list[str]] = mapped_column(
|
||||
JSON, default=list, server_default=text("'[]'"), nullable=False,
|
||||
)
|
||||
# 与库存同构:Warehouse 是查询条件之一(支持多值),逐仓拆分在排程/触发时由该条件运行时派生,不单独持久化仓库清单。
|
||||
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
|
||||
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
updated_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
|
||||
@@ -67,19 +67,6 @@ def _json_object(data: dict[str, Any], field: str) -> dict[str, Any]:
|
||||
return dict(value)
|
||||
|
||||
|
||||
def _json_string_list(data: dict[str, Any], field: str) -> list[str]:
|
||||
"""读取非空、去重的字符串列表,供 Source 别名等业务配置使用。"""
|
||||
value = data.get(field, [])
|
||||
if not isinstance(value, list) or any(not isinstance(item, str) for item in value):
|
||||
raise ValidationError(f'{field} must be a string list', code='SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID')
|
||||
result: list[str] = []
|
||||
for item in value:
|
||||
normalized = item.strip()
|
||||
if normalized and normalized not in result:
|
||||
result.append(normalized)
|
||||
return result
|
||||
|
||||
|
||||
def _validate_profile_login_config(data: dict[str, Any]) -> dict[str, str]:
|
||||
"""校验连接级登录配置,不接收页面选择器或报表操作字段。"""
|
||||
value = data.get('login_config_json', {})
|
||||
@@ -269,19 +256,18 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
|
||||
'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
|
||||
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
|
||||
enabled = _bool(data, 'enabled', True)
|
||||
) -> tuple[dict[str, str], list[dict[str, Any]]]:
|
||||
"""规范收料配置,与库存同构:路径+查询条件;日期禁填,DBS 以 Warehouse 条件为逐仓拆分维度。"""
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
@@ -289,19 +275,22 @@ def _validate_receipt_report_config(
|
||||
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
|
||||
raw_path = _json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
if enabled and not raw_warehouses:
|
||||
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
return enabled, path, parameters, raw_warehouses
|
||||
# Warehouse 条件即逐仓拆分维度(不单独持久化仓库清单):必须恰一条且至少一个有效值。
|
||||
warehouse_conditions = [item for item in parameters if str(item.get('name') or '').strip().lower() == 'warehouse']
|
||||
warehouse_values = [str(value or '').strip() for value in (warehouse_conditions[0].get('values') or [])] if warehouse_conditions else []
|
||||
if len(warehouse_conditions) != 1 or not any(warehouse_values):
|
||||
raise ValidationError(
|
||||
'DBS receipt report requires exactly one Warehouse query condition with values',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return path, parameters
|
||||
if source.connector_type == 'crane':
|
||||
if raw_warehouses:
|
||||
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
@@ -309,7 +298,7 @@ def _validate_receipt_report_config(
|
||||
'Crane receipt report does not support query parameters',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return enabled, {'report_name': 'Inbound Details'}, [], []
|
||||
return {'report_name': 'Inbound Details'}, []
|
||||
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
@@ -327,7 +316,7 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
|
||||
path, parameters = _validate_receipt_report_config(source, data)
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
before = _receipt_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
@@ -337,10 +326,8 @@ def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.enabled = enabled
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.warehouse_ids_json = warehouses
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:file_preparation / erp_adapter / precheck_service / models。
|
||||
逻辑:默认实现 fail-closed —— 收料文件行读取(Q3 样例未冻结)与路由归属
|
||||
(Q1 规则未冻结)在真实契约冻结前拒绝执行;ERP SOAP 在 WSDL 冻结前拒绝。
|
||||
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile, ReceiptFileRepository
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
RouteNotResolvedError,
|
||||
@@ -21,28 +22,6 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
TransferDeps,
|
||||
)
|
||||
|
||||
RECEIPT_ROWS_NOT_FROZEN_CODE = "TRANSFER.RECEIPT_ROWS_NOT_FROZEN"
|
||||
|
||||
|
||||
class ReceiptRowsNotFrozenError(AppError):
|
||||
"""收料文件行读取契约未冻结(Q3:正式样例/Sheet/表头缺失)。"""
|
||||
|
||||
def __init__(self, message: str = "receipt file row contract not frozen"):
|
||||
super().__init__(code=RECEIPT_ROWS_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
"""默认收料 ready 文件仓库(只读复用 shipping 收料归档)。
|
||||
|
||||
行读取依赖收料文件正式样例契约(Q3);未冻结前 fail-closed。
|
||||
"""
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回最新 ready 文件;行内容契约未冻结时抛 ReceiptRowsNotFrozenError。"""
|
||||
raise ReceiptRowsNotFrozenError(
|
||||
"receipt file rows unfrozen: sample/sheet contract required (Q3)"
|
||||
)
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:来源固定仓 + 外部系统仓库映射。
|
||||
@@ -86,7 +65,7 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先,默认 fail-closed)。"""
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
@@ -98,21 +77,19 @@ def get_transfer_dependencies() -> TransferDeps:
|
||||
|
||||
|
||||
class _DefaultRpaTrigger:
|
||||
"""默认收料 RPA 触发器:复用既有收料 RPA trigger 目录。
|
||||
"""默认收料 RPA 触发器:委托真实触发服务(trigger_receipt_rpa)。
|
||||
|
||||
依赖来源配置(ShippingInventorySource + 收料报表配置);来源未启用或
|
||||
trigger 目录未配置时返回失败(fail-closed),不伪造等待。
|
||||
真实链路 = 落单元行 + 原子写 trigger 文件;来源/收料配置缺失或 trigger
|
||||
目录未配置时由触发服务返回 fail-closed(ok=False),本类只透传结果。
|
||||
"""
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
from flask import current_app
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
trigger_dir = str(
|
||||
current_app.config.get("SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR") or ""
|
||||
).strip()
|
||||
if not trigger_dir:
|
||||
return {"ok": False, "error_code": "RPA_TRIGGER_DIR_NOT_CONFIGURED"}
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
return {"ok": False, "error_code": "SOURCE_NOT_ENABLED"}
|
||||
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
|
||||
outcome = trigger_receipt_rpa(source_code=source_code, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": bool(outcome.get("ok")),
|
||||
"callback_id": outcome.get("callback_id"),
|
||||
"error_code": outcome.get("error_code"),
|
||||
"error_message": outcome.get("error_message"),
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、openpyxl。
|
||||
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行完整校验由下游 file_parser 完成。
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
|
||||
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
|
||||
file_parser 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -31,14 +33,14 @@ class ShippingReceiptFileRepository:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段名 dict)或 None。
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
return None
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is None or config.parsing_profile_id is None:
|
||||
return None
|
||||
profile = config.parsing_profile
|
||||
@@ -85,7 +87,8 @@ def _extract_movement_rows(
|
||||
"""从 xlsx 字节按 movement field_mapping 提取领域行 dict。
|
||||
|
||||
field_mapping: {定死领域字段 code: Excel 表头别名}(端点必须是 MOVEMENT_FIELDS 的 code)。
|
||||
输出以领域字段 code 为 key 的行,供 file_parser.parse_movement_rows 校验。
|
||||
输出以领域字段 code 为 key 的行,并附带溯源字段(sheet=实际使用的工作表标题、
|
||||
row_no=数据行在工作表中的真实 1-based 行号),供 file_parser.parse_movement_rows 校验。
|
||||
"""
|
||||
from openpyxl import load_workbook
|
||||
from app.services.shipping_notice.inventory_snapshot import find_inventory_header_row_index
|
||||
@@ -112,7 +115,15 @@ def _extract_movement_rows(
|
||||
data_rows = [list(r) for r in raw_rows[header_idx + 1:] if r]
|
||||
|
||||
header_to_code = {str(alias).strip(): str(code).strip() for code, alias in field_mapping.items()}
|
||||
return [_map_header_row(headers, row, header_to_code) for row in data_rows]
|
||||
# 溯源字段:sheet 取实际使用的工作表标题;row_no 为数据行在工作表中的真实
|
||||
# 1-based 行号(表头在第 header_idx+1 行,第 offset 个数据行 = header_idx+2+offset),
|
||||
# 使下游 RawLineRef 证据引用指向真实电子表格行,并满足 parse_movement_rows 行校验。
|
||||
sheet_title = str(ws.title or '').strip()
|
||||
return [
|
||||
{"sheet": sheet_title, "row_no": header_idx + 2 + offset,
|
||||
**_map_header_row(headers, row, header_to_code)}
|
||||
for offset, row in enumerate(data_rows)
|
||||
]
|
||||
|
||||
|
||||
def _map_header_row(headers: list[str], row: list[Any], header_to_code: dict[str, str]) -> dict[str, Any]:
|
||||
|
||||
@@ -37,6 +37,7 @@ from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_movement_rows,
|
||||
parse_receipt_rows,
|
||||
)
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
@@ -188,7 +189,9 @@ def run_precheck(
|
||||
"file_version": ready_file.file_version,
|
||||
"checksum": ready_file.checksum,
|
||||
}
|
||||
parsed = parse_receipt_rows(source_code=source_code, rows=ready_file.rows)
|
||||
# 真实仓库(movement_file_repository)产出 movement 领域字段行
|
||||
# (doc_no/material_code/quantity/movement_date),按异动解析规则映射校验。
|
||||
parsed = parse_movement_rows(source_code=source_code, rows=ready_file.rows)
|
||||
invoices = aggregate_invoices(parsed, file_version=ready_file.file_version)
|
||||
source_items = _precheck_invoices(
|
||||
invoices=invoices,
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import TransferSourceJob
|
||||
@@ -55,3 +55,33 @@ def advance_source_job_from_receipt_callback(
|
||||
job.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
return job
|
||||
|
||||
|
||||
def recover_stale_waiting_source_jobs() -> int:
|
||||
"""把超过收料回调超时仍 waiting_rpa_callback 的调拨来源任务回收为 failed。
|
||||
|
||||
【AI 触发时机】:仅由排程队列周期扫描(queue_service)与收料超时回收同批调用;
|
||||
不自动重试 RPA——用户可在来源选择卡手动重试(与收料回收"绝不自动重试"口径一致)。
|
||||
Returns:
|
||||
本次回收的任务数。
|
||||
"""
|
||||
from flask import current_app
|
||||
|
||||
try:
|
||||
timeout = max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
timeout = 900
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout)
|
||||
stale = (
|
||||
TransferSourceJob.query
|
||||
.filter(TransferSourceJob.status == _WAITING_RPA_CALLBACK, TransferSourceJob.updated_at < cutoff)
|
||||
.all()
|
||||
)
|
||||
for job in stale:
|
||||
job.status = _FAILED
|
||||
job.error_code = 'RPA_RECEIPT_CALLBACK_TIMEOUT'
|
||||
job.error_message = f'receipt rpa callback not received within {timeout}s'
|
||||
job.finished_at = datetime.utcnow()
|
||||
if stale:
|
||||
db.session.commit()
|
||||
return len(stale)
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
||||
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
||||
装配收料 trigger unit,调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_receipt_export_batch_trigger(默认 writer)、models。
|
||||
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
||||
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
依赖:write_receipt_export_batch_trigger(默认 writer)、models、db。
|
||||
逻辑:来源停用/收料配置缺失/rpa_profile 缺失时 fail-closed(返回 ok=False),绝不伪造等待;
|
||||
写 trigger writer 可注入替身(测试)。
|
||||
写 trigger 失败把单元行标 failed 并 commit;写 trigger writer 可注入替身(测试)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,27 +24,29 @@ def _build_trigger_unit(
|
||||
) -> dict[str, Any]:
|
||||
"""装配单来源收料 trigger unit;配置缺失时抛 RuntimeError(由调用方转 fail-closed)。"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RuntimeError(f'source not enabled: {source_code}')
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id, enabled=True).first()
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).first()
|
||||
if config is None:
|
||||
raise RuntimeError(f'receipt config missing: {source_code}')
|
||||
profile = source.rpa_profile
|
||||
if profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {source_code}')
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
warehouse_id = str(warehouses[0]) if warehouses else None
|
||||
# Warehouse 条件即逐仓拆分维度:按需触发取第一个仓,单元快照剥离 Warehouse 条件。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
warehouse_id = str(warehouses[0]) if warehouses and warehouses[0] else None
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version,
|
||||
'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'query_parameters_json': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return {
|
||||
'unit_run_id': 0,
|
||||
'inventory_source_id': source.id,
|
||||
'callback_id': f'receipt:{uuid.uuid4().hex}',
|
||||
'source_code': source.source_code,
|
||||
'connector_type': source.connector_type,
|
||||
@@ -71,7 +74,7 @@ def trigger_receipt_rpa(
|
||||
reason: str = 'transfer_retry_receipt',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""触发一次来源收料 RPA 抓取。
|
||||
"""触发一次来源收料 RPA 抓取(先落单元行再写 trigger,保证回调可达)。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
@@ -83,13 +86,33 @@ def trigger_receipt_rpa(
|
||||
{"ok": False, "error_code": ...}(配置缺失 / 触发目录不可用)。
|
||||
"""
|
||||
try:
|
||||
unit = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
|
||||
unit_payload = _build_trigger_unit(source_code=source_code, business_date=business_date, reason=reason)
|
||||
except RuntimeError as exc:
|
||||
return {"ok": False, "error_code": "RPA_RECEIPT_CONFIG_MISSING", "error_message": str(exc)}
|
||||
|
||||
# [STEP 1] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库,
|
||||
# 不落行则回调必然 404(与排程路径 _build_unit 同一模式)。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, # 调拨触发无 ScheduleRun,沿用 0 占位约定
|
||||
inventory_source_id=unit_payload['inventory_source_id'],
|
||||
source_code=unit_payload['source_code'],
|
||||
connector_type=unit_payload['connector_type'],
|
||||
warehouse_id=unit_payload.get('warehouse_id'),
|
||||
callback_id=unit_payload['callback_id'],
|
||||
status='awaiting_rpa',
|
||||
config_snapshot_json=dict(unit_payload['config_snapshot']),
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.flush()
|
||||
unit_payload['unit_run_id'] = unit.id
|
||||
|
||||
# [STEP 2] 原子写 trigger;目录不可用则单元标 failed(fail-closed,不留永久 awaiting)。
|
||||
run_no = f"TRIG-{source_code}-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
path = writer_fn(run_no, [unit], payload={
|
||||
path = writer_fn(run_no, [unit_payload], payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'source_code': source_code,
|
||||
@@ -97,5 +120,13 @@ def trigger_receipt_rpa(
|
||||
'reason': reason,
|
||||
})
|
||||
if not path:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'receipt trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE"}
|
||||
return {"ok": True, "callback_id": unit['callback_id'], "trigger_path": path}
|
||||
|
||||
# [STEP 3] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
unit.trigger_snapshot_json = unit_payload
|
||||
db.session.commit()
|
||||
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
||||
@@ -7,7 +7,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
from app.services.shipping_notice.receipt_rpa import receipt_unit_parameters, receipt_warehouse_values, write_receipt_export_batch_trigger
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
@@ -28,7 +28,7 @@ def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource,
|
||||
wanted = _wanted_source_codes(task)
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).all()
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportCo
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': receipt_unit_parameters(config),
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
@@ -78,7 +78,8 @@ def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
for source, config in _eligible_sources(task):
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
# Warehouse 条件即逐仓拆分维度:运行时从条件派生仓库清单,不读取持久化列表。
|
||||
warehouses = receipt_warehouse_values(config) if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
|
||||
@@ -57,7 +57,7 @@ def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
).filter(ShippingInventorySource.enabled.is_(True)).all()
|
||||
return [{
|
||||
'label': source.display_name or source.source_code, 'value': source.source_code,
|
||||
'description': f'{source.connector_type} · 收料已配置',
|
||||
|
||||
@@ -371,6 +371,14 @@ def prepare_schedule_queue() -> int:
|
||||
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
|
||||
_worker_initialized = True
|
||||
|
||||
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
|
||||
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||||
|
||||
transfer_stale = recover_stale_waiting_source_jobs()
|
||||
if transfer_stale:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
services/shipping_notice/effective_order_view.py
|
||||
|
||||
用途:向履约链提供「冻结快照 + 冻结后人工修正」的有效订单值视图。
|
||||
依赖:export.order_field_id_values(冻结投影)、ShippingOrderFieldValue/ShippingOrderLine/
|
||||
ShippingOrderTask/ShippingOrderSnapshot(修正事实与行对位)。
|
||||
逻辑:快照仍是审计锚点,本模块把当前 accepted Extraction 的 FieldValue 按(行 position × field_id)
|
||||
对位叠加到快照投影上,供库存匹配、Excel 导出与 Notice 行物化统一消费;整行替换(增删行)
|
||||
后 position 不再可比,行级叠加保守跳过(保持冻结值),由后续行集有效视图统一承接。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.shipping_notice.export import order_field_id_values
|
||||
|
||||
|
||||
def _owner_task(task: Any) -> Any:
|
||||
"""与 export.order_field_id_values 同源的任务归属解析(Notice → OT;OT 原样返回)。"""
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id:
|
||||
return db.session.get(ShippingOrderTask, order_task_id)
|
||||
return task
|
||||
|
||||
|
||||
def effective_order_field_values(task: Any) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""
|
||||
返回叠加了冻结后人工修正的订单 Header/Line 有效值(形状同 order_field_id_values)。
|
||||
|
||||
核心逻辑:以冻结快照为基线;当前 accepted Extraction 的 FieldValue 按(行 position ×
|
||||
field_id)对位覆盖。当前 Extraction 与快照 Extraction 不同(发生过整行替换)时跳过
|
||||
行级叠加,避免错位污染匹配键;单头值不受行替换影响,始终叠加最新已接受值。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 或 ShippingOrderTask。
|
||||
Returns:
|
||||
(header dict[field_id, value], lines list[dict[field_id, value]])。
|
||||
"""
|
||||
header, lines = order_field_id_values(task)
|
||||
owner = _owner_task(task)
|
||||
current_id = getattr(owner, 'current_order_extraction_id', None)
|
||||
if current_id is None:
|
||||
return header, lines
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
header = dict(header)
|
||||
lines = [dict(row) for row in lines]
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=int(current_id)).all()
|
||||
# [STEP 1] 单头修正:整行替换会把单头决定复制到新 Extraction(见 task_order_field_editor),
|
||||
# 因此单头值始终以当前 Extraction 的已接受值为准。
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
header[str(item.field_id)] = item.value_json
|
||||
# [STEP 2] 行级修正:仅在当前 Extraction 即冻结来源 Extraction 时按 position 对位。
|
||||
if snapshot is not None and int(current_id) == int(snapshot.extraction_id):
|
||||
position_by_line_id = {
|
||||
int(row.id): int(row.position)
|
||||
for row in ShippingOrderLine.query.filter_by(extraction_id=int(current_id)).all()
|
||||
}
|
||||
overlay_by_index: dict[int, dict[str, Any]] = {}
|
||||
for item in values:
|
||||
if item.line_id is None:
|
||||
continue
|
||||
index = position_by_line_id.get(int(item.line_id))
|
||||
if index is None:
|
||||
continue
|
||||
overlay_by_index.setdefault(index, {})[str(item.field_id)] = item.value_json
|
||||
for index, row in enumerate(lines):
|
||||
row.update(overlay_by_index.get(index, {}))
|
||||
return header, lines
|
||||
|
||||
|
||||
def _coerce_qty(value: Any) -> Decimal | None:
|
||||
"""把字段值安全转为数量;空/非法值返回 None。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
try:
|
||||
return Decimal(str(value).replace(',', '').strip())
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def effective_line_facts_for_notice(owner: ShippingOrderTask) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
按 snapshot_line_id 返回 Notice 行物化所需的有效事实(强类型键 + 完整字段值)。
|
||||
|
||||
核心逻辑:经 effective_order_field_values 取有效值后,按冻结履约规则的
|
||||
required_field_ids 把 part_number/reservation_id/qty 三个用途键解析为强类型事实;
|
||||
缺少规则映射时对应键为 None(由消费方回退冻结列)。
|
||||
|
||||
Args:
|
||||
owner: 已冻结订单的 ShippingOrderTask。
|
||||
Returns:
|
||||
{snapshot_line_id: {'part_number', 'reservation_id', 'qty', 'field_values'}}。
|
||||
Raises:
|
||||
ValueError: 任务没有冻结快照。
|
||||
"""
|
||||
snapshot = (
|
||||
db.session.get(ShippingOrderSnapshot, int(owner.order_snapshot_id))
|
||||
if getattr(owner, 'order_snapshot_id', None) else None
|
||||
)
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于通知行物化的冻结订单快照')
|
||||
_header, lines = effective_order_field_values(owner)
|
||||
required_ids = (snapshot.rule_versions_json or {}).get('fulfillment_rule', {}).get('required_field_ids')
|
||||
required_ids = required_ids if isinstance(required_ids, dict) else {}
|
||||
part_fid = str(required_ids.get('part_number') or '')
|
||||
rsv_fid = str(required_ids.get('reservation_id') or '')
|
||||
qty_fid = str(required_ids.get('qty') or '')
|
||||
facts: dict[int, dict[str, Any]] = {}
|
||||
for line_orm, values in zip(snapshot.lines, lines, strict=True):
|
||||
facts[int(line_orm.id)] = {
|
||||
'part_number': values.get(part_fid) if part_fid else None,
|
||||
'reservation_id': values.get(rsv_fid) if rsv_fid else None,
|
||||
'qty': _coerce_qty(values.get(qty_fid)) if qty_fid else None,
|
||||
'field_values': dict(values),
|
||||
}
|
||||
return facts
|
||||
@@ -142,7 +142,10 @@ def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。
|
||||
|
||||
库存匹配/Excel 消费方应改用 effective_order_view.effective_order_field_values 获取含冻结后修正的有效值。
|
||||
"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
|
||||
@@ -779,7 +782,8 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
header_values, all_line_values = effective_order_field_values(task)
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
@@ -814,6 +818,26 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
# [STEP 1] 已结案(close_unfulfillable)行不再有履约要求:即使预约仍有库存,
|
||||
# 也必须从滚动导出资格中剔除(与上方放行查询同源同口径:只认活动决定)。
|
||||
closed_snapshot_line_ids = set()
|
||||
if source_notice.id is not None:
|
||||
closed_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
closed_snapshot_line_ids = {
|
||||
int(snapshot.lines[int(decision.line_index)].id)
|
||||
for decision in closed_rows
|
||||
if decision.line_index is not None
|
||||
and 0 <= int(decision.line_index) < len(snapshot.lines)
|
||||
}
|
||||
selected_snapshot_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
|
||||
@@ -824,6 +848,7 @@ def prepare_export_match_inputs(task: ShippingNotice) -> dict[str, Any]:
|
||||
source_notice,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
closed_snapshot_line_ids=closed_snapshot_line_ids,
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
|
||||
@@ -718,12 +718,47 @@ def _released_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
}
|
||||
|
||||
|
||||
def _closed_snapshot_line_ids_for_task(task: ShippingNotice) -> set[int]:
|
||||
"""读取当前任务已结案(close_unfulfillable)的冻结行 ID,供满足性与聚合豁免共用。
|
||||
|
||||
核心逻辑:与 ``_released_snapshot_line_ids_for_task`` 同源同口径——只认活动决定,
|
||||
经 line_index 映射快照行;结案行不再是履约要求,在满足性/建单/导出各处按豁免处理。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
if task.id is None:
|
||||
return set()
|
||||
if not getattr(task, 'order_snapshot_id', None):
|
||||
return set()
|
||||
decisions = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'close_unfulfillable',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
from app.models import ShippingOrderSnapshot
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if snapshot is None:
|
||||
return set()
|
||||
return {
|
||||
int(snapshot.lines[int(row.line_index)].id)
|
||||
for row in decisions
|
||||
if row.line_index is not None
|
||||
and 0 <= int(row.line_index) < len(snapshot.lines)
|
||||
}
|
||||
|
||||
|
||||
def match_completed(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
|
||||
|
||||
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
|
||||
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
|
||||
已人工放行的短缺行视同满足;已结案(close_unfulfillable)行不再是履约要求,
|
||||
从覆盖校验与逐行判定中双重豁免;全部行结案时无剩余履约内容,按不通过处理。
|
||||
"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
@@ -738,17 +773,23 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
if getattr(task, 'order_snapshot_id', None) else None
|
||||
)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []}
|
||||
closed_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
expected_line_ids = {int(line.id) for line in getattr(snapshot, 'lines', []) or []} - closed_ids
|
||||
if not expected_line_ids:
|
||||
# 全部行已结案:订单无剩余履约内容,不得自动进入建通知/Excel(应走作废流程)。
|
||||
return False
|
||||
current_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in rows
|
||||
if getattr(row, 'snapshot_line_id', None) is not None
|
||||
}
|
||||
# 满足性必须覆盖冻结订单的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if expected_line_ids and current_line_ids != expected_line_ids:
|
||||
} - closed_ids
|
||||
# 满足性必须覆盖剩余待履约的全部项次;仅有部分当前 Match 不能代表整单可履约。
|
||||
if current_line_ids != expected_line_ids:
|
||||
return False
|
||||
released_ids = _released_snapshot_line_ids_for_task(task)
|
||||
for row in rows:
|
||||
if getattr(row, 'snapshot_line_id', None) is not None and int(row.snapshot_line_id) in closed_ids:
|
||||
continue
|
||||
result = str(row.match_result or '').strip()
|
||||
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
|
||||
if result == 'matched' and shortage <= 0:
|
||||
@@ -823,6 +864,7 @@ def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
return set()
|
||||
@@ -1344,6 +1386,8 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
|
||||
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
|
||||
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
|
||||
已结案(close_unfulfillable)行不再是履约要求:不阻断、不进缺货列表,
|
||||
但也不计入满足(结案行非可履约内容),全结案 ⇒ unfulfillable,与 match_completed 口径一致。
|
||||
"""
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
@@ -1353,6 +1397,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
if not rows:
|
||||
return 'unfulfillable', []
|
||||
released_snapshot_line_ids = _released_snapshot_line_ids_for_task(task)
|
||||
closed_snapshot_line_ids = _closed_snapshot_line_ids_for_task(task)
|
||||
has_ok = False
|
||||
has_block = False
|
||||
shortages: list[dict[str, Any]] = []
|
||||
@@ -1378,7 +1423,12 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
|
||||
shortage = _line_shortage_qty(shortage_qty)
|
||||
released = entry['snapshot_line_id'] in released_snapshot_line_ids
|
||||
if match_result == 'matched' and shortage <= 0:
|
||||
closed = entry['snapshot_line_id'] in closed_snapshot_line_ids
|
||||
if closed:
|
||||
# [BE-结案-豁免] 结案行不再是履约要求:不阻断、不进缺货列表,
|
||||
# 但也不计入满足(非可履约内容);全结案 ⇒ 无可履约内容 ⇒ unfulfillable。
|
||||
entry['line_status'] = 'closed'
|
||||
elif match_result == 'matched' and shortage <= 0:
|
||||
entry['line_status'] = 'ok'
|
||||
has_ok = True
|
||||
elif released and shortage > 0:
|
||||
@@ -1390,21 +1440,25 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
|
||||
has_block = True
|
||||
shortages.append(entry)
|
||||
line_results.append(entry)
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': 'partial' if has_block and has_ok else ('unfulfillable' if has_block else 'fulfillable'),
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
# 结案行既不计满足也不阻断:无 ok 且无 block(如全结案)时无可履约内容 ⇒ unfulfillable,
|
||||
# 与 match_completed 的整单口径保持一致,避免 Gate 同步误判满足后空转编排。
|
||||
if has_block and has_ok:
|
||||
status = 'partial'
|
||||
elif has_block:
|
||||
status = 'unfulfillable'
|
||||
else:
|
||||
elif has_ok:
|
||||
status = 'fulfillable'
|
||||
else:
|
||||
status = 'unfulfillable'
|
||||
owner = _workflow_owner(task)
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
payload = dict(owner.step_payload_json or {})
|
||||
payload['current_match_projection'] = {
|
||||
'match_status': status,
|
||||
'line_results': line_results,
|
||||
'shortage': {'lines': shortages},
|
||||
}
|
||||
owner.step_payload_json = payload
|
||||
return status, shortages
|
||||
|
||||
|
||||
@@ -1615,7 +1669,11 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if lang:
|
||||
inv_payload["lang"] = lang
|
||||
return ensure_inventory(inv_payload)
|
||||
_order_header_values, order_field_lines = order_field_id_values(task)
|
||||
# [STEP 2] 兜底匹配基线读取有效视图(冻结快照 + 冻结后人工修正):
|
||||
# 匹配身份键(料号/预约等字段值)必须与展示值(__required_qty/__display_part_number)
|
||||
# 同源,否则出现"按冻结料号匹配、却展示有效料号"的混合投影。
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
_order_header_values, order_field_lines = effective_order_field_values(task)
|
||||
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
|
||||
for index, order_line in enumerate(order_field_lines):
|
||||
purpose_line = purpose_lines[index] if index < len(purpose_lines) else {}
|
||||
@@ -2039,6 +2097,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
_verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
closed_snapshot_line_ids=_closed_snapshot_line_ids_for_task(task),
|
||||
)
|
||||
except ConflictError:
|
||||
available_line_ids = set()
|
||||
|
||||
@@ -508,6 +508,26 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str,
|
||||
return out
|
||||
|
||||
|
||||
def load_current_match_facts_by_line_index(task_id: int | None) -> dict[int, dict[str, Any]]:
|
||||
"""按 line_index 索引当前匹配事实(Case 履约投影专用)。
|
||||
|
||||
核心逻辑:与 load_current_match_facts_by_task 同一查询;Case 草稿行只有
|
||||
_line_index 没有 snapshot_line_id,必须按行号索引才能关联上事实。
|
||||
"""
|
||||
if task_id is None:
|
||||
return {}
|
||||
rows = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task_id), is_current=True)
|
||||
.all()
|
||||
)
|
||||
return {
|
||||
int(row.line_index): serialize_match_fact(row)
|
||||
for row in rows
|
||||
if row.line_index is not None
|
||||
}
|
||||
|
||||
|
||||
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
|
||||
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
|
||||
facts = list(load_current_match_facts_by_task(task_id).values())
|
||||
|
||||
@@ -21,6 +21,7 @@ def replace_notice_lines_from_snapshot(
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
snapshot_line_ids: set[int] | None = None,
|
||||
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
|
||||
line_overrides: dict[int, dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
@@ -29,6 +30,10 @@ def replace_notice_lines_from_snapshot(
|
||||
notice_id: shipping_notices.id。
|
||||
snapshot: 已 flush 且带 lines 的 Snapshot。
|
||||
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
|
||||
inventory_facts_by_snapshot_line_id: 行级库存事实(来源/文件/仓库)。
|
||||
line_overrides: effective_order_view.effective_line_facts_for_notice 的输出,
|
||||
按 snapshot_line_id 携带冻结后人工修正;仅非 None 值覆盖快照列,
|
||||
缺失或 None 时回退冻结快照值。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
@@ -44,6 +49,7 @@ def replace_notice_lines_from_snapshot(
|
||||
continue
|
||||
notice_position += 1
|
||||
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
|
||||
override = (line_overrides or {}).get(int(line.id)) or {}
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
@@ -51,13 +57,17 @@ def replace_notice_lines_from_snapshot(
|
||||
position=notice_position - 1,
|
||||
# 发货通知项次按当前通知单重新从 1 编排。
|
||||
line_no=notice_position,
|
||||
part_number=getattr(line, 'part_number', None),
|
||||
reservation_id=getattr(line, 'reservation_id', None),
|
||||
required_qty=getattr(line, 'qty', None),
|
||||
part_number=override.get('part_number')
|
||||
if override.get('part_number') is not None else getattr(line, 'part_number', None),
|
||||
reservation_id=override.get('reservation_id')
|
||||
if override.get('reservation_id') is not None else getattr(line, 'reservation_id', None),
|
||||
required_qty=override.get('qty')
|
||||
if override.get('qty') is not None else getattr(line, 'qty', None),
|
||||
inventory_source_code=inventory_facts.get('inventory_source_code'),
|
||||
inventory_file_id=inventory_facts.get('inventory_file_id'),
|
||||
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
|
||||
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
|
||||
field_values_json=dict(override['field_values'])
|
||||
if override.get('field_values') else dict(getattr(line, 'field_values_json', None) or {}),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/order_field_purposes.py
|
||||
|
||||
用途:将冻结订单 Snapshot 按冻结货代策略能力投影给履约链。
|
||||
依赖:冻结履约策略、export.order_field_id_values、ShippingNotice。
|
||||
依赖:冻结履约策略、effective_order_view.effective_order_field_values、ShippingNotice。
|
||||
逻辑:路由、门禁、匹配和展示只通过固定规则冻结的 stable field_id 定位字段,禁止读取 Schema business_purpose 或任务行固定列。
|
||||
"""
|
||||
|
||||
@@ -12,7 +12,8 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingNotice
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
|
||||
_PURPOSE_BY_CAPABILITY = {
|
||||
@@ -47,9 +48,9 @@ def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | No
|
||||
|
||||
|
||||
def task_line_purpose_values(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""按订单行位置返回用途键值,值只来自冻结 Snapshot。"""
|
||||
"""按订单行位置返回用途键值,值来自冻结 Snapshot 叠加冻结后人工修正的有效视图(effective_order_view)。"""
|
||||
purpose_ids = task_line_purpose_field_ids(task, required=required)
|
||||
_header, lines = order_field_id_values(task)
|
||||
_header, lines = effective_order_field_values(task)
|
||||
return [
|
||||
{purpose: line.get(field_id) for purpose, field_id in purpose_ids.items()}
|
||||
for line in lines
|
||||
|
||||
@@ -426,12 +426,20 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
|
||||
]
|
||||
|
||||
|
||||
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
|
||||
def _sync_confirmed_task_fulfillment_gates(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_id: int,
|
||||
trigger: str = 'inventory_shortage_released',
|
||||
) -> None:
|
||||
"""
|
||||
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
短缺放行/行结案后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
|
||||
|
||||
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
|
||||
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
|
||||
|
||||
Args:
|
||||
trigger: 编排触发标签(放行 inventory_shortage_released / 结案 line_fulfillment_closed)。
|
||||
"""
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
if task_id is None:
|
||||
@@ -469,7 +477,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
submit_auto_progress(
|
||||
task=task,
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
operator_id=actor_id,
|
||||
commit=False,
|
||||
)
|
||||
@@ -480,7 +488,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
|
||||
|
||||
enqueue_post_ot_auto_fulfill_job(
|
||||
task_no=str(task.task_no),
|
||||
trigger='inventory_shortage_released',
|
||||
trigger=trigger,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
@@ -763,7 +771,6 @@ def project_review_case_line_decisions(
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
line_auto_fulfill_enabled,
|
||||
load_current_match_facts_by_task,
|
||||
project_line_inventory_view,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
@@ -810,7 +817,11 @@ def project_review_case_line_decisions(
|
||||
'status': 'resolving',
|
||||
'source': 'inventory_source_clue',
|
||||
}
|
||||
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
|
||||
# [BE-键修复] Case 草稿行只有 _line_index;补一条按行号索引的事实通道。
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
load_current_match_facts_by_line_index,
|
||||
)
|
||||
match_facts_by_line = load_current_match_facts_by_line_index(formal_ot.get('task_id'))
|
||||
labels = dict(source_labels or {})
|
||||
if not labels:
|
||||
draft = getattr(case, 'current_draft', None)
|
||||
@@ -835,7 +846,12 @@ def project_review_case_line_decisions(
|
||||
decision = by_key.get(key)
|
||||
# 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留
|
||||
# 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。
|
||||
fact = match_facts.get(key)
|
||||
# [BE-键修复] 草稿行只有 _line_index;旧实现误用 draft_line_id 查 snapshot_line_id 键,恒 miss。
|
||||
line_index = draft_line.get('_line_index')
|
||||
fact = (
|
||||
match_facts_by_line.get(int(line_index))
|
||||
if line_index is not None else None
|
||||
)
|
||||
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
|
||||
fulfill_proj = dict(proj)
|
||||
if isinstance(fact, dict):
|
||||
@@ -1083,7 +1099,7 @@ def decide_review_line_fulfillment(
|
||||
case_no: Case 编号。
|
||||
draft_line_id: 草稿行键。
|
||||
decision_code: 决定码。
|
||||
reason: 关闭/重开/短缺放行必填原因。
|
||||
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
||||
expected_draft_version: 可选草稿乐观锁。
|
||||
actor_is_admin: 是否管理员(重开授权)。
|
||||
@@ -1098,7 +1114,9 @@ def decide_review_line_fulfillment(
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_INVALID',
|
||||
details={'decision_code': code},
|
||||
)
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN, DECISION_RELEASE_SHORTAGE} and not str(reason or '').strip():
|
||||
# [BE-放行免因] 短缺放行不强制原因:人工放行事实已由审计链完整记录
|
||||
# (操作人 + 时间 + 决定快照 release_field_values);结案/重开仍要求原因。
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN} and not str(reason or '').strip():
|
||||
raise ValidationError(
|
||||
'Reason is required',
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_REASON_REQUIRED',
|
||||
@@ -1239,8 +1257,13 @@ def decide_review_line_fulfillment(
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
|
||||
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
|
||||
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=case,
|
||||
actor_id=int(user_id),
|
||||
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
@@ -914,14 +914,12 @@ AUDIT_SNAPSHOT_ALLOWED_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'snapshot_after_ref',
|
||||
'path_id_hash',
|
||||
'revision_no',
|
||||
# 独立收料报表配置快照:路径、受控条件与仓库清单均不含 selector、凭据或日期筛选。
|
||||
# 独立收料报表配置快照:路径与受控条件(含 Warehouse 拆分条件)均不含 selector、凭据、日期筛选或启停字段。
|
||||
'inventory_source_id',
|
||||
'connector_type',
|
||||
'enabled',
|
||||
'config_version',
|
||||
'report_path_json',
|
||||
'query_parameters_json',
|
||||
'warehouse_ids_json',
|
||||
'file_id',
|
||||
'recipient_user_id',
|
||||
'message_type',
|
||||
|
||||
@@ -1468,8 +1468,8 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
order_task_id → ShippingOrderTask。有 OT 时用领域事实映射为
|
||||
shipping_processing_status(与 shipping_processing_projection 同源),
|
||||
并注入 shipping_processing_stage / progress_version / order_task_no;
|
||||
另附带 review_run_no / owner_agent_id / conversation_id(经 OT.extraction_run),
|
||||
供任务中心「进入订单处理」深链。
|
||||
另附带 review_run_no / review_case_no / owner_agent_id / conversation_id(经 OT.extraction_run
|
||||
与 OT 反查确认 Case),供任务中心「进入订单处理」深链。
|
||||
|
||||
Args:
|
||||
task: ShippingNotice 或 ShippingOrderTask。
|
||||
@@ -1517,6 +1517,19 @@ def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]
|
||||
data['conversation_id'] = cid
|
||||
if data.get('owner_agent_id') is None and getattr(run, 'owner_agent_id', None) is not None:
|
||||
data['owner_agent_id'] = int(run.owner_agent_id)
|
||||
# [STEP 3] 注入确认 Case 号:工作台以 case_no 绑定工作项,OT 直链缺失该字段时
|
||||
# 选法 2 不会拉 Case,任务详情身份链断裂、五阶段页签全锁(2026-09-17 工作台直链修复)。
|
||||
# confirmed_task_id 唯一约束保证 OT→Case 至多一条,点查代价可忽略。
|
||||
if order_task is not None and not str(data.get('review_case_no') or '').strip():
|
||||
confirmed_case = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(confirmed_task_id=int(order_task.id))
|
||||
.first()
|
||||
)
|
||||
if confirmed_case is not None:
|
||||
case_no = str(confirmed_case.case_no or '').strip()
|
||||
if case_no:
|
||||
data['review_case_no'] = case_no
|
||||
|
||||
|
||||
def _enrich_task_center_fields(
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
"""收料 RPA callback 的原样归档服务。"""
|
||||
"""收料 RPA callback 的原样归档服务。
|
||||
|
||||
用途:接收收料 RPA 单元回调,原样归档文件三年且不写库存快照表;终态落库后
|
||||
通过收料回调桥推进在途调拨的 waiting_rpa_callback 来源任务(B3 接线)。
|
||||
依赖:models(ShippingReceiptReportFile/ShippingReceiptRpaUnitRun)、file_asset_storage、
|
||||
audit_service、in_transit_transfer.receipt_callback_bridge(惰性导入)。
|
||||
逻辑:success/empty/failed 三个终态分支各自 commit 后调用 _advance_transfer_source_job;
|
||||
桥是记账不是收料链路的正确性依赖,桥内异常只记日志绝不回滚归档终态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -35,6 +43,35 @@ def _read_receipt_callback_file(file_path: str) -> bytes:
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def _advance_transfer_source_job(
|
||||
unit: 'ShippingReceiptRpaUnitRun', *, ok: bool,
|
||||
file_no: str | None = None, file_sha256: str | None = None,
|
||||
error_code: str | None = None, error_message: str | None = None,
|
||||
) -> None:
|
||||
"""收料回调终态推进调拨来源任务;失败只记日志,绝不回滚收料归档终态。
|
||||
|
||||
Args:
|
||||
unit: 已落终态的收料单元行(用其 source_code 定位调拨任务)。
|
||||
ok: 回调是否成功(True 仅在 success 且带 file_no 时推进 file_ready)。
|
||||
file_no / file_sha256: success 时绑定的归档文件号与指纹。
|
||||
error_code / error_message: 失败时的错误码与描述。
|
||||
"""
|
||||
try:
|
||||
from app import db
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import advance_source_job_from_receipt_callback
|
||||
advanced = advance_source_job_from_receipt_callback(
|
||||
source_code=unit.source_code, file_no=file_no, file_sha256=file_sha256,
|
||||
callback_ok=ok, error_code=error_code, error_message=error_message,
|
||||
)
|
||||
if advanced is not None:
|
||||
# 桥内只 flush 不 commit;empty/failed 且 finalize 提前返回时无人提交,
|
||||
# 必须在此 commit,否则请求结束回滚会丢掉已推进的任务(B3 持久性)。
|
||||
db.session.commit()
|
||||
except Exception as exc: # noqa: BLE001 —— 桥是记账,不是收料链路的正确性依赖
|
||||
from flask import current_app
|
||||
current_app.logger.warning('[receipt-callback] advance transfer source job failed: %s', exc)
|
||||
|
||||
|
||||
def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""幂等接收单个收料单元回调,原样归档三年且不写库存快照表。"""
|
||||
if payload.get('schema_version') != 'shipping_receipt_rpa.v1':
|
||||
@@ -55,6 +92,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
metadata={'callback_status': status},
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code='RPA_RECEIPT_EMPTY', error_message='receipt export empty')
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'empty'}
|
||||
@@ -68,6 +106,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
metadata={'callback_status': status},
|
||||
)
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=False, error_code=unit.error_code, error_message=unit.error_message)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
finalize_receipt_schedule_run_if_complete(unit.schedule_run_id)
|
||||
return {'unit_run_id': unit.id, 'status': 'failed'}
|
||||
@@ -88,6 +127,7 @@ def ingest_receipt_callback(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
db.session.flush()
|
||||
append_shipping_audit_event(event_type='shipping_receipt_report_archived', aggregate_type='shipping_receipt_unit', aggregate_id=str(unit.id), run_no=unit.schedule_run.run_no if unit.schedule_run else None, actor_type='rpa', actor_id='receipt-worker', unit_id=unit.id, result='success', before=before, after={'status': 'success', 'source_run_no': unit.callback_id, 'file_id': record.id, 'sha256': sha256, 'file_size': len(data)}, artifact_refs=[{'kind': 'receipt_report', 'id': str(record.id), 'sha256': sha256}], metadata={'file_size': len(data), 'retention_days': 365 * 3})
|
||||
db.session.commit()
|
||||
_advance_transfer_source_job(unit, ok=True, file_no=str(record.id), file_sha256=sha256)
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_receipt_file
|
||||
deliver_receipt_file(record.id)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
@@ -18,6 +18,35 @@ def receipt_trigger_dir() -> Path | None:
|
||||
return Path(value) if value else None
|
||||
|
||||
|
||||
def receipt_warehouse_values(config: Any) -> list[str]:
|
||||
"""从收料配置的查询条件中提取 Warehouse 条件值(去空去重,保持顺序)。
|
||||
|
||||
Warehouse 条件即逐仓拆分维度(与库存配置同构,不单独持久化仓库清单);
|
||||
排程/触发按返回值逐仓展开执行单元。DBS 配置由校验保证恰一条非空条件。
|
||||
"""
|
||||
values: list[str] = []
|
||||
for item in (config.query_parameters_json or []):
|
||||
if not isinstance(item, dict) or str(item.get('name') or '').strip().lower() != 'warehouse':
|
||||
continue
|
||||
for raw in (item.get('values') or []):
|
||||
cleaned = str(raw or '').strip()
|
||||
if cleaned and cleaned not in values:
|
||||
values.append(cleaned)
|
||||
return values
|
||||
|
||||
|
||||
def receipt_unit_parameters(config: Any) -> list[dict[str, Any]]:
|
||||
"""构建单个执行单元的受控条件:剥离 Warehouse 条件。
|
||||
|
||||
Worker 会按单元的 warehouse_id 自动追加单值 Warehouse 条件,
|
||||
快照里保留用户维护的 Warehouse 条件会与之重复冲突。
|
||||
"""
|
||||
return [
|
||||
dict(item) for item in (config.query_parameters_json or [])
|
||||
if not (isinstance(item, dict) and str(item.get('name') or '').strip().lower() == 'warehouse')
|
||||
]
|
||||
|
||||
|
||||
def write_receipt_export_batch_trigger(run_no: str, units: list[dict[str, Any]], payload: dict[str, Any] | None = None) -> str | None:
|
||||
"""写入收料批量 trigger;worker 仅允许消费 shipping_receipt_rpa.v1。"""
|
||||
trigger_dir = receipt_trigger_dir()
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
services/shipping_notice/reservation_service.py
|
||||
|
||||
用途:管理冻结订单预约单的注册、库存核验轮次和滚动制单占用。
|
||||
依赖:ShippingOrderSnapshot、履约 ORM、统一 AppError。
|
||||
逻辑:每轮核验追加记录;只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。
|
||||
依赖:ShippingOrderSnapshot、effective_order_view(有效订单值视图)、履约 ORM、统一 AppError。
|
||||
逻辑:预约身份按「冻结快照 + 冻结后已接受人工修正」的有效值注册;每轮核验追加记录;
|
||||
只有本轮全部满足的预约单可被同一事务选择并绑定到一个新 Artifact。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,17 +41,37 @@ def _decimal(value: Any) -> Decimal:
|
||||
|
||||
|
||||
def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservation]:
|
||||
"""由冻结 Snapshot 注册全局预约号;同 PO 的变更只能作为人工修订候选。"""
|
||||
"""
|
||||
由有效订单视图(冻结快照 + 已接受人工修正)注册全局预约号;同 PO 的料号/数量
|
||||
变更按同一 OT 确认修订自动接替,跨任务或已占用预约仍走人工复核/锁定拒绝。
|
||||
|
||||
核心逻辑:预约身份(预约号/料号/数量)以 effective_line_facts_for_notice 的有效值为准;
|
||||
否则就地编辑料号/数量后,重匹配写入的有效值与按冻结列注册的预约不一致,
|
||||
核验比对必抛 RESERVATION_MISMATCH 使核验轮次无法创建、任务卡死。
|
||||
行集替换等无法按行对位的场景(ValueError)保守回退冻结快照列,
|
||||
由行集有效视图特性统一承接。
|
||||
"""
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValidationError('Frozen order snapshot is required', code='SHIPPING.ORDER_SNAPSHOT_REQUIRED')
|
||||
po_number = normalize_po_number(snapshot.customer_po_number).upper()
|
||||
# [BE-有效视图] 延迟导入避免与 export 的模块级循环依赖(export 反向惰性引用本模块)。
|
||||
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
|
||||
try:
|
||||
effective_facts = effective_line_facts_for_notice(task)
|
||||
except ValueError:
|
||||
effective_facts = {}
|
||||
registered: list[ShippingReservation] = []
|
||||
seen: set[str] = set()
|
||||
for line in snapshot.lines:
|
||||
reservation_id = validated_reservation_id(line.reservation_id)
|
||||
part_number = str(line.part_number or '').strip()
|
||||
if not reservation_id or not part_number or line.qty is None:
|
||||
eff = effective_facts.get(int(line.id)) or {}
|
||||
# 有效事实优先,None(无规则映射/值非法)回退冻结快照列。
|
||||
effective_reservation_id = eff.get('reservation_id') if eff.get('reservation_id') is not None else line.reservation_id
|
||||
effective_part_number = eff.get('part_number') if eff.get('part_number') is not None else line.part_number
|
||||
effective_qty = eff.get('qty') if eff.get('qty') is not None else line.qty
|
||||
reservation_id = validated_reservation_id(effective_reservation_id)
|
||||
part_number = str(effective_part_number or '').strip()
|
||||
if not reservation_id or not part_number or effective_qty is None:
|
||||
raise ValidationError('Reservation id, part number and quantity are required', code='SHIPPING.RESERVATION_INVALID')
|
||||
if reservation_id in seen:
|
||||
raise ConflictError('Reservation is duplicated in the frozen order', code='SHIPPING.RESERVATION_DUPLICATED_IN_ORDER')
|
||||
@@ -59,7 +80,7 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
|
||||
if row is None:
|
||||
row = ShippingReservation(
|
||||
task_id=task.id, snapshot_line_id=line.id, reservation_id=reservation_id,
|
||||
po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(line.qty), status='pending',
|
||||
po_number_normalized=po_number, part_number=part_number, required_qty=_decimal(effective_qty), status='pending',
|
||||
)
|
||||
db.session.add(row)
|
||||
elif not po_number:
|
||||
@@ -77,15 +98,16 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
|
||||
row.task_id != task.id
|
||||
or row.snapshot_line_id != line.id
|
||||
or row.part_number != part_number
|
||||
or row.required_qty != _decimal(line.qty)
|
||||
or row.required_qty != _decimal(effective_qty)
|
||||
):
|
||||
if row.current_artifact_id is not None or row.status in {'artifact_reserved', 'uploaded'}:
|
||||
raise ConflictError('Reservation cannot be revised after export or upload', code='SHIPPING.RESERVATION_REVISION_LOCKED')
|
||||
if row.part_number != part_number or row.required_qty != _decimal(line.qty):
|
||||
if row.part_number != part_number or row.required_qty != _decimal(effective_qty):
|
||||
# 同一 OT 的确认修订复用该 OT(仅 bump order_data_version/progress_version),
|
||||
# Reservation 与审计事件仍指向该 OT,不新建任务;跨任务变更须人工复核。
|
||||
# [BE-有效视图] 编辑料号/数量后的差异在此自动完成接替,核验得以继续。
|
||||
if row.task_id == task.id:
|
||||
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number)
|
||||
_transfer_confirmed_revision(row, task=task, line=line, part_number=part_number, qty=effective_qty)
|
||||
registered.append(row)
|
||||
continue
|
||||
raise ConflictError(
|
||||
@@ -95,7 +117,7 @@ def ensure_task_reservations(task: ShippingOrderTask) -> list[ShippingReservatio
|
||||
'reservation_id': reservation_id,
|
||||
'registered_task_id': row.task_id,
|
||||
'previous': {'part_number': row.part_number, 'qty': str(row.required_qty)},
|
||||
'proposed': {'part_number': part_number, 'qty': str(_decimal(line.qty))},
|
||||
'proposed': {'part_number': part_number, 'qty': str(_decimal(effective_qty))},
|
||||
},
|
||||
)
|
||||
raise ConflictError('Reservation is already registered by another order version', code='SHIPPING.RESERVATION_ALREADY_REGISTERED')
|
||||
@@ -120,12 +142,20 @@ def _transfer_confirmed_revision(
|
||||
*, task: ShippingOrderTask,
|
||||
line: Any,
|
||||
part_number: str,
|
||||
qty: Any | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
同一 OT 的已确认修订:复用该 OT(版本 bump),接替未履约 Reservation,并落 OT 级审计。
|
||||
|
||||
核心逻辑:修订不新建任务行;仅递增 ``order_data_version`` / ``progress_version``,
|
||||
Reservation 与 ShippingTaskEvent 均保持指向该 OT,避免写入 Notice id 造成错误外键。
|
||||
|
||||
Args:
|
||||
reservation: 待接替的未履约预约单。
|
||||
task: 当前归属 OT(或可解析到 OT 的任务)。
|
||||
line: 预约对应的冻结快照行(修订后 snapshot_line_id 仍指向该行)。
|
||||
part_number: 有效料号(已 strip)。
|
||||
qty: 有效数量;缺省时回退冻结行数量 ``line.qty``(供既有调用方兼容)。
|
||||
"""
|
||||
owner = _owner_task(task)
|
||||
previous = {
|
||||
@@ -140,7 +170,8 @@ def _transfer_confirmed_revision(
|
||||
reservation.task_id = owner.id
|
||||
reservation.snapshot_line_id = line.id
|
||||
reservation.part_number = part_number
|
||||
reservation.required_qty = _decimal(line.qty)
|
||||
# [BE-有效视图] 数量以有效值为准;行集替换等回退场景沿用冻结行数量。
|
||||
reservation.required_qty = _decimal(qty if qty is not None else line.qty)
|
||||
reservation.status = 'pending'
|
||||
reservation.current_artifact_id = None
|
||||
details = {
|
||||
@@ -175,11 +206,13 @@ def record_inventory_verification(
|
||||
reservation_id = validated_reservation_id(item.get('reservation_id'))
|
||||
part_number = str(item.get('part_number') or '').strip()
|
||||
reservation = by_key.get(reservation_id)
|
||||
if reservation is None or reservation.part_number != part_number:
|
||||
# [BE-有效视图] 料号比对两侧归一化(strip + upper):匹配结果与注册值可能仅存在
|
||||
# 大小写/空白差异,直接比较会造成假阳性 RESERVATION_MISMATCH 阻断核验。
|
||||
if reservation is None or str(reservation.part_number or '').strip().upper() != str(part_number or '').strip().upper():
|
||||
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
|
||||
required = _decimal(item.get('required_qty'))
|
||||
# The frozen order is the quantity authority. A reduced or duplicate result
|
||||
# must not turn an insufficient reservation into an exportable line.
|
||||
# [BE-有效视图] 数量权威是按有效订单值视图注册的预约值(非冻结快照列);
|
||||
# 缩量/重复的核验结果不得把短缺行升级为可导出行。
|
||||
if reservation_id in seen_reservation_ids or required != reservation.required_qty:
|
||||
raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
|
||||
seen_reservation_ids.add(reservation_id)
|
||||
@@ -277,6 +310,7 @@ def current_available_snapshot_line_ids(
|
||||
*,
|
||||
released_snapshot_line_ids: set[int] | None = None,
|
||||
selected_snapshot_line_ids: set[int] | None = None,
|
||||
closed_snapshot_line_ids: set[int] | None = None,
|
||||
) -> tuple[ShippingInventoryVerification, set[int]]:
|
||||
"""
|
||||
取得最新核验中可导出的冻结订单行。
|
||||
@@ -288,6 +322,7 @@ def current_available_snapshot_line_ids(
|
||||
task: 当前正式发货任务。
|
||||
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
|
||||
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。
|
||||
closed_snapshot_line_ids: 已结案冻结行 ID;无论库存状态一律从可导出集合剔除。
|
||||
|
||||
Returns:
|
||||
(最新核验轮次, 本次可导出的冻结订单行 ID)。
|
||||
@@ -323,10 +358,11 @@ def current_available_snapshot_line_ids(
|
||||
ShippingReservation.status.in_({'available', 'pending'}),
|
||||
).all() if reservation_ids else []
|
||||
selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())}
|
||||
closed_ids = {int(item) for item in (closed_snapshot_line_ids or set())}
|
||||
line_ids = {
|
||||
item.snapshot_line_id for item in reservations
|
||||
if not selected_ids or int(item.snapshot_line_id) in selected_ids
|
||||
}
|
||||
} - closed_ids
|
||||
if not line_ids:
|
||||
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
|
||||
return verification, line_ids
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""
|
||||
services/shipping_notice/schema_edit_policy.py
|
||||
|
||||
用途:正式任务字段编辑策略(Schema 显式放行;无策略默认只读;Excel ready 硬冻结)。
|
||||
用途:正式任务字段编辑策略(状态制:无策略默认可写;显式 editable=False 反向锁;Excel ready 硬冻结)。
|
||||
依赖:task_order_field_editor(锁定 Schema)、ShippingExportArtifact、ConflictError;
|
||||
被 task_workflow / 复核 formal patch / 投影 formal_editable_field_ids 引用。
|
||||
逻辑:默认 editable_after_task_creation=False;仅 Schema editable=True 可写;
|
||||
Excel ready = ready Artifact 匹配路径 + 可选 order_data_version 指纹;
|
||||
change_effect 供 task_workflow 下游失效编排消费。不考虑 legacy 白名单兼容绕过。
|
||||
逻辑:默认 editable_after_task_creation=True(建单后 Excel 生成前可编辑);
|
||||
仅 Schema 显式 editable=False 反向关闭;Excel ready = ready Artifact 匹配路径 +
|
||||
可选 order_data_version 指纹;change_effect 供 task_workflow 下游失效编排消费。
|
||||
不考虑 legacy 白名单兼容绕过。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,8 +19,8 @@ from app.core.errors import ConflictError
|
||||
if TYPE_CHECKING:
|
||||
from app.models import ShippingNotice
|
||||
|
||||
# 默认:创建正式任务后字段不可编辑。
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = False
|
||||
# 默认:建单后 Excel 生成前字段可编辑(状态制);个别字段需要锁定时在 Schema 配置 editable=false 反向关闭。
|
||||
DEFAULT_EDITABLE_AFTER_TASK_CREATION: Final[bool] = True
|
||||
|
||||
# 允许的 change_effect。
|
||||
ALLOWED_CHANGE_EFFECTS: Final[frozenset[str]] = frozenset({
|
||||
@@ -36,7 +37,7 @@ _AUDIT_VALUE_MAX_CHARS: Final[int] = 256
|
||||
|
||||
def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
读取 Schema 字段上的 task_edit_policy;缺省返回安全只读策略。
|
||||
读取 Schema 字段上的 task_edit_policy;无策略时按状态制默认(Excel ready 前可写)。
|
||||
|
||||
Args:
|
||||
field_config: Schema 单字段配置。
|
||||
@@ -46,7 +47,8 @@ def field_task_edit_policy(field_config: dict[str, Any] | None) -> dict[str, Any
|
||||
"""
|
||||
raw = field_config.get('task_edit_policy') if isinstance(field_config, dict) else None
|
||||
policy = dict(raw) if isinstance(raw, dict) else {}
|
||||
editable = bool(policy.get('editable')) if policy else False
|
||||
# 无策略时初始化为全局默认开关;显式 editable=false 的反向锁优先于默认值。
|
||||
editable = bool(policy.get('editable')) if policy else DEFAULT_EDITABLE_AFTER_TASK_CREATION
|
||||
if not DEFAULT_EDITABLE_AFTER_TASK_CREATION and 'editable' not in policy:
|
||||
editable = False
|
||||
effect = str(policy.get('change_effect') or 'none').strip() or 'none'
|
||||
@@ -98,7 +100,8 @@ def is_field_editable_for_formal_task(
|
||||
"""
|
||||
判断正式任务下该字段是否可编辑。
|
||||
|
||||
核心逻辑:Excel ready 时一律不可编辑;否则必须 Schema 显式 editable=True;
|
||||
核心逻辑:Excel ready 时一律不可编辑;否则按状态制默认可写,
|
||||
仅 Schema 显式 editable=False 反向关闭;
|
||||
若 editable_until=excel_ready 且 Excel 已就绪则关闭(与全局冻结一致)。
|
||||
|
||||
Args:
|
||||
@@ -182,7 +185,7 @@ def is_formal_field_code_editable(
|
||||
"""
|
||||
判断正式任务下 field_code 是否允许写入。
|
||||
|
||||
核心逻辑:仅 Schema 显式 editable=True 且未 Excel 冻结时放行;无 legacy 白名单。
|
||||
核心逻辑:未 Excel 冻结时按状态制默认放行,仅 Schema 显式 editable=False 反向关闭;无 legacy 白名单。
|
||||
|
||||
Args:
|
||||
task: 目标 ShippingNotice。
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
)
|
||||
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
|
||||
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
|
||||
from app.services.shipping_notice.tool_common import generate_task_no
|
||||
|
||||
@@ -34,6 +35,10 @@ def create_shipping_notice_after_inventory_gate(
|
||||
【触发时机】:库存准备成功、所有目标订单行匹配成功或已人工放行,且即将生成 Excel 时。
|
||||
不得在接收解析或订单复核确认阶段调用。
|
||||
|
||||
核心逻辑:通知行物化使用 effective_order_view 的有效行事实,携带冻结后人工修正值。
|
||||
已结案(close_unfulfillable)行从目标行集剔除,不参与门禁也不写入通知行;
|
||||
全部行结案时 target_ids 为空仍按门禁未通过拒绝。
|
||||
|
||||
Args:
|
||||
order_task: 已冻结订单快照的 OT。
|
||||
snapshot_line_ids: 可选的本次通知行集合;为空表示整单。
|
||||
@@ -87,10 +92,15 @@ def create_shipping_notice_after_inventory_gate(
|
||||
fact_rows = ShippingNoticeLineInventoryMatch.query.filter_by(
|
||||
task_id=int(order_task.id), is_current=True,
|
||||
).all()
|
||||
target_ids = selected_ids or {int(line.id) for line in snapshot.lines}
|
||||
by_line = {int(row.snapshot_line_id): row for row in fact_rows if row.snapshot_line_id is not None}
|
||||
from app.services.shipping_notice.fulfillment_workflow import _released_snapshot_line_ids_for_task
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_closed_snapshot_line_ids_for_task,
|
||||
_released_snapshot_line_ids_for_task,
|
||||
)
|
||||
released_ids = _released_snapshot_line_ids_for_task(order_task)
|
||||
# [BE-结案-豁免] 结案行不再是履约要求:从目标行集剔除,不参与门禁、不物化为通知行。
|
||||
closed_ids = _closed_snapshot_line_ids_for_task(order_task)
|
||||
target_ids = (selected_ids or {int(line.id) for line in snapshot.lines}) - closed_ids
|
||||
if not target_ids or any(
|
||||
int(line_id) not in by_line
|
||||
or (
|
||||
@@ -154,7 +164,9 @@ def create_shipping_notice_after_inventory_gate(
|
||||
replace_notice_lines_from_snapshot(
|
||||
notice_id=int(notice.id),
|
||||
snapshot=snapshot,
|
||||
snapshot_line_ids=selected_ids,
|
||||
# [BE-结案-豁免] 物化行集必须与门禁通过的 target_ids 一致:结案行不写入通知行。
|
||||
snapshot_line_ids=target_ids,
|
||||
inventory_facts_by_snapshot_line_id=inventory_facts_by_snapshot_line_id,
|
||||
line_overrides=effective_line_facts_for_notice(order_task),
|
||||
)
|
||||
return notice
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/task_order_field_editor.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
@@ -177,6 +178,19 @@ def _normalized_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _json_value(value: Any) -> Any:
|
||||
"""把人工输入转为 JSON 列可序列化形状;与 order_schema.runtime._json_value 对齐。
|
||||
|
||||
核心逻辑:Decimal → format(normalize, 'f') 字符串(保留精度且 json.dumps 可序列化),
|
||||
date → isoformat;其余原样。类型化列(value_decimal 等)仍保存原生值。
|
||||
"""
|
||||
if isinstance(value, Decimal):
|
||||
return format(value.normalize(), 'f')
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
|
||||
"""生成唯一 FieldValue 的类型化列,JSON 值始终作为下游读取的统一入口。"""
|
||||
return {
|
||||
@@ -185,7 +199,7 @@ def _field_value_columns(value: Any, value_type: str) -> dict[str, Any]:
|
||||
'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': value,
|
||||
'value_json': _json_value(value),
|
||||
}
|
||||
|
||||
|
||||
@@ -222,7 +236,7 @@ def replace_current_line_field_value(*, task: ShippingNotice, position: int, fie
|
||||
raise ConflictError('Order field decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
# 人工复核后的值成为当前决策真相,保留原 Observation 与冲突审计链。
|
||||
decision.decision_status = 'accepted'
|
||||
decision.resolved_value_json = normalized
|
||||
decision.resolved_value_json = _json_value(normalized)
|
||||
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
|
||||
if field_value is None:
|
||||
field_value = ShippingOrderFieldValue(
|
||||
@@ -264,7 +278,7 @@ def replace_current_header_field_value(*, task: ShippingNotice, field_code: str,
|
||||
if decision is None:
|
||||
raise ConflictError('Order header decision is unavailable', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
decision.decision_status = 'accepted'
|
||||
decision.resolved_value_json = normalized
|
||||
decision.resolved_value_json = _json_value(normalized)
|
||||
columns = _field_value_columns(normalized, str(config.get('value_type') or 'string'))
|
||||
if field_value is None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
@@ -349,7 +363,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A
|
||||
line_id=line.id,
|
||||
field_id=str(config['field_id']),
|
||||
decision_status='accepted' if value is not None else 'missing',
|
||||
resolved_value_json=value,
|
||||
resolved_value_json=_json_value(value),
|
||||
supporting_observation_ids_json=[],
|
||||
reason_code='human_line_set' if value is not None else 'missing',
|
||||
)
|
||||
|
||||
@@ -920,7 +920,8 @@ def _commit_notice_edit(
|
||||
reviewed_by_id = review_context.get('reviewed_by_id')
|
||||
evidence_ref = str(review_context.get('evidence_ref') or '')
|
||||
reason = str(review_context.get('reason') or '')
|
||||
if not reviewed_by_id or not evidence_ref or not reason:
|
||||
# 仅操作人身份是审计底线;reason/evidence_ref 已由 _prepare_review_context 哨兵兜底。
|
||||
if not reviewed_by_id:
|
||||
raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
@@ -1029,7 +1030,7 @@ def _commit_notice_edit(
|
||||
|
||||
|
||||
def _prepare_review_context(task: ShippingNotice, payload: dict[str, Any]) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
||||
"""校验正式编辑的操作者、证据和原因;Excel ready 后拒绝写入。"""
|
||||
"""校验正式编辑的操作者身份;reason/evidence 可缺省并落哨兵值;Excel ready 后拒绝写入。"""
|
||||
from app.services.shipping_notice.schema_edit_policy import assert_formal_task_not_excel_frozen
|
||||
|
||||
try:
|
||||
@@ -1050,14 +1051,18 @@ def _prepare_review_context(task: ShippingNotice, payload: dict[str, Any]) -> tu
|
||||
actor_id = int(payload.get('reviewed_by_id'))
|
||||
except (TypeError, ValueError):
|
||||
return None, tool_response(status='failed', task=task, message='缺少复核人员', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
|
||||
reason = str(payload.get('reason') or payload.get('comment') or '').strip()
|
||||
if not reason:
|
||||
return None, tool_response(status='failed', task=task, message='人工纠错必须提供证据和原因', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
|
||||
# 快捷就地编辑不强制填写原因/证据:审计链自动记录 old→new + 操作人 + 时间;
|
||||
# 提供了证据时仍走原校验。哨兵值满足 shipping_order_review_events 的 NOT NULL 列。
|
||||
reason = str(payload.get('reason') or payload.get('comment') or '').strip() or 'quick_field_edit'
|
||||
from app.services.shipping_notice.review_evidence_service import validate_review_evidence
|
||||
try:
|
||||
evidence_ref = validate_review_evidence(task=task, evidence=payload.get('evidence'), reason=reason)
|
||||
except ValidationError as exc:
|
||||
return None, tool_response(status='failed', task=task, message='人工纠错证据无效', data={'error_code': exc.code})
|
||||
evidence = payload.get('evidence') or None
|
||||
if evidence is not None:
|
||||
try:
|
||||
evidence_ref = validate_review_evidence(task=task, evidence=evidence, reason=reason)
|
||||
except ValidationError as exc:
|
||||
return None, tool_response(status='failed', task=task, message='人工纠错证据无效', data={'error_code': exc.code})
|
||||
else:
|
||||
evidence_ref = 'inline:match-table'
|
||||
return {'reviewed_by_id': actor_id, 'evidence_ref': evidence_ref, 'reason': reason}, None
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,9 @@ services/shipping_notice/ui_state.py
|
||||
Gate 摘要经 Notice.order_task_id→OT 查 Execution(禁止用 Notice.id);
|
||||
五阶段 processing_stage 同样经 Notice→OT.stage(Notice 无 stage 列),
|
||||
禁止仅靠 Gate 兜底把 order_freeze 误映射为订单复核;
|
||||
stage_context.preparation 以 Snapshot 行 + 当前 Match 投影(Notice 经 order_task_id→OT),
|
||||
stage_context.preparation 值列(预约号/料号/需求数量)有效值优先(快照 + 已接受修正,
|
||||
经 effective_line_facts_for_notice),无有效值时回退快照列;匹配结果列仍以 Snapshot 行
|
||||
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
|
||||
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
|
||||
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
|
||||
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
|
||||
@@ -830,6 +832,7 @@ def _build_stage_context(
|
||||
_shortage_release_required_fields,
|
||||
)
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
from app.services.shipping_notice.effective_order_view import effective_line_facts_for_notice
|
||||
|
||||
facts = stp_facts if isinstance(stp_facts, dict) else {}
|
||||
# [STEP 1] Snapshot/Match/Candidate 归属 OT;Notice 详情入口必须经 order_task_id 解析,
|
||||
@@ -846,6 +849,19 @@ def _build_stage_context(
|
||||
if snapshot is not None else []
|
||||
)
|
||||
match_by_snapshot_line_id = load_current_match_facts_by_task(getattr(order_task, 'id', None))
|
||||
# [BE-有效视图] 值列消费有效订单值(快照 + 已接受修正):保存即显新值,
|
||||
# 匹配结果列仍读当前匹配事实,诚实反映最近一轮匹配结论。
|
||||
# 全循环只算一次,行内按 snapshot_line_id 取用;无冻结快照(如未绑定 OT 的 Notice)
|
||||
# 保持空映射,行级回退快照列。有效视图解析失败(如历史/合成数据缺 Schema 版本)
|
||||
# 与 ODM 投影同款降级:不阻断工作台渲染,值列退回快照列(此时有效值=快照值)。
|
||||
effective_facts: dict[int, dict[str, Any]] = {}
|
||||
if order_task is not None and getattr(order_task, 'order_snapshot_id', None):
|
||||
try:
|
||||
effective_facts = effective_line_facts_for_notice(order_task)
|
||||
except Exception: # 遗留/合成快照缺 Schema 版本等:回退冻结列展示
|
||||
from flask import current_app
|
||||
current_app.logger.warning('effective order view resolution failed; falling back to frozen columns', exc_info=True)
|
||||
effective_facts = {}
|
||||
# [STEP] 与 Case 投影同源:库存 RPA 运行态只查一次 Attempt(请求内 memo),再传入各行纯函数。
|
||||
inventory_rpa_running = inventory_rpa_is_running(order_task)
|
||||
candidate_codes_by_line_no: dict[int, list[str]] = {}
|
||||
@@ -869,17 +885,38 @@ def _build_stage_context(
|
||||
for snapshot_line in snapshot_lines:
|
||||
qty_text = str(snapshot_line.qty) if snapshot_line.qty is not None else None
|
||||
line_no = int(snapshot_line.line_no) if snapshot_line.line_no is not None else None
|
||||
# [BE-有效视图] 冻结订单行值列有效值优先(预约号/料号/需求数量):行内按
|
||||
# snapshot_line_id 取有效事实,取不到(None)时回退冻结快照列;键名与前端
|
||||
# 契约稳定不动(shipping.api.types.ts ShippingOrderFrozenLine)。
|
||||
eff = effective_facts.get(int(snapshot_line.id)) or {}
|
||||
frozen_order_lines.append({
|
||||
'snapshot_line_id': int(snapshot_line.id),
|
||||
'line_no': line_no,
|
||||
'reservation_id': snapshot_line.reservation_id,
|
||||
'part_number': snapshot_line.part_number,
|
||||
'required_qty': qty_text,
|
||||
'reservation_id': eff.get('reservation_id') if eff.get('reservation_id') is not None else snapshot_line.reservation_id,
|
||||
'part_number': eff.get('part_number') if eff.get('part_number') is not None else snapshot_line.part_number,
|
||||
'required_qty': str(eff['qty']) if eff.get('qty') is not None else qty_text,
|
||||
})
|
||||
fact = match_by_snapshot_line_id.get(int(snapshot_line.id))
|
||||
required_qty = (fact or {}).get('required_qty')
|
||||
# [BE-有效视图] 需求数量:有效事实 → 匹配事实 → 快照列(Decimal 需 str 化)。
|
||||
required_qty = (
|
||||
str(eff['qty'])
|
||||
if eff.get('qty') is not None
|
||||
else (fact or {}).get('required_qty')
|
||||
)
|
||||
if required_qty is None:
|
||||
required_qty = qty_text
|
||||
# [BE-有效视图] 预约号/料号:有效事实 → 匹配事实 → 快照列;保存修正后即使
|
||||
# 匹配事实未刷新,prep 覆盖合并也立即显示新值。
|
||||
reservation_id_value = (
|
||||
eff.get('reservation_id')
|
||||
if eff.get('reservation_id') is not None
|
||||
else (fact or {}).get('reservation_id') or snapshot_line.reservation_id
|
||||
)
|
||||
part_number_value = (
|
||||
eff.get('part_number')
|
||||
if eff.get('part_number') is not None
|
||||
else (fact or {}).get('part_number') or snapshot_line.part_number
|
||||
)
|
||||
inv_view = project_line_inventory_view(
|
||||
has_formal_ot=has_formal_ot,
|
||||
fact=fact,
|
||||
@@ -934,8 +971,8 @@ def _build_stage_context(
|
||||
field_id_by_code,
|
||||
'customer_po_line_no',
|
||||
),
|
||||
'reservation_id': (fact or {}).get('reservation_id') or snapshot_line.reservation_id,
|
||||
'part_number': (fact or {}).get('part_number') or snapshot_line.part_number,
|
||||
'reservation_id': reservation_id_value,
|
||||
'part_number': part_number_value,
|
||||
'required_qty': required_qty,
|
||||
'available_qty': inv_view.get('available_qty'),
|
||||
'shortage_qty': inv_view.get('shortage_qty'),
|
||||
|
||||
Reference in new issue
Block a user