feat(in-transit-transfer): 外部调用切换集成连接器并新增调拨类型与在途仓编码
- 退役 erp_adapter/gateway_adapter:外部查询/写经 capability_client 走集成连接器,端点凭据与并发超时由客户端实例管理 - 域能力代码注册 capabilities:入参出参 Schema、幂等语义与读写标志随域代码版本化,组合根 create_app 幂等注册 - 新增调拨业务类型 transfer_type(在途仓至HUB/HUB维修出/HUB间)冻结枚举,迁移落 CheckConstraint 数据库兜底 - 外部仓库映射新增 in_transit_warehouse_code 拨出库位来源,管理端库存映射页同步维护 - 单据命名外部化:erp_* 字段与索引改称 external_*,单据号格式交由连接器映射,测试数据同步换牌 - 收料归档文件可用性判定收敛 receipt_file_gate 单一事实来源(当天抓取/保留期/清理态) - 同步 chat 调拨卡片、useChatTransfer、e2e、全套服务/API/Job 测试与域文档
This commit is contained in:
1 parent
31591e663e
commit
9959b06acd
97 files changed
+3525
-1489
No files matched your search
@@ -72,6 +72,13 @@ def create_app(config_name='default'):
|
||||
|
||||
register_blueprints(app)
|
||||
|
||||
# 能力声明是代码级契约:组合根在每次 create_app 时显式注册各域能力(幂等),
|
||||
# 保证管理端「能力清单」冷启动即可见,且测试 reset 注册表后建新 app 也能恢复。
|
||||
# 注意用 from-import:`import app.services...` 会把局部名 app 遮蔽成包模块。
|
||||
from app.services.in_transit_transfer import capabilities as _transfer_capabilities
|
||||
|
||||
_transfer_capabilities.register_transfer_capabilities()
|
||||
|
||||
# Eagerly load persisted runtime settings so the very first request after
|
||||
# a worker boot already sees the admin-saved configuration (otherwise the
|
||||
# window between worker boot and the first ``before_request`` would still
|
||||
|
||||
@@ -72,9 +72,11 @@ def _ok(payload: Any, *, status: int = 200):
|
||||
@in_transit_transfer_bp.route("/prechecks", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def create_precheck_api():
|
||||
"""创建或复用一次调拨预检(只读,不写 ERP)。
|
||||
"""创建或复用一次调拨预检(只读,不写 外部系统)。
|
||||
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选)}。
|
||||
请求体:{"source_codes": [...], "business_date": "YYYY-MM-DD"(可选),
|
||||
"receipt_date_from"/"receipt_date_to"(可选),
|
||||
"transfer_type": "in_transit_to_hub"(可选,缺省在途仓至HUB仓)}。
|
||||
响应:201 envelope,data 为预检摘要(precheck_id/hash/计数/来源进度)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
@@ -91,6 +93,7 @@ def create_precheck_api():
|
||||
deps=deps,
|
||||
receipt_date_from=str(body.get("receipt_date_from")) if body.get("receipt_date_from") else None,
|
||||
receipt_date_to=str(body.get("receipt_date_to")) if body.get("receipt_date_to") else None,
|
||||
transfer_type=str(body.get("transfer_type")) if body.get("transfer_type") else None,
|
||||
)
|
||||
return _ok(serialize_summary(summary), status=201)
|
||||
|
||||
@@ -113,7 +116,7 @@ def execute_precheck_api(precheck_id: str):
|
||||
"""确认预检选择范围并直接生成执行 Run(决策 4/5:无独立确认页)。
|
||||
|
||||
请求体:{"invoice_nos": [...]}(可选;缺省执行全部可执行项)。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / ERP 单号聚合结果。
|
||||
响应:201 envelope,data 为 run_no / run 状态 / 外部系统 单号聚合结果。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body, dict) else None
|
||||
@@ -135,7 +138,7 @@ def execute_precheck_api(precheck_id: str):
|
||||
@in_transit_transfer_bp.route("/prechecks/<precheck_no>/items/requery", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def requery_items_api(precheck_no: str):
|
||||
"""批量重查 ERP 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
"""批量重查 外部系统 库存(可恢复阻断行);body 可选 invoice_nos 限定范围。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True) or {}
|
||||
invoice_nos = body.get("invoice_nos") if isinstance(body.get("invoice_nos"), list) else None
|
||||
@@ -157,6 +160,8 @@ def download_source_receipt_files_api():
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
body = request.get_json(silent=True) or {}
|
||||
source_codes = body.get("source_codes")
|
||||
@@ -175,7 +180,9 @@ def download_source_receipt_files_api():
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)与徽标/预检取文件同口径,
|
||||
# 单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -229,14 +236,14 @@ def cancel_run_api(run_no: str):
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/retry", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_item_api(item_id: int):
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 ERP,创建新 Attempt)。
|
||||
"""人工重试异常项(基于冻结文件仅重新查询 外部系统,创建新 Attempt)。
|
||||
|
||||
请求体:{"kind": "erp_recheck"}(可选,默认 erp_recheck)。
|
||||
请求体:{"kind": "external_recheck"}(可选,默认 external_recheck)。
|
||||
"""
|
||||
body = request.get_json(silent=True) or {}
|
||||
kind = body.get("kind") if isinstance(body, dict) else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "erp_recheck"))
|
||||
return _ok(retry_item(item_id=item_id, deps=deps, kind=kind or "external_recheck"))
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/items/<int:item_id>/manual-close", methods=["POST"])
|
||||
@@ -337,10 +344,10 @@ def receipt_files_api(run_no: str):
|
||||
)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/erp-inventory", methods=["GET"])
|
||||
@in_transit_transfer_bp.route("/runs/<run_no>/external-inventory", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def erp_inventory_api(run_no: str):
|
||||
"""下载本次预检冻结的 ERP 库存表(csv);记录访问审计。"""
|
||||
"""下载本次预检冻结的 外部系统 库存表(csv);记录访问审计。"""
|
||||
import io
|
||||
|
||||
from app import db
|
||||
@@ -350,19 +357,19 @@ def erp_inventory_api(run_no: str):
|
||||
run = TransferRun.query.filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,erp_quantity,result,erp_document_no"]
|
||||
lines = ["invoice_no,source_code,material_no,from_warehouse,to_warehouse,receipt_quantity,external_quantity,result,external_document_no"]
|
||||
for item in TransferInvoiceItem.query.filter_by(run_id=run.id).order_by(TransferInvoiceItem.invoice_no).all():
|
||||
lines.append(",".join([
|
||||
str(item.invoice_no), str(item.source_code), str(item.material_no),
|
||||
str(item.from_warehouse), str(item.to_warehouse),
|
||||
str(item.receipt_quantity), str(item.erp_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.erp_document_no or ""),
|
||||
str(item.receipt_quantity), str(item.external_quantity or ""),
|
||||
str(item.result_code or item.status), str(item.external_document_no or ""),
|
||||
]))
|
||||
data = ("\n".join(lines) + "\n").encode("utf-8")
|
||||
|
||||
user = _require_user()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED",
|
||||
event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id=run_no,
|
||||
run_no=run_no,
|
||||
@@ -377,7 +384,7 @@ def erp_inventory_api(run_no: str):
|
||||
io.BytesIO(data),
|
||||
mimetype="text/csv",
|
||||
as_attachment=True,
|
||||
download_name=f"erp-inventory-{run_no}.csv",
|
||||
download_name=f"external-inventory-{run_no}.csv",
|
||||
)
|
||||
|
||||
|
||||
@@ -395,8 +402,9 @@ def transfer_metrics_api():
|
||||
def transfer_sources_api():
|
||||
"""来源实例列表(决策 3:平台 DBS/Crane 仅分组,实例为执行边界)。
|
||||
|
||||
每来源附收料文件状态(ready/fetching/failed/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识。只读复用已启用库存来源。
|
||||
每来源附收料文件状态(ready/fetching/failed/expired/none + has_ready_file),
|
||||
供前端门禁(无 ready 文件时禁止确认预检)与状态标识;保留期已到或非当天
|
||||
(业务日)抓取且未清理均投影 expired。只读复用已启用库存来源。
|
||||
"""
|
||||
from app.models import ShippingInventorySource
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
@@ -31,14 +31,15 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
raise RuntimeError(f"missing_transfer_precheck: {precheck_no}")
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
source_codes = list(precheck.scope_json.get("source_codes") or []) if isinstance(
|
||||
precheck.scope_json, dict
|
||||
) else []
|
||||
scope = precheck.scope_json if isinstance(precheck.scope_json, dict) else {}
|
||||
source_codes = list(scope.get("source_codes") or [])
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=precheck.business_date,
|
||||
deps=deps,
|
||||
run_no=precheck.run.run_no if precheck.run else "RUN-PENDING",
|
||||
# 类型范围随预检落库回读:异步重跑与创建时口径一致(缺省回落类型1)。
|
||||
transfer_type=str(scope.get("transfer_type")) if scope.get("transfer_type") else None,
|
||||
)
|
||||
summary = result.summary
|
||||
precheck.status = summary.status
|
||||
@@ -50,6 +51,6 @@ def run_in_transit_transfer_precheck(_ctx, payload: dict) -> None:
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
}
|
||||
precheck.estimated_transfer_quantity = summary.estimated_transfer_quantity
|
||||
precheck.estimated_erp_write_count = summary.estimated_erp_write_count
|
||||
precheck.estimated_external_write_count = summary.estimated_external_write_count
|
||||
precheck.precheck_hash = summary.precheck_hash
|
||||
db.session.commit()
|
||||
@@ -41,6 +41,11 @@ TRANSFER_RUN_STATUSES = (
|
||||
'queued', 'preparing_files', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'partial_failed', 'failed', 'cancelled',
|
||||
)
|
||||
# 与 services/in_transit_transfer/transfer_type.py TransferType 保持一致的冻结枚举
|
||||
# (数据库级兜底);一期仅 in_transit_to_hub 进入处理链路,其余为占位值。
|
||||
TRANSFER_RUN_TYPES = (
|
||||
'in_transit_to_hub', 'hub_repair_out', 'hub_to_hub',
|
||||
)
|
||||
TRANSFER_SOURCE_JOB_STATUSES = (
|
||||
'pending', 'checking_file', 'file_ready', 'waiting_rpa_callback', 'parsing',
|
||||
'prechecking', 'executing', 'success', 'partial_failed', 'failed', 'cancelled',
|
||||
@@ -49,7 +54,7 @@ TRANSFER_PRECHECK_STATUSES = (
|
||||
'file_pending', 'file_ready', 'prechecking', 'ready_to_execute', 'executing',
|
||||
'success', 'failed', 'cancelled', 'expired',
|
||||
)
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'erp_query', 'erp_write')
|
||||
TRANSFER_ATTEMPT_KINDS = ('precheck', 'rpa', 'external_query', 'external_write')
|
||||
TRANSFER_ATTEMPT_STATUSES = (
|
||||
'queued', 'running', 'waiting_external', 'success', 'failed',
|
||||
'result_unknown', 'superseded',
|
||||
@@ -75,6 +80,10 @@ class TransferRun(Base):
|
||||
"trigger_type IN ('manual', 'schedule')",
|
||||
name='ck_transfer_runs_trigger_type',
|
||||
),
|
||||
CheckConstraint(
|
||||
f"transfer_type IN ({', '.join(repr(t) for t in TRANSFER_RUN_TYPES)})",
|
||||
name='ck_transfer_runs_transfer_type',
|
||||
),
|
||||
Index('ix_transfer_runs_status_created', 'status', 'created_at'),
|
||||
Index('ix_transfer_runs_business_date', 'business_date'),
|
||||
)
|
||||
@@ -82,6 +91,10 @@ class TransferRun(Base):
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
trigger_type: Mapped[str] = mapped_column(String(16), nullable=False, default='manual', server_default='manual')
|
||||
# 调拨业务类型(在途仓至HUB仓/HUB仓维修出/HUB仓间调拨);决定预检收料数据范围。
|
||||
transfer_type: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='in_transit_to_hub', server_default='in_transit_to_hub',
|
||||
)
|
||||
business_date: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
source_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
@@ -167,7 +180,7 @@ class TransferPrecheck(Base):
|
||||
strategy_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
counts_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
estimated_transfer_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
estimated_erp_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
estimated_external_write_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
precheck_hash: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
expires_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
@@ -201,7 +214,7 @@ class TransferInvoiceItem(Base):
|
||||
),
|
||||
Index('ix_transfer_invoice_items_source_invoice_status', 'source_code', 'invoice_no', 'status'),
|
||||
Index('ix_transfer_invoice_items_run_id', 'run_id'),
|
||||
Index('ix_transfer_invoice_items_erp_document_no', 'erp_document_no'),
|
||||
Index('ix_transfer_invoice_items_external_document_no', 'external_document_no'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
@@ -211,6 +224,8 @@ class TransferInvoiceItem(Base):
|
||||
invoice_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 批号(External ASN 等)原值;「拨入批号」展示由 WTP→HOW 转换派生,不落库。
|
||||
lot_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
material_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
material_name: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
specification: Mapped[str] = mapped_column(String(200), nullable=False, default='')
|
||||
@@ -219,11 +234,11 @@ class TransferInvoiceItem(Base):
|
||||
to_warehouse: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# 数量以 Decimal 文本保存,杜绝浮点误差;比较在服务层完成。
|
||||
receipt_quantity: Mapped[str] = mapped_column(String(40), nullable=False)
|
||||
erp_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
external_quantity: Mapped[Optional[str]] = mapped_column(String(40), nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
result_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
result_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
erp_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
external_document_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
# 原始文件行追溯:Sheet + 行号 + 文件版本(决策 11)。
|
||||
raw_lines_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default=text('0'))
|
||||
|
||||
@@ -362,11 +362,13 @@ class ShippingInventoryRoutingRuleVersion(Base):
|
||||
|
||||
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
"""货代仓库到外部系统仓库的映射。
|
||||
"""库存源到外部系统仓库的映射。
|
||||
|
||||
freight_warehouse_id(货代仓库)是必维护的业务维度,同时是调拨拨出仓库的
|
||||
来源(in_transit_transfer DefaultRouteResolver);历史遗留的 NULL"默认映射"
|
||||
行不再允许新建(保存端必填校验),仅存量数据兼容。
|
||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||
「仓库」列(空值即「空库位」默认映射行,下方两个部分唯一索引保证同源最多
|
||||
一条启用的精确/默认映射);fixed 源仅一条启用映射直接取用。
|
||||
in_transit_warehouse_code(在途仓编码)是在途调拨拨出库位的来源
|
||||
(in_transit_transfer DefaultRouteResolver),保存端必填,库内空串仅为存量行兼容。
|
||||
"""
|
||||
|
||||
__tablename__ = 'shipping_inventory_external_mappings'
|
||||
@@ -396,6 +398,8 @@ class ShippingInventoryExternalMapping(Base):
|
||||
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)
|
||||
# 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
|
||||
in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
|
||||
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)
|
||||
|
||||
@@ -1177,6 +1177,7 @@ def _external_payload(mapping: ShippingInventoryExternalMapping) -> dict[str, An
|
||||
'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,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
|
||||
@@ -1208,9 +1209,11 @@ def save_external_mapping(data: dict[str, Any], *, actor_id: int | None, mapping
|
||||
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
|
||||
# 货代仓库是映射必要维度(调拨拨出仓库来源),不再支持"库存源默认映射";
|
||||
# 归一化为大写以与库存行 Warehouse 身份精确匹配。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id', required=True)).upper()
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
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')
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
依赖:同包 date_policy / status / quantity / strategy / contracts / audit;
|
||||
Phase 1 起扩展 file_preparation / precheck_service 等。
|
||||
逻辑:本包只承载调拨领域规则与确定性门禁,不混入 shipping_notice 订单解析;
|
||||
对外部系统(RPA/ERP/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
对外部系统(RPA/外部系统/企微)的访问通过本包隔离的 adapter 与 job/worker 完成。
|
||||
"""
|
||||
@@ -108,7 +108,7 @@ def archive_snapshot(
|
||||
"""归档一份对象并持久化索引 + 审计。
|
||||
|
||||
Args:
|
||||
object_type: 对象类型(erp_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_type: 对象类型(external_inventory_snapshot / exception_excel / receipt_file)。
|
||||
object_id: 业务对象编号(precheck_no / run_no)。
|
||||
data: 待归档字节。
|
||||
original_filename: 原始文件名。
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:组合"每日恢复 → 自动预检 → 自动执行 → 企微汇总通知",
|
||||
供 in-transit-transfer platform job 调用。
|
||||
依赖:recovery_service、precheck_service、execution_service、notification。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 ERP 结果。
|
||||
逻辑:各阶段独立 try/except,任一阶段失败不阻断后续;通知失败不改 外部系统 结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -45,7 +45,7 @@ def cancel_run(*, run_no: str, reason: str, actor_id: int | None = None, request
|
||||
|
||||
cancelled = 0
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.erp_document_no:
|
||||
if item.status == status_machine.TransferStatus.READY_TO_EXECUTE.value and not item.external_document_no:
|
||||
item.status = status_machine.TransferStatus.CANCELLED.value
|
||||
item.result_code = "cancelled"
|
||||
item.result_message = reason_value
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
"""services/in_transit_transfer/capabilities.py
|
||||
|
||||
用途:在途调拨域的能力声明——本域经集成连接器暴露的能力契约(入参/出参 Schema、
|
||||
幂等语义、读写标志),代码注册、禁止管理端动态定义。
|
||||
依赖:integration_connector.capability(机制层:CapabilitySpec/注册表)。
|
||||
逻辑:本模块属于领域包而非连接器框架——框架只提供注册/校验机制,域契约随域代码
|
||||
版本化;应用组合根(app/__init__.py)在每次 create_app 时调用
|
||||
register_transfer_capabilities()(幂等),保证管理端「能力清单」冷启动即可见,
|
||||
测试 reset 注册表后也能重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
)
|
||||
|
||||
# 在途调拨能力输入/输出 Schema(JSON Schema 最小子集,供入参/出参校验)。
|
||||
# 查询契约:按组织批量查库存,目标为 (料号, 拨出库位, 拨出批号) 元组列表;
|
||||
# external_org 取自仓库映射(external_organization_code),由绑定参数映射翻译为接口的 organization。
|
||||
_QUERY_INPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["external_org", "targets"],
|
||||
"properties": {
|
||||
"external_org": {"type": "string"},
|
||||
"targets": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_QUERY_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["rows"],
|
||||
"properties": {
|
||||
"rows": {"type": "array", "items": {
|
||||
"type": "object",
|
||||
"required": ["material_no", "from_warehouse", "lot_no", "quantity"],
|
||||
"properties": {
|
||||
"material_no": {"type": "string"},
|
||||
"from_warehouse": {"type": "string"},
|
||||
"lot_no": {"type": "string"},
|
||||
"quantity": {"type": "number"},
|
||||
},
|
||||
}},
|
||||
},
|
||||
}
|
||||
_WRITE_OUTPUT_SCHEMA: dict = {
|
||||
"type": "object",
|
||||
"required": ["status"],
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["success", "business_failed", "technical_failed", "timeout", "result_unknown"],
|
||||
},
|
||||
"document_no": {"type": ["string", "null"]},
|
||||
"verified_posted": {"type": ["boolean", "null"]},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def register_transfer_capabilities() -> None:
|
||||
"""注册在途调拨域的三个能力(幂等:已注册的同名跳过)。
|
||||
|
||||
幂等是硬要求:组合根每次 create_app 都会调用;测试 reset 注册表后(模块缓存导致
|
||||
import 副作用不再执行)也依赖本函数重建,故不能依赖「只注册一次」。
|
||||
"""
|
||||
registered = {spec.name for spec in list_capabilities()}
|
||||
for spec in (
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.query_inventory",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_QUERY_OUTPUT_SCHEMA,
|
||||
idempotency="none",
|
||||
write=False,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.create_transfer",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=True,
|
||||
),
|
||||
CapabilitySpec(
|
||||
name="in_transit_transfer.verify_duplicate",
|
||||
input_schema=_QUERY_INPUT_SCHEMA,
|
||||
output_schema=_WRITE_OUTPUT_SCHEMA,
|
||||
idempotency="invoice",
|
||||
write=False,
|
||||
),
|
||||
):
|
||||
if spec.name not in registered:
|
||||
register_capability(spec)
|
||||
|
||||
|
||||
register_transfer_capabilities()
|
||||
@@ -0,0 +1,283 @@
|
||||
"""services/in_transit_transfer/capability_client.py
|
||||
|
||||
用途:在途调拨域的外部访问统一客户端——查询经 CapabilityGateway 按能力批量调用;
|
||||
写路径在外部契约冻结前 fail-closed(Phase 2 接线点);域异常与写结果分类集中于此。
|
||||
依赖:integration_connector.gateway / errors、app.core.errors。
|
||||
逻辑:查询按 (料号, 拨出库位, 拨出批号) 元组批量进行,组织键 external_org 取自
|
||||
仓库映射(external_organization_code);查询超时→ExternalQueryTimeoutError,
|
||||
网关失败→AppError;写 transport 未注入时 create_transfer/verify_duplicate
|
||||
抛 ExternalNotFrozenError,注入后超时分类为 technical_failed / result_unknown。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
EXTERNAL_NOT_FROZEN_CODE = "TRANSFER.EXTERNAL_NOT_FROZEN"
|
||||
EXTERNAL_QUERY_TIMEOUT_CODE = "TRANSFER.EXTERNAL_QUERY_TIMEOUT"
|
||||
EXTERNAL_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
class ExternalNotFrozenError(AppError):
|
||||
"""外部系统契约(WSDL/endpoint)尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "external system contract not frozen"):
|
||||
super().__init__(code=EXTERNAL_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ExternalQueryTimeoutError(AppError):
|
||||
"""外部系统查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "external query timeout"):
|
||||
super().__init__(code=EXTERNAL_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ExternalResultUnknownError(AppError):
|
||||
"""外部系统写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "external result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=EXTERNAL_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ExternalWriteTimeoutError(TimeoutError):
|
||||
"""外部系统写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockTarget:
|
||||
"""库存查询目标元组:料号 + 拨出库位 + 拨出批号。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockRow:
|
||||
"""外部系统返回的一行账面库存。"""
|
||||
|
||||
material_no: str
|
||||
from_warehouse: str
|
||||
lot_no: str
|
||||
quantity: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StockQueryResult:
|
||||
"""一次批量库存查询的结果;按元组精确匹配取数。"""
|
||||
|
||||
rows: tuple[StockRow, ...]
|
||||
|
||||
def lookup(self, *, material_no: str, from_warehouse: str, lot_no: str) -> Decimal | None:
|
||||
"""按三元组取库存数量;同键多行累加;未命中返回 None。"""
|
||||
total: Decimal | None = None
|
||||
for row in self.rows:
|
||||
if (row.material_no, row.from_warehouse, row.lot_no) == (material_no, from_warehouse, lot_no):
|
||||
total = row.quantity if total is None else total + row.quantity
|
||||
return total
|
||||
|
||||
|
||||
class CapabilityClient:
|
||||
"""域内外部访问统一客户端:查询经 CapabilityGateway,写路径 fail-closed。
|
||||
|
||||
Args:
|
||||
gateway: 可注入替身(测试);缺省 get_capability_gateway()。
|
||||
write_transport: 写路径传输替身(Phase 2 前恒 None → 写调用抛
|
||||
ExternalNotFrozenError;测试注入后走经典写分类:可证明未落单→
|
||||
technical_failed,否则 result_unknown)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None, write_transport: Any | None = None) -> None:
|
||||
self._gateway_override = gateway
|
||||
self._write_transport = write_transport
|
||||
|
||||
def _gateway(self) -> Any:
|
||||
if self._gateway_override is not None:
|
||||
return self._gateway_override
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_stock(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
external_org: str,
|
||||
targets: list[StockTarget],
|
||||
) -> StockQueryResult:
|
||||
"""按组织批量查询库存(一次调用覆盖全部目标元组)。
|
||||
|
||||
Raises:
|
||||
ExternalQueryTimeoutError: 查询超时(可重试)。
|
||||
AppError: 网关失败(绑定缺失/调用失败,fail-closed)。
|
||||
"""
|
||||
if not targets:
|
||||
return StockQueryResult(rows=())
|
||||
result = self._gateway().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"external_org": external_org,
|
||||
"targets": [
|
||||
{
|
||||
"material_no": target.material_no,
|
||||
"from_warehouse": target.from_warehouse,
|
||||
"lot_no": target.lot_no,
|
||||
}
|
||||
for target in targets
|
||||
],
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ExternalQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
rows = [
|
||||
StockRow(
|
||||
material_no=str(row.get("material_no") or ""),
|
||||
from_warehouse=str(row.get("from_warehouse") or ""),
|
||||
lot_no=str(row.get("lot_no") or ""),
|
||||
quantity=Decimal(str(row.get("quantity") or "0")),
|
||||
)
|
||||
for row in ((result.data or {}).get("rows") or [])
|
||||
]
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""外部系统原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ExternalNotFrozenError: 写契约未冻结(write_transport 未注入)。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external create_transfer contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except ExternalWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
external_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
if self._write_transport is None:
|
||||
raise ExternalNotFrozenError("external verify_duplicate contract not frozen (endpoint missing)")
|
||||
try:
|
||||
response = self._write_transport.verify_duplicate(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, external_org=external_org,
|
||||
from_warehouse=from_warehouse, to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
except (TimeoutError, ExternalWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="EXTERNAL_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按外部系统写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "EXTERNAL_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_UNKNOWN_RESPONSE")
|
||||
@@ -42,16 +42,18 @@ class TransferPrecheckAction:
|
||||
"""执行只读预检并输出 transfer-precheck 卡片。
|
||||
|
||||
【AI 触发时机】:用户表达"查询今天可调拨 / 预检"等意图后由候选 Action 触发;
|
||||
只读,不写 ERP。
|
||||
只读,不写 外部系统。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_codes = [str(item).strip() for item in (payload.get("source_codes") or [])]
|
||||
business_date = str(payload.get("business_date") or business_date_now())
|
||||
transfer_type = str(payload.get("transfer_type")) if payload.get("transfer_type") else None
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
summary = create_precheck(
|
||||
source_codes=source_codes,
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
transfer_type=transfer_type,
|
||||
)
|
||||
detail = restore_precheck(summary.precheck_id)
|
||||
yield _message(
|
||||
@@ -71,7 +73,7 @@ class TransferExecuteAction:
|
||||
"""执行勾选范围并输出 transfer-result 卡片。
|
||||
|
||||
【AI 触发时机】:用户在预检卡点击"直接生成调拨单"后触发;
|
||||
后台确定性服务完成写前复查与 ERP 原子写入。
|
||||
后台确定性服务完成写前复查与 外部系统 原子写入。
|
||||
"""
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
precheck_id = str(payload.get("precheck_id") or "").strip()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨并发参数与单写者约束。
|
||||
|
||||
用途:冻结来源并发(2)、ERP 查询并发(2)与 ERP 写并发(1)默认值;
|
||||
ERP 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
用途:冻结来源并发(2)、外部系统 查询并发(2)与 外部系统 写并发(1)默认值;
|
||||
外部系统 写并发恒为 1,同预检只允许一个执行 Run(由 orchestrator 门禁兜底)。
|
||||
依赖:无(纯常量)。
|
||||
逻辑:写并发 1 与"同 Invoice 执行数=1"为一期硬约束,禁止运行时提升。
|
||||
"""
|
||||
@@ -10,8 +10,8 @@ from __future__ import annotations
|
||||
|
||||
# 一期冻结并发参数(与规格 §10 一致)。
|
||||
SOURCE_CONCURRENCY = 3
|
||||
ERP_QUERY_CONCURRENCY = 3
|
||||
ERP_WRITE_CONCURRENCY = 3
|
||||
外部系统_QUERY_CONCURRENCY = 3
|
||||
外部系统_WRITE_CONCURRENCY = 3
|
||||
|
||||
|
||||
def assert_single_writer(run_count: int) -> None:
|
||||
@@ -22,4 +22,4 @@ def assert_single_writer(run_count: int) -> None:
|
||||
Raises:
|
||||
AssertionError: run_count > 1(一期硬约束)。
|
||||
"""
|
||||
assert run_count <= 1, "ERP write concurrency must stay 1 for the same precheck"
|
||||
assert run_count <= 1, "External write concurrency must stay 1 for the same precheck"
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨 DTO 与稳定错误码契约。
|
||||
|
||||
用途:冻结前后端契约(预检摘要、明细项、ERP 单据聚合结果)与一期错误码,
|
||||
用途:冻结前后端契约(预检摘要、明细项、外部系统 单据聚合结果)与一期错误码,
|
||||
保证前端只依赖稳定 DTO、不感知 SOAP/WSDL/文件路径。
|
||||
依赖:标准库 dataclasses / decimal。
|
||||
逻辑:DTO 全部 frozen;aggregate_erp_documents 按 ERP 单号聚合最终结果页
|
||||
(决策 20:ERP 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
逻辑:DTO 全部 frozen;aggregate_external_documents 按 外部系统 单号聚合最终结果页
|
||||
(决策 20:外部系统 单号、拨出仓、拨入仓、物料数、调拨总数量、过账状态)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +20,7 @@ TRANSFER_FILE_NOT_READY = "TRANSFER_FILE_NOT_READY"
|
||||
TRANSFER_FILE_SCHEMA_INVALID = "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
TRANSFER_INVOICE_CONFLICT = "TRANSFER_INVOICE_CONFLICT"
|
||||
TRANSFER_QUANTITY_MISMATCH = "TRANSFER_QUANTITY_MISMATCH"
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND = "TRANSFER_ERP_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND = "TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND"
|
||||
TRANSFER_PRECHECK_EXPIRED = "TRANSFER_PRECHECK_EXPIRED"
|
||||
TRANSFER_CONFIRMATION_REQUIRED = "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED = "TRANSFER_DUPLICATE_NOT_VERIFIED"
|
||||
@@ -37,7 +37,7 @@ KNOWN_TRANSFER_ERROR_CODES: frozenset[str] = frozenset({
|
||||
TRANSFER_FILE_SCHEMA_INVALID,
|
||||
TRANSFER_INVOICE_CONFLICT,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED,
|
||||
@@ -98,14 +98,16 @@ class PrecheckInvoiceItemDTO:
|
||||
result: str
|
||||
receipt_date: str | None = None
|
||||
reason: str = ""
|
||||
erp_document_no: str | None = None
|
||||
external_document_no: str | None = None
|
||||
raw_lines: tuple[RawLineRefDTO, ...] = field(default_factory=tuple)
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PrecheckSummaryDTO:
|
||||
"""预检摘要(含预计调拨数量、预计 ERP 写入数与预检 Hash)。"""
|
||||
"""预检摘要(含预计调拨数量、预计 外部系统 写入数与预检 Hash)。"""
|
||||
|
||||
precheck_id: str
|
||||
status: str
|
||||
@@ -114,14 +116,14 @@ class PrecheckSummaryDTO:
|
||||
expires_at: str
|
||||
counts: PrecheckCountsDTO
|
||||
estimated_transfer_quantity: str
|
||||
estimated_erp_write_count: int
|
||||
estimated_external_write_count: int
|
||||
precheck_hash: str
|
||||
|
||||
|
||||
# ---- 结果页 DTO(决策 20)--------------------------------------------------
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentLineDTO:
|
||||
"""ERP 单据内物料明细。"""
|
||||
class ExternalDocumentLineDTO:
|
||||
"""外部系统 单据内物料明细。"""
|
||||
|
||||
material_no: str
|
||||
material_name: str
|
||||
@@ -131,8 +133,8 @@ class ErpDocumentLineDTO:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpDocumentDTO:
|
||||
"""按 ERP 单号聚合的结果项。"""
|
||||
class ExternalDocumentDTO:
|
||||
"""按 外部系统 单号聚合的结果项。"""
|
||||
|
||||
document_no: str
|
||||
from_warehouse: str
|
||||
@@ -140,12 +142,12 @@ class ErpDocumentDTO:
|
||||
material_count: int
|
||||
total_quantity: Decimal
|
||||
posting_status: str
|
||||
lines: tuple[ErpDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
lines: tuple[ExternalDocumentLineDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferExceptionDTO:
|
||||
"""未生成 ERP 单据的异常项(单独展示)。"""
|
||||
"""未生成 外部系统 单据的异常项(单独展示)。"""
|
||||
|
||||
source_code: str
|
||||
invoice_no: str
|
||||
@@ -156,31 +158,31 @@ class TransferExceptionDTO:
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RunResultDTO:
|
||||
"""Run 最终结果投影:ERP 单据聚合 + 未生成单据异常。"""
|
||||
"""Run 最终结果投影:外部系统 单据聚合 + 未生成单据异常。"""
|
||||
|
||||
run_no: str
|
||||
status: str
|
||||
erp_documents: tuple[ErpDocumentDTO, ...] = field(default_factory=tuple)
|
||||
external_documents: tuple[ExternalDocumentDTO, ...] = field(default_factory=tuple)
|
||||
exceptions: tuple[TransferExceptionDTO, ...] = field(default_factory=tuple)
|
||||
|
||||
|
||||
def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ErpDocumentDTO, ...]:
|
||||
"""按 ERP 单号聚合成功项,产出结果页文档视图。
|
||||
def aggregate_external_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[ExternalDocumentDTO, ...]:
|
||||
"""按 外部系统 单号聚合成功项,产出结果页文档视图。
|
||||
|
||||
Args:
|
||||
items: 预检明细项(含 erp_document_no 与 result)。
|
||||
items: 预检明细项(含 external_document_no 与 result)。
|
||||
Returns:
|
||||
按单号聚合的 ErpDocumentDTO 元组(行按 Invoice 排序)。
|
||||
按单号聚合的 ExternalDocumentDTO 元组(行按 Invoice 排序)。
|
||||
"""
|
||||
grouped: dict[str, list[PrecheckInvoiceItemDTO]] = {}
|
||||
for item in items:
|
||||
if item.erp_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.erp_document_no, []).append(item)
|
||||
documents: list[ErpDocumentDTO] = []
|
||||
if item.external_document_no and item.result in {"success", "duplicate_success"}:
|
||||
grouped.setdefault(item.external_document_no, []).append(item)
|
||||
documents: list[ExternalDocumentDTO] = []
|
||||
for document_no in sorted(grouped):
|
||||
rows = sorted(grouped[document_no], key=lambda row: row.invoice_no)
|
||||
lines = tuple(
|
||||
ErpDocumentLineDTO(
|
||||
ExternalDocumentLineDTO(
|
||||
material_no=row.material_no,
|
||||
material_name=row.material_name,
|
||||
specification=row.specification,
|
||||
@@ -189,7 +191,7 @@ def aggregate_erp_documents(items: Iterable[PrecheckInvoiceItemDTO]) -> tuple[Er
|
||||
)
|
||||
for row in rows
|
||||
)
|
||||
documents.append(ErpDocumentDTO(
|
||||
documents.append(ExternalDocumentDTO(
|
||||
document_no=document_no,
|
||||
from_warehouse=rows[0].from_warehouse,
|
||||
to_warehouse=rows[0].to_warehouse,
|
||||
|
||||
@@ -62,6 +62,29 @@ def business_date_now(moment: datetime | None = None) -> date:
|
||||
return moment.astimezone(SHANGHAI_TZ).date()
|
||||
|
||||
|
||||
def business_date_utc_window(now: datetime | None = None) -> tuple[datetime, datetime]:
|
||||
"""返回当前业务日期(Asia/Shanghai)在 UTC 存储时间轴上的 [起, 止) 窗口。
|
||||
|
||||
用途:判定"文件是否当天抓取"等新鲜度场景。数据库统一存 naive UTC 时间,
|
||||
直接取 .date() 与业务日期比较会漂移 8 小时,必须先换算窗口再比较。
|
||||
Args:
|
||||
now: 可选时刻;naive 按 UTC 兼容处理(与 business_date_now 口径一致)。
|
||||
Returns:
|
||||
(窗口起, 窗口止);两者均为 naive UTC datetime,止为开区间(时长 24h)。
|
||||
"""
|
||||
if now is None:
|
||||
now = datetime.now(SHANGHAI_TZ)
|
||||
if now.tzinfo is None:
|
||||
now = now.replace(tzinfo=ZoneInfo("UTC"))
|
||||
sh_now = now.astimezone(SHANGHAI_TZ)
|
||||
start_utc = (
|
||||
datetime(sh_now.year, sh_now.month, sh_now.day, tzinfo=SHANGHAI_TZ)
|
||||
.astimezone(ZoneInfo("UTC"))
|
||||
.replace(tzinfo=None)
|
||||
)
|
||||
return start_utc, start_utc + timedelta(hours=24)
|
||||
|
||||
|
||||
def maturity_status(receipt_date: date | str, business_date: date | str) -> str:
|
||||
"""按 D+1 规则判定收料日期成熟度。
|
||||
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""在途调拨依赖装配(Dependencies)。
|
||||
|
||||
用途:为 API / Job Handler 组装默认 TransferDeps;测试通过 _override 注入 Fake。
|
||||
依赖:movement_file_repository / gateway_adapter / precheck_service / models。
|
||||
依赖:movement_file_repository / capability_client / precheck_service / models。
|
||||
逻辑:默认实现直接接线真实链路 —— 收料文件行读取走 movement_file_repository
|
||||
(复用货代收料归档 + movement 解析规则,无文件/无规则时返回 None 由
|
||||
预检走等待 RPA);路由归属规则(Q1)冻结前由 DefaultRouteResolver
|
||||
fail-closed 拒绝;ERP 访问走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
fail-closed 拒绝;外部访问统一走 CapabilityClient(绑定缺失时 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.movement_file_repository import ShippingReceiptFileRepository
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
@@ -24,40 +24,66 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
|
||||
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:仓库映射的货代仓库 + 外部系统仓库。
|
||||
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
|
||||
|
||||
拨出仓库 = 映射行的货代仓库(货现在所在的 WMS 仓);拨入仓库 = 映射的
|
||||
目标仓库代码。不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""按来源配置与外部映射解析路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mapping = ShippingInventoryExternalMapping.query.filter_by(
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
).first()
|
||||
if mapping is None or not mapping.external_organization_code:
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
selected = next(
|
||||
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
|
||||
)
|
||||
if selected is None:
|
||||
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
|
||||
else:
|
||||
selected = mappings[0] if mappings else None
|
||||
if selected is None or not selected.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
from_warehouse = str(mapping.freight_warehouse_id or "").strip()
|
||||
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
|
||||
if not from_warehouse:
|
||||
# 拨出仓库无来源(映射未维护货代仓库)——fail-closed,不猜测。
|
||||
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return RouteMapping(
|
||||
erp_org=mapping.external_organization_code,
|
||||
external_org=selected.external_organization_code,
|
||||
from_warehouse=from_warehouse,
|
||||
to_warehouse=mapping.external_warehouse_code,
|
||||
to_warehouse=selected.external_warehouse_code,
|
||||
)
|
||||
|
||||
|
||||
def _build_erp_adapter() -> CapabilityErpAdapter:
|
||||
"""装配调拨 ERP 访问:默认走 CapabilityGateway(query_inventory 首消费者)。
|
||||
def _build_capability_client() -> CapabilityClient:
|
||||
"""装配调拨外部访问客户端:查询走 CapabilityGateway(绑定缺失时 fail-closed)。
|
||||
|
||||
P1 连接器框架:外部系统差异由配置(ClientInstance/InterfaceDefinition/Binding/映射)
|
||||
承担;缺绑定/契约未冻结时 fail-closed。create_transfer/verify_duplicate 待执行阶段接线。
|
||||
承担;create_transfer/verify_duplicate 在 WSDL 冻结前 fail-closed(Phase 2 接线)。
|
||||
"""
|
||||
return CapabilityErpAdapter()
|
||||
return CapabilityClient()
|
||||
|
||||
|
||||
_override: TransferDeps | None = None
|
||||
@@ -70,14 +96,14 @@ def set_transfer_dependencies(deps: TransferDeps | None) -> None:
|
||||
|
||||
|
||||
def get_transfer_dependencies() -> TransferDeps:
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/ERP 网关)。"""
|
||||
"""返回装配好的 TransferDeps(测试覆盖优先;默认接线真实文件仓库/触发服务/外部系统 网关)。"""
|
||||
if _override is not None:
|
||||
return _override
|
||||
return TransferDeps(
|
||||
file_repository=ShippingReceiptFileRepository(),
|
||||
rpa_trigger=_DefaultRpaTrigger(),
|
||||
route_resolver=DefaultRouteResolver(),
|
||||
erp=_build_erp_adapter(),
|
||||
capabilities=_build_capability_client(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,295 +0,0 @@
|
||||
"""在途调拨 ERP 访问统一边界(Adapter)。
|
||||
|
||||
用途:隔离全部 ERP 请求;业务服务只允许经本模块访问 ERP。
|
||||
Phase 1 启用只读 query_inventory;Phase 2 增加 create_transfer /
|
||||
verify_duplicate / 结果分类。
|
||||
依赖:typing.Protocol 传输层(测试注入 FakeERP;生产为 SOAP 传输)。
|
||||
逻辑:请求统一携带 operation_id / run_no / attempt_no / invoice_no /
|
||||
erp_org / 拨出仓 / 拨入仓 / 数量;查询超时分类为可重试;
|
||||
SOAP 传输在 WSDL/endpoint 冻结前 fail-closed(ErpNotFrozenError)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any, Protocol
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
ERP_NOT_FROZEN_CODE = "TRANSFER.ERP_NOT_FROZEN"
|
||||
ERP_QUERY_TIMEOUT_CODE = "TRANSFER.ERP_QUERY_TIMEOUT"
|
||||
ERP_RESULT_UNKNOWN_CODE = "TRANSFER_RESULT_UNKNOWN"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InventoryQuery:
|
||||
"""ERP 账面库存查询结果。"""
|
||||
|
||||
found: bool
|
||||
quantity: Decimal | None = None
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class ErpNotFrozenError(AppError):
|
||||
"""ERP WSDL/endpoint 尚未冻结,禁止调用(fail-closed)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP contract not frozen"):
|
||||
super().__init__(code=ERP_NOT_FROZEN_CODE, message=message, http_status=503, retryable=False)
|
||||
|
||||
|
||||
class ErpQueryTimeoutError(AppError):
|
||||
"""ERP 查询超时(只读路径,允许上层重试)。"""
|
||||
|
||||
def __init__(self, message: str = "ERP query timeout"):
|
||||
super().__init__(code=ERP_QUERY_TIMEOUT_CODE, message=message, http_status=503, retryable=True)
|
||||
|
||||
|
||||
class ErpResultUnknownError(AppError):
|
||||
"""ERP 写结果无法确认(Phase 2 使用);禁止自动重试。"""
|
||||
|
||||
def __init__(self, message: str = "ERP result unknown", *, operation_id: str | None = None):
|
||||
details = {"operation_id": operation_id} if operation_id else {}
|
||||
super().__init__(code=ERP_RESULT_UNKNOWN_CODE, message=message, http_status=503, retryable=False, details=details)
|
||||
|
||||
|
||||
class ErpWriteTimeoutError(TimeoutError):
|
||||
"""ERP 写超时;committed 表达是否可证明已落单。"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
*,
|
||||
committed: bool | None,
|
||||
document_no: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.committed = committed
|
||||
self.document_no = document_no
|
||||
self.operation_id = operation_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账结果分类。"""
|
||||
|
||||
status: str # success | duplicate_success | duplicate_unverified | business_failed | technical_failed | result_unknown
|
||||
document_no: str | None = None
|
||||
verified_posted: bool | None = None
|
||||
error_code: str | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class ErpTransport(Protocol):
|
||||
"""ERP 传输层协议(SOAP 或测试替身)。"""
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""按 Invoice 查询账面库存。"""
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账(Phase 2)。"""
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""核实重复 Invoice 原单是否已审核过账。"""
|
||||
|
||||
|
||||
class SoapErpTransport:
|
||||
"""真实 SOAP 传输;凭据只来自配置/环境,不写入请求体回显。
|
||||
|
||||
Args:
|
||||
config: 来自 Flask config 或环境变量(endpoint/username/password 等)。
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict[str, Any] | None = None) -> None:
|
||||
self._config = config or {}
|
||||
|
||||
def _require_frozen(self, operation: str) -> None:
|
||||
"""WSDL/endpoint 未冻结前任何调用直接拒绝。"""
|
||||
if not str(self._config.get("endpoint") or "").strip():
|
||||
raise ErpNotFrozenError(f"ERP {operation} contract not frozen (endpoint missing)")
|
||||
|
||||
def query_inventory(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 查询账面库存(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("query_inventory")
|
||||
raise NotImplementedError("SOAP query_inventory implementation pending frozen WSDL")
|
||||
|
||||
def create_transfer(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 原子建单/审核/过账(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("create_transfer")
|
||||
raise NotImplementedError("SOAP create_transfer implementation pending frozen WSDL")
|
||||
|
||||
def verify_duplicate(self, **kwargs: Any) -> dict[str, Any]:
|
||||
"""SOAP 核实重复 Invoice 原单状态(实现待 WSDL 冻结后落地)。"""
|
||||
self._require_frozen("verify_duplicate")
|
||||
raise NotImplementedError("SOAP verify_duplicate implementation pending frozen WSDL")
|
||||
|
||||
|
||||
class ErpAdapter:
|
||||
"""ERP 唯一访问入口;组装统一请求并分类结果。"""
|
||||
|
||||
def __init__(self, transport: ErpTransport, *, default_org: str = "") -> None:
|
||||
self._transport = transport
|
||||
self._default_org = default_org
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询 ERP 账面库存并分类结果。
|
||||
|
||||
Args:
|
||||
operation_id / run_no / attempt_no / invoice_no / erp_org /
|
||||
from_warehouse / to_warehouse / quantity: 请求强制追踪字段。
|
||||
Returns:
|
||||
InventoryQuery。
|
||||
Raises:
|
||||
ErpQueryTimeoutError: 查询超时(可重试)。
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
try:
|
||||
response = self._transport.query_inventory(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
raise ErpQueryTimeoutError() from exc
|
||||
response = response if isinstance(response, dict) else {}
|
||||
if response.get("found"):
|
||||
return InventoryQuery(found=True, quantity=Decimal(str(response.get("quantity") or "0")))
|
||||
return InventoryQuery(found=False)
|
||||
|
||||
def _build_request(self, *, operation_id, run_no, attempt_no, invoice_no, erp_org,
|
||||
from_warehouse, to_warehouse, quantity) -> dict[str, Any]:
|
||||
"""组装携带全部强制追踪字段的 ERP 请求。"""
|
||||
return {
|
||||
"operation_id": operation_id,
|
||||
"run_no": run_no,
|
||||
"attempt_no": attempt_no,
|
||||
"invoice_no": invoice_no,
|
||||
"erp_org": erp_org or self._default_org,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
}
|
||||
|
||||
def create_transfer(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""ERP 原子建单/审核/过账并按结果分类。
|
||||
|
||||
Returns:
|
||||
TransferWriteResult:success / duplicate_success / duplicate_unverified /
|
||||
business_failed / technical_failed / result_unknown。
|
||||
Raises:
|
||||
ErpNotFrozenError: ERP 契约未冻结。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.create_transfer(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except ErpWriteTimeoutError as exc:
|
||||
if exc.committed is False:
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_TIMEOUT_BEFORE_COMMIT")
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="ERP_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=exc.document_no,
|
||||
)
|
||||
except TimeoutError:
|
||||
# 无法区分是否落单 → result_unknown,禁止自动重试。
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
return _classify_write_response(response)
|
||||
|
||||
def verify_duplicate(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str | None = None,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单是否已审核过账(幂等确认)。
|
||||
|
||||
Returns:
|
||||
duplicate_success(已过账,含原单号)或 duplicate_unverified。
|
||||
"""
|
||||
request = self._build_request(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=attempt_no,
|
||||
invoice_no=invoice_no, erp_org=erp_org, from_warehouse=from_warehouse,
|
||||
to_warehouse=to_warehouse, quantity=quantity,
|
||||
)
|
||||
try:
|
||||
response = self._transport.verify_duplicate(**request)
|
||||
except ErpNotFrozenError:
|
||||
raise
|
||||
except (TimeoutError, ErpWriteTimeoutError):
|
||||
return TransferWriteResult(status="result_unknown", error_code="ERP_TIMEOUT_UNKNOWN")
|
||||
response = response if isinstance(response, dict) else {}
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if status == "duplicate_success" and posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=posted,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
|
||||
def _classify_write_response(response: dict[str, Any]) -> TransferWriteResult:
|
||||
"""按 ERP 写响应原文分类业务结果。"""
|
||||
status = str(response.get("status") or "")
|
||||
document_no = response.get("document_no")
|
||||
if status == "success":
|
||||
return TransferWriteResult(status="success", document_no=document_no)
|
||||
if status == "duplicate_success":
|
||||
posted = bool(response.get("verified_posted"))
|
||||
if posted:
|
||||
return TransferWriteResult(status="duplicate_success", document_no=document_no, verified_posted=True)
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", document_no=document_no, verified_posted=False,
|
||||
error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
if status == "business_failed":
|
||||
return TransferWriteResult(
|
||||
status="business_failed",
|
||||
error_code=str(response.get("code") or "ERP_BUSINESS_REJECT"),
|
||||
error_message=str(response.get("message") or ""),
|
||||
)
|
||||
return TransferWriteResult(status="technical_failed", error_code="ERP_UNKNOWN_RESPONSE")
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨七 Sheet 异常 Excel 导出。
|
||||
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/ERP无库存/
|
||||
ERP技术失败/ERP结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
用途:按规格生成七 Sheet 异常 Excel(执行汇总/数量不一致/外部系统无库存/
|
||||
外部系统技术失败/外部系统结果未知/通知失败/原始文件追溯),供企微附件与下载。
|
||||
依赖:openpyxl、models、execution_service。
|
||||
逻辑:Sheet 内容按状态归类;原始文件追溯保留 Sheet/行号/文件版本;
|
||||
Secret 明文永不写入单元格(仅输出业务字段)。
|
||||
@@ -21,9 +21,9 @@ from app.core.errors import NotFoundError
|
||||
EXCEL_SHEET_NAMES = [
|
||||
"执行汇总",
|
||||
"数量不一致",
|
||||
"ERP无库存",
|
||||
"ERP技术失败",
|
||||
"ERP结果未知",
|
||||
"外部系统无库存",
|
||||
"外部系统技术失败",
|
||||
"外部系统结果未知",
|
||||
"通知失败",
|
||||
"原始文件追溯",
|
||||
]
|
||||
@@ -53,8 +53,8 @@ def build_exceptions_workbook(run_no: str) -> bytes:
|
||||
|
||||
_sheet_summary(workbook, run, items)
|
||||
_sheet_blocked(workbook, items, "数量不一致", {"blocked_quantity_mismatch", "precheck_expired"})
|
||||
_sheet_blocked(workbook, items, "ERP无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "ERP技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_blocked(workbook, items, "外部系统无库存", {"blocked_inventory_not_found"})
|
||||
_sheet_blocked(workbook, items, "外部系统技术失败", {"business_failed", "technical_failed", "item_execution_error"})
|
||||
_sheet_unknown(workbook, items)
|
||||
_sheet_notification(workbook, run)
|
||||
_sheet_raw_trace(workbook, items)
|
||||
@@ -71,30 +71,30 @@ def _sheet_summary(workbook: Workbook, run: TransferRun, items: list[TransferInv
|
||||
sheet.append(["Run 状态", run.status])
|
||||
sheet.append(["通知状态", run.notification_status])
|
||||
sheet.append([])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "ERP 单号"])
|
||||
sheet.append(["Invoice", "来源", "料号", "预检结果", "外部系统 单号"])
|
||||
for item in items:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.result_code or item.status, item.erp_document_no or "",
|
||||
item.result_code or item.status, item.external_document_no or "",
|
||||
])
|
||||
|
||||
|
||||
def _sheet_blocked(workbook: Workbook, items: list[TransferInvoiceItem], sheet_name: str, codes: set[str]) -> None:
|
||||
"""按阻断原因归类 Sheet。"""
|
||||
sheet = workbook.create_sheet(sheet_name)
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "ERP 数量", "原因"])
|
||||
sheet.append(["Invoice", "来源", "料号", "收料数量", "外部系统 数量", "原因"])
|
||||
for item in items:
|
||||
if (item.result_code or "") in codes or item.status in codes:
|
||||
sheet.append([
|
||||
item.invoice_no, item.source_code, item.material_no,
|
||||
item.receipt_quantity, item.erp_quantity or "",
|
||||
item.receipt_quantity, item.external_quantity or "",
|
||||
item.result_message or item.result_code or item.status,
|
||||
])
|
||||
|
||||
|
||||
def _sheet_unknown(workbook: Workbook, items: list[TransferInvoiceItem]) -> None:
|
||||
"""ERP 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("ERP结果未知")
|
||||
"""外部系统 结果未知 Sheet(只读提示,含 Operation 关联)。"""
|
||||
sheet = workbook.create_sheet("外部系统结果未知")
|
||||
sheet.append(["Invoice", "来源", "料号", "说明"])
|
||||
sheet.append(["仅展示事实,禁止重试/关闭;请按人工核实 SOP 处理", "", "", ""])
|
||||
for item in items:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + ERP 原子写入 + 结果投影)。
|
||||
"""在途调拨执行服务(确认门禁 + 写前复查 + 外部系统 原子写入 + 结果投影)。
|
||||
|
||||
用途:执行一次预检:校验确认范围与预检快照(fail-closed)→ 创建执行 Run →
|
||||
逐项写前复查 ERP 库存 → 原子建单/审核/过账 → 按 ERP 单号投影最终结果。
|
||||
依赖:orchestrator、erp_adapter、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → ERP 写调用为 0;
|
||||
逐项写前复查 外部系统 库存 → 原子建单/审核/过账 → 按 外部系统 单号投影最终结果。
|
||||
依赖:orchestrator、capability_client、quantity、contracts、audit、status、models。
|
||||
逻辑:未确认/过期/快照变化/选择含不可执行项 → 外部系统 写调用为 0;
|
||||
每个 Invoice 独立写入,单项失败/结果未知不阻断其他项;
|
||||
result_unknown 为终态,禁止自动重试;每次写入创建新 Attempt。
|
||||
"""
|
||||
@@ -24,11 +24,11 @@ from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
ErpDocumentDTO,
|
||||
ExternalDocumentDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
RunResultDTO,
|
||||
TransferExceptionDTO,
|
||||
aggregate_erp_documents,
|
||||
aggregate_external_documents,
|
||||
)
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
@@ -36,6 +36,7 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteNotResolvedError,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
PRECHECK_EXPIRED_RESULT = "precheck_expired"
|
||||
@@ -72,7 +73,7 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": item.receipt_quantity,
|
||||
"erp_quantity": item.erp_quantity,
|
||||
"external_quantity": item.external_quantity,
|
||||
"result": _item_result_of(item),
|
||||
}
|
||||
for item in sorted(precheck.items, key=lambda row: row.id)
|
||||
@@ -88,6 +89,11 @@ def recompute_precheck_hash(precheck: TransferPrecheck) -> str:
|
||||
},
|
||||
"items": items,
|
||||
}
|
||||
# [调拨类型] 创建时快照含 transfer_type(2026-09-22 起 scope_json 恒写入);
|
||||
# 存量预检 scope_json 无该字段时保持旧快照形状,避免复算 Hash 不一致误判过期。
|
||||
scope_transfer_type = str(precheck.scope_json.get("transfer_type") or "").strip()
|
||||
if scope_transfer_type:
|
||||
snapshot["transfer_type"] = scope_transfer_type
|
||||
return f"sha256:{canonical_hash(snapshot)}"
|
||||
|
||||
|
||||
@@ -115,7 +121,7 @@ def execute_precheck(
|
||||
Returns:
|
||||
ExecuteOutcome(run_no / run 状态 / 单据聚合结果)。
|
||||
Raises:
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(ERP 写入为 0)。
|
||||
NotFoundError / ValidationError / AppError: 门禁失败(外部系统 写入为 0)。
|
||||
ConflictError: 重复执行。
|
||||
"""
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(
|
||||
@@ -185,42 +191,48 @@ def execute_precheck(
|
||||
|
||||
|
||||
def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, request_id: str | None) -> None:
|
||||
"""写前复查 + ERP 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
"""写前复查 + 外部系统 原子写入单个 Invoice(创建新 Attempt)。"""
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
if route.from_warehouse != item.from_warehouse or route.to_warehouse != item.to_warehouse:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "route mapping changed since precheck")
|
||||
return
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
# [STEP 1] 写前复查:重新查询 ERP 库存并严格匹配冻结收料数量。
|
||||
# [STEP 1] 写前复查:重新查询外部系统库存并严格匹配冻结收料数量。
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)
|
||||
except RouteNotResolvedError:
|
||||
raise
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "erp inventory changed since precheck")
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
_mark_recheck_blocked(item, "precheck_expired", "external inventory changed since precheck")
|
||||
return
|
||||
|
||||
# [STEP 2] 记录写 Attempt 并调用 ERP 原子建单/审核/过账。
|
||||
# [STEP 2] 记录写 Attempt 并调用外部系统原子建单/审核/过账。
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_write",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_write",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"run_no": run_no, "invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
result = deps.erp.create_transfer(
|
||||
result = deps.capabilities.create_transfer(
|
||||
operation_id=operation_id, run_no=run_no, attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no, erp_org=route.erp_org,
|
||||
invoice_no=item.invoice_no, external_org=route.external_org,
|
||||
from_warehouse=route.from_warehouse, to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
)
|
||||
@@ -230,7 +242,7 @@ def _write_item(item: TransferInvoiceItem, *, deps: TransferDeps, run_no: str, r
|
||||
|
||||
|
||||
def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str) -> None:
|
||||
"""写前复查失败:fail-closed,不写 ERP。"""
|
||||
"""写前复查失败:fail-closed,不写 外部系统。"""
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = result
|
||||
item.result_message = message
|
||||
@@ -238,7 +250,7 @@ def _mark_recheck_blocked(item: TransferInvoiceItem, result: str, message: str)
|
||||
|
||||
|
||||
def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, result) -> None:
|
||||
"""按 ERP 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
"""按 外部系统 写结果分类落位 item 与 attempt(result_unknown 为终态)。"""
|
||||
attempt.response_summary_json = {
|
||||
"status": result.status,
|
||||
"document_no": result.document_no,
|
||||
@@ -247,12 +259,12 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
}
|
||||
if result.status == "success":
|
||||
item.status = status_machine.TransferStatus.SUCCESS.value
|
||||
item.erp_document_no = result.document_no
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "duplicate_success":
|
||||
item.status = status_machine.TransferStatus.DUPLICATE_SUCCESS.value
|
||||
item.erp_document_no = result.document_no
|
||||
item.external_document_no = result.document_no
|
||||
item.result_code = None
|
||||
attempt.status = "success"
|
||||
elif result.status == "result_unknown":
|
||||
@@ -270,7 +282,7 @@ def _apply_write_result(item: TransferInvoiceItem, attempt: TransferAttempt, res
|
||||
|
||||
|
||||
def _audit_item_write(item, run_no, request_id, operation_id, before_status) -> None:
|
||||
"""为每次 ERP 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
"""为每次 外部系统 写入追加审计事件(脱敏快照 + Hash)。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_ITEM_EXECUTED",
|
||||
aggregate_type="transfer_item",
|
||||
@@ -284,7 +296,7 @@ def _audit_item_write(item, run_no, request_id, operation_id, before_status) ->
|
||||
operation_id=operation_id,
|
||||
result="success" if item.status in {"success", "duplicate_success"} else "failure",
|
||||
before={"status": before_status},
|
||||
after={"status": item.status, "erp_document_no": item.erp_document_no},
|
||||
after={"status": item.status, "external_document_no": item.external_document_no},
|
||||
)
|
||||
db.session.add(event)
|
||||
|
||||
@@ -312,7 +324,7 @@ def execute_item(*, item_id: int, deps: TransferDeps, request_id: str | None = N
|
||||
|
||||
|
||||
def get_run(run_no: str) -> dict[str, Any]:
|
||||
"""按 run_no 恢复 Run 最终结果(ERP 单号聚合 + 未生成单据异常)。"""
|
||||
"""按 run_no 恢复 Run 最终结果(外部系统 单号聚合 + 未生成单据异常)。"""
|
||||
run = db.session.query(TransferRun).filter_by(run_no=str(run_no).strip()).first()
|
||||
if run is None:
|
||||
raise NotFoundError("run not found", code="TRANSFER.RUN_NOT_FOUND")
|
||||
@@ -337,12 +349,13 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=result,
|
||||
reason=item.result_message or "",
|
||||
erp_document_no=item.erp_document_no,
|
||||
external_document_no=item.external_document_no,
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
))
|
||||
if result not in {"success", "duplicate_success"}:
|
||||
exceptions.append(TransferExceptionDTO(
|
||||
@@ -350,12 +363,12 @@ def _build_run_result(run: TransferRun) -> RunResultDTO:
|
||||
invoice_no=item.invoice_no,
|
||||
material_no=item.material_no,
|
||||
reason=result,
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / ERP {item.erp_quantity}" if item.erp_quantity else ""),
|
||||
facts=f"收料 {item.receipt_quantity}" + (f" / 外部系统 {item.external_quantity}" if item.external_quantity else ""),
|
||||
))
|
||||
return RunResultDTO(
|
||||
run_no=run.run_no,
|
||||
status=run.status,
|
||||
erp_documents=aggregate_erp_documents(item_dtos),
|
||||
external_documents=aggregate_external_documents(item_dtos),
|
||||
exceptions=tuple(exceptions),
|
||||
)
|
||||
|
||||
@@ -365,7 +378,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
return {
|
||||
"run_no": result.run_no,
|
||||
"status": result.status,
|
||||
"erp_documents": [
|
||||
"external_documents": [
|
||||
{
|
||||
"document_no": document.document_no,
|
||||
"from_warehouse": document.from_warehouse,
|
||||
@@ -384,7 +397,7 @@ def serialize_run_result(result: RunResultDTO) -> dict[str, Any]:
|
||||
for line in document.lines
|
||||
],
|
||||
}
|
||||
for document in result.erp_documents
|
||||
for document in result.external_documents
|
||||
],
|
||||
"exceptions": [
|
||||
{
|
||||
|
||||
@@ -35,6 +35,8 @@ class ParsedReceiptRow:
|
||||
receipt_date: date
|
||||
receipt_quantity: Decimal
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class ReceiptFileSchemaError(AppError):
|
||||
@@ -73,8 +75,9 @@ def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]])
|
||||
doc_no → invoice_no(幂等/汇总键)
|
||||
quantity → receipt_quantity(严格数量匹配)
|
||||
movement_date → receipt_date(成熟过滤)
|
||||
其余字段(material_code→material_no、material_name、warehouse_code、storage_code、
|
||||
doc_no)透传/展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
其余字段(material_code→material_no、material_name、doc_no)透传/展示保留;
|
||||
warehouse_code 透传至 ParsedReceiptRow.warehouse_code(inventory_match 源路由匹配键);
|
||||
storage_code 仍仅展示保留。较 parse_receipt_rows,本函数只改字段名映射,校验逻辑一致。
|
||||
|
||||
Args:
|
||||
source_code: 任务来源实例(行内来源身份一致性校验)。
|
||||
@@ -189,6 +192,7 @@ def _parse_rows(
|
||||
receipt_date=receipt_date,
|
||||
receipt_quantity=quantity,
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
"""services/in_transit_transfer/gateway_adapter.py
|
||||
|
||||
用途:把调拨的 ERP 访问收敛为通过 Integration Connector CapabilityGateway 调用
|
||||
(query_inventory 是首个配置绑定消费者)。
|
||||
依赖:integration_connector.gateway / capability、erp_adapter.InventoryQuery/ErpQueryTimeoutError。
|
||||
逻辑:领域只调 query_inventory 能力;外部系统差异全在连接器层。create_transfer /
|
||||
verify_duplicate 留待调拨执行阶段(Phase 2)接线。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError, InventoryQuery
|
||||
|
||||
QUERY_INVENTORY_CAPABILITY = "in_transit_transfer.query_inventory"
|
||||
|
||||
|
||||
class CapabilityErpAdapter:
|
||||
"""把调拨 query_inventory 收敛为通过 CapabilityGateway 调用。
|
||||
|
||||
Args:
|
||||
gateway: 可选 Gateway;缺省用 get_capability_gateway()(可注入替身测试)。
|
||||
"""
|
||||
|
||||
def __init__(self, gateway: Any | None = None) -> None:
|
||||
self._gateway = gateway
|
||||
|
||||
def _gateway_or_default(self):
|
||||
if self._gateway is not None:
|
||||
return self._gateway
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
|
||||
return get_capability_gateway()
|
||||
|
||||
def query_inventory(
|
||||
self,
|
||||
*,
|
||||
operation_id: str,
|
||||
run_no: str,
|
||||
attempt_no: int,
|
||||
invoice_no: str,
|
||||
erp_org: str,
|
||||
from_warehouse: str,
|
||||
to_warehouse: str,
|
||||
quantity: Decimal,
|
||||
) -> InventoryQuery:
|
||||
"""查询外部系统库存(经连接器框架)。
|
||||
|
||||
Args/Raises:
|
||||
与 erp_adapter.ErpAdapter.query_inventory 一致;超时→ErpQueryTimeoutError;
|
||||
写失败→AppError(预检把它归为来源失败)。P1 用默认绑定(context={});
|
||||
来源专属绑定待 P2/P3。
|
||||
"""
|
||||
result = self._gateway_or_default().call(
|
||||
capability=QUERY_INVENTORY_CAPABILITY,
|
||||
context={},
|
||||
params={
|
||||
"invoice_no": invoice_no,
|
||||
"from_warehouse": from_warehouse,
|
||||
"to_warehouse": to_warehouse,
|
||||
"quantity": quantity,
|
||||
},
|
||||
operation_id=operation_id,
|
||||
)
|
||||
if result.status == "timeout":
|
||||
raise ErpQueryTimeoutError()
|
||||
if result.status != "success":
|
||||
raise AppError(
|
||||
code=result.error_code or "INTEGRATION.CALL_FAILED",
|
||||
message=result.error_message or "query_inventory failed",
|
||||
http_status=503,
|
||||
retryable=False,
|
||||
)
|
||||
data = result.data or {}
|
||||
found = bool(data.get("found"))
|
||||
qty = data.get("quantity")
|
||||
return InventoryQuery(found=found, quantity=Decimal(str(qty)) if qty is not None else None)
|
||||
@@ -31,6 +31,8 @@ class AggregatedInvoice:
|
||||
receipt_quantity: Decimal
|
||||
raw_lines: tuple[RawLineRefDTO, ...]
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
|
||||
|
||||
class InvoiceConflictError(AppError):
|
||||
@@ -80,5 +82,6 @@ def aggregate_invoices(rows: Iterable[ParsedReceiptRow], *, file_version: str =
|
||||
receipt_quantity=sum((row.receipt_quantity for row in group), Decimal("0")),
|
||||
raw_lines=raw_lines,
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
))
|
||||
return invoices
|
||||
@@ -4,11 +4,11 @@
|
||||
用该来源收料配置绑定的 movement 解析规则(purpose='movement',端点=定死
|
||||
领域字段 MOVEMENT_FIELDS)的 field_mapping 把列映射为领域行,产出 ReadyReceiptFile。
|
||||
依赖:ShippingReceiptReportFile / ShippingReceiptReportConfig / file_asset_storage、
|
||||
movement_contract、openpyxl。
|
||||
逻辑:按来源取最新未过期(未清理)收料文件;无绑定 movement profile 或文件缺失时
|
||||
返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域字段 + 溯源字段
|
||||
(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整校验由下游
|
||||
file_parser 完成。
|
||||
movement_contract、receipt_file_gate(可用性门禁)、openpyxl。
|
||||
逻辑:按来源取最新【当天(业务日)抓取】且未过期(未清理)的收料文件;无绑定规则、
|
||||
文件缺失或隔日旧文件时返回 None(fail-closed),绝不伪造 ready 文件。行 dict = 领域
|
||||
字段 + 溯源字段(sheet=实际工作表标题、row_no=工作表真实 1-based 行号);行完整
|
||||
校验由下游 file_parser 完成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +18,7 @@ from typing import Any, Mapping
|
||||
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.receipt_file_gate import usable_receipt_file_condition
|
||||
|
||||
|
||||
class ShippingReceiptFileRepository:
|
||||
@@ -27,13 +28,14 @@ class ShippingReceiptFileRepository:
|
||||
self._storage = file_asset_storage
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""返回该来源最新未过期收料文件;无绑定规则或文件缺失时返回 None。
|
||||
"""返回该来源最新且当天(业务日)抓取的未过期收料文件;否则返回 None。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码。
|
||||
business_date: 业务日期(用于展示/匹配成熟度,不强制匹配文件日期)。
|
||||
Returns:
|
||||
ReadyReceiptFile(rows 为领域字段 + 溯源 sheet/row_no 的 dict)或 None。
|
||||
新鲜度/保留期/缺失均 fail-closed 返回 None(fail 消息由上游触发重抓)。
|
||||
"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptReportFile
|
||||
|
||||
@@ -52,7 +54,8 @@ class ShippingReceiptFileRepository:
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
# 可用门禁(未清理 + 当天业务日抓取 + 未过保留期)单一事实来源见 receipt_file_gate。
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企业微信汇总通知。
|
||||
|
||||
用途:每个非空 Run 恰好一条汇总通知;空数据不通知;通知失败记录
|
||||
notification_failed 且不改变 ERP 业务结果(run.status 保持)。
|
||||
notification_failed 且不改变 外部系统 业务结果(run.status 保持)。
|
||||
依赖:models、audit、typing.Protocol。
|
||||
逻辑:通知状态独立于 ERP 状态;已成功投递幂等(每个 Run 一条)。
|
||||
逻辑:通知状态独立于 外部系统 状态;已成功投递幂等(每个 Run 一条)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,7 +65,7 @@ def notify_run_summary(*, run_no: str, sender: WeComSender, recipients: list[str
|
||||
if failed:
|
||||
run.notification_error_code = str(outcome.get("error_code") or "WECOM_SEND_FAILED")
|
||||
run.notification_error_message = str(outcome.get("error_message") or "")
|
||||
# 关键:通知失败绝不修改 run.status(ERP 业务结果保持)。
|
||||
# 关键:通知失败绝不修改 run.status(外部系统 业务结果保持)。
|
||||
db.session.add(build_transfer_audit_event(
|
||||
event_type="TRANSFER_NOTIFICATION",
|
||||
aggregate_type="transfer_run",
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""在途调拨预检服务。
|
||||
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → ERP 库存查询 →
|
||||
用途:编排"文件准备 → 解析 → Invoice 汇总 → D+1 成熟过滤 → 外部系统 库存查询 →
|
||||
严格数量匹配 → 预检快照与 Hash",并支持预检进度恢复(restore)。
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / erp_adapter /
|
||||
依赖:file_preparation / file_parser / invoice_aggregator / capability_client /
|
||||
date_policy / quantity / contracts / audit / models。
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 ERP;
|
||||
逻辑:来源实例独立处理,任一来源失败不阻断其他来源;当天收料不查询 外部系统;
|
||||
预检 Hash 由冻结快照复算;create_precheck 落库 Run + Precheck + Items。
|
||||
"""
|
||||
|
||||
@@ -35,7 +35,7 @@ from app.services.in_transit_transfer.date_policy import (
|
||||
maturity_status,
|
||||
parse_date,
|
||||
)
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpQueryTimeoutError
|
||||
from app.services.in_transit_transfer.capability_client import ExternalQueryTimeoutError, StockTarget
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
@@ -56,6 +56,13 @@ from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
default_strategy,
|
||||
)
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
ROUTE_NOT_RESOLVED_CODE = "TRANSFER.ROUTE_NOT_RESOLVED"
|
||||
|
||||
@@ -65,15 +72,15 @@ RESULT_NOT_MATURED = "not_matured"
|
||||
RESULT_QUANTITY_MISMATCH = "blocked_quantity_mismatch"
|
||||
RESULT_INVENTORY_NOT_FOUND = "blocked_inventory_not_found"
|
||||
RESULT_FUTURE_DATE = "blocked_future_date"
|
||||
RESULT_ERP_QUERY_FAILED = "blocked_erp_query_failed"
|
||||
RESULT_ERP_QUERY_TIMEOUT = "erp_query_timeout"
|
||||
RESULT_EXTERNAL_QUERY_FAILED = "blocked_external_query_failed"
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT = "external_query_timeout"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RouteMapping:
|
||||
"""来源路由:ERP 组织 / 拨出仓(ERP 在途仓)/ 拨入仓(ERP 映射仓)。"""
|
||||
"""来源路由:外部组织(external_org,取自仓库映射)/ 拨出仓(外部在途仓)/ 拨入仓(映射仓)。"""
|
||||
|
||||
erp_org: str
|
||||
external_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
|
||||
@@ -93,8 +100,8 @@ class RouteNotResolvedError(AppError):
|
||||
class RouteResolver(Protocol):
|
||||
"""来源路由解析协议(路由归属规则冻结前由 Fake/门禁兜底)。"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""返回 Invoice 的路由;无法归属时抛 RouteNotResolvedError。"""
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -126,7 +133,7 @@ class TransferDeps:
|
||||
file_repository: ReceiptFileRepository
|
||||
rpa_trigger: RpaTrigger
|
||||
route_resolver: RouteResolver
|
||||
erp: Any
|
||||
capabilities: Any
|
||||
strategy: TransferStrategyPolicy = field(default_factory=default_strategy)
|
||||
|
||||
|
||||
@@ -148,22 +155,27 @@ def run_precheck(
|
||||
run_no: str = "RUN-PENDING",
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckRunResult:
|
||||
"""执行一次只读预检(不写 ERP)。
|
||||
"""执行一次只读预检(不写 外部系统)。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例列表(DBS/Crane 仅分组,实例为执行边界)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / ERP 依赖。
|
||||
deps: 注入的文件仓库 / RPA / 路由 / 外部系统 依赖。
|
||||
active_source_job_key: 活动 Source Job 键(缺文件时绑定已有任务)。
|
||||
run_no: Run 编号(创建 Run 前可为占位)。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期查询范围。
|
||||
transfer_type: 调拨业务类型(缺省在途仓至HUB仓);类型决定收料数据范围。
|
||||
Returns:
|
||||
PrecheckRunResult(摘要 + 明细 + 来源进度)。
|
||||
Raises:
|
||||
ValidationError: source_codes 为空。
|
||||
ValidationError: source_codes 为空、日期范围非法或调拨类型非法/未支持。
|
||||
"""
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
# [日期范围] 可选收料日期过滤;卡控:截止不得超出 D+1 规则(业务日期-1),起始不得晚于截止。
|
||||
range_from = parse_date(receipt_date_from) if receipt_date_from else None
|
||||
range_to = parse_date(receipt_date_to) if receipt_date_to else None
|
||||
@@ -212,6 +224,9 @@ def run_precheck(
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date >= range_from]
|
||||
if range_to is not None:
|
||||
invoices = [invoice for invoice in invoices if invoice.receipt_date <= range_to]
|
||||
# [调拨类型] 类型决定收料数据范围(如类型1仅保留 INVOICE 前缀 HOM/HOX/WTP),
|
||||
# 范围外票与日期范围过滤同语义:静默排除、不入明细、不阻断来源。
|
||||
invoices = filter_invoices_for_type(invoices, resolved_transfer_type)
|
||||
source_items = _precheck_invoices(
|
||||
invoices=invoices,
|
||||
source_code=source_code,
|
||||
@@ -260,6 +275,7 @@ def run_precheck(
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"file_snapshot": file_snapshot,
|
||||
"counts": {
|
||||
"file_invoice_count": counts.file_invoice_count,
|
||||
@@ -275,7 +291,7 @@ def run_precheck(
|
||||
"from_warehouse": item.from_warehouse,
|
||||
"to_warehouse": item.to_warehouse,
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"result": item.result,
|
||||
}
|
||||
for item in items
|
||||
@@ -293,7 +309,7 @@ def run_precheck(
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_erp_write_count=counts.executable_count,
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
precheck_hash=precheck_hash,
|
||||
)
|
||||
return PrecheckRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
@@ -308,8 +324,12 @@ def _precheck_invoices(
|
||||
deps: TransferDeps,
|
||||
run_no: str,
|
||||
) -> list[PrecheckInvoiceItemDTO]:
|
||||
"""对单个来源的汇总 Invoice 逐项预检(成熟过滤 → 路由 → ERP → 匹配)。"""
|
||||
"""对单个来源的汇总 Invoice 预检(成熟过滤 → 路由 → 按组织分组批量查 外部系统 → 匹配)。"""
|
||||
output: list[PrecheckInvoiceItemDTO] = []
|
||||
|
||||
# [STEP 1] 成熟过滤与路由解析(不查询):未成熟/未来日期直接落位,
|
||||
# 成熟项按 external_org(仓库映射的外部组织)分组,每组合并为一次批量查询。
|
||||
matured: list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]] = []
|
||||
for invoice in invoices:
|
||||
maturity = maturity_status(invoice.receipt_date, business_date)
|
||||
raw = tuple(
|
||||
@@ -325,6 +345,7 @@ def _precheck_invoices(
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_NOT_MATURED, reason="receipt not matured until next business day",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
@@ -336,72 +357,94 @@ def _precheck_invoices(
|
||||
from_warehouse="", from_quantity=None,
|
||||
to_warehouse="", to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_FUTURE_DATE, reason="future receipt date",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
route = deps.route_resolver.resolve(source_code=source_code, invoice_no=invoice.invoice_no)
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
matured.append((invoice, route, raw, receipt_date_iso))
|
||||
|
||||
groups: dict[str, list[tuple[Any, RouteMapping, tuple[RawLineRefDTO, ...], str]]] = {}
|
||||
for entry in matured:
|
||||
groups.setdefault(entry[1].external_org, []).append(entry)
|
||||
|
||||
# [STEP 2] 每个组织一次批量查询(targets = 料号+拨出库位+拨出批号 元组列表),
|
||||
# 组内逐票按三元组精确匹配库存数量;组级故障降级到组内全部票,不炸整来源。
|
||||
for external_org, entries in groups.items():
|
||||
targets = [
|
||||
StockTarget(material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no)
|
||||
for invoice, route, _, _ in entries
|
||||
]
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=run_no,
|
||||
attempt_no=1,
|
||||
invoice_no=invoice.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=invoice.receipt_quantity,
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=external_org, targets=targets,
|
||||
)
|
||||
except ErpQueryTimeoutError:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_ERP_QUERY_TIMEOUT, reason="erp query timeout",
|
||||
raw_lines=raw,
|
||||
))
|
||||
except ExternalQueryTimeoutError:
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_TIMEOUT, reason="external query timeout",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
except Exception as exc: # noqa: BLE001 —— ERP 网关/绑定层故障降级为单据阻断,不炸整来源
|
||||
except Exception as exc: # noqa: BLE001 —— 网关/绑定层故障降级为整组阻断,不炸整来源
|
||||
# [语义] 绑定缺失、连接失败等基础设施故障是环境问题而非业务阻断:
|
||||
# 逐票给 blocked_erp_query_failed + 原因,预检列表保持可见可解释。
|
||||
# 组内逐票给 blocked_external_query_failed + 原因,预检列表保持可见可解释。
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_EXTERNAL_QUERY_FAILED, reason=f"external query failed: {detail}",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
for invoice, route, raw, receipt_date_iso in entries:
|
||||
stock_qty = stock.lookup(
|
||||
material_no=invoice.material_no, from_warehouse=route.from_warehouse, lot_no=invoice.lot_no,
|
||||
)
|
||||
if stock_qty is None:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
# 查无库存记录也是外部系统的真实答复:库存数按 0 展示(而非"-"),
|
||||
# 避免用户误以为查询失败;分类仍为 blocked_inventory_not_found。
|
||||
from_quantity=Decimal("0"), to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="external inventory not found",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, stock_qty)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
from_quantity=stock_qty, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_ERP_QUERY_FAILED, reason=f"erp query failed: {detail}",
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
receipt_warehouse_code=invoice.warehouse_code or "",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
if not query.found:
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=None, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=RESULT_INVENTORY_NOT_FOUND, reason="erp inventory not found",
|
||||
raw_lines=raw,
|
||||
))
|
||||
continue
|
||||
match = classify_quantity_match(invoice.receipt_quantity, query.quantity)
|
||||
output.append(PrecheckInvoiceItemDTO(
|
||||
source_code=source_code, material_no=invoice.material_no,
|
||||
material_name=invoice.material_name, specification=invoice.specification,
|
||||
invoice_no=invoice.invoice_no, lot_no=invoice.lot_no, receipt_date=receipt_date_iso,
|
||||
from_warehouse=route.from_warehouse,
|
||||
from_quantity=query.quantity, to_warehouse=route.to_warehouse,
|
||||
to_quantity=invoice.receipt_quantity,
|
||||
result=match, reason="" if match == RESULT_EXECUTABLE else "strict quantity mismatch",
|
||||
raw_lines=raw,
|
||||
))
|
||||
return output
|
||||
|
||||
|
||||
@@ -411,7 +454,7 @@ def _item_status(result: str) -> str:
|
||||
RESULT_EXECUTABLE: status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
RESULT_NOT_MATURED: status_machine.TransferStatus.NOT_MATURED.value,
|
||||
RESULT_FUTURE_DATE: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_ERP_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_EXTERNAL_QUERY_TIMEOUT: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_QUANTITY_MISMATCH: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
RESULT_INVENTORY_NOT_FOUND: status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
}
|
||||
@@ -432,14 +475,18 @@ def create_precheck(
|
||||
active_source_job_key: str | None = None,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
transfer_type: TransferType | str | None = None,
|
||||
) -> PrecheckSummaryDTO:
|
||||
"""运行预检并落库 TransferRun + TransferPrecheck + InvoiceItems。
|
||||
|
||||
Args:
|
||||
source_codes / business_date / deps: 同 run_precheck。
|
||||
receipt_date_from / receipt_date_to / transfer_type: 同 run_precheck。
|
||||
Returns:
|
||||
预检摘要(precheck_id 已回填)。
|
||||
"""
|
||||
resolved_transfer_type = normalize_transfer_type(transfer_type)
|
||||
ensure_transfer_type_supported(resolved_transfer_type)
|
||||
run_no = _generate_no("RUN", business_date)
|
||||
result = run_precheck(
|
||||
source_codes=source_codes,
|
||||
@@ -448,6 +495,7 @@ def create_precheck(
|
||||
active_source_job_key=active_source_job_key,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
transfer_type=resolved_transfer_type,
|
||||
run_no=run_no,
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
@@ -458,6 +506,7 @@ def create_precheck(
|
||||
status="prechecking",
|
||||
source_codes_json=list(source_codes),
|
||||
counts_json=asdict(result.summary.counts),
|
||||
transfer_type=resolved_transfer_type.value,
|
||||
)
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
@@ -485,7 +534,13 @@ def create_precheck(
|
||||
run_id=run.id,
|
||||
business_date=business_date,
|
||||
status=result.summary.status,
|
||||
scope_json={"source_codes": list(source_codes), "receipt_date_from": receipt_date_from, "receipt_date_to": receipt_date_to},
|
||||
scope_json={
|
||||
"source_codes": list(source_codes),
|
||||
"receipt_date_from": receipt_date_from,
|
||||
"receipt_date_to": receipt_date_to,
|
||||
"transfer_type": resolved_transfer_type.value,
|
||||
"transfer_type_scope": transfer_type_scope_note(resolved_transfer_type),
|
||||
},
|
||||
file_snapshot_json={
|
||||
stage.source_code: {
|
||||
"file_no": stage.file_no,
|
||||
@@ -499,7 +554,7 @@ def create_precheck(
|
||||
strategy_version="v0",
|
||||
counts_json=asdict(result.summary.counts),
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
expires_at=now + timedelta(seconds=deps.strategy.confirm_ttl_seconds),
|
||||
)
|
||||
@@ -524,8 +579,9 @@ def create_precheck(
|
||||
"from_warehouse": item.from_warehouse or "",
|
||||
"to_warehouse": item.to_warehouse or "",
|
||||
"receipt_quantity": str(item.to_quantity),
|
||||
"erp_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"external_quantity": str(item.from_quantity) if item.from_quantity is not None else None,
|
||||
"lot_no": item.lot_no or "",
|
||||
"receipt_warehouse_code": item.receipt_warehouse_code or "",
|
||||
"raw_lines_json": [
|
||||
{"sheet": line.sheet, "row_no": line.row_no, "file_version": line.file_version}
|
||||
for line in item.raw_lines
|
||||
@@ -568,7 +624,7 @@ def create_precheck(
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=result.summary.counts,
|
||||
estimated_transfer_quantity=result.summary.estimated_transfer_quantity,
|
||||
estimated_erp_write_count=result.summary.estimated_erp_write_count,
|
||||
estimated_external_write_count=result.summary.estimated_external_write_count,
|
||||
precheck_hash=result.summary.precheck_hash,
|
||||
)
|
||||
return summary
|
||||
@@ -604,7 +660,7 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
expires_at=precheck.expires_at.isoformat() if precheck.expires_at else "",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=precheck.estimated_transfer_quantity or "0",
|
||||
estimated_erp_write_count=int(precheck.estimated_erp_write_count or 0),
|
||||
estimated_external_write_count=int(precheck.estimated_external_write_count or 0),
|
||||
precheck_hash=precheck.precheck_hash,
|
||||
)
|
||||
items = []
|
||||
@@ -617,13 +673,17 @@ def restore_precheck(precheck_id: str) -> dict[str, Any]:
|
||||
invoice_no=item.invoice_no,
|
||||
receipt_date=item.receipt_date,
|
||||
lot_no=item.lot_no or "",
|
||||
receipt_warehouse_code=item.receipt_warehouse_code or "",
|
||||
from_warehouse=item.from_warehouse,
|
||||
from_quantity=Decimal(item.erp_quantity) if item.erp_quantity else None,
|
||||
from_quantity=Decimal(item.external_quantity) if item.external_quantity else None,
|
||||
to_warehouse=item.to_warehouse,
|
||||
to_quantity=Decimal(item.receipt_quantity),
|
||||
result=item.result_code or (
|
||||
RESULT_EXECUTABLE if item.status == "ready_to_execute" else item.status
|
||||
),
|
||||
# 失败原因落库于 result_message(预检/重查降级均写);restore 不回读则
|
||||
# 前端刷新后原因恒为空,呈现「安静阻断」无法排查。
|
||||
reason=item.result_message or "",
|
||||
raw_lines=tuple(
|
||||
RawLineRefDTO(
|
||||
sheet=line.get("sheet", ""),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁。
|
||||
|
||||
用途:实现"收料数量 == ERP 账面库存 才可执行"的精确匹配规则,
|
||||
用途:实现"收料数量 == 外部系统 账面库存 才可执行"的精确匹配规则,
|
||||
禁止部分调拨、数量容差与隐式截断。
|
||||
依赖:标准库 decimal。
|
||||
逻辑:所有比较基于 Decimal 精确语义;非法数量(0/负数/非数字)在解析层拒绝。
|
||||
@@ -45,17 +45,17 @@ def strict_quantities_equal(left: Any, right: Any) -> bool:
|
||||
return Decimal(str(left)) == Decimal(str(right))
|
||||
|
||||
|
||||
def classify_quantity_match(receipt_quantity: Any, erp_quantity: Any | None) -> str:
|
||||
def classify_quantity_match(receipt_quantity: Any, external_quantity: Any | None) -> str:
|
||||
"""按严格相等规则分类数量匹配结果。
|
||||
|
||||
Args:
|
||||
receipt_quantity: 收料数量。
|
||||
erp_quantity: ERP 账面库存;None 表示无库存。
|
||||
external_quantity: 外部系统 账面库存;None 表示无库存。
|
||||
Returns:
|
||||
'executable' | 'blocked_quantity_mismatch' | 'blocked_inventory_not_found'。
|
||||
"""
|
||||
if erp_quantity is None:
|
||||
if external_quantity is None:
|
||||
return MATCH_INVENTORY_NOT_FOUND
|
||||
if strict_quantities_equal(receipt_quantity, erp_quantity):
|
||||
if strict_quantities_equal(receipt_quantity, external_quantity):
|
||||
return MATCH_EXECUTABLE
|
||||
return MATCH_QUANTITY_MISMATCH
|
||||
@@ -0,0 +1,69 @@
|
||||
"""在途调拨收料归档文件的可用性门禁(单一事实来源)。
|
||||
|
||||
用途:把「一份 ShippingReceiptReportFile 是否可用于调拨链路」的判定收敛为本模块,
|
||||
供来源状态投影(source_file_status)、预检取文件(movement_file_repository)、
|
||||
收料文件下载(api/in_transit_transfer)三处统一引用,防止口径漂移。
|
||||
依赖:models(ShippingReceiptReportFile)、date_policy(业务日 UTC 窗口换算)。
|
||||
逻辑:可用 = 未清理 且 当天(Asia/Shanghai 业务日)抓取 且 未过保留期;
|
||||
已失效(expired)= 可用核心的反相(未清理 且 [保留期已到 或 非当天抓取])。
|
||||
两函数同核推导,规则文本只存在一处。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import ColumnElement, and_, not_, or_
|
||||
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.in_transit_transfer.date_policy import business_date_utc_window
|
||||
|
||||
|
||||
def _fresh_and_retention_valid(now: datetime) -> ColumnElement:
|
||||
"""新鲜度 + 保留期核心条件(不含清理态,供可用/失效两函数共用)。"""
|
||||
window_start, window_end = business_date_utc_window(now)
|
||||
return and_(
|
||||
ShippingReceiptReportFile.created_at >= window_start,
|
||||
ShippingReceiptReportFile.created_at < window_end,
|
||||
or_(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_(None),
|
||||
ShippingReceiptReportFile.archive_expires_at > now,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def usable_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「当前可用的收料归档文件」SQL 条件。
|
||||
|
||||
判定:未清理(archive_deleted_at 为空)+ 当天(Asia/Shanghai 业务日)抓取
|
||||
+ 未过保留期(archive_expires_at 为空视为长期有效)。预检复用与下载
|
||||
只认可用文件;隔日/过期文件一律 fail-closed,交由上游触发重抓。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
_fresh_and_retention_valid(now),
|
||||
)
|
||||
|
||||
|
||||
def expired_receipt_file_condition(*, now: datetime | None = None) -> ColumnElement:
|
||||
"""返回「文件仍在但已失效」SQL 条件(来源状态投影 expired 的依据)。
|
||||
|
||||
判定:未清理 且 可用核心不成立(保留期已到 或 非当天业务日抓取)。
|
||||
命中即提示用户重试重抓,不报 ready,也不等待保留期清理任务落位。
|
||||
|
||||
Args:
|
||||
now: 可选判定时刻;naive 按 UTC 兼容处理,缺省取当前 UTC。
|
||||
Returns:
|
||||
可直接并入 .filter() 的单个 SQLAlchemy 条件。
|
||||
"""
|
||||
now = now or datetime.utcnow()
|
||||
return and_(
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
not_(_fresh_and_retention_valid(now)),
|
||||
)
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨每日历史恢复(自动复核待处理池)。
|
||||
|
||||
用途:下一排程对可恢复异常项用最新文件与 ERP 重新预检并创建新 Attempt;
|
||||
用途:下一排程对可恢复异常项用最新文件与 外部系统 重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:models、retry_service._recheck_item、TransferDeps。
|
||||
逻辑:恢复仅查询/匹配,不写 ERP;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
逻辑:恢复仅查询/匹配,不写 外部系统;每次恢复新 Attempt,旧 Attempt 不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 ERP)。
|
||||
"""在途调拨人工重试服务(基于冻结文件仅重新查询 外部系统)。
|
||||
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 ERP;
|
||||
用途:对允许的异常项执行人工重试,只创建新 Attempt 并重新查询 外部系统;
|
||||
Run 创建后禁止重新抓取 RPA(文件冻结);result_unknown 只读拒绝。
|
||||
依赖:models、erp_adapter、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 ERP、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
依赖:models、capability_client、quantity、status、audit、precheck_service.TransferDeps。
|
||||
逻辑:重试不写 外部系统、不替换文件;匹配成功进入 ready_to_execute,否则保持阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
@@ -17,58 +18,75 @@ from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer import status as status_machine
|
||||
from app.services.in_transit_transfer.audit import build_transfer_audit_event
|
||||
from app.services.in_transit_transfer.capability_client import StockTarget
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RESULT_ERP_QUERY_FAILED,
|
||||
RESULT_EXTERNAL_QUERY_FAILED,
|
||||
RESULT_EXECUTABLE,
|
||||
TransferDeps,
|
||||
)
|
||||
from app.services.in_transit_transfer.quantity import classify_quantity_match
|
||||
|
||||
RETRY_KIND_ERP_RECHECK = "erp_recheck"
|
||||
RETRY_KIND_EXTERNAL_RECHECK = "external_recheck"
|
||||
RETRY_KIND_RPA_REFETCH = "rpa_refetch"
|
||||
|
||||
# 可重查状态:可恢复阻断 + 可执行(已可执行的行也允许重查核对最新库存,
|
||||
# 避免预检后库存变化无法发现);终态(已执行/人工关闭等)仍不可重查。
|
||||
_RETRYABLE_STATUSES = {
|
||||
status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
status_machine.TransferStatus.READY_TO_EXECUTE.value,
|
||||
}
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id: str | None) -> str:
|
||||
"""对单个异常项重新查询 ERP 并更新状态(创建新 Attempt)。
|
||||
"""对单个异常项重新查询 外部系统 并更新状态(创建新 Attempt)。
|
||||
|
||||
Returns:
|
||||
重检后的 item 状态。
|
||||
"""
|
||||
route = deps.route_resolver.resolve(source_code=item.source_code, invoice_no=item.invoice_no)
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
operation_id = f"op-{uuid.uuid4().hex[:12]}"
|
||||
receipt_qty = Decimal(item.receipt_quantity)
|
||||
item.attempt_no += 1
|
||||
before_status = item.status
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="erp_query",
|
||||
item_id=item.id, attempt_no=item.attempt_no, kind="external_query",
|
||||
status="running", operation_id=operation_id,
|
||||
request_snapshot_json={
|
||||
"invoice_no": item.invoice_no, "erp_org": route.erp_org,
|
||||
"invoice_no": item.invoice_no, "external_org": route.external_org,
|
||||
"from_warehouse": route.from_warehouse, "to_warehouse": route.to_warehouse,
|
||||
"quantity": str(receipt_qty),
|
||||
},
|
||||
)
|
||||
db.session.add(attempt)
|
||||
db.session.flush()
|
||||
# [降级] 与 precheck 逐票语义一致:ERP 网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_erp_query_failed + 原因,
|
||||
# [降级] 与 precheck 逐票语义一致:外部系统网关/绑定故障(如集成连接器缺绑定
|
||||
# BindingNotFoundError)记为该行 blocked_external_query_failed + 原因,
|
||||
# 不中断批量重查、不向调用方抛基础设施异常(避免全局错误弹窗)。
|
||||
try:
|
||||
query = deps.erp.query_inventory(
|
||||
operation_id=operation_id,
|
||||
run_no=item.run.run_no if item.run else "RUN-PENDING",
|
||||
attempt_no=item.attempt_no,
|
||||
invoice_no=item.invoice_no,
|
||||
erp_org=route.erp_org,
|
||||
from_warehouse=route.from_warehouse,
|
||||
to_warehouse=route.to_warehouse,
|
||||
quantity=receipt_qty,
|
||||
stock = deps.capabilities.query_stock(
|
||||
operation_id=operation_id, external_org=route.external_org,
|
||||
targets=[StockTarget(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)],
|
||||
)
|
||||
stock_qty = stock.lookup(
|
||||
material_no=item.material_no, from_warehouse=item.from_warehouse, lot_no=item.lot_no or "",
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
detail = str(exc).strip() or getattr(exc, "message", "") or exc.__class__.__name__
|
||||
# 降级只落 DB(result_message/审计),若再无应用日志,控制台侧完全无痕可查。
|
||||
logger.warning(
|
||||
"transfer external recheck failed (degrade to blocked): invoice=%s item=%s attempt=%s error=%s",
|
||||
item.invoice_no, item.id, item.attempt_no, detail,
|
||||
)
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = RESULT_ERP_QUERY_FAILED
|
||||
item.result_message = f"erp query failed: {detail}"
|
||||
item.result_code = RESULT_EXTERNAL_QUERY_FAILED
|
||||
item.result_message = f"external query failed: {detail}"
|
||||
attempt.status = "failed"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
@@ -88,16 +106,19 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
))
|
||||
db.session.flush()
|
||||
return item.status
|
||||
if not query.found or classify_quantity_match(receipt_qty, query.quantity) != RESULT_EXECUTABLE:
|
||||
if stock_qty is None or classify_quantity_match(receipt_qty, stock_qty) != RESULT_EXECUTABLE:
|
||||
item.status = status_machine.TransferStatus.BLOCKED_RECOVERABLE.value
|
||||
item.result_code = "blocked_inventory_not_found" if not query.found else "blocked_quantity_mismatch"
|
||||
item.result_message = "erp inventory not found" if not query.found else "strict quantity mismatch"
|
||||
item.result_code = "blocked_inventory_not_found" if stock_qty is None else "blocked_quantity_mismatch"
|
||||
item.result_message = "external inventory not found" if stock_qty is None else "strict quantity mismatch"
|
||||
# 查无记录与数量不足都是外部系统的真实答复:库存数必须落库展示(查无记录按 0),
|
||||
# 不得显示"-"让用户误以为查询失败。
|
||||
item.external_quantity = str(stock_qty) if stock_qty is not None else "0"
|
||||
attempt.status = "failed"
|
||||
else:
|
||||
item.status = status_machine.TransferStatus.READY_TO_EXECUTE.value
|
||||
item.result_code = None
|
||||
item.result_message = None
|
||||
item.erp_quantity = str(query.quantity)
|
||||
item.external_quantity = str(stock_qty)
|
||||
attempt.status = "success"
|
||||
attempt.completed_at = datetime.utcnow()
|
||||
db.session.add(build_transfer_audit_event(
|
||||
@@ -119,14 +140,14 @@ def _recheck_item(item: TransferInvoiceItem, *, deps: TransferDeps, request_id:
|
||||
return item.status
|
||||
|
||||
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_RECHECK,
|
||||
def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""人工重试异常项。
|
||||
|
||||
Args:
|
||||
item_id: TransferInvoiceItem.id。
|
||||
deps: 注入依赖。
|
||||
kind: erp_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
kind: external_recheck(默认);rpa_refetch 在 Run 创建后禁止。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"item_id": ..., "status": ..., "attempt_no": ...}。
|
||||
@@ -137,14 +158,14 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
|
||||
kind_value = str(kind or "").strip()
|
||||
if kind_value == RETRY_KIND_RPA_REFETCH:
|
||||
raise ValidationError("RPA refetch is not allowed after execution run is created", code="TRANSFER.RETRY_RPA_NOT_ALLOWED")
|
||||
if kind_value != RETRY_KIND_ERP_RECHECK:
|
||||
if kind_value != RETRY_KIND_EXTERNAL_RECHECK:
|
||||
raise ValidationError(f"unsupported retry kind: {kind_value}", code="TRANSFER.RETRY_KIND_INVALID")
|
||||
item = db.session.get(TransferInvoiceItem, item_id)
|
||||
if item is None:
|
||||
raise NotFoundError("transfer invoice item not found", code="TRANSFER.ITEM_NOT_FOUND")
|
||||
if item.status == status_machine.TransferStatus.RESULT_UNKNOWN.value:
|
||||
raise ValidationError("result_unknown is read-only; follow manual verification SOP", code="TRANSFER_RESULT_UNKNOWN")
|
||||
if item.status not in {status_machine.TransferStatus.BLOCKED_RECOVERABLE.value}:
|
||||
if item.status not in _RETRYABLE_STATUSES:
|
||||
raise ValidationError(f"item status {item.status} is not retryable", code="TRANSFER.RETRY_NOT_ALLOWED")
|
||||
|
||||
status = _recheck_item(item, deps=deps, request_id=request_id)
|
||||
@@ -154,12 +175,12 @@ def retry_item(*, item_id: int, deps: TransferDeps, kind: str = RETRY_KIND_ERP_R
|
||||
|
||||
def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str] | None = None,
|
||||
actor_id: int | None = None, request_id: str | None = None) -> dict:
|
||||
"""批量重查 ERP 库存:对同一预检下全部/指定的可恢复阻断行逐票重查并刷新。
|
||||
"""批量重查 外部系统 库存:对同一预检下全部/指定的可重查行(可恢复阻断 + 可执行)逐票重查并刷新。
|
||||
|
||||
Args:
|
||||
precheck_no: 预检编号(定位明细集合)。
|
||||
deps: 注入依赖(erp = 网关适配器)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可恢复阻断行。
|
||||
deps: 注入依赖(capabilities = 外部系统网关客户端)。
|
||||
invoice_nos: 可选,按 Invoice(单号)过滤;缺省 = 该预检全部可重查行。
|
||||
actor_id / request_id: 审计上下文。
|
||||
Returns:
|
||||
{"precheck_no", "total", "results": [{invoice_no, item_id, ok, status|error}]};
|
||||
@@ -170,8 +191,9 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=precheck_no).first()
|
||||
if precheck is None:
|
||||
raise NotFoundError("precheck not found", code="TRANSFER.PRECHECK_NOT_FOUND")
|
||||
query = TransferInvoiceItem.query.filter_by(
|
||||
precheck_id=precheck.id, status=status_machine.TransferStatus.BLOCKED_RECOVERABLE.value,
|
||||
query = TransferInvoiceItem.query.filter(
|
||||
TransferInvoiceItem.precheck_id == precheck.id,
|
||||
TransferInvoiceItem.status.in_(_RETRYABLE_STATUSES),
|
||||
)
|
||||
wanted = [str(x or "").strip() for x in (invoice_nos or []) if str(x or "").strip()]
|
||||
if wanted:
|
||||
@@ -181,7 +203,7 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
results: list[dict] = []
|
||||
for item in items:
|
||||
try:
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_ERP_RECHECK,
|
||||
retry_item(item_id=item.id, deps=deps, kind=RETRY_KIND_EXTERNAL_RECHECK,
|
||||
actor_id=actor_id, request_id=request_id)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": True, "status": item.status})
|
||||
@@ -189,6 +211,11 @@ def requery_items(*, precheck_no: str, deps: TransferDeps, invoice_nos: list[str
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False, "error": exc.message})
|
||||
except Exception as exc: # noqa: BLE001 —— 批量隔离兜底:任何单行异常不炸整批
|
||||
# 与 _recheck_item 降级同理:DB 只留单行结果,控制台必须同步留痕。
|
||||
logger.warning(
|
||||
"transfer requery row crashed (skipped): invoice=%s item=%s error=%s",
|
||||
item.invoice_no, item.id, str(exc).strip() or exc.__class__.__name__,
|
||||
)
|
||||
results.append({"invoice_no": item.invoice_no, "item_id": item.id,
|
||||
"ok": False,
|
||||
"error": str(exc).strip() or exc.__class__.__name__})
|
||||
|
||||
@@ -28,7 +28,7 @@ def serialize_summary(summary) -> dict[str, Any]:
|
||||
"blocked_count": summary.counts.blocked_count,
|
||||
},
|
||||
"estimated_transfer_quantity": summary.estimated_transfer_quantity,
|
||||
"estimated_erp_write_count": summary.estimated_erp_write_count,
|
||||
"estimated_external_write_count": summary.estimated_external_write_count,
|
||||
"precheck_hash": summary.precheck_hash,
|
||||
}
|
||||
|
||||
|
||||
@@ -3,14 +3,20 @@
|
||||
用途:只读货代收料链路已有事实(ShippingReceiptRpaUnitRun + ShippingReceiptReportFile),
|
||||
按来源实例投影出"是否有 ready 文件 / 是否抓取中 / 是否失败 / 无文件待触发",
|
||||
供 /sources 接口与前端门禁/状态标识使用。调拨不维护独立抓取状态表(低耦合)。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)。
|
||||
逻辑:按来源取该来源最新收料执行单元;有文件 → ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;否则 → none。
|
||||
依赖:models(ShippingReceiptRpaUnitRun / ShippingReceiptReportFile)、
|
||||
receipt_file_gate(可用/失效判定单一事实来源)。
|
||||
逻辑:按来源取该来源最新收料执行单元;命中可用门禁(当天业务日抓取且未过期,
|
||||
见 receipt_file_gate)→ ready;有进行中单元 → fetching;
|
||||
最新单元为失败终态 → failed;文件仍在但已失效 → expired;否则 → none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingReceiptReportFile, ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
expired_receipt_file_condition,
|
||||
usable_receipt_file_condition,
|
||||
)
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
@@ -19,16 +25,19 @@ FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
"""返回某来源的收料文件状态投影。
|
||||
|
||||
失效判定(不依赖保留期清理任务落位,与预检取文件/下载同口径,见
|
||||
receipt_file_gate):保留期已到 或 非当前业务日(Asia/Shanghai)抓取。
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'none'}。
|
||||
file_status ∈ {'ready', 'fetching', 'failed', 'expired', 'none'}。
|
||||
"""
|
||||
report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
usable_receipt_file_condition(),
|
||||
)
|
||||
.order_by(ShippingReceiptReportFile.created_at.desc(), ShippingReceiptReportFile.id.desc())
|
||||
.first()
|
||||
@@ -60,4 +69,17 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
if latest_unit is not None and latest_unit.status in FAILED_UNIT_STATUSES:
|
||||
return {'file_status': 'failed', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
# 文件仍在但已失效(保留期已到或隔日旧文件):不报 ready,单独投影 expired 提示重抓。
|
||||
expired_report = (
|
||||
ShippingReceiptReportFile.query
|
||||
.join(ShippingReceiptReportFile.unit_run)
|
||||
.filter(
|
||||
ShippingReceiptReportFile.unit_run.has(source_code=source_code),
|
||||
expired_receipt_file_condition(),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if expired_report is not None:
|
||||
return {'file_status': 'expired', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
|
||||
return {'file_status': 'none', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
@@ -4,7 +4,7 @@
|
||||
让 create_precheck / restore / 未来回调等调用方都经由本服务,不各自散落改表。
|
||||
依赖:models(TransferSourceJob)、status_machine。
|
||||
逻辑:本服务只操作 run 内来源状态;(run_id, source_code) 唯一由模型约束;
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 ERP/触发 RPA。
|
||||
不承担跨 run 防重(不同 run/不同人各自独立 job),也不写 外部系统/触发 RPA。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
逻辑:转换表声明即白名单,未声明的迁移一律抛 TransferStateError;
|
||||
result_unknown / manually_closed / success / duplicate_success /
|
||||
not_matured / cancelled 为无出边终态;
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 ERP 业务结果。
|
||||
通知失败(notification_failed)是通知投递状态,绝不改写 外部系统 业务结果。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,7 +39,7 @@ class TransferStatus(StrEnum):
|
||||
|
||||
|
||||
class TransferRunStatus(StrEnum):
|
||||
"""Run 级生命周期;ERP 结果与通知结果分离。"""
|
||||
"""Run 级生命周期;外部系统 结果与通知结果分离。"""
|
||||
|
||||
QUEUED = "queued"
|
||||
PREPARING_FILES = "preparing_files"
|
||||
@@ -101,7 +101,7 @@ ITEM_TRANSITIONS: dict[str, frozenset[str]] = {
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
TransferStatus.BLOCKED_RECOVERABLE.value: frozenset({
|
||||
TransferStatus.PRECHECKING.value, # 仅 ERP 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.PRECHECKING.value, # 仅 外部系统 重查/重新预检,创建新 Attempt
|
||||
TransferStatus.MANUALLY_CLOSED.value,
|
||||
TransferStatus.CANCELLED.value,
|
||||
}),
|
||||
@@ -199,19 +199,19 @@ def assert_transition_allowed(
|
||||
|
||||
|
||||
def apply_notification_failure(run_status: str) -> str:
|
||||
"""通知失败不改变 ERP 结果。
|
||||
"""通知失败不改变 外部系统 结果。
|
||||
|
||||
Args:
|
||||
run_status: Run 的 ERP 业务终态。
|
||||
run_status: Run 的 外部系统 业务终态。
|
||||
Returns:
|
||||
原 run_status(保持不变)。
|
||||
Raises:
|
||||
TransferStateError: Run 尚未进入 ERP 终态时不允许记录通知失败。
|
||||
TransferStateError: Run 尚未进入 外部系统 终态时不允许记录通知失败。
|
||||
"""
|
||||
status = str(run_status or "").strip()
|
||||
if status not in {TransferRunStatus.SUCCESS.value, TransferRunStatus.PARTIAL_FAILED.value}:
|
||||
raise TransferStateError(
|
||||
"notification failure only allowed after ERP terminal status",
|
||||
"notification failure only allowed after 外部系统 terminal status",
|
||||
current=status,
|
||||
)
|
||||
return status
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨策略硬门禁。
|
||||
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
用途:一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
强制默认 10 分钟确认有效期。
|
||||
依赖:app.core.errors.AppError、standard decimal。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError,
|
||||
@@ -24,7 +24,7 @@ class TransferStrategyPolicy:
|
||||
|
||||
allow_partial: bool = False
|
||||
quantity_tolerance: Decimal = Decimal("0")
|
||||
allow_erp_auto_retry: bool = False
|
||||
allow_external_auto_retry: bool = False
|
||||
confirm_ttl_seconds: int = DEFAULT_CONFIRM_TTL_SECONDS
|
||||
|
||||
|
||||
@@ -46,14 +46,14 @@ def validate_strategy(strategy: TransferStrategyPolicy) -> None:
|
||||
Args:
|
||||
strategy: 待校验策略。
|
||||
Raises:
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 ERP 自动重试。
|
||||
StrategyViolationError: 开启部分调拨、非零容差或 外部系统 自动重试。
|
||||
"""
|
||||
if strategy.allow_partial:
|
||||
raise StrategyViolationError("partial transfer is not supported in phase 1", reason="allow_partial")
|
||||
if strategy.quantity_tolerance != Decimal("0"):
|
||||
raise StrategyViolationError("quantity tolerance is not supported in phase 1", reason="quantity_tolerance")
|
||||
if strategy.allow_erp_auto_retry:
|
||||
raise StrategyViolationError("ERP auto retry is forbidden in phase 1", reason="allow_erp_auto_retry")
|
||||
if strategy.allow_external_auto_retry:
|
||||
raise StrategyViolationError("External auto retry is forbidden in phase 1", reason="allow_external_auto_retry")
|
||||
|
||||
|
||||
def default_strategy() -> TransferStrategyPolicy:
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
"""在途调拨类型契约。
|
||||
|
||||
用途:定义调拨业务类型(在途仓至HUB仓 / HUB仓维修出 / HUB仓间调拨)及各类型
|
||||
的收料数据范围规则;类型 2/3 一期占位(fail-closed 拒绝预检,规则先冻结)。
|
||||
依赖:app.core.errors.ValidationError、invoice_aggregator.AggregatedInvoice。
|
||||
逻辑:类型决定预检纳入哪些收料票——类型 1 只保留 INVOICE 以 HOM/HOX/WTP 开头
|
||||
的票(大小写不敏感,范围外票与收料日期范围过滤同语义,静默排除不入明细);
|
||||
类型 2 规则已定(ODM ID=HoxinRMA)待收料文件解析层支持 odm_id 字段后启用;
|
||||
类型 3 规则待业务定义。调用方必须先 ensure_transfer_type_supported 再过滤。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from enum import StrEnum
|
||||
from typing import Iterable
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
|
||||
# 类型不支持(占位类型被调用)时的稳定错误码。
|
||||
TRANSFER_TYPE_NOT_SUPPORTED = "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
|
||||
|
||||
class TransferType(StrEnum):
|
||||
"""调拨业务类型(值与前端/i18n、transfer_runs.transfer_type 列一致)。"""
|
||||
|
||||
IN_TRANSIT_TO_HUB = "in_transit_to_hub" # 在途仓至HUB仓
|
||||
HUB_REPAIR_OUT = "hub_repair_out" # HUB仓维修出(占位)
|
||||
HUB_TO_HUB = "hub_to_hub" # HUB仓间调拨(占位)
|
||||
|
||||
|
||||
# 一期已实现预检/执行链路的类型;其余类型 fail-closed(占位,防止误生成 外部系统 单)。
|
||||
SUPPORTED_TRANSFER_TYPES: frozenset[TransferType] = frozenset({TransferType.IN_TRANSIT_TO_HUB})
|
||||
|
||||
# 类型 1(在途仓至HUB仓)数据范围:INVOICE 开头前缀(大小写不敏感)。
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES: tuple[str, ...] = ("HOM", "HOX", "WTP")
|
||||
|
||||
# 类型 2(HUB仓维修出)数据范围:ODM ID 精确值;待 movement 文件暴露 odm_id 后启用。
|
||||
HUB_REPAIR_OUT_ODM_ID = "HoxinRMA"
|
||||
|
||||
|
||||
def normalize_transfer_type(value: str | TransferType | None) -> TransferType:
|
||||
"""规范化调拨类型入参;缺省/空值回落到类型 1(存量调用方语义不变)。
|
||||
|
||||
Args:
|
||||
value: 前端/API 传入的调拨类型值。
|
||||
Returns:
|
||||
TransferType 枚举。
|
||||
Raises:
|
||||
ValidationError: 非法类型值(不在枚举内)。
|
||||
"""
|
||||
raw = str(value.value if isinstance(value, TransferType) else (value or "")).strip()
|
||||
if not raw:
|
||||
return TransferType.IN_TRANSIT_TO_HUB
|
||||
try:
|
||||
return TransferType(raw)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f"unknown transfer type: {raw}",
|
||||
code="TRANSFER.TRANSFER_TYPE_INVALID",
|
||||
details={"transfer_type": raw},
|
||||
) from exc
|
||||
|
||||
|
||||
def ensure_transfer_type_supported(transfer_type: TransferType) -> None:
|
||||
"""占位类型 fail-closed:类型 2/3 处理链路未实现前禁止进入预检。
|
||||
|
||||
Args:
|
||||
transfer_type: 已规范化的调拨类型。
|
||||
Raises:
|
||||
ValidationError: 类型未实现(TRANSFER_TYPE_NOT_SUPPORTED)。
|
||||
"""
|
||||
if transfer_type not in SUPPORTED_TRANSFER_TYPES:
|
||||
raise ValidationError(
|
||||
f"transfer type not supported yet: {transfer_type.value}",
|
||||
code=TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
details={"transfer_type": transfer_type.value},
|
||||
)
|
||||
|
||||
|
||||
def filter_invoices_for_type(
|
||||
invoices: Iterable[AggregatedInvoice],
|
||||
transfer_type: TransferType,
|
||||
) -> list[AggregatedInvoice]:
|
||||
"""按类型的收料数据范围过滤汇总票(返回保留项,保持原顺序)。
|
||||
|
||||
Args:
|
||||
invoices: 已汇总的收料票。
|
||||
transfer_type: 已规范化且已确认支持的调拨类型。
|
||||
Returns:
|
||||
类型范围内的票列表。
|
||||
"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
prefixes = tuple(prefix.upper() for prefix in IN_TRANSIT_TO_HUB_INVOICE_PREFIXES)
|
||||
return [
|
||||
invoice for invoice in invoices
|
||||
if str(invoice.invoice_no or "").strip().upper().startswith(prefixes)
|
||||
]
|
||||
# 类型 2/3 的过滤规则在启用时补齐(此前 ensure_transfer_type_supported 已拦截)。
|
||||
return list(invoices)
|
||||
|
||||
|
||||
def transfer_type_scope_note(transfer_type: TransferType) -> str:
|
||||
"""类型的范围规则说明(写入 TransferPrecheck.scope_json 供审计追溯)。"""
|
||||
if transfer_type == TransferType.IN_TRANSIT_TO_HUB:
|
||||
return f"invoice_prefix:{'+'.join(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES).lower()}"
|
||||
if transfer_type == TransferType.HUB_REPAIR_OUT:
|
||||
return f"odm_id:{HUB_REPAIR_OUT_ODM_ID}"
|
||||
return "pending_rule"
|
||||
@@ -0,0 +1,99 @@
|
||||
"""在途调拨存储层去 ERP 化:列/索引改名、枚举值刷写、约束替换
|
||||
|
||||
Revision ID: ex1a2b3c4d5e6
|
||||
Revises: tt3d4e5f6a7b
|
||||
Create Date: 2026-09-22 21:40:00.000000
|
||||
|
||||
用途:与代码去 ERP 化(外部系统通用命名)配套的存储层改造——
|
||||
1) 列改名:transfer_invoice_items.erp_quantity→external_quantity、
|
||||
erp_document_no→external_document_no;transfer_prechecks.estimated_erp_write_count→
|
||||
estimated_external_write_count;同步索引 ix_transfer_invoice_items_erp_document_no 改名。
|
||||
2) 枚举/审计值刷写:transfer_attempts.kind(erp_query/erp_write→external_query/external_write)、
|
||||
transfer_invoice_items.result_code(blocked_erp_query_failed→blocked_external_query_failed、
|
||||
erp_query_timeout→external_query_timeout)与 result_message 前缀、
|
||||
transfer_audit_events.event_type(TRANSFER_ERP_→TRANSFER_EXTERNAL_)、
|
||||
transfer_archives.object_type(erp_inventory_snapshot→external_inventory_snapshot)。
|
||||
3) 约束替换:ck_transfer_attempts_kind 枚举集合改为 external_*。
|
||||
依赖:tt3d4e5f6a7b 为上一 head。
|
||||
逻辑:先删旧约束再刷历史行数据(避免刷写被旧 CHECK 拦截)后建新约束;列/索引经 batch 兼容 SQLite;
|
||||
downgrade 全量反向恢复。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'ex1a2b3c4d5e6'
|
||||
down_revision = 'tt3d4e5f6a7b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""删旧约束 → 刷历史枚举值 → 建新约束 → 列/索引改名。"""
|
||||
# [STEP 1] 先删旧 Attempt 类型约束,否则刷写 external_* 值会被旧 CHECK 拦截。
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
|
||||
|
||||
# [STEP 2] 历史行数据刷写。
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'external_query' WHERE kind = 'erp_query'")
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'external_write' WHERE kind = 'erp_write'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_code = 'blocked_external_query_failed' "
|
||||
"WHERE result_code = 'blocked_erp_query_failed'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_code = 'external_query_timeout' "
|
||||
"WHERE result_code = 'erp_query_timeout'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_message = REPLACE(result_message, 'erp ', 'external ') "
|
||||
"WHERE result_message LIKE '%erp %'")
|
||||
op.execute("UPDATE transfer_audit_events SET event_type = REPLACE(event_type, 'TRANSFER_ERP_', 'TRANSFER_EXTERNAL_') "
|
||||
"WHERE event_type LIKE 'TRANSFER_ERP_%'")
|
||||
op.execute("UPDATE transfer_archives SET object_type = 'external_inventory_snapshot' "
|
||||
"WHERE object_type = 'erp_inventory_snapshot'")
|
||||
|
||||
# [STEP 3] 建新 Attempt 类型约束(新枚举集合)。
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_attempts_kind',
|
||||
"kind IN ('precheck', 'rpa', 'external_query', 'external_write')",
|
||||
)
|
||||
|
||||
# [STEP 3] 列与索引改名(与模型 external_* 命名对齐)。
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.alter_column('erp_quantity', new_column_name='external_quantity', existing_type=sa.String(length=40))
|
||||
batch.alter_column('erp_document_no', new_column_name='external_document_no', existing_type=sa.String(length=64))
|
||||
batch.drop_index('ix_transfer_invoice_items_erp_document_no')
|
||||
batch.create_index('ix_transfer_invoice_items_external_document_no', ['external_document_no'])
|
||||
with op.batch_alter_table('transfer_prechecks') as batch:
|
||||
batch.alter_column(
|
||||
'estimated_erp_write_count', new_column_name='estimated_external_write_count', existing_type=sa.Integer(),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""反向恢复:列/索引改回 → 删新约束 → 枚举值还原 → 旧约束回补。"""
|
||||
with op.batch_alter_table('transfer_prechecks') as batch:
|
||||
batch.alter_column(
|
||||
'estimated_external_write_count', new_column_name='estimated_erp_write_count', existing_type=sa.Integer(),
|
||||
)
|
||||
with op.batch_alter_table('transfer_invoice_items') as batch:
|
||||
batch.drop_index('ix_transfer_invoice_items_external_document_no')
|
||||
batch.create_index('ix_transfer_invoice_items_erp_document_no', ['erp_document_no'])
|
||||
batch.alter_column('external_document_no', new_column_name='erp_document_no', existing_type=sa.String(length=64))
|
||||
batch.alter_column('external_quantity', new_column_name='erp_quantity', existing_type=sa.String(length=40))
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.drop_constraint('ck_transfer_attempts_kind', type_='check')
|
||||
op.execute("UPDATE transfer_archives SET object_type = 'erp_inventory_snapshot' "
|
||||
"WHERE object_type = 'external_inventory_snapshot'")
|
||||
op.execute("UPDATE transfer_audit_events SET event_type = REPLACE(event_type, 'TRANSFER_EXTERNAL_', 'TRANSFER_ERP_') "
|
||||
"WHERE event_type LIKE 'TRANSFER_EXTERNAL_%'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_message = REPLACE(result_message, 'external ', 'erp ') "
|
||||
"WHERE result_message LIKE '%external %'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_code = 'blocked_erp_query_failed' "
|
||||
"WHERE result_code = 'blocked_external_query_failed'")
|
||||
op.execute("UPDATE transfer_invoice_items SET result_code = 'erp_query_timeout' "
|
||||
"WHERE result_code = 'external_query_timeout'")
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'erp_write' WHERE kind = 'external_write'")
|
||||
op.execute("UPDATE transfer_attempts SET kind = 'erp_query' WHERE kind = 'external_query'")
|
||||
with op.batch_alter_table('transfer_attempts') as batch:
|
||||
batch.create_check_constraint(
|
||||
'ck_transfer_attempts_kind',
|
||||
"kind IN ('precheck', 'rpa', 'erp_query', 'erp_write')",
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
"""仓库映射新增在途仓编码;调拨明细记录收料仓库匹配键
|
||||
|
||||
Revision ID: it2c3d4e5f6a7
|
||||
Revises: re1f3a4b5c6d
|
||||
Create Date: 2026-09-22 12:00:00.000000
|
||||
|
||||
用途:shipping_inventory_external_mappings 增加 in_transit_warehouse_code(在途调拨拨出库位
|
||||
来源,保存端必填);transfer_invoice_items 增加 receipt_warehouse_code(收料文件
|
||||
「仓库」列原值,inventory_match 源映射行匹配键的审计留痕)。
|
||||
依赖:re1f3a4b5c6d 为当前 head。
|
||||
逻辑:两列均为带 '' 默认值的追加列,不改既有数据;downgrade 直接删列。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'it2c3d4e5f6a7'
|
||||
down_revision = 're1f3a4b5c6d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""映射表加在途仓编码(拨出库位来源)、调拨明细表加收料仓库匹配键。"""
|
||||
op.add_column(
|
||||
'shipping_inventory_external_mappings',
|
||||
sa.Column('in_transit_warehouse_code', sa.String(length=64), nullable=False,
|
||||
server_default='', comment='在途仓编码(在途调拨拨出库位来源)'),
|
||||
)
|
||||
op.add_column(
|
||||
'transfer_invoice_items',
|
||||
sa.Column('receipt_warehouse_code', sa.String(length=64), nullable=False,
|
||||
server_default='', comment='收料文件仓库列原值(映射行匹配键)'),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚:删除两列(存量数据随列丢弃,无其他依赖)。"""
|
||||
op.drop_column('transfer_invoice_items', 'receipt_warehouse_code')
|
||||
op.drop_column('shipping_inventory_external_mappings', 'in_transit_warehouse_code')
|
||||
@@ -0,0 +1,42 @@
|
||||
"""transfer_runs 新增调拨业务类型列
|
||||
|
||||
Revision ID: tt3d4e5f6a7b
|
||||
Revises: it2c3d4e5f6a7
|
||||
Create Date: 2026-09-22 18:00:00.000000
|
||||
|
||||
用途:transfer_runs 增加 transfer_type(调拨业务类型:在途仓至HUB仓/HUB仓维修出/
|
||||
HUB仓间调拨),作为 Run 级数据范围真相源;一期仅 in_transit_to_hub 进入
|
||||
处理链路,其余为占位值(服务层 fail-closed)。
|
||||
依赖:it2c3d4e5f6a7 为当前 head。
|
||||
逻辑:带 'in_transit_to_hub' 默认值的追加列,存量 Run 归类型 1(与原行为一致);
|
||||
downgrade 直接删列。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = 'tt3d4e5f6a7b'
|
||||
down_revision = 'it2c3d4e5f6a7'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""调拨 Run 表加调拨业务类型列(存量数据默认归在途仓至HUB仓)。"""
|
||||
op.add_column(
|
||||
'transfer_runs',
|
||||
sa.Column('transfer_type', sa.String(length=32), nullable=False,
|
||||
server_default='in_transit_to_hub', comment='调拨业务类型(in_transit_to_hub/hub_repair_out/hub_to_hub)'),
|
||||
)
|
||||
op.create_check_constraint(
|
||||
'ck_transfer_runs_transfer_type',
|
||||
'transfer_runs',
|
||||
"transfer_type IN ('in_transit_to_hub', 'hub_repair_out', 'hub_to_hub')",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚:删除检查约束与列(存量数据随列丢弃,无其他依赖)。"""
|
||||
op.drop_constraint('ck_transfer_runs_transfer_type', 'transfer_runs', type_='check')
|
||||
op.drop_column('transfer_runs', 'transfer_type')
|
||||
@@ -29,8 +29,8 @@ def _jwt_headers(user: User) -> dict:
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 预检依赖,并预置可执行库存。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
@@ -99,7 +99,7 @@ def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_he
|
||||
data = body["data"]
|
||||
assert data["precheck_id"].startswith("TPC-")
|
||||
assert data["precheck_hash"].startswith("sha256:")
|
||||
assert data["estimated_erp_write_count"] == 2
|
||||
assert data["estimated_external_write_count"] == 2
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
@@ -136,6 +136,25 @@ def test_create_precheck_validates_source_codes(app, client, admin_headers, tran
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps):
|
||||
"""transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": "in_transit_to_hub",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
|
||||
for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"):
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": bad_type,
|
||||
})
|
||||
assert response.status_code == 400, bad_type
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
"""GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
@@ -146,7 +165,7 @@ def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
assert restored.status_code == 200
|
||||
body = restored.get_json()["data"]
|
||||
assert body["summary"]["precheck_hash"] == created["precheck_hash"]
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"}
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
|
||||
@@ -156,14 +175,14 @@ def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps)
|
||||
|
||||
|
||||
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。"""
|
||||
"""执行预检 → 201 run_no;GET run 返回 外部系统 单号聚合结果。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
@@ -172,7 +191,7 @@ def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers)
|
||||
assert run.status_code == 200
|
||||
result = run.get_json()["data"]["result"]
|
||||
assert len(result["erp_documents"]) == 2
|
||||
assert len(result["external_documents"]) == 2
|
||||
assert result["exceptions"] == []
|
||||
|
||||
|
||||
@@ -190,7 +209,7 @@ def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, trans
|
||||
db.session.commit()
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
@@ -219,7 +238,7 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
|
||||
@@ -228,9 +247,9 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=run_no).first()
|
||||
run.status = "executing"
|
||||
item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first()
|
||||
item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="HOX-002").first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
item.external_document_no = None
|
||||
db.session.commit()
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={
|
||||
"reason": "货源调整,停止剩余",
|
||||
@@ -248,7 +267,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
@@ -266,7 +285,7 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
@@ -286,7 +305,7 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
|
||||
@@ -308,7 +327,7 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
|
||||
@@ -322,24 +341,24 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a
|
||||
|
||||
|
||||
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。"""
|
||||
"""下载预检冻结的 外部系统 库存表 → 200(csv),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers)
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/external-inventory", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert "csv" in response.content_type
|
||||
assert b"INV-001" in response.data
|
||||
assert b"HOM-001" in response.data
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first()
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
@@ -355,7 +374,7 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
|
||||
f"{API_PREFIX}/runs/{run_no}/erp-inventory",
|
||||
f"{API_PREFIX}/runs/{run_no}/external-inventory",
|
||||
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
|
||||
response = client.get(path, headers=unauthorized_headers)
|
||||
assert response.status_code == 403, path
|
||||
@@ -370,7 +389,7 @@ def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client,
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={
|
||||
"invoice_nos": ["INV-001"],
|
||||
"invoice_nos": ["HOM-001"],
|
||||
"from_warehouse": "FAKE-TRANSIT",
|
||||
"to_warehouse": "FAKE-HUB",
|
||||
"quantity": "1",
|
||||
@@ -379,7 +398,7 @@ def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client,
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"]
|
||||
documents = run["result"]["erp_documents"]
|
||||
documents = run["result"]["external_documents"]
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
|
||||
assert documents[0]["to_warehouse"] == "HUB-CN01"
|
||||
assert documents[0]["total_quantity"] == "1200"
|
||||
@@ -395,17 +414,17 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
item.result_message = "收料 1200 / ERP 1000"
|
||||
item.result_message = "收料 1200 / 外部系统 1000"
|
||||
db.session.commit()
|
||||
|
||||
listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
|
||||
assert listed.status_code == 200
|
||||
invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]}
|
||||
assert "INV-001" in invoice_set
|
||||
assert "INV-002" not in invoice_set # 可执行项不在待处理池
|
||||
assert "HOM-001" in invoice_set
|
||||
assert "HOX-002" not in invoice_set # 可执行项不在待处理池
|
||||
assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"}
|
||||
|
||||
summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers)
|
||||
@@ -456,8 +475,8 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
|
||||
用户上下文(actor_id)随请求正确传递。
|
||||
"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # 与文件 1200 不符 → blocked_quantity_mismatch
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 与文件 1200 不符 → blocked_quantity_mismatch
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
@@ -469,7 +488,7 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{precheck_no}/items/requery",
|
||||
headers=admin_headers,
|
||||
json={"invoice_nos": ["INV-001"]},
|
||||
json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
@@ -478,5 +497,5 @@ def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch,
|
||||
assert data["precheck_no"] == precheck_no
|
||||
assert data["total"] == 1
|
||||
result = data["results"][0]
|
||||
assert result["invoice_no"] == "INV-001"
|
||||
assert result["invoice_no"] == "HOM-001"
|
||||
assert result["ok"] is True
|
||||
@@ -701,13 +701,13 @@ def dbs_ready_file() -> dict:
|
||||
"checksum": "d" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "lot_no": "LOT-10", "material_code": "MAT-001",
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "lot_no": "LOT-11", "material_code": "MAT-001",
|
||||
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "lot_no": "LOT-20", "material_code": "MAT-002",
|
||||
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
|
||||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||||
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
@@ -729,7 +729,7 @@ def crane_ready_file() -> dict:
|
||||
"checksum": "c" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "lot_no": "LOT-8", "material_code": "MAT-200",
|
||||
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
|
||||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||||
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
|
||||
],
|
||||
@@ -751,7 +751,7 @@ def same_day_receipt_file() -> dict:
|
||||
"checksum": "s" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 3, "doc_no": "RCP-3", "lot_no": "INV-041", "material_code": "MAT-041",
|
||||
{"sheet": "Receipt", "row_no": 3, "doc_no": "HOM-3", "lot_no": "INV-041", "material_code": "MAT-041",
|
||||
"material_name": "连接器组件", "specification": "C 型",
|
||||
"movement_date": "2026-08-06", "quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
],
|
||||
|
||||
@@ -23,8 +23,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 依赖并预置库存。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
@@ -90,12 +90,12 @@ def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, tran
|
||||
|
||||
create_execution_run(precheck, deps=transfer_deps, actor_id=None)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
invoice_no="INV-001",
|
||||
invoice_no="HOM-001",
|
||||
).first()
|
||||
handler = get_handler(JobType.TRANSFER_ITEM)
|
||||
handler(None, {"item_id": item.id})
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "success"
|
||||
assert refreshed.erp_document_no
|
||||
assert refreshed.external_document_no
|
||||
|
||||
@@ -16,18 +16,19 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _bulk_file(count: int) -> dict:
|
||||
"""生成 count 行收料文件(每 Invoice 单行)。"""
|
||||
"""生成 count 行收料文件(每 Invoice 单行;movement 领域字段键 + 类型1前缀)。"""
|
||||
rows = []
|
||||
for index in range(1, count + 1):
|
||||
rows.append({
|
||||
"sheet": "Receipt",
|
||||
"row_no": index,
|
||||
"invoice_no": f"INV-BULK-{index:04d}",
|
||||
"material_no": f"MAT-{index:04d}",
|
||||
"doc_no": f"HOM-BULK-{index:04d}",
|
||||
"lot_no": f"LOT-BULK-{index:04d}",
|
||||
"material_code": f"MAT-{index:04d}",
|
||||
"material_name": "批量物料",
|
||||
"specification": "T-100",
|
||||
"receipt_date": "2026-08-05",
|
||||
"receipt_quantity": "100",
|
||||
"movement_date": "2026-08-05",
|
||||
"quantity": "100",
|
||||
"source_code": "DBS-AWSBI",
|
||||
})
|
||||
return {
|
||||
@@ -41,7 +42,8 @@ def test_bulk_precheck_300_invoices(transfer_db):
|
||||
"""300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。"""
|
||||
deps, erp, _ = make_transfer_deps(_bulk_file(300))
|
||||
for index in range(1, 301):
|
||||
erp.seed_inventory(f"INV-BULK-{index:04d}", "100")
|
||||
# 库存种子按 (料号, 拨出库位, 拨出批号) 三元组与文件行一一对应。
|
||||
erp.seed_stock(f"MAT-{index:04d}", "DBS-TRANSIT", f"LOT-BULK-{index:04d}", "100")
|
||||
|
||||
started = time.perf_counter()
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
@@ -534,7 +534,7 @@ def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
|
||||
|
||||
def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
"""同一库存源只能有一条启用的默认外部系统映射。"""
|
||||
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
@@ -542,29 +542,46 @@ def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
payload = {
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_organization_code': None, 'external_site_code': 'EU01',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_requires_freight_warehouse(app):
|
||||
"""货代仓库是映射必要维度(调拨拨出仓库来源)——缺省必须拒绝,不再支持默认映射。"""
|
||||
def test_external_mapping_allows_empty_freight_warehouse(app):
|
||||
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 缺货代仓库的映射会让调拨拨出仓库无来源,保存端必须 fail-closed。
|
||||
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] is None
|
||||
assert mapping['in_transit_warehouse_code'] == 'TZR2'
|
||||
|
||||
|
||||
def test_external_mapping_requires_in_transit_warehouse_code(app):
|
||||
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'external_system_code': 'TOPGP',
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
|
||||
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
@@ -572,7 +589,7 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
|
||||
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
|
||||
'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] == 'DUB'
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨测试断言辅助。
|
||||
|
||||
用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。
|
||||
依赖:fakes.ErpCallRecord。
|
||||
依赖:fakes.ExternalCallRecord。
|
||||
逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。
|
||||
"""
|
||||
|
||||
@@ -10,26 +10,26 @@ from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP
|
||||
from tests.services.in_transit_transfer.fakes import ExternalCallRecord, FakeCapabilityClient
|
||||
|
||||
|
||||
def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None:
|
||||
"""断言 ERP 调用次数(可按 Invoice 过滤)。"""
|
||||
def assert_erp_calls(erp: FakeCapabilityClient, expected: int, *, invoice_no: str | None = None) -> None:
|
||||
"""断言 外部系统 调用次数(可按 Invoice 过滤)。"""
|
||||
calls = erp.calls(invoice_no=invoice_no)
|
||||
assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}"
|
||||
assert len(calls) == expected, f"expected {expected} 外部系统 calls, got {len(calls)}: {calls}"
|
||||
|
||||
|
||||
def assert_erp_write_zero(erp: FakeERP) -> None:
|
||||
"""断言没有任何 ERP 写调用(fail-closed 场景通用断言)。"""
|
||||
def assert_external_write_zero(erp: FakeCapabilityClient) -> None:
|
||||
"""断言没有任何 外部系统 写调用(fail-closed 场景通用断言)。"""
|
||||
writes = erp.write_calls()
|
||||
assert not writes, f"unexpected ERP write calls: {writes}"
|
||||
assert not writes, f"unexpected 外部系统 write calls: {writes}"
|
||||
|
||||
|
||||
def assert_call_fields(record: ErpCallRecord) -> None:
|
||||
"""断言单次 ERP 调用携带全部必需追踪字段。"""
|
||||
def assert_call_fields(record: ExternalCallRecord) -> None:
|
||||
"""断言单次 外部系统 调用携带全部必需追踪字段。"""
|
||||
assert record.operation_id
|
||||
assert record.invoice_no
|
||||
assert record.erp_org
|
||||
assert record.external_org
|
||||
assert record.from_warehouse
|
||||
assert record.to_warehouse
|
||||
assert isinstance(record.quantity, Decimal)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
|
||||
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
|
||||
same_day_receipt_file),并组装 FakeERP/FakeRPA/FakeWeCom。
|
||||
same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
|
||||
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
|
||||
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
|
||||
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom
|
||||
from tests.services.in_transit_transfer.fakes import FakeClock, FakeCapabilityClient, FakeRPA, FakeWeCom
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -22,9 +22,9 @@ def fixed_clock() -> FakeClock:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def erp_fake() -> FakeERP:
|
||||
"""FakeERP:账面库存与写响应全部可注入,调用记录可断言。"""
|
||||
return FakeERP()
|
||||
def erp_fake() -> FakeCapabilityClient:
|
||||
"""FakeCapabilityClient:账面库存与写响应全部可注入,调用记录可断言。"""
|
||||
return FakeCapabilityClient()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -18,7 +18,7 @@ class ReceiptRow:
|
||||
|
||||
sheet: str = "Receipt"
|
||||
row_no: int = 1
|
||||
invoice_no: str = "INV-001"
|
||||
invoice_no: str = "HOM-001"
|
||||
material_no: str = "MAT-001"
|
||||
material_name: str = "连接器组件"
|
||||
specification: str = "A 型 / 24PIN"
|
||||
@@ -43,11 +43,11 @@ class ReceiptRow:
|
||||
|
||||
def make_invoice_item(
|
||||
*,
|
||||
invoice_no: str = "INV-001",
|
||||
invoice_no: str = "HOM-001",
|
||||
source_code: str = "DBS-AWSBI",
|
||||
material_no: str = "MAT-001",
|
||||
receipt_quantity: Decimal | str | int = "1200",
|
||||
erp_quantity: Decimal | str | int | None = "1200",
|
||||
external_quantity: Decimal | str | int | None = "1200",
|
||||
receipt_date: str = "2026-08-05",
|
||||
) -> dict[str, Any]:
|
||||
"""构造一条预检明细项(默认严格匹配、可执行)。"""
|
||||
@@ -59,5 +59,5 @@ def make_invoice_item(
|
||||
"specification": "A 型 / 24PIN",
|
||||
"receipt_date": receipt_date,
|
||||
"receipt_quantity": Decimal(str(receipt_quantity)),
|
||||
"erp_quantity": None if erp_quantity is None else Decimal(str(erp_quantity)),
|
||||
"external_quantity": None if external_quantity is None else Decimal(str(external_quantity)),
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。
|
||||
"""在途调拨测试的可控外部系统替身:FakeCapabilityClient / FakeRPA / FakeWeCom / FakeClock。
|
||||
|
||||
用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支,
|
||||
用途:让 L0/L1 测试在不接触真实 RPA、外部系统、企业微信的前提下覆盖全部业务分支,
|
||||
并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。
|
||||
依赖:标准库(dataclasses / decimal / zoneinfo)。
|
||||
逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据;
|
||||
create_transfer 按注入的 scenario 返回 success / duplicate_success /
|
||||
business_failed / timeout_before_commit / timeout_after_commit;
|
||||
所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、
|
||||
来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。
|
||||
依赖:标准库(dataclasses / decimal / zoneinfo)、capability_client(域类型)。
|
||||
逻辑:FakeCapabilityClient 以 (料号, 拨出库位, 拨出批号) 三元组维护账面库存;
|
||||
query_stock 一次返回组内全部命中行;create_transfer 按注入的 scenario
|
||||
返回已分类的 TransferWriteResult(success / duplicate_success /
|
||||
business_failed / technical_failed / result_unknown)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +17,12 @@ from decimal import Decimal
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError
|
||||
from app.services.in_transit_transfer.capability_client import (
|
||||
ExternalQueryTimeoutError,
|
||||
StockQueryResult,
|
||||
StockRow,
|
||||
TransferWriteResult,
|
||||
)
|
||||
|
||||
|
||||
class FakeClock:
|
||||
@@ -41,154 +45,182 @@ class FakeClock:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpCallRecord:
|
||||
"""FakeERP 单次调用的事实记录;测试断言优先读取该记录。"""
|
||||
class ExternalCallRecord:
|
||||
"""FakeCapabilityClient 单次调用的事实记录;测试断言优先读取该记录。"""
|
||||
|
||||
operation_id: str
|
||||
invoice_no: str
|
||||
erp_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
quantity: Decimal
|
||||
external_org: str
|
||||
call_seq: int
|
||||
returned_status: str
|
||||
method: str
|
||||
# 查询调用:记录目标元组;写调用:invoice_no + 数量。
|
||||
targets: tuple[tuple[str, str, str], ...] = ()
|
||||
invoice_no: str = ""
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class FakeERP:
|
||||
"""可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。"""
|
||||
class FakeCapabilityClient:
|
||||
"""可注入账面库存与响应场景的外部系统客户端替身;每次调用写入 call log。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.inventory: dict[str, dict[str, Any]] = {}
|
||||
self.inventory: dict[tuple[str, str, str], Decimal] = {}
|
||||
self.documents: dict[str, str] = {}
|
||||
self.verified_posted: dict[str, bool] = {}
|
||||
self.query_scenario: str = "normal"
|
||||
self.write_scenario: str = "success"
|
||||
# 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。
|
||||
self.write_scenarios: dict[str, str] = {}
|
||||
self.call_log: list[ErpCallRecord] = []
|
||||
self.call_log: list[ExternalCallRecord] = []
|
||||
self._seq = 0
|
||||
|
||||
# -- 控制注入 ----------------------------------------------------------
|
||||
def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None:
|
||||
"""设置指定 Invoice 的账面库存。"""
|
||||
self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))}
|
||||
def seed_stock(self, material_no: str, from_warehouse: str, lot_no: str,
|
||||
quantity: str | int | Decimal) -> None:
|
||||
"""设置指定 (料号, 拨出库位, 拨出批号) 的账面库存。"""
|
||||
key = (str(material_no).strip(), str(from_warehouse).strip(), str(lot_no).strip())
|
||||
self.inventory[key] = Decimal(str(quantity))
|
||||
|
||||
def clear_stock(self) -> None:
|
||||
"""清空全部账面库存(模拟 外部系统 库存被移走/未上账)。"""
|
||||
self.inventory.clear()
|
||||
|
||||
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
|
||||
"""预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。"""
|
||||
"""预置某 Invoice 已存在的单据(幂等重复场景)。"""
|
||||
self.documents[str(invoice_no).strip()] = document_no
|
||||
self.verified_posted[str(invoice_no).strip()] = posted
|
||||
|
||||
def set_query_scenario(self, scenario: str) -> None:
|
||||
"""normal | inventory_not_found | timeout。"""
|
||||
"""normal | inventory_not_found | timeout | error。"""
|
||||
self.query_scenario = scenario
|
||||
|
||||
def set_write_scenario(self, scenario: str) -> None:
|
||||
"""success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。"""
|
||||
self.write_scenario = scenario
|
||||
|
||||
# -- ERP 能力 ----------------------------------------------------------
|
||||
def query_inventory(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
"""按 Invoice 返回账面库存;timeout 场景抛超时异常。"""
|
||||
# -- 外部系域能力 ----------------------------------------------------------
|
||||
def query_stock(self, *, operation_id: str, external_org: str,
|
||||
targets: list) -> StockQueryResult:
|
||||
"""按组织批量返回库存行;timeout/error 场景按客户端语义抛错。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
target_keys = [
|
||||
(str(t.material_no).strip(), str(t.from_warehouse).strip(), str(t.lot_no).strip())
|
||||
for t in targets
|
||||
]
|
||||
if self.query_scenario == "timeout":
|
||||
raise TimeoutError(f"query timeout operation_id={operation_id}")
|
||||
raise ExternalQueryTimeoutError(f"query timeout operation_id={operation_id}")
|
||||
if self.query_scenario == "error":
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "error", "query_inventory")
|
||||
self.call_log.append(record)
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "error", "query_stock",
|
||||
targets=tuple(target_keys),
|
||||
))
|
||||
raise RuntimeError("binding not found for capability query_inventory")
|
||||
if self.query_scenario == "inventory_not_found" or key not in self.inventory:
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "inventory_not_found", "query_inventory")
|
||||
self.call_log.append(record)
|
||||
return {"found": False, "quantity": Decimal("0")}
|
||||
qty = self.inventory[key]["quantity"]
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "success", "query_inventory")
|
||||
self.call_log.append(record)
|
||||
return {"found": True, "quantity": qty}
|
||||
rows: list[StockRow] = []
|
||||
for key in target_keys:
|
||||
if self.query_scenario == "inventory_not_found":
|
||||
continue
|
||||
if key in self.inventory:
|
||||
rows.append(StockRow(
|
||||
material_no=key[0], from_warehouse=key[1], lot_no=key[2],
|
||||
quantity=self.inventory[key],
|
||||
))
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq,
|
||||
"success" if rows else "inventory_not_found", "query_stock",
|
||||
targets=tuple(target_keys),
|
||||
))
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账;按注入场景返回结果并记录调用。"""
|
||||
invoice_no: str, external_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> TransferWriteResult:
|
||||
"""原子建单/审核/过账;按注入场景返回已分类结果并记录调用。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
scenario = self.write_scenarios.get(key, self.write_scenario)
|
||||
if scenario == "timeout_before_commit":
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "timeout_before_commit", "create_transfer")
|
||||
self.call_log.append(record)
|
||||
raise ErpWriteTimeoutError(
|
||||
"write timeout before commit", committed=False, operation_id=operation_id,
|
||||
)
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "timeout_before_commit",
|
||||
"create_transfer", invoice_no=key,
|
||||
))
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
|
||||
if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit":
|
||||
# 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。
|
||||
self.documents.setdefault(key, f"TRF-{self._seq:05d}")
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "timeout_after_commit", "create_transfer",
|
||||
self.documents[key])
|
||||
self.call_log.append(record)
|
||||
raise ErpWriteTimeoutError(
|
||||
"write timeout after commit", committed=True,
|
||||
document_no=self.documents[key], operation_id=operation_id,
|
||||
document_no = self.documents[key]
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "timeout_after_commit",
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=document_no,
|
||||
)
|
||||
if scenario == "business_failed" or self.write_scenario == "business_failed":
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "business_failed", "create_transfer")
|
||||
self.call_log.append(record)
|
||||
return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "business_failed",
|
||||
"create_transfer", invoice_no=key,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="business_failed", error_code="EXTERNAL_BUSINESS_REJECT",
|
||||
error_message="rejected by external system",
|
||||
)
|
||||
if key in self.documents:
|
||||
document_no = self.documents[key]
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "duplicate_success", "create_transfer",
|
||||
document_no)
|
||||
self.call_log.append(record)
|
||||
return {
|
||||
"status": "duplicate_success",
|
||||
"document_no": document_no,
|
||||
"verified_posted": self.verified_posted.get(key, False),
|
||||
}
|
||||
posted = self.verified_posted.get(key, False)
|
||||
status = "duplicate_success" if posted else "duplicate_unverified"
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, status,
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status=status, document_no=document_no, verified_posted=posted,
|
||||
error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
document_no = f"TRF-{self._seq:05d}"
|
||||
self.documents[key] = document_no
|
||||
self.verified_posted[key] = True
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "success", "create_transfer", document_no)
|
||||
self.call_log.append(record)
|
||||
return {"status": "success", "document_no": document_no, "posted": True}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "success",
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(status="success", document_no=document_no, verified_posted=True)
|
||||
|
||||
def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
invoice_no: str, external_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> TransferWriteResult:
|
||||
"""核实重复 Invoice 原单状态(已审核过账/未确认)。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
if key not in self.documents:
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "duplicate_unverified", "verify_duplicate")
|
||||
self.call_log.append(record)
|
||||
return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "duplicate_unverified", "verify_duplicate",
|
||||
invoice_no=key,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
document_no = self.documents[key]
|
||||
posted = self.verified_posted.get(key, False)
|
||||
status = "duplicate_success" if posted else "duplicate_unverified"
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, status, "verify_duplicate", document_no)
|
||||
self.call_log.append(record)
|
||||
return {"status": status, "document_no": document_no, "verified_posted": posted}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, status, "verify_duplicate",
|
||||
invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status=status, document_no=document_no,
|
||||
verified_posted=posted if posted else None,
|
||||
error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
# -- 断言辅助 ----------------------------------------------------------
|
||||
def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]:
|
||||
"""按 Invoice 过滤调用记录(默认返回全部)。"""
|
||||
def calls(self, *, invoice_no: str | None = None) -> list[ExternalCallRecord]:
|
||||
"""按 Invoice 过滤调用记录(默认返回全部;查询调用 invoice_no 为空串)。"""
|
||||
if invoice_no is None:
|
||||
return list(self.call_log)
|
||||
return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()]
|
||||
|
||||
def write_calls(self) -> list[ErpCallRecord]:
|
||||
def write_calls(self) -> list[ExternalCallRecord]:
|
||||
"""仅返回 create_transfer 调用记录(写副作用断言)。"""
|
||||
return [record for record in self.call_log if record.method == "create_transfer"]
|
||||
|
||||
|
||||
@@ -4,15 +4,14 @@
|
||||
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。
|
||||
依赖:app.services.in_transit_transfer(仅类型)、fakes。
|
||||
逻辑:所有替身只返回测试注入的值,不触碰真实存储;
|
||||
TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。
|
||||
TransferDeps.capabilities 直接注入 FakeCapabilityClient(客户端替身)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
|
||||
|
||||
class FakeReceiptFileRepository:
|
||||
@@ -45,38 +44,38 @@ def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
|
||||
|
||||
def make_transfer_deps(
|
||||
*files: dict,
|
||||
erp: FakeERP | None = None,
|
||||
capabilities: FakeCapabilityClient | None = None,
|
||||
rpa: FakeRPA | None = None,
|
||||
routes: dict[str, RouteMapping] | None = None,
|
||||
) -> tuple[TransferDeps, FakeERP, FakeRPA]:
|
||||
"""组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。
|
||||
) -> tuple[TransferDeps, FakeCapabilityClient, FakeRPA]:
|
||||
"""组装注入 Fake 的 TransferDeps(外部访问直接注入客户端替身)。
|
||||
|
||||
Returns:
|
||||
(deps, erp_fake, rpa_fake) 元组。
|
||||
(deps, capabilities_fake, rpa_fake) 元组。
|
||||
"""
|
||||
erp = erp or FakeERP()
|
||||
capabilities = capabilities or FakeCapabilityClient()
|
||||
rpa = rpa or FakeRPA()
|
||||
deps = TransferDeps(
|
||||
file_repository=make_ready_repo(*files),
|
||||
rpa_trigger=rpa,
|
||||
route_resolver=FakeRouteResolver(routes=routes),
|
||||
erp=ErpAdapter(transport=erp, default_org="HX-CN01"),
|
||||
capabilities=capabilities,
|
||||
)
|
||||
return deps, erp, rpa
|
||||
return deps, capabilities, rpa
|
||||
|
||||
|
||||
class FakeRouteResolver:
|
||||
"""按来源返回固定路由(ERP 组织/拨出仓/拨入仓)。"""
|
||||
"""按来源返回固定路由(外部组织/拨出仓/拨入仓)。"""
|
||||
|
||||
def __init__(self, routes: dict[str, RouteMapping] | None = None) -> None:
|
||||
self.routes = routes if routes is not None else {
|
||||
"DBS-AWSBI": RouteMapping(erp_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
|
||||
"DBS-AWSSG": RouteMapping(erp_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
|
||||
"CRANE-SZ": RouteMapping(erp_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"),
|
||||
"DBS-AWSBI": RouteMapping(external_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
|
||||
"DBS-AWSSG": RouteMapping(external_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
|
||||
"CRANE-SZ": RouteMapping(external_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"),
|
||||
}
|
||||
self.raised_on: set[str] = set()
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回来源路由;未配置来源抛 RouteNotResolvedError。"""
|
||||
if source_code in self.raised_on:
|
||||
raise RuntimeError("route resolution failed")
|
||||
|
||||
@@ -42,7 +42,7 @@ class FakeObjectStore:
|
||||
|
||||
|
||||
def _sample_data() -> bytes:
|
||||
return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
|
||||
return b"external-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
|
||||
|
||||
|
||||
def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
@@ -50,17 +50,17 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_type="external_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
data=data,
|
||||
original_filename="erp-inventory-20260806.csv",
|
||||
original_filename="external-inventory-20260806.csv",
|
||||
content_type="text/csv",
|
||||
object_store=store,
|
||||
bucket="hxops-transfer",
|
||||
)
|
||||
assert archive.sha256 == hashlib.sha256(data).hexdigest()
|
||||
assert archive.storage_provider == "minio"
|
||||
assert archive.object_type == "erp_inventory_snapshot"
|
||||
assert archive.object_type == "external_inventory_snapshot"
|
||||
assert store.objects # 对象已写入存储
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first()
|
||||
assert audit is not None
|
||||
@@ -72,7 +72,7 @@ def test_verify_archive_hash_ok_and_corruption_detected(transfer_db):
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data,
|
||||
object_type="external_inventory_snapshot", object_id="OBJ-1", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
@@ -89,7 +89,7 @@ def test_restore_archive_bytes_roundtrip(transfer_db):
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot", object_id="OBJ-2", data=data,
|
||||
object_type="external_inventory_snapshot", object_id="OBJ-2", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
|
||||
@@ -111,7 +111,7 @@ def test_event_hash_recomputable_from_fields():
|
||||
actor_type="worker",
|
||||
operation_id="op_002",
|
||||
result="success",
|
||||
after={"erp_document_no": "TRF-10001"},
|
||||
after={"external_document_no": "TRF-10001"},
|
||||
)
|
||||
assert compute_event_hash(event) == event.event_hash
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def _blocked_precheck(dbs_ready_file):
|
||||
"""构造含数量不一致(blocked)项的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # 1200 ≠ 1000 → blocked
|
||||
erp.seed_inventory("INV-002", "1200") # executable
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return summary
|
||||
|
||||
@@ -47,18 +47,18 @@ def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
items = list_backlog()
|
||||
invoice_set = {item.invoice_no for item in items}
|
||||
assert "INV-001" in invoice_set
|
||||
assert "INV-002" not in invoice_set
|
||||
assert "HOM-001" in invoice_set
|
||||
assert "HOX-002" not in invoice_set
|
||||
|
||||
|
||||
def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
"""老化等级按明细更新日期计算。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.updated_at = datetime.utcnow() - timedelta(days=6)
|
||||
db.session.commit()
|
||||
items = list_backlog(now=datetime.utcnow())
|
||||
target = next(item_dto for item_dto in items if item_dto.invoice_no == "INV-001")
|
||||
target = next(item_dto for item_dto in items if item_dto.invoice_no == "HOM-001")
|
||||
assert target.age_days == 6
|
||||
assert target.aging_level == "escalate_5d"
|
||||
|
||||
@@ -66,7 +66,7 @@ def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file):
|
||||
"""汇总包含可恢复/已关闭/未知计数与老化分级。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "manually_closed"
|
||||
item.manually_closed_reason = "线下处理"
|
||||
db.session.commit()
|
||||
|
||||
@@ -19,10 +19,10 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeERP"]).FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp)
|
||||
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeCapabilityClient"]).FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
@@ -46,14 +46,14 @@ def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file):
|
||||
# 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success
|
||||
run.status = "executing"
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
run_id=run.id, invoice_no="INV-002",
|
||||
run_id=run.id, invoice_no="HOX-002",
|
||||
).first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
item.external_document_no = None
|
||||
db.session.commit()
|
||||
|
||||
result = cancel_run(run_no=outcome.run_no, reason="业务原因")
|
||||
items = {i.invoice_no: i for i in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()}
|
||||
assert items["INV-001"].status == "success" # 已成功单据保留
|
||||
assert items["INV-002"].status == "cancelled" # 未开始项取消
|
||||
assert items["HOM-001"].status == "success" # 已成功单据保留
|
||||
assert items["HOX-002"].status == "cancelled" # 未开始项取消
|
||||
assert result["cancelled_count"] == 1
|
||||
@@ -0,0 +1,38 @@
|
||||
"""tests/services/in_transit_transfer/test_capabilities.py
|
||||
|
||||
用途:验证在途调拨域能力声明模块:import/显式注册后注册表含三个能力且 write 标志正确。
|
||||
依赖:services/in_transit_transfer/capabilities.py、integration_connector.capability(机制层)。
|
||||
逻辑:能力契约属领域包——声明随域代码版本化;reset 后可经 register_transfer_capabilities 重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.capabilities import register_transfer_capabilities
|
||||
from app.services.integration_connector.capability import (
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_registry():
|
||||
reset_capability_registry_for_tests()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
def test_register_transfer_capabilities_registers_three():
|
||||
"""注册后含三个在途调拨能力,write 标志与读写语义一致。"""
|
||||
register_transfer_capabilities()
|
||||
names = {spec.name for spec in list_capabilities()}
|
||||
assert {
|
||||
"in_transit_transfer.query_inventory",
|
||||
"in_transit_transfer.create_transfer",
|
||||
"in_transit_transfer.verify_duplicate",
|
||||
} == names
|
||||
assert get_capability("in_transit_transfer.create_transfer").write is True
|
||||
assert get_capability("in_transit_transfer.query_inventory").write is False
|
||||
assert get_capability("in_transit_transfer.verify_duplicate").write is False
|
||||
@@ -0,0 +1,190 @@
|
||||
"""在途调拨 CapabilityClient 查询/写分类契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证 query_stock 请求携带 (external_org, targets) 契约并正确分类
|
||||
有库存/无库存/超时/网关失败;写路径在契约未冻结前 fail-closed,
|
||||
注入 transport 后超时按 committed 分类(technical_failed / result_unknown)。
|
||||
依赖:capability_client + integration_connector.transports.base.IntegrationCallResult。
|
||||
逻辑:CapabilityClient 是唯一外部访问边界;查询经注入的假网关,
|
||||
写经注入的 transport 替身(生产 Phase 2 前恒为 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.capability_client import (
|
||||
CapabilityClient,
|
||||
ExternalNotFrozenError,
|
||||
ExternalQueryTimeoutError,
|
||||
ExternalWriteTimeoutError,
|
||||
StockQueryResult,
|
||||
StockTarget,
|
||||
TransferWriteResult,
|
||||
_classify_write_response,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
class FakeGateway:
|
||||
"""按 inventory 字典应答的假网关;可注入 status 覆盖。"""
|
||||
|
||||
def __init__(self, rows: list[dict], *, status: str = "success", error_code: str | None = None):
|
||||
self.rows = rows
|
||||
self.status = status
|
||||
self.error_code = error_code
|
||||
self.seen: dict | None = None
|
||||
|
||||
def call(self, *, capability, context, params, operation_id, **kwargs):
|
||||
self.seen = {"capability": capability, "params": params, "operation_id": operation_id}
|
||||
if self.status != "success":
|
||||
return IntegrationCallResult(status=self.status, error_code=self.error_code)
|
||||
return IntegrationCallResult(status="success", data={"rows": self.rows})
|
||||
|
||||
|
||||
def _targets(**overrides) -> list[StockTarget]:
|
||||
value = [StockTarget(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10")]
|
||||
return overrides.get("targets", value)
|
||||
|
||||
|
||||
def test_query_stock_found_returns_row():
|
||||
"""命中库存 → StockQueryResult 携带数量行。"""
|
||||
gateway = FakeGateway([{"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT",
|
||||
"lot_no": "LOT-10", "quantity": "1200"}])
|
||||
client = CapabilityClient(gateway=gateway)
|
||||
result = client.query_stock(
|
||||
operation_id="op-001", external_org="HX-CN01",
|
||||
targets=_targets(),
|
||||
)
|
||||
assert isinstance(result, StockQueryResult)
|
||||
assert result.lookup(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10") == Decimal("1200")
|
||||
|
||||
|
||||
def test_query_stock_missing_tuple_is_none():
|
||||
"""响应无该元组 → lookup None(上层归 inventory_not_found)。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([]))
|
||||
result = client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert result.lookup(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10") is None
|
||||
|
||||
|
||||
def test_query_stock_params_carry_contract():
|
||||
"""网关入参严格为 (external_org, targets) 契约;不含发票/数量/凭据字段。"""
|
||||
gateway = FakeGateway([])
|
||||
CapabilityClient(gateway=gateway).query_stock(
|
||||
operation_id="op-001", external_org="HX-CN01", targets=_targets(),
|
||||
)
|
||||
assert gateway.seen["capability"] == "in_transit_transfer.query_inventory"
|
||||
assert gateway.seen["params"]["external_org"] == "HX-CN01"
|
||||
assert gateway.seen["params"]["targets"] == [
|
||||
{"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT", "lot_no": "LOT-10"},
|
||||
]
|
||||
serialized = str(gateway.seen)
|
||||
for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key", "quantity"):
|
||||
assert fragment not in serialized.lower()
|
||||
|
||||
|
||||
def test_query_stock_timeout_classified_retryable():
|
||||
"""网关超时 → ExternalQueryTimeoutError(可重试)。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([], status="timeout"))
|
||||
with pytest.raises(ExternalQueryTimeoutError) as excinfo:
|
||||
client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert excinfo.value.retryable is True
|
||||
|
||||
|
||||
def test_query_stock_gateway_failure_fail_closed():
|
||||
"""网关失败(如绑定缺失)→ AppError fail-closed。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([], status="failed", error_code="INTEGRATION.BINDING_NOT_FOUND"))
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert excinfo.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def _write_kwargs(**overrides):
|
||||
kwargs = {
|
||||
"operation_id": "op-001", "run_no": "RUN-1", "attempt_no": 1,
|
||||
"invoice_no": "INV-001", "external_org": "HX-CN01",
|
||||
"from_warehouse": "DBS-TRANSIT", "to_warehouse": "HUB-CN01",
|
||||
"quantity": Decimal("1200"),
|
||||
}
|
||||
kwargs.update(overrides)
|
||||
return kwargs
|
||||
|
||||
|
||||
class _ScriptedWriteTransport:
|
||||
"""按脚本返回/抛出的写传输替身。"""
|
||||
|
||||
def __init__(self, outcome):
|
||||
self.outcome = outcome
|
||||
|
||||
def create_transfer(self, **kwargs):
|
||||
if isinstance(self.outcome, Exception):
|
||||
raise self.outcome
|
||||
return self.outcome
|
||||
|
||||
def verify_duplicate(self, **kwargs):
|
||||
return {"status": "duplicate_success", "document_no": "TRF-OLD", "verified_posted": True}
|
||||
|
||||
|
||||
def test_write_fail_closed_before_contract_frozen():
|
||||
"""写契约未冻结(未注入 transport)→ ExternalNotFrozenError。"""
|
||||
client = CapabilityClient()
|
||||
with pytest.raises(ExternalNotFrozenError):
|
||||
client.create_transfer(**_write_kwargs())
|
||||
with pytest.raises(ExternalNotFrozenError):
|
||||
client.verify_duplicate(**_write_kwargs())
|
||||
|
||||
|
||||
def test_create_transfer_success_classified():
|
||||
"""success 响应 → TransferWriteResult(success, document_no)。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
{"status": "success", "document_no": "TRF-1"}))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert isinstance(result, TransferWriteResult)
|
||||
assert result.status == "success"
|
||||
assert result.document_no == "TRF-1"
|
||||
|
||||
|
||||
def test_create_transfer_business_failed_classified():
|
||||
"""business_failed → 保留外部拒绝码。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
{"status": "business_failed", "code": "EXTERNAL_BUSINESS_REJECT", "message": "reject"}))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "EXTERNAL_BUSINESS_REJECT"
|
||||
|
||||
|
||||
def test_create_transfer_timeout_before_commit_technical_failed():
|
||||
"""提交前超时(可证明未落单)→ technical_failed。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
ExternalWriteTimeoutError("timeout", committed=False)))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "technical_failed"
|
||||
assert result.error_code == "EXTERNAL_TIMEOUT_BEFORE_COMMIT"
|
||||
|
||||
|
||||
def test_create_transfer_timeout_after_commit_result_unknown():
|
||||
"""提交后超时(无法确认)→ result_unknown,禁止自动重试。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
ExternalWriteTimeoutError("timeout", committed=True, document_no="TRF-9")))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "result_unknown"
|
||||
assert result.error_code == "EXTERNAL_TIMEOUT_AFTER_COMMIT"
|
||||
assert result.document_no == "TRF-9"
|
||||
|
||||
|
||||
def test_verify_duplicate_posted_returns_original_document():
|
||||
"""verify_duplicate 已过账 → duplicate_success 含原单号。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(None))
|
||||
result = client.verify_duplicate(**_write_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-OLD"
|
||||
|
||||
|
||||
def test_classify_write_response_unknown_shape_technical_failed():
|
||||
"""未知响应形状 → technical_failed(fail-closed)。"""
|
||||
result = _classify_write_response({"status": "weird"})
|
||||
assert result.status == "technical_failed"
|
||||
@@ -71,8 +71,8 @@ def test_transfer_action_agent_permission_enforced():
|
||||
def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {
|
||||
@@ -84,16 +84,16 @@ def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
assert event.data["message_type"] == "transfer-precheck"
|
||||
payload = event.data["payload"]
|
||||
assert payload["kind"] == "precheck"
|
||||
assert payload["summary"]["estimated_erp_write_count"] == 2
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"INV-001", "INV-002"}
|
||||
assert payload["summary"]["estimated_external_write_count"] == 2
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.execute 流式产出 transfer-result 卡片(按 ERP 单号聚合)。"""
|
||||
"""transfer.execute 流式产出 transfer-result 卡片(按 外部系统 单号聚合)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
# 先跑预检拿 precheck_id
|
||||
@@ -105,10 +105,10 @@ def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeyp
|
||||
|
||||
execute_events = list(TransferExecuteAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_EXECUTE,
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]},
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)))
|
||||
assert len(execute_events) == 1
|
||||
payload = execute_events[0].data["payload"]
|
||||
assert payload["kind"] == "result"
|
||||
assert payload["status"] == "success"
|
||||
assert len(payload["run"]["result"]["erp_documents"]) == 2
|
||||
assert len(payload["run"]["result"]["external_documents"]) == 2
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
|
||||
ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
外部系统 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
依赖:app.services.in_transit_transfer.contracts。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 外部系统 单号分组并统计物料数/总数量。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +21,7 @@ from app.services.in_transit_transfer.contracts import (
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
aggregate_erp_documents,
|
||||
aggregate_external_documents,
|
||||
require_known_error_code,
|
||||
)
|
||||
|
||||
@@ -34,7 +34,7 @@ EXPECTED_ERROR_CODES = {
|
||||
"TRANSFER_FILE_SCHEMA_INVALID",
|
||||
"TRANSFER_INVOICE_CONFLICT",
|
||||
"TRANSFER_QUANTITY_MISMATCH",
|
||||
"TRANSFER_ERP_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_PRECHECK_EXPIRED",
|
||||
"TRANSFER_CONFIRMATION_REQUIRED",
|
||||
"TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
@@ -77,7 +77,7 @@ def test_precheck_counts_dto_fields():
|
||||
|
||||
|
||||
def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。"""
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与预检 Hash。"""
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="TPC-20260806-001",
|
||||
status="ready_to_execute",
|
||||
@@ -86,11 +86,11 @@ def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
expires_at="2026-08-06T09:20:00+08:00",
|
||||
counts=PrecheckCountsDTO(40, 8, 32, 27, 5),
|
||||
estimated_transfer_quantity="18460",
|
||||
estimated_erp_write_count=27,
|
||||
estimated_external_write_count=27,
|
||||
precheck_hash="sha256:abc",
|
||||
)
|
||||
assert summary.estimated_transfer_quantity == "18460"
|
||||
assert summary.estimated_erp_write_count == 27
|
||||
assert summary.estimated_external_write_count == 27
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
|
||||
|
||||
@@ -108,32 +108,32 @@ def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
|
||||
assert item.from_quantity == item.to_quantity
|
||||
|
||||
|
||||
def test_aggregate_erp_documents_groups_by_document_no():
|
||||
"""结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
def test_aggregate_external_documents_groups_by_document_no():
|
||||
"""结果页按 外部系统 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
items = [
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", invoice_no="INV-001",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("500"),
|
||||
result="success", erp_document_no="TRF-10001",
|
||||
result="success", external_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件",
|
||||
specification="标准型 / 48V", invoice_no="INV-002",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
|
||||
result="success", erp_document_no="TRF-10001",
|
||||
result="success", external_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组",
|
||||
specification="SZ-8 / IP67", invoice_no="INV-008",
|
||||
from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"),
|
||||
to_warehouse="HUB-SH", to_quantity=Decimal("600"),
|
||||
result="success", erp_document_no="TRF-10008",
|
||||
result="success", external_document_no="TRF-10008",
|
||||
),
|
||||
]
|
||||
documents = aggregate_erp_documents(items)
|
||||
documents = aggregate_external_documents(items)
|
||||
assert len(documents) == 2
|
||||
by_no = {document.document_no: document for document in documents}
|
||||
first = by_no["TRF-10001"]
|
||||
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
business_date_now,
|
||||
business_date_utc_window,
|
||||
eligible_receipt_date_to,
|
||||
maturity_status,
|
||||
)
|
||||
@@ -24,7 +25,7 @@ BUSINESS_T = date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_same_day_receipt_is_not_matured():
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。"""
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。"""
|
||||
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
|
||||
|
||||
|
||||
@@ -72,6 +73,22 @@ def test_business_date_now_defaults_to_shanghai_now():
|
||||
assert business_date_now() == today
|
||||
|
||||
|
||||
def test_business_date_utc_window_maps_shanghai_day_to_utc():
|
||||
"""业务日窗口必须换算 UTC+8:上海 9-22 全天 = UTC [9-21 16:00, 9-22 16:00)。
|
||||
|
||||
[断言意图] 库里存 naive UTC 时间,判定"文件是否当天抓取"不得直接取 .date()
|
||||
比较(会漂移 8 小时);窗口起止与 naive-UTC 入参口径须与 business_date_now 一致。
|
||||
"""
|
||||
# [边界] UTC 15:00 = 上海 23:00,仍属 9-22 → 窗口 [9-21 16:00, 9-22 16:00)。
|
||||
start, end = business_date_utc_window(datetime(2026, 9, 22, 15, 0))
|
||||
assert (start, end) == (datetime(2026, 9, 21, 16, 0), datetime(2026, 9, 22, 16, 0))
|
||||
# [边界] UTC 16:30 = 上海次日 00:30 → 窗口滚动到上海 9-23。
|
||||
start_next, end_next = business_date_utc_window(datetime(2026, 9, 22, 16, 30))
|
||||
assert (start_next, end_next) == (datetime(2026, 9, 22, 16, 0), datetime(2026, 9, 23, 16, 0))
|
||||
# [断言意图] 窗口固定 24 小时,止为开区间。
|
||||
assert (end_next - start_next).total_seconds() == 24 * 3600
|
||||
|
||||
|
||||
def test_invalid_date_string_raises():
|
||||
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
|
||||
with pytest.raises(ValueError):
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
"""在途调拨 ERP Adapter 查询契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证 query_inventory 请求携带全部必需追踪字段(operation_id/run_no/
|
||||
attempt_no/invoice_no/erp_org/拨出仓/拨入仓/数量),并正确分类
|
||||
有库存/无库存/超时;SOAP 传输在 WSDL 未冻结前 fail-closed。
|
||||
依赖:app.services.in_transit_transfer.erp_adapter + fakes.FakeERP。
|
||||
逻辑:Adapter 是唯一 ERP 访问边界;测试注入 FakeERP 作为 transport。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import (
|
||||
ErpAdapter,
|
||||
ErpNotFrozenError,
|
||||
ErpQueryTimeoutError,
|
||||
ErpTransport,
|
||||
ErpWriteTimeoutError,
|
||||
InventoryQuery,
|
||||
SoapErpTransport,
|
||||
TransferWriteResult,
|
||||
)
|
||||
from tests.services.in_transit_transfer.assertions import assert_call_fields
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _adapter(erp: FakeERP) -> ErpAdapter:
|
||||
return ErpAdapter(transport=erp, default_org="HX-CN01")
|
||||
|
||||
|
||||
def _query_kwargs(**overrides):
|
||||
kwargs = {
|
||||
"operation_id": "op-001",
|
||||
"run_no": "RUN-20260806-001",
|
||||
"attempt_no": 1,
|
||||
"invoice_no": "INV-001",
|
||||
"erp_org": "HX-CN01",
|
||||
"from_warehouse": "DBS-TRANSIT",
|
||||
"to_warehouse": "HUB-CN01",
|
||||
"quantity": Decimal("1200"),
|
||||
}
|
||||
kwargs.update(overrides)
|
||||
return kwargs
|
||||
|
||||
|
||||
def test_query_inventory_found():
|
||||
"""有库存 → InventoryQuery(found=True, quantity)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.query_inventory(**_query_kwargs())
|
||||
assert isinstance(result, InventoryQuery)
|
||||
assert result.found is True
|
||||
assert result.quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_query_inventory_not_found():
|
||||
"""无库存 → found=False。"""
|
||||
erp = FakeERP()
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.query_inventory(**_query_kwargs())
|
||||
assert result.found is False
|
||||
assert result.quantity is None
|
||||
|
||||
|
||||
def test_query_request_carries_all_trace_fields():
|
||||
"""调用记录包含全部追踪字段(提示词 §五 强制字段)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
adapter = _adapter(erp)
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
records = erp.calls(invoice_no="INV-001")
|
||||
assert len(records) == 1
|
||||
assert_call_fields(records[0])
|
||||
assert records[0].operation_id == "op-001"
|
||||
assert records[0].erp_org == "HX-CN01"
|
||||
assert records[0].from_warehouse == "DBS-TRANSIT"
|
||||
assert records[0].to_warehouse == "HUB-CN01"
|
||||
|
||||
|
||||
def test_query_timeout_classified_retryable():
|
||||
"""查询超时 → ErpQueryTimeoutError(可重试,只读路径不落未知态)。"""
|
||||
erp = FakeERP()
|
||||
erp.set_query_scenario("timeout")
|
||||
adapter = _adapter(erp)
|
||||
with pytest.raises(ErpQueryTimeoutError) as excinfo:
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
assert excinfo.value.retryable is True
|
||||
|
||||
|
||||
def test_soap_transport_fails_closed_before_wsdl_frozen():
|
||||
"""WSDL/endpoint 未冻结 → SoapErpTransport 调用必须抛 ErpNotFrozenError。"""
|
||||
transport = SoapErpTransport(config={})
|
||||
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
|
||||
with pytest.raises(ErpNotFrozenError):
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
|
||||
|
||||
def test_soap_transport_refuses_without_frozen_config():
|
||||
"""未配置 endpoint 的传输对象直接拒绝查询。"""
|
||||
transport = SoapErpTransport(config={})
|
||||
with pytest.raises(ErpNotFrozenError):
|
||||
transport.query_inventory(**_query_kwargs())
|
||||
|
||||
|
||||
def test_request_payload_never_contains_credentials():
|
||||
"""Adapter 请求体不得携带任何凭据字段(Secret 边界)。"""
|
||||
|
||||
class RecordingTransport:
|
||||
def __init__(self) -> None:
|
||||
self.seen: dict | None = None
|
||||
|
||||
def query_inventory(self, **kwargs):
|
||||
self.seen = kwargs
|
||||
return {"found": True, "quantity": Decimal("1200")}
|
||||
|
||||
def create_transfer(self, **kwargs):
|
||||
self.seen = kwargs
|
||||
return {"status": "success", "document_no": "TRF-1", "posted": True}
|
||||
|
||||
def verify_duplicate(self, **kwargs):
|
||||
return {"status": "duplicate_success", "document_no": "TRF-1", "verified_posted": True}
|
||||
|
||||
transport = RecordingTransport()
|
||||
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
serialized = str(transport.seen)
|
||||
for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key"):
|
||||
assert fragment not in serialized.lower()
|
||||
|
||||
|
||||
# ---- Phase 2:create_transfer / verify_duplicate ---------------------------
|
||||
|
||||
def test_create_transfer_success():
|
||||
"""成功写入 → TransferWriteResult(success, document_no)。"""
|
||||
erp = FakeERP()
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert isinstance(result, TransferWriteResult)
|
||||
assert result.status == "success"
|
||||
assert result.document_no.startswith("TRF-")
|
||||
|
||||
|
||||
def test_create_transfer_duplicate_success_when_posted():
|
||||
"""重复 Invoice 且原单已审核过账 → duplicate_success(含原单号)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-00001", posted=True)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-00001"
|
||||
assert result.verified_posted is True
|
||||
|
||||
|
||||
def test_create_transfer_duplicate_unverified_blocks():
|
||||
"""重复 Invoice 但无法证明原单已过账 → duplicate_unverified(阻断)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-00001", posted=False)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "duplicate_unverified"
|
||||
assert result.document_no == "TRF-00001"
|
||||
assert result.verified_posted is False
|
||||
|
||||
|
||||
def test_create_transfer_business_failed():
|
||||
"""明确业务失败且原子回滚 → business_failed(不得产生单据)。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("business_failed")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "ERP_BUSINESS_REJECT"
|
||||
assert result.document_no is None
|
||||
|
||||
|
||||
def test_create_transfer_timeout_before_commit_is_technical_failed():
|
||||
"""提交前超时(可证明未落单)→ technical_failed,非 result_unknown。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("timeout_before_commit")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "technical_failed"
|
||||
assert result.document_no is None
|
||||
|
||||
|
||||
def test_create_transfer_timeout_after_commit_is_result_unknown():
|
||||
"""提交后超时(无法确认是否落单)→ result_unknown,禁止自动重试。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "result_unknown"
|
||||
assert result.document_no is not None # Fake 已知落单,但业务层视为无法确认
|
||||
|
||||
|
||||
def test_verify_duplicate_returns_original_document():
|
||||
"""verify_duplicate 获取原 ERP 单号并确认已过账。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-OLD-1", posted=True)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.verify_duplicate(**_query_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-OLD-1"
|
||||
|
||||
|
||||
def test_verify_duplicate_unverified_when_not_posted():
|
||||
"""原单未确认过账 → duplicate_unverified。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-OLD-1", posted=False)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.verify_duplicate(**_query_kwargs())
|
||||
assert result.status == "duplicate_unverified"
|
||||
assert result.verified_posted is False
|
||||
@@ -24,9 +24,9 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def _executed_run(dbs_ready_file):
|
||||
"""构造含 1 成功 + 1 业务失败(未生成单据)的 Run。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
return outcome.run_no, deps
|
||||
@@ -46,10 +46,10 @@ def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file):
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
summary_sheet = workbook["执行汇总"]
|
||||
summary_text = _sheet_text(summary_sheet)
|
||||
assert "INV-002" in summary_text
|
||||
failed_sheet = workbook["ERP技术失败"]
|
||||
assert "HOX-002" in summary_text
|
||||
failed_sheet = workbook["外部系统技术失败"]
|
||||
failed_text = _sheet_text(failed_sheet)
|
||||
assert "INV-001" in failed_text
|
||||
assert "HOM-001" in failed_text
|
||||
|
||||
|
||||
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file):
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、
|
||||
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
|
||||
选择子集执行、重复点击防重与按 ERP 单号投影最终结果。
|
||||
选择子集执行、重复点击防重与按 外部系统 单号投影最终结果。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。
|
||||
逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。
|
||||
"""
|
||||
@@ -22,23 +22,31 @@ from app.services.in_transit_transfer.contracts import (
|
||||
)
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple:
|
||||
def _ready_precheck(*files: dict, capabilities=None, source_codes=None) -> tuple:
|
||||
"""创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。"""
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, erp=erp)
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, capabilities=capabilities)
|
||||
source_codes = source_codes or [files[0]["source_code"]]
|
||||
summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps)
|
||||
return deps, erp_fake, summary
|
||||
|
||||
|
||||
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeERP:
|
||||
"""按 Invoice 预置账面库存的 FakeERP。"""
|
||||
erp = FakeERP()
|
||||
_INVOICE_TUPLES = {
|
||||
# dbs_ready_file 汇总键 (料号, 拨出库位, 拨出批号) —— 与夹具行一致。
|
||||
"HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"),
|
||||
"HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"),
|
||||
}
|
||||
|
||||
|
||||
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeCapabilityClient:
|
||||
"""按 Invoice 预置账面库存的 FakeCapabilityClient(发票号映射到夹具三元组)。"""
|
||||
erp = FakeCapabilityClient()
|
||||
for invoice_no, quantity in seeds:
|
||||
erp.seed_inventory(invoice_no, quantity)
|
||||
material_no, from_warehouse, lot_no = _INVOICE_TUPLES[invoice_no]
|
||||
erp.seed_stock(material_no, from_warehouse, lot_no, quantity)
|
||||
return erp
|
||||
|
||||
|
||||
@@ -51,61 +59,61 @@ def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
|
||||
|
||||
|
||||
def test_execute_happy_path(transfer_db, dbs_ready_file):
|
||||
"""两个可执行 Invoice → Run 成功,按 ERP 单号投影两张单据,Attempt 落库。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
"""两个可执行 Invoice → Run 成功,按 外部系统 单号投影两张单据,Attempt 落库。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
assert outcome.run_no.startswith("RUN-")
|
||||
assert len(outcome.result.erp_documents) == 2
|
||||
assert len(outcome.result.external_documents) == 2
|
||||
assert outcome.result.exceptions == ()
|
||||
|
||||
items = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in items.values())
|
||||
assert all(item.erp_document_no for item in items.values())
|
||||
assert all(item.external_document_no for item in items.values())
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.run_id == run.id,
|
||||
).all()
|
||||
assert len([a for a in attempts if a.kind == "erp_write"]) == 2
|
||||
assert len([a for a in attempts if a.kind == "external_write"]) == 2
|
||||
|
||||
|
||||
def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file):
|
||||
"""重复 Invoice(原单已过账)→ item duplicate_success + 原单号。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.seed_document("INV-002", "TRF-OLD-002", posted=True)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.seed_document("HOX-002", "TRF-OLD-002", posted=True)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-002"].status == "duplicate_success"
|
||||
assert items["INV-002"].erp_document_no == "TRF-OLD-002"
|
||||
assert items["HOX-002"].status == "duplicate_success"
|
||||
assert items["HOX-002"].external_document_no == "TRF-OLD-002"
|
||||
# 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file):
|
||||
"""单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-001"].status == "blocked_recoverable"
|
||||
assert items["INV-002"].status == "success"
|
||||
assert items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
# 异常项进入结果页"未生成单据"区
|
||||
assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions)
|
||||
assert any(exc.invoice_no == "HOM-001" for exc in outcome.result.exceptions)
|
||||
|
||||
|
||||
def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
|
||||
"""result_unknown:状态终态、每 Invoice 写调用仅 1 次。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
@@ -116,9 +124,9 @@ def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""预检未就绪(prechecking)→ 拒绝执行,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
"""预检未就绪(prechecking)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
@@ -130,9 +138,9 @@ def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""确认过期(超过 10 分钟)→ 拒绝执行,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
"""确认过期(超过 10 分钟)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
@@ -144,9 +152,9 @@ def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
|
||||
"""预检快照(数量)变化 → fail-closed,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
"""预检快照(数量)变化 → fail-closed,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first()
|
||||
item.receipt_quantity = "999"
|
||||
@@ -160,19 +168,19 @@ def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_execute_selected_subset_only(transfer_db, dbs_ready_file):
|
||||
"""仅选择 INV-001 → 只写入该 Invoice。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"],
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["HOM-001"],
|
||||
)
|
||||
assert outcome.status == "success"
|
||||
assert len(outcome.result.erp_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"]
|
||||
assert len(outcome.result.external_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"]
|
||||
|
||||
|
||||
def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file):
|
||||
"""勾选当天收料项 → 拒绝,ERP 写入为 0。"""
|
||||
"""勾选当天收料项 → 拒绝,外部系统 写入为 0。"""
|
||||
deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"])
|
||||
with pytest.raises(AppError):
|
||||
execute_precheck(
|
||||
@@ -183,8 +191,8 @@ def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_fil
|
||||
|
||||
def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
|
||||
"""重复点击执行 → 第二次 409,不创建重复 Run。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
first = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
@@ -199,26 +207,26 @@ def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file):
|
||||
"""写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp.seed_inventory("INV-001", "999") # 预检后库存变化
|
||||
"""写前复查发现 外部系统 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "999") # 预检后库存变化
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-001"].status == "blocked_recoverable"
|
||||
assert items["INV-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["INV-002"]
|
||||
assert items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOX-002"]
|
||||
|
||||
|
||||
def test_get_run_restores_document_projection(transfer_db, dbs_ready_file):
|
||||
"""GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
"""GET run → 按 外部系统 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
restored = get_run(outcome.run_no)
|
||||
assert restored["run_no"] == outcome.run_no
|
||||
assert len(restored["result"]["erp_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "INV-001" for exc in restored["result"]["exceptions"])
|
||||
assert len(restored["result"]["external_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"])
|
||||
@@ -29,12 +29,14 @@ def _parsed(rows: list[dict]) -> list:
|
||||
|
||||
def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件",
|
||||
specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05",
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt") -> dict:
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt",
|
||||
warehouse_code: str = "WMS-A") -> dict:
|
||||
return {
|
||||
"sheet": sheet, "row_no": row_no, "invoice_no": invoice_no,
|
||||
"material_no": material_no, "material_name": material_name,
|
||||
"specification": specification, "receipt_date": receipt_date,
|
||||
"receipt_quantity": quantity, "source_code": "DBS-AWSBI",
|
||||
"warehouse_code": warehouse_code,
|
||||
}
|
||||
|
||||
|
||||
@@ -105,6 +107,17 @@ def test_aggregated_invoice_keeps_material_identity():
|
||||
assert invoice.receipt_date == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_first_row_warehouse_code():
|
||||
"""汇总发票取组内首行的仓库值(与 lot_no 同策略),供路由匹配使用。"""
|
||||
rows = [
|
||||
_row("INV-001", warehouse_code="WMS-A", row_no=10),
|
||||
_row("INV-001", warehouse_code="WMS-B", row_no=11),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
# [断言意图] 同单多行仓库值不一致时取首行,保证路由匹配输入确定。
|
||||
assert invoices[0].warehouse_code == "WMS-A"
|
||||
|
||||
|
||||
def test_raw_lines_carry_file_version():
|
||||
"""原始行追溯包含文件版本(决策 11:来源证据)。"""
|
||||
rows = [
|
||||
|
||||
@@ -20,8 +20,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file):
|
||||
"""指标包含 Run 状态分布与明细状态分布。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
@@ -33,10 +33,10 @@ def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file):
|
||||
def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready_file):
|
||||
"""指标含待处理老化与通知失败计数。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # mismatch → blocked
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.updated_at = item.updated_at # 保持默认年龄
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
|
||||
)
|
||||
@@ -87,7 +87,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id,
|
||||
attempt_no=1,
|
||||
kind="erp_query",
|
||||
kind="external_query",
|
||||
status="success",
|
||||
request_snapshot_json={"invoice_no": "INV-001"},
|
||||
operation_id="op_001",
|
||||
@@ -127,7 +127,7 @@ def test_invoice_item_unique_per_precheck(transfer_db):
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[],
|
||||
)
|
||||
@@ -164,7 +164,7 @@ def test_invoice_item_status_check_constraint(transfer_db):
|
||||
precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999",
|
||||
material_no="MAT-9", receipt_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1", erp_quantity="1",
|
||||
receipt_quantity="1", external_quantity="1",
|
||||
status="no_such_status", raw_lines_json=[],
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
@@ -197,12 +197,12 @@ def test_archive_roundtrip(transfer_db):
|
||||
"""归档记录保存对象路径与 Hash,供 Phase 4 MinIO 归档校验。"""
|
||||
archive = TransferArchive(
|
||||
archive_no="ARC-20260806-001",
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_type="external_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
storage_provider="minio",
|
||||
storage_bucket="hxops-transfer",
|
||||
storage_key="transfer/20260806/snapshot.xlsx",
|
||||
original_filename="erp-inventory-20260806.xlsx",
|
||||
original_filename="external-inventory-20260806.xlsx",
|
||||
file_size=1024,
|
||||
sha256="a" * 64,
|
||||
)
|
||||
@@ -210,4 +210,4 @@ def test_archive_roundtrip(transfer_db):
|
||||
transfer_db.session.commit()
|
||||
loaded = transfer_db.session.get(TransferArchive, archive.id)
|
||||
assert loaded.sha256 == "a" * 64
|
||||
assert loaded.object_type == "erp_inventory_snapshot"
|
||||
assert loaded.object_type == "external_inventory_snapshot"
|
||||
@@ -94,6 +94,12 @@ def test_optional_fields_default_empty():
|
||||
assert row.material_name == ""
|
||||
|
||||
|
||||
def test_movement_row_keeps_warehouse_code():
|
||||
"""收料文件「仓库」列必须透传到解析行——inventory_match 源映射行匹配键的数据源头。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert parsed[0].warehouse_code == "DBS-TRANSIT"
|
||||
|
||||
|
||||
def test_pending_intransit_rows_are_skipped():
|
||||
"""未收料在途行(无异动日期且数量为空/0)是 WMS 报告常态——必须跳过而不是整文件报错。"""
|
||||
pending_zero_qty = {"sheet": "Movement", "row_no": 2, "doc_no": "MOV-100", "material_code": "MAT-X",
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企微汇总通知测试(Phase 3,L1)。
|
||||
|
||||
用途:验证每个非空 Run 恰好一条汇总通知、空数据不通知、
|
||||
通知失败不改变 ERP 结果(run.status 保持)。
|
||||
通知失败不改变 外部系统 结果(run.status 保持)。
|
||||
依赖:transfer_db、execution_service、notification、fakes.FakeWeCom。
|
||||
逻辑:通知状态独立于 ERP 业务状态;失败记录 notification_failed。
|
||||
逻辑:通知状态独立于 外部系统 业务状态;失败记录 notification_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,8 +21,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
def _executed_run(dbs_ready_file):
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
return outcome.run_no
|
||||
@@ -39,7 +39,7 @@ def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file):
|
||||
assert len(wecom.deliveries) == 1
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
assert run.notification_status == "success"
|
||||
assert run.status == "success" # ERP 结果不受影响
|
||||
assert run.status == "success" # 外部系统 结果不受影响
|
||||
|
||||
|
||||
def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file):
|
||||
@@ -51,4 +51,4 @@ def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_
|
||||
assert result["notification_status"] == "failed"
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
assert run.notification_status == "failed"
|
||||
assert run.status == "success" # 关键:通知失败不改变 ERP 业务结果
|
||||
assert run.status == "success" # 关键:通知失败不改变 外部系统 业务结果
|
||||
@@ -16,16 +16,16 @@ from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.status import TransferRunStatus
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
"""创建已预检 precheck 并返回 (deps, summary)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp)
|
||||
erp = FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨预检服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证 D+1 过滤(当天收料 ERP 调用=0)、严格数量匹配、来源隔离、
|
||||
用途:验证 D+1 过滤(当天收料 外部系统 调用=0)、严格数量匹配、来源隔离、
|
||||
预检快照 Hash 稳定、缺文件等待与进度恢复。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。
|
||||
逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck),
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
TransferDeps,
|
||||
@@ -20,20 +20,23 @@ from app.services.in_transit_transfer.precheck_service import (
|
||||
run_precheck,
|
||||
)
|
||||
from tests.services.in_transit_transfer.assertions import assert_erp_calls
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
from tests.services.in_transit_transfer.repo_fakes import FakeRouteResolver, make_ready_repo, make_transfer_deps
|
||||
|
||||
|
||||
def _deps(*files: dict, erp: FakeERP | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeERP, FakeRPA]:
|
||||
def _deps(*files: dict, erp: FakeCapabilityClient | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeCapabilityClient, FakeRPA]:
|
||||
"""构造注入 Fake 依赖的 TransferDeps。"""
|
||||
return make_transfer_deps(*files, erp=erp, rpa=rpa)
|
||||
return make_transfer_deps(*files, capabilities=erp, rpa=rpa)
|
||||
|
||||
|
||||
def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file):
|
||||
"""两个来源全部严格匹配 → executable_count 正确,无阻断。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file, crane_ready_file)
|
||||
for invoice, qty in [("INV-001", "1200"), ("INV-002", "1200"), ("INV-008", "600")]:
|
||||
erp.seed_inventory(invoice, qty)
|
||||
for material, warehouse, lot, qty in [
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10", "1200"), ("MAT-002", "DBS-TRANSIT", "LOT-20", "1200"),
|
||||
("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600"),
|
||||
]:
|
||||
erp.seed_stock(material, warehouse, lot, qty)
|
||||
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
@@ -44,70 +47,70 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
assert summary.counts.blocked_count == 0
|
||||
assert summary.status == "ready_to_execute"
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
assert summary.estimated_erp_write_count == 3
|
||||
assert summary.estimated_external_write_count == 3
|
||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-001"].from_warehouse == "DBS-TRANSIT"
|
||||
assert items["INV-001"].to_warehouse == "HUB-CN01"
|
||||
assert items["INV-001"].from_quantity == items["INV-001"].to_quantity == 1200
|
||||
assert len(items["INV-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
||||
assert items["HOM-001"].to_warehouse == "HUB-CN01"
|
||||
assert items["HOM-001"].from_quantity == items["HOM-001"].to_quantity == 1200
|
||||
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,ERP 调用次数为 0。"""
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.not_matured_count == 1
|
||||
assert result.summary.counts.executable_count == 0
|
||||
assert result.summary.estimated_erp_write_count == 0
|
||||
assert result.summary.estimated_external_write_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
|
||||
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
"""收料 1200 vs ERP 1000 → blocked_recoverable;无任何写调用。"""
|
||||
"""收料 1200 vs 外部系统 1000 → blocked_recoverable;无任何写调用。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-001"].result == "blocked_quantity_mismatch"
|
||||
assert items["INV-002"].result == "executable"
|
||||
assert items["HOM-001"].result == "blocked_quantity_mismatch"
|
||||
assert items["HOX-002"].result == "executable"
|
||||
assert result.summary.counts.blocked_count == 1
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_erp_inventory_not_found_blocked(dbs_ready_file):
|
||||
"""ERP 无库存 → blocked_inventory_not_found。"""
|
||||
"""外部系统 无库存 → blocked_inventory_not_found。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200") # INV-002 无库存
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # INV-002 无库存
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-002"].result == "blocked_inventory_not_found"
|
||||
assert items["HOX-002"].result == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
def test_erp_query_failure_degrades_to_blocked_item(dbs_ready_file):
|
||||
"""ERP 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。"""
|
||||
def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file):
|
||||
"""外部系统 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.query_scenario = "error"
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
# [断言意图] ERP 基础设施故障必须降级为逐票 blocked_erp_query_failed:
|
||||
# [断言意图] 外部系统 基础设施故障必须降级为逐票 blocked_external_query_failed:
|
||||
# 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、预检全 0。
|
||||
assert result.sources[0].stage == "file_ready"
|
||||
assert result.items and all(item.result == "blocked_erp_query_failed" for item in result.items)
|
||||
assert result.items and all(item.result == "blocked_external_query_failed" for item in result.items)
|
||||
assert all("query_inventory" in item.reason for item in result.items)
|
||||
assert result.summary.counts.blocked_count == len(result.items)
|
||||
|
||||
|
||||
def test_missing_file_waits_without_erp():
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。"""
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 外部系统 调用。"""
|
||||
deps, erp, _ = _deps()
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
@@ -121,7 +124,7 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
"""DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。"""
|
||||
deps, erp, rpa = _deps(crane_ready_file)
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
erp.seed_inventory("INV-008", "600")
|
||||
erp.seed_stock("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600")
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
@@ -129,14 +132,14 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
assert by_source["DBS-AWSBI"].stage == "failed"
|
||||
assert by_source["CRANE-SZ"].stage == "file_ready"
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-008"].result == "executable"
|
||||
assert items["WTP-008"].result == "executable"
|
||||
|
||||
|
||||
def test_snapshot_hash_is_stable(dbs_ready_file):
|
||||
"""相同输入两次预检 → 预检 Hash 一致(可审计复算)。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert first.summary.precheck_hash == second.summary.precheck_hash
|
||||
@@ -145,8 +148,8 @@ def test_snapshot_hash_is_stable(dbs_ready_file):
|
||||
def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
"""create_precheck 落库后 restore_precheck 可完整恢复进度与明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
@@ -156,14 +159,14 @@ def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
assert restored["summary"].precheck_hash == summary.precheck_hash
|
||||
assert restored["summary"].status == summary.status
|
||||
restored_items = {item.invoice_no: item for item in restored["items"]}
|
||||
assert set(restored_items) == {"INV-001", "INV-002"}
|
||||
assert restored_items["INV-001"].result == "executable"
|
||||
assert set(restored_items) == {"HOM-001", "HOX-002"}
|
||||
assert restored_items["HOM-001"].result == "executable"
|
||||
# 落库数量与 DTO 一致(Decimal 文本持久化)
|
||||
assert str(restored_items["INV-001"].to_quantity) == "1200"
|
||||
assert str(restored_items["HOM-001"].to_quantity) == "1200"
|
||||
# [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。
|
||||
assert restored_items["INV-001"].receipt_date == "2026-08-05"
|
||||
assert restored_items["INV-001"].lot_no == "LOT-10"
|
||||
assert restored_items["INV-002"].lot_no == "LOT-20"
|
||||
assert restored_items["HOM-001"].receipt_date == "2026-08-05"
|
||||
assert restored_items["HOM-001"].lot_no == "LOT-10"
|
||||
assert restored_items["HOX-002"].lot_no == "LOT-20"
|
||||
|
||||
|
||||
def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
@@ -184,7 +187,7 @@ def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
assert summary.status == "file_pending"
|
||||
@@ -222,15 +225,15 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "RCP-1", "lot_no": "ASN-1",
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "ASN-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "RCP-2", "lot_no": "ASN-1",
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "HOX-2", "lot_no": "ASN-1",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 7, "movement_date": "2026-09-16"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.query_scenario = "error"
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
@@ -241,8 +244,8 @@ def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
"""收料日期范围作为预检查询范围:范围外发票不进入明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
|
||||
@@ -271,13 +274,13 @@ def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
"""来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。"""
|
||||
erp = FakeERP()
|
||||
erp = FakeCapabilityClient()
|
||||
rpa = FakeRPA()
|
||||
deps = TransferDeps(
|
||||
file_repository=make_ready_repo(dbs_ready_file),
|
||||
rpa_trigger=rpa,
|
||||
route_resolver=FakeRouteResolver(routes={}),
|
||||
erp=ErpAdapter(transport=erp, default_org="HX-CN01"),
|
||||
capabilities=erp,
|
||||
)
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
@@ -298,13 +301,125 @@ def test_run_precheck_consumes_movement_field_rows(app):
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1,
|
||||
"doc_no": "INV-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
|
||||
"doc_no": "WTP-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_inventory("INV-1", 5) # FakeERP 按 invoice_no 键维护账面库存
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) # 按 (料号, 拨出库位, 拨出批号) 维护账面库存
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
item = next(i for i in result.items if i.invoice_no == "INV-1")
|
||||
item = next(i for i in result.items if i.invoice_no == "WTP-1")
|
||||
assert item.result == "executable"
|
||||
|
||||
|
||||
# ---- 调拨类型(2026-09-22)-------------------------------------------------
|
||||
|
||||
def test_type1_filters_invoices_by_prefix(app):
|
||||
"""类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的票,范围外静默排除。"""
|
||||
# [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行;
|
||||
# HOM/HOX/WTP 前缀票正常走完整预检(成熟 + 外部系统 匹配)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-100", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "INV-9", "lot_no": "LOT-2",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 6, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 3, "doc_no": "WTP-300", "lot_no": "LOT-3",
|
||||
"material_code": "M3", "material_name": "物料3",
|
||||
"quantity": 7, "movement_date": "2026-09-16"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
erp_fake.seed_stock("M3", "WH1", "LOT-3", 7)
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
invoice_nos = {item.invoice_no for item in result.items}
|
||||
assert invoice_nos == {"HOM-100", "WTP-300"}
|
||||
assert all(item.result == "executable" for item in result.items)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
|
||||
|
||||
def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
"""create_precheck 落库 Run.transfer_type 与 Precheck.scope_json 类型口径。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1, "doc_no": "HOX-1", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=summary.precheck_id and TransferRun.query.first().run_no).first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert run is not None and run.transfer_type == "in_transit_to_hub"
|
||||
scope = precheck.scope_json
|
||||
assert scope["transfer_type"] == "in_transit_to_hub"
|
||||
assert scope["transfer_type_scope"] == "invoice_prefix:hom+hox+wtp"
|
||||
|
||||
|
||||
def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db):
|
||||
"""缺省 transfer_type → 类型 1(存量调用方/排程行为不变但纳入前缀过滤)。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
|
||||
run = TransferRun.query.first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert run.transfer_type == "in_transit_to_hub"
|
||||
assert precheck.scope_json["transfer_type"] == "in_transit_to_hub"
|
||||
|
||||
|
||||
def test_placeholder_transfer_types_fail_closed():
|
||||
"""类型 2/3(占位)fail-closed:非法值/未支持类型均 ValidationError,不产生 Run。"""
|
||||
from app.models import TransferRun
|
||||
|
||||
deps, _erp, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [],
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValidationError) as not_supported:
|
||||
create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="hub_repair_out",
|
||||
)
|
||||
assert not_supported.value.code == "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
with pytest.raises(ValidationError) as invalid:
|
||||
create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="bogus_type",
|
||||
)
|
||||
assert invalid.value.code == "TRANSFER.TRANSFER_TYPE_INVALID"
|
||||
assert TransferRun.query.count() == 0
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证"收料数量 == ERP 账面库存 才可执行",大于/小于/缺失均阻断,
|
||||
用途:验证"收料数量 == 外部系统 账面库存 才可执行",大于/小于/缺失均阻断,
|
||||
且不允许 0、负数、非数字与隐式截断。
|
||||
依赖:app.services.in_transit_transfer.quantity。
|
||||
逻辑:数量比较全部基于 Decimal 精确语义,杜绝浮点误差。
|
||||
@@ -28,17 +28,17 @@ def test_equal_quantities_are_executable():
|
||||
|
||||
|
||||
def test_erp_greater_than_receipt_is_blocked():
|
||||
"""ERP 库存大于收料数量 → 阻断(不允许部分调拨)。"""
|
||||
"""外部系统 库存大于收料数量 → 阻断(不允许部分调拨)。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_erp_less_than_receipt_is_blocked():
|
||||
"""ERP 库存小于收料数量 → 阻断。"""
|
||||
"""外部系统 库存小于收料数量 → 阻断。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_erp_missing_is_blocked():
|
||||
"""ERP 无库存(None)→ 阻断,与数量不一致分开归类。"""
|
||||
"""外部系统 无库存(None)→ 阻断,与数量不一致分开归类。"""
|
||||
assert classify_quantity_match(Decimal("1200"), None) == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""tests/services/in_transit_transfer/test_query_inventory_gateway.py
|
||||
|
||||
用途:验证调拨 query_inventory 经 CapabilityGateway 接线(首个消费者)——
|
||||
网关被调用、成熟过滤(当天收料不查)、fail-closed(无绑定来源失败但不阻断)。
|
||||
依赖:run_precheck、CapabilityErpAdapter、repo_fakes.make_transfer_deps、transports.base。
|
||||
用途:验证调拨 query_inventory 经 CapabilityGateway 接线——网关被调用且入参为
|
||||
(external_org, targets) 契约、成熟过滤(当天收料不查)、fail-closed
|
||||
(无绑定来源逐票降级但不阻断其他来源)。
|
||||
依赖:run_precheck、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。
|
||||
逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。
|
||||
"""
|
||||
|
||||
@@ -12,7 +13,7 @@ from dataclasses import replace
|
||||
from decimal import Decimal
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.capability_client import CapabilityClient
|
||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
||||
from app.services.integration_connector.errors import BindingNotFoundError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
@@ -20,9 +21,9 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
class FakeGateway:
|
||||
"""按 Invoice 返回库存结果的替代网关,并记录调用。"""
|
||||
"""按 (料号, 拨出库位, 拨出批号) 三元组返回库存行的替代网关,并记录调用。"""
|
||||
|
||||
def __init__(self, inventory: dict[str, str] | None = None, *, fail: bool = False) -> None:
|
||||
def __init__(self, inventory: dict[tuple[str, str, str], str] | None = None, *, fail: bool = False) -> None:
|
||||
self.inventory = inventory or {}
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, dict, dict]] = []
|
||||
@@ -31,35 +32,44 @@ class FakeGateway:
|
||||
self.calls.append((capability, context, params))
|
||||
if self.fail:
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
invoice_no = params["invoice_no"]
|
||||
qty = self.inventory.get(invoice_no)
|
||||
if qty is None:
|
||||
return IntegrationCallResult(status="success", data={"found": False})
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal(qty)})
|
||||
rows = []
|
||||
for target in params["targets"]:
|
||||
key = (target["material_no"], target["from_warehouse"], target["lot_no"])
|
||||
qty = self.inventory.get(key)
|
||||
if qty is not None:
|
||||
rows.append({"material_no": key[0], "from_warehouse": key[1],
|
||||
"lot_no": key[2], "quantity": Decimal(qty)})
|
||||
return IntegrationCallResult(status="success", data={"rows": rows})
|
||||
|
||||
|
||||
def _cap_deps(file, gw):
|
||||
deps, _, _ = make_transfer_deps(file)
|
||||
return replace(deps, erp=CapabilityErpAdapter(gateway=gw))
|
||||
return replace(deps, capabilities=CapabilityClient(gateway=gw))
|
||||
|
||||
|
||||
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
|
||||
gw = FakeGateway(inventory={"INV-001": "1200", "INV-002": "1200"})
|
||||
gw = FakeGateway(inventory={
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
|
||||
("MAT-002", "DBS-TRANSIT", "LOT-20"): "1200",
|
||||
})
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06",
|
||||
deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T",
|
||||
)
|
||||
# 网关被调用,且携带 query_inventory 能力名
|
||||
# 网关被调用,且携带 query_inventory 能力名与 (external_org, targets) 契约
|
||||
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
|
||||
# INV-001 汇总 1200 == ERP 1200 → executable
|
||||
item = next(i for i in result.items if i.invoice_no == "INV-001")
|
||||
capability, _, params = next(c for c in gw.calls if c[0] == "in_transit_transfer.query_inventory")
|
||||
assert params["external_org"] == "HX-CN01"
|
||||
assert {"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT", "lot_no": "LOT-10"} in params["targets"]
|
||||
# INV-001 汇总 1200 == 库存 1200 → executable
|
||||
item = next(i for i in result.items if i.invoice_no == "HOM-001")
|
||||
assert item.result == "executable"
|
||||
assert item.from_quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
"""当天收料(not_matured)不查 ERP——网关零调用。"""
|
||||
"""当天收料(not_matured)不查外部系统——网关零调用。"""
|
||||
gw = FakeGateway(inventory={})
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
@@ -72,30 +82,35 @@ def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
|
||||
"""无绑定(网关抛错)→ 该来源发票逐票阻断并带原因,其余来源照常执行。"""
|
||||
class _SplitGateway:
|
||||
"""按 Invoice 区分失败来源:DBS(INV-001/002)失败,CRANE(INV-008)成功。"""
|
||||
"""按来源区分失败:DBS(拨出仓 DBS-TRANSIT)失败,CRANE 成功。"""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def call(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
invoice = kwargs["params"]["invoice_no"]
|
||||
if invoice in {"INV-001", "INV-002"}:
|
||||
warehouses = {t["from_warehouse"] for t in kwargs["params"]["targets"]}
|
||||
if "DBS-TRANSIT" in warehouses:
|
||||
raise BindingNotFoundError(capability="in_transit_transfer.query_inventory")
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal("600")})
|
||||
rows = [
|
||||
{"material_no": t["material_no"], "from_warehouse": t["from_warehouse"],
|
||||
"lot_no": t["lot_no"], "quantity": Decimal("600")}
|
||||
for t in kwargs["params"]["targets"]
|
||||
]
|
||||
return IntegrationCallResult(status="success", data={"rows": rows})
|
||||
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file)
|
||||
deps = replace(deps, erp=CapabilityErpAdapter(gateway=_SplitGateway()))
|
||||
deps = replace(deps, capabilities=CapabilityClient(gateway=_SplitGateway()))
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T",
|
||||
)
|
||||
# [断言意图] ERP 基础设施故障降级为逐票 blocked_erp_query_failed:
|
||||
# [断言意图] 外部系统基础设施故障降级为逐票 blocked_external_query_failed:
|
||||
# 来源保持 file_ready,发票带原因可见,其余来源(CRANE)不受影响。
|
||||
dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI")
|
||||
assert dbs_source.stage == "file_ready"
|
||||
dbs_items = [i for i in result.items if i.source_code == "DBS-AWSBI"]
|
||||
assert dbs_items and all(i.result == "blocked_erp_query_failed" for i in dbs_items)
|
||||
assert dbs_items and all(i.result == "blocked_external_query_failed" for i in dbs_items)
|
||||
assert all("no binding for capability" in i.reason for i in dbs_items)
|
||||
# CRANE 正常执行 → 出可执行项
|
||||
assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items)
|
||||
assert any(i.invoice_no == "WTP-008" and i.result == "executable" for i in result.items)
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证历史可恢复项下一排程重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:transfer_db、precheck_service、recovery_service、repo_fakes。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 ERP;每次恢复新 Attempt。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,20 +20,20 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def _mixed_precheck(dbs_ready_file):
|
||||
"""构造 1 个数量不一致 + 1 个可执行的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # mismatch → blocked
|
||||
erp.seed_inventory("INV-002", "1200") # executable
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file):
|
||||
"""ERP 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。"""
|
||||
"""外部系统 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_no = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
outcome = run_daily_recovery(business_date="2026-08-06", deps=deps)
|
||||
assert outcome.recovered_count == 1
|
||||
assert outcome.attempts_created == 1
|
||||
@@ -42,15 +42,15 @@ def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_fil
|
||||
assert refreshed.status == "ready_to_execute"
|
||||
assert refreshed.attempt_no == old_attempt_no + 1
|
||||
attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all()
|
||||
assert len(attempts) == 1 and attempts[0].kind == "erp_query"
|
||||
# 恢复仅预检,不写 ERP
|
||||
assert len(attempts) == 1 and attempts[0].kind == "external_query"
|
||||
# 恢复仅预检,不写 外部系统
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动恢复,也不产生 ERP 调用。"""
|
||||
"""result_unknown 不自动恢复,也不产生 外部系统 调用。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
|
||||
@@ -63,10 +63,10 @@ def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file):
|
||||
"""manually_closed / success 永久排除,不生成 Attempt。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
blocked.status = "manually_closed"
|
||||
blocked.manually_closed_reason = "线下处理"
|
||||
success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-002").first()
|
||||
success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
|
||||
success.status = "success"
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨人工重试与人工关闭测试(Phase 3,L1)。
|
||||
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 ERP,不重新抓 RPA、不写 ERP),
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 外部系统,不重新抓 RPA、不写 外部系统),
|
||||
result_unknown 拒绝重试;人工关闭原因必填且永久排除。
|
||||
依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。
|
||||
逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。
|
||||
@@ -22,8 +22,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def _mismatch_precheck(dbs_ready_file):
|
||||
"""构造 INV-001 数量不一致的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
@@ -33,13 +33,13 @@ def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem:
|
||||
|
||||
|
||||
def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
"""ERP 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
"""外部系统 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_count = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
assert result["status"] == "ready_to_execute"
|
||||
assert result["attempt_no"] == old_attempt_count + 1
|
||||
@@ -49,25 +49,79 @@ def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
assert refreshed.attempt_no == old_attempt_count + 1
|
||||
attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all()
|
||||
assert len(attempts) == 1
|
||||
assert attempts[0].kind == "erp_query"
|
||||
# 重试不写 ERP
|
||||
assert attempts[0].kind == "external_query"
|
||||
# 重试不写 外部系统
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file):
|
||||
"""重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
old = item.attempt_no
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
assert result["status"] == "blocked_recoverable"
|
||||
assert result["attempt_no"] == old + 1
|
||||
# [断言意图] 数量不足也是 外部系统 的真实答复:外部系统 库存数必须落库(从数量列可见),
|
||||
# 用户不得因只看到"已阻断"而误以为查询失败。
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.external_quantity == "1000"
|
||||
assert refreshed.result_code == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file):
|
||||
"""重查后外部系统查无记录 → 库存数按 0 落库展示,不显示"-"误导为查询失败。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
retry_item(item_id=item.id, deps=deps) # 先产生 external_quantity=1000
|
||||
assert _item_by_invoice("HOM-001").external_quantity == "1000"
|
||||
|
||||
erp.clear_stock() # 外部系统库存被移走(查无记录)
|
||||
retry_item(item_id=item.id, deps=deps)
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.result_code == "blocked_inventory_not_found"
|
||||
# [断言意图] 无记录按 0 展示而非空值,用户可直观看到"外部系统已无库存"。
|
||||
assert refreshed.external_quantity == "0"
|
||||
|
||||
|
||||
def test_retry_ready_row_allowed(transfer_db, dbs_ready_file):
|
||||
"""可执行(ready_to_execute)行也允许重查:预检后库存变化需可复核。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 库存已补足
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
|
||||
assert result["status"] == "ready_to_execute"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.external_quantity == "1200"
|
||||
|
||||
|
||||
def test_requery_includes_ready_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查范围含可执行行:可执行行也会被逐票刷新,而非只刷阻断行。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500") # 库存被挪用
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
|
||||
# [断言意图] 可执行行不再被重查排除;库存变化后被重查回阻断态并保留 外部系统 数。
|
||||
assert result["total"] == 2
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "blocked_recoverable"
|
||||
assert refreshed.result_code == "blocked_quantity_mismatch"
|
||||
assert refreshed.external_quantity == "500"
|
||||
|
||||
|
||||
def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:拒绝重试(禁止猜测性二次写入)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
item.result_code = "result_unknown"
|
||||
db.session.commit()
|
||||
@@ -79,7 +133,7 @@ def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
"""Run 创建后禁止重新抓取 RPA(文件冻结)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
retry_item(item_id=item.id, deps=deps, kind="rpa_refetch")
|
||||
|
||||
@@ -87,7 +141,7 @@ def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""人工关闭原因必填。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="")
|
||||
|
||||
@@ -95,7 +149,7 @@ def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
"""人工关闭 → manually_closed(永久排除,后续排程不再处理)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
result = manual_close_item(item_id=item.id, reason="货代确认无需调拨")
|
||||
assert result["status"] == "manually_closed"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
@@ -110,7 +164,7 @@ def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:禁止人工关闭(需按 SOP 核实)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError):
|
||||
@@ -118,38 +172,40 @@ def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查:同预检全部可恢复阻断行逐票刷新,结果按行回报。"""
|
||||
"""批量重查:同预检全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
assert result["total"] == 1
|
||||
row = result["results"][0]
|
||||
assert row["ok"] is True
|
||||
assert row["invoice_no"] == "INV-001"
|
||||
assert row["status"] == "ready_to_execute"
|
||||
# [断言意图] 阻断行(HOM-001)与可执行行(HOX-002)都在重查范围内。
|
||||
assert result["total"] == 2
|
||||
rows = {row["invoice_no"]: row for row in result["results"]}
|
||||
assert rows["HOM-001"]["ok"] is True
|
||||
assert rows["HOM-001"]["status"] == "ready_to_execute"
|
||||
assert rows["HOX-002"]["ok"] is True
|
||||
assert rows["HOX-002"]["status"] == "ready_to_execute"
|
||||
|
||||
|
||||
def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_ready_file):
|
||||
"""invoice_nos 限定范围:不在清单的阻断行不被触碰。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(status="blocked_recoverable").all()
|
||||
assert [i.invoice_no for i in blocked] == ["INV-001"]
|
||||
assert [i.invoice_no for i in blocked] == ["HOM-001"]
|
||||
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps, invoice_nos=["INV-XXX"])
|
||||
assert result["total"] == 0
|
||||
assert _item_by_invoice("INV-001").status == "blocked_recoverable"
|
||||
assert _item_by_invoice("HOM-001").status == "blocked_recoverable"
|
||||
|
||||
|
||||
def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_ready_file):
|
||||
"""[回归防线 2026-09-21] ERP 网关/绑定故障 → 单行重查降级为
|
||||
blocked_erp_query_failed + 原因,不向调用方抛异常。
|
||||
"""[回归防线 2026-09-21] 外部系统 网关/绑定故障 → 单行重查降级为
|
||||
blocked_external_query_failed + 原因,不向调用方抛异常。
|
||||
|
||||
此前该场景抛 BindingNotFoundError('no binding for capability'),
|
||||
与 precheck 的逐票降级语义不一致,用户侧表现为全局错误弹窗。
|
||||
"""
|
||||
deps, erp, _summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.set_query_scenario("error") # RuntimeError: binding not found for capability query_inventory
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
old_attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).count()
|
||||
|
||||
result = retry_item(item_id=item.id, deps=deps) # 不得抛出
|
||||
@@ -157,7 +213,7 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_
|
||||
assert result["status"] == "blocked_recoverable"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
# [断言意图] 失败事实落库可见:结果码 + 原因行内可解释。
|
||||
assert refreshed.result_code == "blocked_erp_query_failed"
|
||||
assert refreshed.result_code == "blocked_external_query_failed"
|
||||
assert "binding not found" in (refreshed.result_message or "")
|
||||
attempts = (db.session.query(TransferAttempt).filter_by(item_id=item.id)
|
||||
.order_by(TransferAttempt.id).all())
|
||||
@@ -166,10 +222,10 @@ def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_
|
||||
|
||||
|
||||
def test_requery_with_erp_gateway_failure_stays_batched(transfer_db, dbs_ready_file):
|
||||
"""批量重查遇 ERP 故障:逐票降级、批次正常完成,不炸整批。"""
|
||||
"""批量重查遇 外部系统 故障:逐票降级、批次正常完成,不炸整批。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.set_query_scenario("error")
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
assert result["total"] == 1
|
||||
assert result["results"][0]["ok"] is True
|
||||
assert _item_by_invoice("INV-001").result_code == "blocked_erp_query_failed"
|
||||
assert result["total"] == 2
|
||||
assert all(row["ok"] for row in result["results"])
|
||||
assert _item_by_invoice("HOM-001").result_code == "blocked_external_query_failed"
|
||||
@@ -1,10 +1,11 @@
|
||||
"""调拨路由解析器测试。
|
||||
|
||||
用途:验证 DefaultRouteResolver 的拨出/拨入仓库来源契约——
|
||||
拨出仓库 = 仓库映射的货代仓库(必填),拨入仓库 = 映射的目标仓库代码。
|
||||
用途:验证 DefaultRouteResolver 的拨出库位与映射行选择契约——
|
||||
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
|
||||
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
|
||||
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
|
||||
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
|
||||
逻辑:不再借用站点固定仓库(那是货代发货/库存导出链路的字段);
|
||||
映射缺货代仓库时 fail-closed,拨出仓库无来源不得放行。
|
||||
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -14,41 +15,112 @@ import pytest
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.deps import DefaultRouteResolver
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
|
||||
|
||||
def _seed_mapping(source: ShippingInventorySource, *, freight_warehouse_id: str | None) -> ShippingInventoryExternalMapping:
|
||||
"""在既有种子站点上挂一条启用映射。"""
|
||||
def _seed_mapping(
|
||||
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
|
||||
in_transit_warehouse_code: str = 'TZT-01',
|
||||
) -> ShippingInventoryExternalMapping:
|
||||
"""在既有种子来源上挂一条启用映射。"""
|
||||
mapping = ShippingInventoryExternalMapping(
|
||||
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
|
||||
external_system_code='TOPGP', external_organization_code='TGHX',
|
||||
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓', enabled=True,
|
||||
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
|
||||
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
|
||||
)
|
||||
db.session.add(mapping)
|
||||
db.session.commit()
|
||||
return mapping
|
||||
|
||||
|
||||
def test_route_resolver_uses_mapping_freight_warehouse_as_from_warehouse(app):
|
||||
"""拨出仓库必须取映射的货代仓库,而不是站点固定仓库。"""
|
||||
def _seed_inventory_match_source() -> ShippingInventorySource:
|
||||
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
|
||||
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = ShippingInventorySource(
|
||||
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
|
||||
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
|
||||
excel_template_id=template.excel_template_id,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_fixed_source_uses_single_mapping_in_transit_code(app):
|
||||
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射货代仓 'TZR2',证明不再借用固定仓。
|
||||
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
|
||||
_seed_mapping(source, freight_warehouse_id='TZR2')
|
||||
|
||||
route = DefaultRouteResolver().resolve(source_code='DSV360_AWSDU', invoice_no='INV-1')
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZR2'
|
||||
assert route.from_warehouse == 'TZT-01'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
assert route.erp_org == 'TGHX'
|
||||
assert route.external_org == 'TGHX'
|
||||
|
||||
|
||||
def test_route_resolver_fails_closed_without_freight_warehouse(app):
|
||||
"""映射未维护货代仓库 → 拨出仓库无来源,fail-closed。"""
|
||||
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
|
||||
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
_seed_mapping(source, freight_warehouse_id=None)
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='wms-a')
|
||||
|
||||
# [断言意图] 收料仓库小写传入也须命中大写归一的货代仓库身份。
|
||||
assert route.from_warehouse == 'TZT-A'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
|
||||
|
||||
def test_inventory_match_falls_back_to_empty_freight_mapping(app):
|
||||
"""inventory_match 源:收料仓库无精确映射 → 回退货代仓库为空的默认映射行(空库位兜底)。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_blank_warehouse_goes_to_default_mapping(app):
|
||||
"""inventory_match 源:收料文件仓库列缺失 → 直接走空库位默认映射行。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_fails_closed_without_any_match(app):
|
||||
"""inventory_match 源:无精确映射也无默认映射行 → fail-closed。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(source_code='DSV360_AWSDU', invoice_no='INV-1')
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
|
||||
def test_route_resolver_fails_closed_without_in_transit_code(app):
|
||||
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
@@ -1,14 +1,16 @@
|
||||
"""来源收料文件状态投影服务测试。
|
||||
|
||||
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
|
||||
按来源投影 ready/fetching/failed/none。调拨不维护独立抓取状态表。
|
||||
按来源投影 ready/fetching/failed/expired/none。调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
逻辑:有文件→ready;有进行中单元→fetching;最新单元失败终态→failed;否则→none。
|
||||
逻辑:有当天(业务日)抓取且未过期文件→ready;有进行中单元→fetching;
|
||||
最新单元失败终态→failed;保留期已到或隔日旧文件(未清理)→expired;否则→none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -86,3 +88,69 @@ def test_report_file_is_ready(app, receipt_unit_run):
|
||||
assert status['has_ready_file'] is True
|
||||
assert status['file_no'] == 'receipt.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
|
||||
|
||||
def test_expired_report_is_expired(app, receipt_unit_run):
|
||||
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
|
||||
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
archive_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'expired'
|
||||
assert status['has_ready_file'] is False
|
||||
|
||||
|
||||
def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
|
||||
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
|
||||
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'fresh workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
archive_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
archive_expires_at=datetime.utcnow() + timedelta(days=365),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'ready'
|
||||
assert status['file_no'] == 'fresh.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
|
||||
|
||||
def test_stale_report_is_expired(app, receipt_unit_run):
|
||||
"""文件保留期未到但非当天(业务日)抓取 → expired,不得误报 ready。"""
|
||||
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
|
||||
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
|
||||
created_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'expired'
|
||||
assert status['has_ready_file'] is False
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨状态机与转换门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证提示词冻结的 13 个状态全部存在、非法迁移被服务端拒绝、
|
||||
result_unknown / manually_closed / success 无出边、通知失败不改变 ERP 结果。
|
||||
result_unknown / manually_closed / success 无出边、通知失败不改变 外部系统 结果。
|
||||
依赖:app.services.in_transit_transfer.status。
|
||||
逻辑:所有转换必须显式声明于转换表;未声明迁移一律抛 TransferStateError。
|
||||
"""
|
||||
@@ -93,7 +93,7 @@ def test_unknown_status_rejected():
|
||||
|
||||
|
||||
def test_not_matured_has_no_outgoing_edges():
|
||||
"""not_matured 无出边:当天不得查询 ERP、不得生成调拨单。"""
|
||||
"""not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。"""
|
||||
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
|
||||
|
||||
|
||||
@@ -106,13 +106,13 @@ def test_run_transition_queued_to_executing_path():
|
||||
|
||||
|
||||
def test_notification_failed_does_not_change_erp_result():
|
||||
"""通知失败不改变 ERP 结果:apply_notification_failure 返回原 ERP 终态。"""
|
||||
"""通知失败不改变 外部系统 结果:apply_notification_failure 返回原 外部系统 终态。"""
|
||||
assert apply_notification_failure(TransferRunStatus.SUCCESS.value) == TransferRunStatus.SUCCESS.value
|
||||
assert apply_notification_failure(TransferRunStatus.PARTIAL_FAILED.value) == TransferRunStatus.PARTIAL_FAILED.value
|
||||
|
||||
|
||||
def test_notification_failed_rejected_on_non_terminal_run():
|
||||
"""非终态 Run 不允许记录通知失败(必须先结束 ERP 阶段)。"""
|
||||
"""非终态 Run 不允许记录通知失败(必须先结束 外部系统 阶段)。"""
|
||||
with pytest.raises(TransferStateError):
|
||||
apply_notification_failure(TransferRunStatus.EXECUTING.value)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨策略硬门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
用途:验证一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
并强制默认确认有效期(10 分钟)。
|
||||
依赖:app.services.in_transit_transfer.strategy。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError。
|
||||
@@ -45,15 +45,15 @@ def test_quantity_tolerance_rejected():
|
||||
|
||||
|
||||
def test_erp_auto_retry_rejected():
|
||||
"""开启 ERP 自动重试必须被拒绝(result_unknown 严禁自动重试)。"""
|
||||
strategy = TransferStrategyPolicy(allow_erp_auto_retry=True)
|
||||
"""开启 外部系统 自动重试必须被拒绝(result_unknown 严禁自动重试)。"""
|
||||
strategy = TransferStrategyPolicy(allow_external_auto_retry=True)
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
def test_combined_violations_still_rejected():
|
||||
"""多项禁令同时开启仍拒绝。"""
|
||||
strategy = TransferStrategyPolicy(allow_partial=True, allow_erp_auto_retry=True)
|
||||
strategy = TransferStrategyPolicy(allow_partial=True, allow_external_auto_retry=True)
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""在途调拨类型契约测试(L1 纯单元)。
|
||||
|
||||
用途:验证调拨类型规范化/支持性门禁/类型 1 INVOICE 前缀过滤与范围说明。
|
||||
依赖:transfer_type 模块、invoice_aggregator(构造汇总票)。
|
||||
逻辑:纯函数测试,不创建 Flask/DB。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
HUB_REPAIR_OUT_ODM_ID,
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
|
||||
TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
|
||||
def _invoice(invoice_no: str) -> AggregatedInvoice:
|
||||
"""构造最小汇总票(过滤只看 invoice_no)。"""
|
||||
return AggregatedInvoice(
|
||||
source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001",
|
||||
material_name="连接器组件", specification="A 型",
|
||||
receipt_date=date(2026, 8, 5), receipt_quantity=Decimal("100"),
|
||||
raw_lines=(),
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_transfer_type_defaults_to_in_transit_to_hub():
|
||||
"""缺省/空值/None 回落类型 1(存量调用方语义不变)。"""
|
||||
assert normalize_transfer_type(None) == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type("") == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type("in_transit_to_hub") == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type(TransferType.HUB_TO_HUB) == TransferType.HUB_TO_HUB
|
||||
|
||||
|
||||
def test_normalize_transfer_type_rejects_unknown_value():
|
||||
"""非法类型值 → ValidationError(TRANSFER.TRANSFER_TYPE_INVALID)。"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
normalize_transfer_type("not_a_type")
|
||||
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_INVALID"
|
||||
|
||||
|
||||
def test_ensure_supported_rejects_placeholder_types():
|
||||
"""类型 2/3 一期占位:进入处理链路被 fail-closed 拒绝。"""
|
||||
ensure_transfer_type_supported(TransferType.IN_TRANSIT_TO_HUB)
|
||||
for placeholder in (TransferType.HUB_REPAIR_OUT, TransferType.HUB_TO_HUB):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ensure_transfer_type_supported(placeholder)
|
||||
assert exc_info.value.code == TRANSFER_TYPE_NOT_SUPPORTED
|
||||
|
||||
|
||||
def test_filter_type1_keeps_invoice_prefixes_case_insensitive():
|
||||
"""类型 1 只保留 INVOICE 前缀 HOM/HOX/WTP(大小写不敏感)。"""
|
||||
invoices = [
|
||||
_invoice("HOM-20260801-01"),
|
||||
_invoice("hox-20260801-02"),
|
||||
_invoice("WTP-20260801-03"),
|
||||
_invoice("INV-001"),
|
||||
_invoice("RCP-9"),
|
||||
_invoice("OTHER-1"),
|
||||
]
|
||||
kept = filter_invoices_for_type(invoices, TransferType.IN_TRANSIT_TO_HUB)
|
||||
assert [invoice.invoice_no for invoice in kept] == [
|
||||
"HOM-20260801-01", "hox-20260801-02", "WTP-20260801-03",
|
||||
]
|
||||
|
||||
|
||||
def test_filter_type1_empty_invoice_no_excluded():
|
||||
"""空/空白 Invoice 号不匹配任何前缀 → 排除(防御性)。"""
|
||||
kept = filter_invoices_for_type([_invoice("")], TransferType.IN_TRANSIT_TO_HUB)
|
||||
assert kept == []
|
||||
assert set(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) == {"HOM", "HOX", "WTP"}
|
||||
assert HUB_REPAIR_OUT_ODM_ID == "HoxinRMA"
|
||||
|
||||
|
||||
def test_scope_note_records_type_rule():
|
||||
"""范围说明写入 scope_json 的审计口径。"""
|
||||
assert transfer_type_scope_note(TransferType.IN_TRANSIT_TO_HUB) == "invoice_prefix:hom+hox+wtp"
|
||||
assert transfer_type_scope_note(TransferType.HUB_REPAIR_OUT) == "odm_id:HoxinRMA"
|
||||
assert transfer_type_scope_note(TransferType.HUB_TO_HUB) == "pending_rule"
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、
|
||||
停滞 Run 可终态收尾、result_unknown 不被自动重试。
|
||||
依赖:transfer_db、precheck/execution/recovery、repo_fakes。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 ERP 返回 duplicate_success。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 外部系统 返回 duplicate_success。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,8 +27,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
def _executing_precheck(dbs_ready_file):
|
||||
"""构造已预检 precheck(不执行),并手动把明细置为 executing。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
for item in db.session.query(TransferInvoiceItem).all():
|
||||
item.status = "executing"
|
||||
@@ -44,13 +44,13 @@ def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_f
|
||||
assert result["recovered"] == 2
|
||||
items = db.session.query(TransferInvoiceItem).all()
|
||||
assert all(item.status == "success" for item in items)
|
||||
assert all(item.erp_document_no for item in items)
|
||||
assert all(item.external_document_no for item in items)
|
||||
# 每 Invoice 恰 1 次写(恢复只写一次,不重复建单)
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_recover_skips_result_unknown(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动重试(不触碰、不写 ERP)。"""
|
||||
"""result_unknown 不自动重试(不触碰、不写 外部系统)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).first()
|
||||
item.status = "result_unknown"
|
||||
@@ -68,14 +68,14 @@ def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file):
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run
|
||||
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
item.status = "success"
|
||||
item.erp_document_no = "TRF-DONE"
|
||||
item.external_document_no = "TRF-DONE"
|
||||
db.session.commit()
|
||||
|
||||
run_ids = finalize_stale_runs()
|
||||
|
||||
@@ -270,7 +270,7 @@ TRANSFER_FILE_NOT_READY
|
||||
TRANSFER_FILE_SCHEMA_INVALID
|
||||
TRANSFER_INVOICE_CONFLICT
|
||||
TRANSFER_QUANTITY_MISMATCH
|
||||
TRANSFER_ERP_INVENTORY_NOT_FOUND
|
||||
TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND
|
||||
TRANSFER_PRECHECK_EXPIRED
|
||||
TRANSFER_CONFIRMATION_REQUIRED
|
||||
TRANSFER_DUPLICATE_NOT_VERIFIED
|
||||
|
||||
@@ -402,7 +402,7 @@ pending
|
||||
"blocked_count": 5
|
||||
},
|
||||
"estimated_transfer_quantity": "18460",
|
||||
"estimated_erp_write_count": 27,
|
||||
"estimated_external_write_count": 27,
|
||||
"precheck_hash": "sha256:..."
|
||||
}
|
||||
```
|
||||
@@ -442,10 +442,6 @@ pending
|
||||
|
||||
```text
|
||||
IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY=2
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY=2
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY=1
|
||||
IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS=60
|
||||
IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS=600
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS=3
|
||||
IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS=5
|
||||
|
||||
@@ -8,13 +8,15 @@
|
||||
- **业务域**:`backend/app/services/in_transit_transfer/`(独立领域模块,不混入 shipping_notice 订单解析)。
|
||||
- **执行边界**:收料来源实例(如 DBS-AWSBI / DBS-AWSSG / CRANE-SZ);DBS/Crane 仅分组。
|
||||
- **真相源**:`TransferRun` / `TransferPrecheck` / `TransferInvoiceItem` / `TransferAttempt`(表:`transfer_*`,迁移 `it1a2b3c4d5e`)。
|
||||
- **ERP 访问唯一出口**:`erp_adapter.py`(query_inventory / create_transfer / verify_duplicate);SOAP 在 WSDL 冻结前 fail-closed(`ErpNotFrozenError`)。
|
||||
- **外部系统访问唯一出口**:`capability_client.py`(`CapabilityClient.query_stock / create_transfer / verify_duplicate`);查询经集成连接器 CapabilityGateway 按 `in_transit_transfer.query_inventory` 能力批量调用(按 external_org 分组、targets = 料号+拨出库位+拨出批号 元组,`external_org` 取自仓库映射 `external_organization_code`);写路径在外部契约冻结前 fail-closed(`ExternalNotFrozenError`,Phase 2 接线)。
|
||||
- **路由归属(拨出库位)**:拨出库位取仓库映射行的「在途仓编码」(`shipping_inventory_external_mappings.in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择(`DefaultRouteResolver`):`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期以它重解析路由,路由变化 fail-closed 阻断(`TRANSFER.ROUTE_NOT_RESOLVED` / precheck_expired)。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
|
||||
- **调拨业务类型(2026-09-22)**:`transfer_type.py` 定义三类——`in_transit_to_hub`(在途仓至HUB仓,一期唯一开放)、`hub_repair_out`(HUB仓维修出,占位)、`hub_to_hub`(HUB仓间调拨,占位)。类型决定预检收料数据范围:类型 1 仅纳入 INVOICE 前缀 `HOM/HOX/WTP`(大小写不敏感)的票,范围外票与收料日期过滤同语义静默排除;类型 2 规则已冻结(ODM ID=`HoxinRMA`)待收料文件解析层支持 `odm_id` 字段后启用,类型 3 规则待业务定义;占位类型被调用时 fail-closed(`TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED`)。类型随 Run 落库(`transfer_runs.transfer_type`,迁移 `tt3d4e5f6a7b`)并写入 `TransferPrecheck.scope_json`(含范围规则说明)参与预检 Hash;前端来源选择卡顶部选择(类型 2/3 禁用展示「即将上线」),异步预检 Job 从 scope_json 回读类型保证口径一致。
|
||||
- **异步**:`transfer` 队列(`worker_in_transit_transfer.py`)消费预检/执行 Run/执行 Item 三类 Job。
|
||||
- **排程**:`in-transit-receipt-file`(08:00)与 `in-transit-transfer`(09:00)platform job(`schedule/job_registry.py`)。
|
||||
|
||||
## 2. 数据库
|
||||
|
||||
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`)。
|
||||
- 迁移链:`it1a2b3c4d5e_add_in_transit_transfer.py`(down_revision=`hw6x7y8z9a0b`);后续 `it2c3d4e5f6a7_add_in_transit_warehouse_code.py` 为 `transfer_invoice_items` 追加 `receipt_warehouse_code`(收料仓库匹配键);`tt3d4e5f6a7b_add_transfer_runs_transfer_type.py` 为 `transfer_runs` 追加 `transfer_type`(调拨业务类型,带检查约束)。
|
||||
- 部署:`cd backend && flask db upgrade`(PostgreSQL)。回滚:`flask db downgrade <上一revision>`。
|
||||
- 表:transfer_runs / transfer_source_jobs / transfer_prechecks / transfer_invoice_items / transfer_attempts / transfer_audit_events / transfer_archives。
|
||||
- 审计表只追加(ORM 门禁 + 前端禁止删除);大对象归档 MinIO(transfer_archives 记录 provider/bucket/key/sha256)。
|
||||
@@ -24,35 +26,33 @@
|
||||
| 变量 | 默认 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `IN_TRANSIT_TRANSFER_SOURCE_CONCURRENCY` | 2 | 来源并发 |
|
||||
| `IN_TRANSIT_TRANSFER_ERP_QUERY_CONCURRENCY` | 2 | ERP 查询并发 |
|
||||
| `IN_TRANSIT_TRANSFER_ERP_WRITE_CONCURRENCY` | 1 | ERP 写并发(一期恒 1,禁止提升) |
|
||||
| `IN_TRANSIT_TRANSFER_ERP_QUERY_TIMEOUT_SECONDS` | 60 | 查询超时 |
|
||||
| `IN_TRANSIT_TRANSFER_ERP_WRITE_TIMEOUT_SECONDS` | 60 | 写超时 |
|
||||
| `IN_TRANSIT_TRANSFER_CONFIRM_TTL_SECONDS` | 600 | 确认有效期(10 分钟) |
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_WARN_DAYS` | 3 | 老化预警阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_ESCALATE_DAYS` | 5 | 老化升级阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_BACKLOG_CRITICAL_DAYS` | 7 | 老化严重阈值 |
|
||||
| `IN_TRANSIT_TRANSFER_ERP_ENDPOINT` / `_USERNAME` / `_PASSWORD` / `_DEFAULT_ORG` | 空 | ERP SOAP 地址与凭据(WSDL 冻结前留空=fail-closed) |
|
||||
| `IN_TRANSIT_TRANSFER_ARCHIVE_BUCKET` | hxops-transfer | 归档 bucket |
|
||||
| `MINIO_ENDPOINT` / `MINIO_ACCESS_KEY` / `MINIO_SECRET_KEY` / `MINIO_SECURE` | 既有 | MinIO 连接(复用既有变量) |
|
||||
| `FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR` | 既有 | 收料 RPA trigger 目录(复用收料链路) |
|
||||
|
||||
> 外部系统(ERP)端点与凭据由集成连接器的客户端实例/凭据引用管理,不使用独立环境变量;
|
||||
> 历史的 `IN_TRANSIT_TRANSFER_ERP_*` 配置键已随去 ERP 化改造删除(零消费死配置)。
|
||||
|
||||
> 凭据纪律:ERP/MinIO 凭据只存在于环境/Secret;不得写入代码、日志、DOM、Excel 或 API 响应。
|
||||
|
||||
## 4. API(`/api/in-transit-transfer`,统一 envelope + requestJson)
|
||||
|
||||
| Method | Path | 说明 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/prechecks` | 创建预检(只读) |
|
||||
| POST | `/prechecks` | 创建预检(只读;可选 `transfer_type`,缺省 `in_transit_to_hub`) |
|
||||
| GET | `/prechecks/{id}` | 预检进度恢复 |
|
||||
| POST | `/prechecks/{id}/execute` | 确认范围并直接生成执行 Run |
|
||||
| GET | `/runs/{run_no}` | Run 结果(按 ERP 单号聚合 + 未生成单据异常) |
|
||||
| POST | `/runs/{run_no}/cancel` | 请求停止剩余任务(原因必填) |
|
||||
| POST | `/items/{id}/retry` | 人工重试(erp_recheck,新 Attempt) |
|
||||
| POST | `/items/{id}/retry` | 人工重试(external_recheck,新 Attempt) |
|
||||
| POST | `/items/{id}/manual-close` | 人工关闭(原因必填) |
|
||||
| GET | `/runs/{run_no}/exceptions.xlsx` | 七 Sheet 异常 Excel(下载留审计) |
|
||||
| GET | `/runs/{run_no}/receipt-files` | 收料来源文件 zip(下载留审计) |
|
||||
| GET | `/runs/{run_no}/erp-inventory` | 预检冻结 ERP 库存表 csv(下载留审计) |
|
||||
| GET | `/runs/{run_no}/external-inventory` | 预检冻结外部系统库存表 csv(下载留审计) |
|
||||
|
||||
权限:admin 或持有 `in_transit_transfer` Agent 权限;无权限 403。
|
||||
|
||||
@@ -72,7 +72,7 @@ cd backend && flask db upgrade
|
||||
- `result_unknown` 项数量(只读隔离,等待人工核实 SOP;禁止自动重试)。
|
||||
- 待处理池 3/5/7 天老化计数(`metrics.collect_metrics()` / 待处理页)。
|
||||
- `notification_status=failed` 的 Run(ERP 结果不受影响,但通知缺失需人工补发)。
|
||||
- ERP 超时率与 `ErpNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。
|
||||
- 外部系统查询超时率与 `ExternalNotFrozenError` 出现(说明契约/配置未冻结或 endpoint 缺失)。
|
||||
- 归档 Hash 复核(`verify_archive_hash`)与 MinIO 容量。
|
||||
|
||||
## 7. 归档与数据保留
|
||||
|
||||
@@ -130,6 +130,8 @@ RPA Trigger、回调、日志和库存文件均不得携带明文凭据。`conne
|
||||
external_system_code
|
||||
external_organization_code # 可空;TOPGP 无此概念时为 NULL
|
||||
external_site_code # 可空
|
||||
freight_warehouse_id # 可空;inventory_match 源按收料文件仓库列匹配的键,空值即「空库位」默认映射行
|
||||
in_transit_warehouse_code # 必填;在途调拨拨出库位来源(in_transit_transfer DefaultRouteResolver)
|
||||
external_warehouse_code
|
||||
external_warehouse_name
|
||||
```
|
||||
@@ -142,7 +144,7 @@ source_code + resolved_warehouse_id 精确映射
|
||||
-> unmapped
|
||||
```
|
||||
|
||||
一个货代 `source + warehouse` 最多对应一个外部系统仓库;多个货代 Warehouse 可以对应同一个外部系统仓库。Crane 若全部 Warehouse 对应同一外部系统仓库,只维护 Source 级默认映射即可。
|
||||
一个货代 `source + warehouse` 最多对应一个外部系统仓库;多个货代 Warehouse 可以对应同一个外部系统仓库。Crane 若全部 Warehouse 对应同一外部系统仓库,只维护 Source 级默认映射即可。在途调拨拨出库位(在途仓编码)按库存源识别方式选择映射行:`inventory_match` 源优先「库存源 + 收料仓库」精确匹配、失败回退「库存源 + 空库位」默认映射行;`fixed` 源仅一条启用映射直接取用(详见 docs/features/in-transit-transfer/technical.md §1 路由归属)。
|
||||
|
||||
## 阶段门禁
|
||||
|
||||
|
||||
@@ -0,0 +1,751 @@
|
||||
# 仓库映射在途仓编码与调拨拨出库位改造 实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 仓库映射新增「在途仓编码」字段并放开货代仓库必填;在途调拨拨出库位改为取映射行的在途仓编码,inventory_match 源按「收料文件仓库列 == 货代仓库」优先匹配、「空库位(货代仓库为空的默认映射行)」兜底。
|
||||
|
||||
**Architecture:** 配置侧为 `shipping_inventory_external_mappings` 加列 `in_transit_warehouse_code`(保存端必填)+ `freight_warehouse_id` 改可选(前后端同步)。调拨侧把收料文件「仓库」列(movement 契约 `warehouse_code`)从解析层贯通到 `transfer_invoice_items.receipt_warehouse_code`(新列),`DefaultRouteResolver.resolve()` 增加 `warehouse_code` 入参并按库存源 `warehouse_resolution_mode` 选择映射行;预检/执行/重试三处调用点同步传参。任何映射行缺失或在途仓编码为空维持 fail-closed(`RouteNotResolvedError`)。
|
||||
|
||||
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(后端);Vue 3 + TailwindCSS + Vue I18n 四语言(前端);pytest(测试)。
|
||||
|
||||
**Spec:** 本需求为会话确认稿(2026-09-22),共 4 点:① 目标仓库编码移至目标仓库名称前;② 原目标仓库编码位置新增「在途仓编码」;③ 货代仓库不再必填;④ 在途调拨拨出库位取在途仓编码,inventory_match 源优先「库存源+收料文件库位」匹配、失败按「库存源+空库位」兜底。已确认决策:库位 = 收料文件 movement 契约 `warehouse_code`(仓库)列;匹配比对映射行 `freight_warehouse_id`(大写归一);fixed(指定仓库)源仅一条启用映射直接取用;在途仓编码保存端必填。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 改表结构必须配套 Alembic 迁移(AGENTS.md §8);迁移 head 当前为 `re1f3a4b5c6d`。
|
||||
- i18n 四语言 zh-CN / zh-TW / en / th 必须同步补齐,禁止硬编码中文。
|
||||
- 新建/调整代码须满足 AGENTS.md §5 注释两层标准:文件层 docstring + 函数层 docstring(含 Args/Returns);逻辑修改必须同步更新过期注释。
|
||||
- JSON API 错误统一 `AppError` 子类;本改造沿用 `ValidationError` / `RouteNotResolvedError`,不新造返回结构。
|
||||
- 禁止自动 commit:每个任务以 `git add` 暂存结束,提交由用户批准后进行;提交信息建议 `feat(shipping-notice): 仓库映射新增在途仓编码并在途调拨拨出库位改取在途仓`。
|
||||
- 后端测试命令在 `backend/` 目录下执行(`python -m pytest ...`,先激活 venv);前端改动后必须 `npm run build` 通过。
|
||||
- 部分唯一索引 `uq_shipping_inv_ext_map_src_default_enabled`(`freight_warehouse_id IS NULL AND enabled`)与 `uq_shipping_inv_ext_map_src_wh_enabled`(`(inventory_source_id, freight_warehouse_id) AND enabled`)已存在,无需改动——同源下「精确映射」与「默认映射」各最多一条启用,保证 resolver 选择确定性。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Alembic 迁移与模型字段
|
||||
|
||||
**Files:**
|
||||
- Create: `backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py`
|
||||
- Modify: `backend/app/models/shipping_inventory_config.py:364-400`(`ShippingInventoryExternalMapping`)
|
||||
- Modify: `backend/app/models/in_transit_transfer.py:186-234`(`TransferInvoiceItem`)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `ShippingInventoryExternalMapping.in_transit_warehouse_code: Mapped[str]`(NOT NULL,默认 `''`);`TransferInvoiceItem.receipt_warehouse_code: Mapped[str]`(NOT NULL,默认 `''`)。后续任务按这两个属性名读写。
|
||||
|
||||
- [ ] **Step 1: 编写迁移文件**
|
||||
|
||||
创建 `backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py`:
|
||||
|
||||
```python
|
||||
"""仓库映射新增在途仓编码;调拨明细记录收料仓库匹配键。
|
||||
|
||||
用途:shipping_inventory_external_mappings 增加 in_transit_warehouse_code(在途调拨拨出库位
|
||||
来源,保存端必填);transfer_invoice_items 增加 receipt_warehouse_code(收料文件
|
||||
「仓库」列原值,inventory_match 源映射行匹配键的审计留痕)。
|
||||
依赖:alembic op / sqlalchemy sa。
|
||||
逻辑:两列均为带 '' 默认值的追加列,不改既有数据;downgrade 直接删列。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = 'it2c3d4e5f6a7'
|
||||
down_revision = 're1f3a4b5c6d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column(
|
||||
'shipping_inventory_external_mappings',
|
||||
sa.Column('in_transit_warehouse_code', sa.String(length=64), nullable=False,
|
||||
server_default='', comment='在途仓编码(在途调拨拨出库位来源)'),
|
||||
)
|
||||
op.add_column(
|
||||
'transfer_invoice_items',
|
||||
sa.Column('receipt_warehouse_code', sa.String(length=64), nullable=False,
|
||||
server_default='', comment='收料文件仓库列原值(映射行匹配键)'),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column('transfer_invoice_items', 'receipt_warehouse_code')
|
||||
op.drop_column('shipping_inventory_external_mappings', 'in_transit_warehouse_code')
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 迁移前重算 head 防漂移**
|
||||
|
||||
Run: `cd backend/migrations/versions && python -c "import re,glob;revs={};downs=set();[ (revs.update({m.group(1):f}),downs.update(re.findall(r'[\'\"]([^\'\"]+)[\'\"]',d.group(1)))) for f in glob.glob('*.py') for m,d in [(re.search(r'^revision(?::\s*str)?\s*=\s*[\'\"]([^\'\"]+)[\'\"]',open(f,encoding='utf-8').read(),re.M),re.search(r'^down_revision(?::[^=]*)?\s*=\s*(.+?)$',open(f,encoding='utf-8').read(),re.M))] if m]" 2>/dev/null || echo "用任务书上的脚本重算"`(若 head 不是 `re1f3a4b5c6d`,改迁移文件的 `down_revision`;head 唯一且为本迁移名时继续)
|
||||
|
||||
- [ ] **Step 3: 模型加列(ShippingInventoryExternalMapping)**
|
||||
|
||||
`backend/app/models/shipping_inventory_config.py` —— 类 docstring(365-369 行)整段替换 + 在 `external_warehouse_name`(398 行)之后加列:
|
||||
|
||||
```python
|
||||
class ShippingInventoryExternalMapping(Base):
|
||||
"""库存源到外部系统仓库的映射。
|
||||
|
||||
freight_warehouse_id(货代仓库)为可选维度:inventory_match 源用它匹配收料文件
|
||||
「仓库」列(空值即「空库位」默认映射行,部分唯一索引保证同源最多一条启用);
|
||||
fixed 源仅一条启用映射直接取用。in_transit_warehouse_code(在途仓编码)是
|
||||
在途调拨拨出库位的来源(in_transit_transfer DefaultRouteResolver),保存端必填,
|
||||
库内空串仅为存量行兼容。
|
||||
"""
|
||||
```
|
||||
|
||||
```python
|
||||
# 在途仓编码:在途调拨拨出库位来源(DefaultRouteResolver);保存端必填。
|
||||
in_transit_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, server_default='', default='')
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 模型加列(TransferInvoiceItem)**
|
||||
|
||||
`backend/app/models/in_transit_transfer.py` —— 在 `lot_no`(213 行)之后加:
|
||||
|
||||
```python
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(拨出库位解析审计)。
|
||||
receipt_warehouse_code: Mapped[str] = mapped_column(String(64), nullable=False, default='', server_default='')
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 跑既有套件确认无回归**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py tests/services/in_transit_transfer -q`
|
||||
Expected: 全部 PASS(加列不影响既有行为;此时尚未改服务逻辑)。若本地库可用,另跑 `flask db upgrade` 确认迁移可执行。
|
||||
|
||||
- [ ] **Step 6: 暂存**
|
||||
|
||||
```bash
|
||||
git add backend/migrations/versions/it2c3d4e5f6a7_add_in_transit_warehouse_code.py backend/app/models/shipping_inventory_config.py backend/app/models/in_transit_transfer.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 后端映射服务——货代仓库改可选、在途仓编码必填
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/admin/shipping_inventory_service.py:1174-1229`
|
||||
- Test: `backend/tests/services/admin/test_shipping_inventory_service.py:536-577`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 的 `ShippingInventoryExternalMapping.in_transit_warehouse_code`。
|
||||
- Produces: `save_external_mapping(data, *, actor_id, mapping_id=None) -> dict`——payload 新增键 `in_transit_warehouse_code`;`freight_warehouse_id` 缺省/空保存为 `None`;`in_transit_warehouse_code` 缺省抛 `ValidationError`。前端与 API 依赖该 payload 键。
|
||||
|
||||
- [ ] **Step 1: 改写测试(先失败)**
|
||||
|
||||
`backend/tests/services/admin/test_shipping_inventory_service.py` —— 三个测试整体替换为:
|
||||
|
||||
```python
|
||||
def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
payload = {
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_organization_code': None, 'external_site_code': 'EU01',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_allows_empty_freight_warehouse(app):
|
||||
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] is None
|
||||
assert mapping['in_transit_warehouse_code'] == 'TZR2'
|
||||
|
||||
|
||||
def test_external_mapping_requires_in_transit_warehouse_code(app):
|
||||
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
|
||||
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
|
||||
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] == 'DUB'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行测试确认失败**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py -q -k external_mapping`
|
||||
Expected: FAIL —— `allows_empty_freight_warehouse` 与 `requires_in_transit_warehouse_code` 失败(现逻辑货代仓库必填、在途仓编码未消费)。
|
||||
|
||||
- [ ] **Step 3: 实现服务层修改**
|
||||
|
||||
`backend/app/services/admin/shipping_inventory_service.py`:
|
||||
|
||||
`_external_payload`(1174-1181 行)替换为:
|
||||
|
||||
```python
|
||||
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,
|
||||
'in_transit_warehouse_code': mapping.in_transit_warehouse_code,
|
||||
'enabled': bool(mapping.enabled), 'version': mapping.version,
|
||||
}
|
||||
```
|
||||
|
||||
`save_external_mapping`(1211-1213 行的三行赋值)替换为:
|
||||
|
||||
```python
|
||||
# 货代仓库改为可选维度:inventory_match 源按「收料文件仓库 == 货代仓库」匹配映射行,
|
||||
# 空值即「空库位」默认映射行;归一化为大写以与收料仓库值精确比对。
|
||||
record.freight_warehouse_id = str(_text(data, 'freight_warehouse_id') or '').upper() or None
|
||||
# 在途仓编码是在途调拨拨出库位来源(DefaultRouteResolver),保存端必填并大写归一。
|
||||
record.in_transit_warehouse_code = str(_text(data, 'in_transit_warehouse_code', required=True)).upper()
|
||||
```
|
||||
|
||||
(其余行不变;`external_system_code` 及之后的赋值保持原序。)
|
||||
|
||||
- [ ] **Step 4: 运行测试确认通过**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/admin/test_shipping_inventory_service.py -q`
|
||||
Expected: 全部 PASS。
|
||||
|
||||
- [ ] **Step 5: 暂存**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/admin/shipping_inventory_service.py backend/tests/services/admin/test_shipping_inventory_service.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 收料文件仓库值贯通(解析层 + 汇总层)
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/in_transit_transfer/file_parser.py:24-37,181-192`
|
||||
- Modify: `backend/app/services/in_transit_transfer/invoice_aggregator.py:21-33,73-83`
|
||||
- Test: `backend/tests/services/in_transit_transfer/test_movement_parser.py`
|
||||
- Test: `backend/tests/services/in_transit_transfer/test_invoice_aggregator.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `ParsedReceiptRow.warehouse_code: str = ""`、`AggregatedInvoice.warehouse_code: str = ""`(两处均带默认值,既有构造点不破坏);`aggregate_invoices` 取组内首行 `warehouse_code`(与 `lot_no` 同策略)。Task 4 的 `resolve()` 消费 `AggregatedInvoice.warehouse_code`。
|
||||
|
||||
- [ ] **Step 1: 写失败测试(parser)**
|
||||
|
||||
`backend/tests/services/in_transit_transfer/test_movement_parser.py` 追加:
|
||||
|
||||
```python
|
||||
def test_movement_row_keeps_warehouse_code():
|
||||
"""收料文件「仓库」列必须透传到解析行——inventory_match 源映射行匹配键的数据源头。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert parsed[0].warehouse_code == "DBS-TRANSIT"
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 写失败测试(aggregator)**
|
||||
|
||||
`backend/tests/services/in_transit_transfer/test_invoice_aggregator.py` —— `_row` 助手(30-38 行)签名与返回 dict 增加 `warehouse_code: str = "WMS-A"` 参数与 `"warehouse_code": warehouse_code` 键,然后追加:
|
||||
|
||||
```python
|
||||
def test_aggregated_invoice_keeps_first_row_warehouse_code():
|
||||
"""汇总发票取组内首行的仓库值(与 lot_no 同策略),供路由匹配使用。"""
|
||||
rows = [
|
||||
_row("INV-001", warehouse_code="WMS-A", row_no=10),
|
||||
_row("INV-001", warehouse_code="WMS-B", row_no=11),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
# [断言意图] 同单多行仓库值不一致时取首行,保证路由匹配输入确定。
|
||||
assert invoices[0].warehouse_code == "WMS-A"
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 运行确认失败**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_movement_parser.py tests/services/in_transit_transfer/test_invoice_aggregator.py -q`
|
||||
Expected: 新增 2 个用例 FAIL(`AttributeError`/断言失败:字段不存在)。
|
||||
|
||||
- [ ] **Step 4: 实现**
|
||||
|
||||
`file_parser.py` —— `ParsedReceiptRow`(24-37 行)`lot_no` 之后加字段:
|
||||
|
||||
```python
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值(movement 契约 warehouse_code):inventory_match 源映射行匹配键。
|
||||
warehouse_code: str = ""
|
||||
```
|
||||
|
||||
`_parse_rows` 构造(181-192 行)`lot_no=...` 之后加:
|
||||
|
||||
```python
|
||||
lot_no=str(row.get("lot_no") or "").strip(),
|
||||
warehouse_code=str(row.get("warehouse_code") or "").strip(),
|
||||
```
|
||||
|
||||
同步更新模块 docstring 第 4 行「输出 ParsedReceiptRow」语义不变,但 `parse_movement_rows` docstring(72-77 行)中「warehouse_code、storage_code 透传/展示保留」改为「warehouse_code 透传至 ParsedReceiptRow.warehouse_code(路由匹配键);storage_code 仍仅展示保留」。
|
||||
|
||||
`invoice_aggregator.py` —— `AggregatedInvoice`(21-33 行)`lot_no` 之后加:
|
||||
|
||||
```python
|
||||
lot_no: str = ""
|
||||
# 组内首行收料仓库值(movement 契约 warehouse_code):inventory_match 源路由匹配键。
|
||||
warehouse_code: str = ""
|
||||
```
|
||||
|
||||
`aggregate_invoices`(73-83 行)`lot_no=first.lot_no,` 之后加:
|
||||
|
||||
```python
|
||||
lot_no=first.lot_no,
|
||||
warehouse_code=first.warehouse_code,
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 运行确认通过**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_movement_parser.py tests/services/in_transit_transfer/test_invoice_aggregator.py -q`
|
||||
Expected: 全部 PASS。
|
||||
|
||||
- [ ] **Step 6: 暂存**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/in_transit_transfer/file_parser.py backend/app/services/in_transit_transfer/invoice_aggregator.py backend/tests/services/in_transit_transfer/test_movement_parser.py backend/tests/services/in_transit_transfer/test_invoice_aggregator.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 路由解析改造与调用点贯通
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/in_transit_transfer/deps.py:26-52`(`DefaultRouteResolver`)
|
||||
- Modify: `backend/app/services/in_transit_transfer/precheck_service.py:93-97`(协议)、`:325/336/367/383/399/411`(DTO 构造)、`:346`(resolve 调用)、`:535-549`(持久化字段)、`:628-640`(恢复明细)
|
||||
- Modify: `backend/app/services/in_transit_transfer/execution_service.py:190`(resolve 调用)、`:336-350`(Run 结果 DTO)
|
||||
- Modify: `backend/app/services/in_transit_transfer/retry_service.py:41`(resolve 调用)
|
||||
- Modify: `backend/app/services/in_transit_transfer/contracts.py:86-103`(`PrecheckInvoiceItemDTO`)
|
||||
- Test: `backend/tests/services/in_transit_transfer/test_route_resolver.py`(整体重写)
|
||||
- Test: `backend/tests/services/in_transit_transfer/repo_fakes.py:67-87`(Fake 签名)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 2 的 `in_transit_warehouse_code`;Task 3 的 `AggregatedInvoice.warehouse_code`;Task 1 的 `TransferInvoiceItem.receipt_warehouse_code`。
|
||||
- Produces: `RouteResolver.resolve(*, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping`(协议级签名变更,三处生产调用点与测试 Fake 同步);`from_warehouse` 语义 = 映射行在途仓编码。`PrecheckInvoiceItemDTO.receipt_warehouse_code: str = ""` 新字段随既有 asdict 序列化进入 API 响应。
|
||||
|
||||
- [ ] **Step 1: 重写 resolver 测试(先失败)**
|
||||
|
||||
`backend/tests/services/in_transit_transfer/test_route_resolver.py` 整文件替换为:
|
||||
|
||||
```python
|
||||
"""调拨路由解析器测试。
|
||||
|
||||
用途:验证 DefaultRouteResolver 的拨出库位与映射行选择契约——
|
||||
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
|
||||
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
|
||||
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
|
||||
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
|
||||
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.deps import DefaultRouteResolver
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
|
||||
|
||||
def _seed_mapping(
|
||||
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
|
||||
in_transit_warehouse_code: str = 'TZT-01',
|
||||
) -> ShippingInventoryExternalMapping:
|
||||
"""在既有种子来源上挂一条启用映射。"""
|
||||
mapping = ShippingInventoryExternalMapping(
|
||||
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
|
||||
external_system_code='TOPGP', external_organization_code='TGHX',
|
||||
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
|
||||
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
|
||||
)
|
||||
db.session.add(mapping)
|
||||
db.session.commit()
|
||||
return mapping
|
||||
|
||||
|
||||
def _seed_inventory_match_source() -> ShippingInventorySource:
|
||||
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
|
||||
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = ShippingInventorySource(
|
||||
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
|
||||
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
|
||||
excel_template_id=template.excel_template_id,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_fixed_source_uses_single_mapping_in_transit_code(app):
|
||||
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
|
||||
_seed_mapping(source, freight_warehouse_id='TZR2')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZT-01'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
assert route.external_org == 'TGHX'
|
||||
|
||||
|
||||
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
|
||||
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='wms-a')
|
||||
|
||||
# [断言意图] 收料仓库小写传入也须命中大写归一的货代仓库身份。
|
||||
assert route.from_warehouse == 'TZT-A'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
|
||||
|
||||
def test_inventory_match_falls_back_to_empty_freight_mapping(app):
|
||||
"""inventory_match 源:收料仓库无精确映射 → 回退货代仓库为空的默认映射行(空库位兜底)。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_blank_warehouse_goes_to_default_mapping(app):
|
||||
"""inventory_match 源:收料文件仓库列缺失 → 直接走空库位默认映射行。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_fails_closed_without_any_match(app):
|
||||
"""inventory_match 源:无精确映射也无默认映射行 → fail-closed。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
|
||||
def test_route_resolver_fails_closed_without_in_transit_code(app):
|
||||
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 更新测试 Fake 签名**
|
||||
|
||||
`backend/tests/services/in_transit_transfer/repo_fakes.py:78` —— `FakeRouteResolver.resolve` 签名改为(方法体不变):
|
||||
|
||||
```python
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 运行确认失败**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_route_resolver.py -q`
|
||||
Expected: FAIL —— 现实现取 `freight_warehouse_id` 且忽略 `warehouse_code`。
|
||||
|
||||
- [ ] **Step 4: 实现 DefaultRouteResolver**
|
||||
|
||||
`backend/app/services/in_transit_transfer/deps.py` —— 类 docstring 与 `resolve` 整体替换:
|
||||
|
||||
```python
|
||||
class DefaultRouteResolver:
|
||||
"""默认路由解析:仓库映射的在途仓编码 + 外部系统仓库。
|
||||
|
||||
拨出库位 = 映射行的在途仓编码(in_transit_warehouse_code);拨入仓库 = 映射的
|
||||
目标仓库代码;组织 = 映射的外部组织编码。映射行按库存源识别方式选择:
|
||||
inventory_match 源优先「收料文件仓库列 == 货代仓库」精确匹配,匹配不到回退
|
||||
货代仓库为空的默认映射行(空库位兜底);fixed 源仅一条启用映射直接取用。
|
||||
不借用站点固定仓库(那是货代发货/库存导出链路的字段)。
|
||||
"""
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""按来源识别方式选择映射行并解析路由;无法归属时抛 RouteNotResolvedError。
|
||||
|
||||
Args:
|
||||
source_code: 来源实例编码(须启用)。
|
||||
invoice_no: Invoice 单号(当前不参与匹配,保留协议兼容)。
|
||||
warehouse_code: 收料文件「仓库」列原值(inventory_match 源的映射匹配键)。
|
||||
Returns:
|
||||
RouteMapping(external_org / from_warehouse=在途仓编码 / to_warehouse)。
|
||||
Raises:
|
||||
RouteNotResolvedError: 来源不存在、无可用映射行或在途仓编码未维护。
|
||||
"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
mappings = ShippingInventoryExternalMapping.query.filter_by(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
).all()
|
||||
selected = None
|
||||
if getattr(source, 'warehouse_resolution_mode', '') == 'inventory_match':
|
||||
# [匹配] 收料仓库大写归一后与货代仓库精确比对;空库位走默认映射行兜底。
|
||||
# 部分唯一索引保证同源「精确/默认」各最多一条启用映射,选择结果确定。
|
||||
key = str(warehouse_code or '').strip().upper()
|
||||
if key:
|
||||
selected = next(
|
||||
(m for m in mappings if str(m.freight_warehouse_id or '').strip().upper() == key), None,
|
||||
)
|
||||
if selected is None:
|
||||
selected = next((m for m in mappings if not str(m.freight_warehouse_id or '').strip()), None)
|
||||
else:
|
||||
selected = mappings[0] if mappings else None
|
||||
if selected is None or not selected.external_organization_code:
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
from_warehouse = str(selected.in_transit_warehouse_code or '').strip()
|
||||
if not from_warehouse:
|
||||
# 拨出库位无来源(映射未维护在途仓编码)——fail-closed,不猜测。
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return RouteMapping(
|
||||
external_org=selected.external_organization_code,
|
||||
from_warehouse=from_warehouse,
|
||||
to_warehouse=selected.external_warehouse_code,
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 5: 运行 resolver 测试确认通过**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer/test_route_resolver.py -q`
|
||||
Expected: 6 个用例 PASS。
|
||||
|
||||
- [ ] **Step 6: 贯通协议、DTO、持久化与三处调用点**
|
||||
|
||||
`precheck_service.py`:
|
||||
- 协议(93-97 行)签名改为:
|
||||
|
||||
```python
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回 Invoice 的路由(warehouse_code 为收料文件仓库列,inventory_match 源匹配键);无法归属时抛 RouteNotResolvedError。"""
|
||||
```
|
||||
|
||||
- `contracts.py` `PrecheckInvoiceItemDTO`(86-103 行)`lot_no` 之后加字段:
|
||||
|
||||
```python
|
||||
lot_no: str = ""
|
||||
# 收料文件「仓库」列原值:inventory_match 源映射行匹配键(明细审计与执行期重解析输入)。
|
||||
receipt_warehouse_code: str = ""
|
||||
```
|
||||
|
||||
- `precheck_service.py` 六处 `PrecheckInvoiceItemDTO(...)` 构造(325/336/367/383/399/411 行)各加一行 `receipt_warehouse_code=invoice.warehouse_code or "",`;
|
||||
- `:346` resolve 调用改为:
|
||||
|
||||
```python
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=source_code, invoice_no=invoice.invoice_no,
|
||||
warehouse_code=invoice.warehouse_code or "",
|
||||
)
|
||||
```
|
||||
|
||||
- `create_precheck` 持久化 `fields` dict(535-549 行)加:
|
||||
|
||||
```python
|
||||
"receipt_warehouse_code": item.receipt_warehouse_code or "",
|
||||
```
|
||||
|
||||
- `get_precheck_detail` 明细 DTO(628-640 行)加 `receipt_warehouse_code=item.receipt_warehouse_code or "",`。
|
||||
|
||||
`execution_service.py`:
|
||||
- `:190` 改为:
|
||||
|
||||
```python
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
```
|
||||
|
||||
- `_build_run_result`(336-350 行)DTO 构造加 `receipt_warehouse_code=item.receipt_warehouse_code or "",`。
|
||||
|
||||
`retry_service.py` `:41` 改为:
|
||||
|
||||
```python
|
||||
route = deps.route_resolver.resolve(
|
||||
source_code=item.source_code, invoice_no=item.invoice_no,
|
||||
warehouse_code=item.receipt_warehouse_code or "",
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 7: 跑整个在途调拨套件并修复夹具级联**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q`
|
||||
Expected: 全部 PASS。若有失败:优先检查断言 `from_warehouse` 的夹具(预检/执行/重试测试用 `FakeRouteResolver`,路由值由 Fake 提供,不受实现影响);`test_precheck_service.py` 若断言持久化字段集合,按新增 `receipt_warehouse_code` 补断言,不删除既有断言。
|
||||
|
||||
- [ ] **Step 8: 暂存**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/in_transit_transfer/ backend/tests/services/in_transit_transfer/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: 前端表单与 i18n 四语言
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue:348-355,666,982,1042`
|
||||
- Modify: `frontend/src/locales/zh-CN/admin.json:975,1188-1189`、`frontend/src/locales/en/admin.json:846,1059-1060`、`frontend/src/locales/zh-TW/admin.json:846,1059-1060`、`frontend/src/locales/th/admin.json:846,1059-1060`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 2 payload 新增键 `in_transit_warehouse_code`(GET 列表回填 + POST/PUT 提交)。
|
||||
- Produces: 表单字段顺序 库存源 → 货代仓库(选填) → 目标系统 → 目标组织 → 目标地点 → 在途仓编码(必填) → 目标仓库编码 → 目标仓库名称 → 启用;两列网格下目标仓库编码与目标仓库名称同行且编码在前。
|
||||
|
||||
- [ ] **Step 1: 模板改造(348-355 行)**
|
||||
|
||||
349 行去掉 `required`;352 行(目标地点)与 353 行(目标仓库编码)之间插入新字段。结果片段:
|
||||
|
||||
```html
|
||||
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalSystem') }}</span><input v-model="mapping.external_system_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalOrganization') }}</span><input v-model="mapping.external_organization_code" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalSite') }}</span><input v-model="mapping.external_site_code" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.inTransitWarehouseCode') }}</span><input v-model="mapping.in_transit_warehouse_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalWarehouseCode') }}</span><input v-model="mapping.external_warehouse_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalWarehouseName') }}</span><input v-model="mapping.external_warehouse_name" class="input-field" required></label>
|
||||
```
|
||||
|
||||
(首行库存源 select 与末行启用 switch 不变。)
|
||||
|
||||
- [ ] **Step 2: 表单状态四处同步**
|
||||
|
||||
- `:666` reactive 声明加 `in_transit_warehouse_code: ''`(置于 `external_site_code` 之后):
|
||||
|
||||
```ts
|
||||
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
```
|
||||
|
||||
- `:982` `createNew` 的 mappings 重置同步加 `in_transit_warehouse_code: ''`;
|
||||
- `:1042` `selectItem` 同步加 `in_transit_warehouse_code: item.in_transit_warehouse_code || ''`:
|
||||
|
||||
```ts
|
||||
if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '', in_transit_warehouse_code: item.in_transit_warehouse_code || '' });
|
||||
```
|
||||
|
||||
- `:1228` `saveCurrent` 无需改动(`...mapping` 展开已携带新键;`freight_warehouse_id: mapping.freight_warehouse_id || null` 恰好实现选填语义)。
|
||||
|
||||
- [ ] **Step 3: i18n 四语言补 key**
|
||||
|
||||
各语言 `admin.json` 的 `externalWarehouseName` 行后新增 `"inTransitWarehouseCode"`,并整体替换 `mappingsHelp`(语义已变:货代仓库选填、新增在途仓编码):
|
||||
|
||||
| 文件 | 新增 key 与值 | mappingsHelp 替换值 |
|
||||
| --- | --- | --- |
|
||||
| `zh-CN/admin.json` | `"inTransitWarehouseCode": "在途仓编码",` | `"将库存源映射到外部系统仓库编码与在途仓编码;货代仓库可空,作为按收料仓库匹配映射行的键。"` |
|
||||
| `zh-TW/admin.json` | `"inTransitWarehouseCode": "在途倉編碼",` | `"將庫存來源對應至外部系統倉庫編碼與在途倉編碼;貨代倉庫可為空,作為按收料倉庫匹配映射列的鍵。"` |
|
||||
| `en/admin.json` | `"inTransitWarehouseCode": "In-transit warehouse code",` | `"Map an inventory source to external system warehouse and in-transit warehouse codes; freight warehouse is optional and used as the receipt-warehouse matching key."` |
|
||||
| `th/admin.json` | `"inTransitWarehouseCode": "รหัสคลังระหว่างทาง",` | `"แมปแหล่งสินค้าคงคลังไปยังรหัสคลังปลายทางและรหัสคลังระหว่างทางของระบบภายนอก คลังผู้ให้บริการเป็นทางเลือกและใช้เป็นคีย์จับคู่คลังรับสินค้า"` |
|
||||
|
||||
- [ ] **Step 4: 构建验证**
|
||||
|
||||
Run: `cd frontend && npm run build`
|
||||
Expected: 构建成功,无 TS/模板错误。
|
||||
|
||||
- [ ] **Step 5: 暂存**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue frontend/src/locales/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 文档同步与全量验证
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/features/in-transit-transfer/technical.md`(路由解析章节)
|
||||
- Modify: `docs/features/shipping-notice/technical.md:3429-3430`(映射主数据描述)
|
||||
- Modify: `docs/features/shipping-notice/inventory_source_plan.md:123-145`(映射字段清单)
|
||||
- Modify: `docs/funclist.md`(若存在仓库映射/在途调拨条目)
|
||||
- Modify: `backend/app/api/admin/shipping_inventory.py`(仅文件层 docstring 如提及字段清单则同步;无则跳过)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1-5 的最终行为。
|
||||
- Produces: 文档与代码一致(AGENTS.md §9 红线)。
|
||||
|
||||
- [ ] **Step 1: 在途调拨技术手册更新**
|
||||
|
||||
`docs/features/in-transit-transfer/technical.md` 中检索「拨出库位 / from_warehouse / 货代仓库」的路由解析段落,把「拨出库位 = 映射行货代仓库」口径整体替换为:
|
||||
|
||||
> 拨出库位取仓库映射行的「在途仓编码」(`in_transit_warehouse_code`,保存端必填)。映射行按库存源 `warehouse_resolution_mode` 选择:`inventory_match`(按库存行匹配)源优先按「库存源 + 收料文件仓库列(`warehouse_code`)== 货代仓库」精确匹配,匹配不到回退「库存源 + 货代仓库为空」的默认映射行(空库位兜底);`fixed`(指定仓库)源仅一条启用映射直接取用。收料文件仓库列原值随明细落库于 `transfer_invoice_items.receipt_warehouse_code`,执行/重试期重解析以它为匹配键,路由变化仍 fail-closed 阻断。映射行缺失或在途仓编码未维护时维持 `TRANSFER.ROUTE_NOT_RESOLVED`。运维注意:来源的 movement 解析方案须把收料文件「仓库」表头映射到领域字段 `warehouse_code`,未映射时该值为空、inventory_match 源将直接走空库位兜底。
|
||||
|
||||
- [ ] **Step 2: shipping-notice 技术手册更新**
|
||||
|
||||
`docs/features/shipping-notice/technical.md:3430` 「外部系统仓库映射保存在 …」段落,替换/追加为:
|
||||
|
||||
> 外部系统仓库映射保存在 `shipping_inventory_external_mappings`:货代仓库(`freight_warehouse_id`)为可选维度(inventory_match 源按收料仓库匹配的键,空值即默认映射行),在途仓编码(`in_transit_warehouse_code`)为在途调拨拨出库位来源(保存端必填);发货链路仍按 `source + warehouse` 精确优先、Source 默认映射兜底查询,调拨链路口径见 docs/features/in-transit-transfer/technical.md。
|
||||
|
||||
- [ ] **Step 3: inventory_source_plan 字段清单更新**
|
||||
|
||||
`docs/features/shipping-notice/inventory_source_plan.md:123-145` 映射字段清单中:`freight_warehouse_id` 标注「可选」,并在其后追加一行 `in_transit_warehouse_code(在途仓编码,必填):在途调拨拨出库位来源`。
|
||||
|
||||
- [ ] **Step 4: 功能清单核对**
|
||||
|
||||
Run: `grep -n "在途调拨\|仓库映射\|external_mapping" docs/funclist.md`
|
||||
若有对应条目:在条目描述中补「映射支持在途仓编码(拨出库位来源),货代仓库选填(按收料仓库匹配映射行)」。若无条目:不改(本需求为既有功能的字段级调整,不新增功能项)。
|
||||
|
||||
- [ ] **Step 5: 全量回归**
|
||||
|
||||
Run: `cd backend && python -m pytest tests/services/in_transit_transfer tests/services/admin/test_shipping_inventory_service.py tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py -q`
|
||||
Run: `cd frontend && npm run build`
|
||||
Expected: 后端全部 PASS、前端构建成功。
|
||||
|
||||
- [ ] **Step 6: 暂存**
|
||||
|
||||
```bash
|
||||
git add docs/features/in-transit-transfer/technical.md docs/features/shipping-notice/technical.md docs/features/shipping-notice/inventory_source_plan.md docs/funclist.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Self-Review 记录
|
||||
|
||||
- 规格覆盖:需求①②→ Task 5(一次插入同时实现「在途仓编码占原位 + 目标仓库编码落到目标仓库名称前」);需求③→ Task 2 + Task 5;需求④→ Task 1(迁移)+ Task 3(仓库值贯通)+ Task 4(解析与调用点)+ Task 6(文档)。
|
||||
- 类型一致性:`in_transit_warehouse_code`(映射表)、`receipt_warehouse_code`(明细表/DTO)、`warehouse_code`(解析 DTO/resolve 入参)三层命名已统一并在 Interfaces 块声明;`resolve()` 协议签名在协议、实现、Fake、三处调用点保持一致。
|
||||
- 已知边界:站点启用就绪检查(`_enabled_external_mapping_exists`)不要求在途仓编码,本计划不改(需求未涉及);`resolve` 的 `invoice_no` 参数保留但当前不参与匹配(协议兼容,注释已说明)。
|
||||
@@ -346,10 +346,11 @@
|
||||
|
||||
<template v-else-if="activeTab === 'mappings'">
|
||||
<label><span>{{ t('admin.shippingInventory.source') }}</span><select v-model.number="mapping.inventory_source_id" class="select-field" required><option :value="0">{{ t('admin.shippingInventory.chooseSource') }}</option><option v-for="item in sources" :key="String(item.id)" :value="Number(item.id)">{{ item.display_name || item.source_code }}</option></select></label>
|
||||
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.freightWarehouse') }}</span><input v-model="mapping.freight_warehouse_id" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalSystem') }}</span><input v-model="mapping.external_system_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalOrganization') }}</span><input v-model="mapping.external_organization_code" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalSite') }}</span><input v-model="mapping.external_site_code" class="input-field"></label>
|
||||
<label><span>{{ t('admin.shippingInventory.inTransitWarehouseCode') }}</span><input v-model="mapping.in_transit_warehouse_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalWarehouseCode') }}</span><input v-model="mapping.external_warehouse_code" class="input-field" required></label>
|
||||
<label><span>{{ t('admin.shippingInventory.externalWarehouseName') }}</span><input v-model="mapping.external_warehouse_name" class="input-field" required></label>
|
||||
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: mapping.enabled }" role="switch" :aria-checked="mapping.enabled" @click="mapping.enabled = !mapping.enabled"><i></i><b>{{ mapping.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
|
||||
@@ -663,7 +664,7 @@ const inventoryPathOpen = ref(true);
|
||||
const receiptBaseline = ref('');
|
||||
const sourceBaseline = ref('');
|
||||
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
|
||||
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line')));
|
||||
const activeInventoryFields = computed(() => inventoryFields.value.filter((item) => item.status === 'active'));
|
||||
const matchingInventoryFields = computed(() => activeInventoryFields.value.filter((item) => item.usage_type === 'match_identity'));
|
||||
@@ -979,7 +980,7 @@ function createNew(): void {
|
||||
sourceBaseline.value = '';
|
||||
}
|
||||
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected: '' }], source_codes: [] });
|
||||
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', in_transit_warehouse_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
|
||||
drawerOpen.value = true;
|
||||
}
|
||||
|
||||
@@ -1039,7 +1040,7 @@ function selectItem(item: Item): void {
|
||||
})),
|
||||
source_codes: item.action_payload_json?.source_codes || [],
|
||||
});
|
||||
if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '' });
|
||||
if (activeTab.value === 'mappings') Object.assign(mapping, { ...item, freight_warehouse_id: item.freight_warehouse_id || '', external_organization_code: item.external_organization_code || '', external_site_code: item.external_site_code || '', in_transit_warehouse_code: item.in_transit_warehouse_code || '' });
|
||||
drawerOpen.value = true;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
TransferRunResult,
|
||||
TransferSourceFileStatus,
|
||||
TransferSourceOption,
|
||||
TransferType,
|
||||
} from '../types/transfer.types';
|
||||
|
||||
const BASE = '/api/in-transit-transfer';
|
||||
@@ -28,6 +29,8 @@ export interface CreatePrecheckPayload {
|
||||
business_date?: string;
|
||||
receipt_date_from?: string;
|
||||
receipt_date_to?: string;
|
||||
/** 调拨业务类型;缺省为在途仓至HUB仓 */
|
||||
transfer_type?: TransferType;
|
||||
}
|
||||
|
||||
/** 创建预检(只读) */
|
||||
@@ -88,7 +91,7 @@ export const downloadTransferReceiptFiles = (runNo: string) =>
|
||||
|
||||
/** 下载预检冻结的 ERP 库存表(csv) */
|
||||
export const downloadTransferErpInventory = (runNo: string) =>
|
||||
requestBlob(`${BASE}/runs/${runNo}/erp-inventory`, { headers: getAuthHeaders() });
|
||||
requestBlob(`${BASE}/runs/${runNo}/external-inventory`, { headers: getAuthHeaders() });
|
||||
|
||||
/** 下载七 Sheet 异常 Excel */
|
||||
export const downloadTransferExceptions = (runNo: string) =>
|
||||
|
||||
@@ -64,14 +64,14 @@ describe('TransferHomePanel chat home entry', () => {
|
||||
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05', expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
|
||||
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, precheck_hash: 'sha256:x',
|
||||
});
|
||||
api.getTransferPrecheck.mockResolvedValue({
|
||||
summary: {
|
||||
precheck_id: 'TPC-1', status: 'ready_to_execute', business_date: '2026-08-06',
|
||||
eligible_receipt_date_to: '2026-08-05', expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200', estimated_erp_write_count: 1, precheck_hash: 'sha256:x',
|
||||
estimated_transfer_quantity: '1200', estimated_external_write_count: 1, precheck_hash: 'sha256:x',
|
||||
},
|
||||
items: [{
|
||||
source_code: 'DBS-AWSBI', material_no: 'MAT-1', material_name: '连接器组件', specification: 'A',
|
||||
|
||||
@@ -38,7 +38,7 @@ const payload = {
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 1, not_matured_count: 0, prechecked_count: 1, executable_count: 1, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '1200',
|
||||
estimated_erp_write_count: 1,
|
||||
estimated_external_write_count: 1,
|
||||
precheck_hash: 'sha256:x',
|
||||
},
|
||||
items: [{
|
||||
@@ -57,7 +57,7 @@ const runPayload = {
|
||||
run_no: 'RUN-1',
|
||||
status: 'success',
|
||||
result: {
|
||||
erp_documents: [{
|
||||
external_documents: [{
|
||||
document_no: 'TRF-10001', from_warehouse: 'DBS-TRANSIT', to_warehouse: 'HUB-CN01',
|
||||
material_count: 1, total_quantity: '1200', posting_status: 'posted',
|
||||
lines: [{ material_no: 'MAT-1', material_name: '连接器组件', specification: 'A', invoice_no: 'INV-001', quantity: '1200' }],
|
||||
@@ -167,7 +167,7 @@ describe('TransferMessageView self-driving wiring', () => {
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
await flushPromises();
|
||||
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'] });
|
||||
expect(api.createTransferPrecheck).toHaveBeenCalledWith({ source_codes: ['DBS-AWSBI'], transfer_type: 'in_transit_to_hub' });
|
||||
expect(wrapper.find('[data-testid="transfer-precheck-card"]').exists()).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -25,6 +25,7 @@ import type {
|
||||
TransferPrecheckSummary,
|
||||
TransferRunResult,
|
||||
TransferSourceProgress,
|
||||
TransferType,
|
||||
} from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -195,14 +196,15 @@ async function onCloseConfirm(reason: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步;收料日期范围为查询范围) */
|
||||
/** 来源实例选择确认 → 创建预检并切换预检卡(决策 4:两步第一步;收料日期范围为查询范围;调拨类型决定数据范围) */
|
||||
async function onSourceConfirm(
|
||||
sourceCodes: string[],
|
||||
dateRange?: { from?: string; to?: string },
|
||||
transferType?: TransferType,
|
||||
) {
|
||||
busy.value = true;
|
||||
try {
|
||||
await transfer.createPrecheck(sourceCodes, undefined, dateRange);
|
||||
await transfer.createPrecheck(sourceCodes, undefined, dateRange, transferType);
|
||||
mode.value = 'precheck';
|
||||
summaryRef.value = transfer.precheck.value;
|
||||
items.value = transfer.items.value;
|
||||
|
||||
@@ -3,14 +3,18 @@
|
||||
用途:预检卡——计数 + 来源失败提示 + 调拨明细表(含筛选)+ 勾选 + “直接生成调拨单”按钮。
|
||||
依赖:props(summary/items/sources/selected/busy)、i18n chat.transfer.*。
|
||||
逻辑:明细表渲染 filtered(关键字/结果筛选生效);阻断/未成熟项 checkbox 禁用;
|
||||
重查范围含可恢复阻断与可执行行;阻断原因经结果徽标 title 悬浮透出不占行高;
|
||||
无选择或 busy 时生成按钮禁用;emit execute(invoiceNos)(决策 4/5:无独立确认页);
|
||||
来源级解析/文件失败经 sources.error_code 透出(防"安静全 0")。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { deriveBatchNo } from './transferBatch';
|
||||
import type { TransferPrecheckItem, TransferPrecheckSummary, TransferSourceProgress } from '../../types/transfer.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
|
||||
const props = defineProps<{
|
||||
summary: TransferPrecheckSummary;
|
||||
items: TransferPrecheckItem[];
|
||||
@@ -54,6 +58,11 @@ function isCheckable(item: TransferPrecheckItem): boolean {
|
||||
return isSelectable(item) || isBlocked(item);
|
||||
}
|
||||
|
||||
/** 可重查行:可恢复阻断 + 可执行(已可执行也允许重查核对最新库存)。 */
|
||||
function isRequeryable(item: TransferPrecheckItem): boolean {
|
||||
return isBlocked(item) || item.result === 'executable';
|
||||
}
|
||||
|
||||
const filtered = computed(() =>
|
||||
props.items.filter((item) => {
|
||||
const kw = keyword.value.trim().toLowerCase();
|
||||
@@ -73,8 +82,8 @@ const filteredInvoiceNos = computed(() => filtered.value.map((item) => item.invo
|
||||
const allFilteredSelected = computed(() =>
|
||||
filteredInvoiceNos.value.length > 0 && filteredInvoiceNos.value.every((no) => props.selected.has(no)),
|
||||
);
|
||||
const selectedBlockedCount = computed(() =>
|
||||
filtered.value.filter((item) => isBlocked(item) && props.selected.has(item.invoice_no)).length,
|
||||
const selectedRequeryableCount = computed(() =>
|
||||
filtered.value.filter((item) => isRequeryable(item) && props.selected.has(item.invoice_no)).length,
|
||||
);
|
||||
|
||||
function toggleAll(): void {
|
||||
@@ -83,7 +92,7 @@ function toggleAll(): void {
|
||||
|
||||
function requerySelected(): void {
|
||||
const nos = filtered.value
|
||||
.filter((item) => isBlocked(item) && props.selected.has(item.invoice_no))
|
||||
.filter((item) => isRequeryable(item) && props.selected.has(item.invoice_no))
|
||||
.map((item) => item.invoice_no);
|
||||
if (nos.length) emit('requery', nos);
|
||||
}
|
||||
@@ -99,11 +108,31 @@ function resultLabel(result: string): string {
|
||||
blocked_quantity_mismatch: 'chat.transfer.resultBlocked',
|
||||
blocked_inventory_not_found: 'chat.transfer.resultBlocked',
|
||||
blocked_future_date: 'chat.transfer.resultBlocked',
|
||||
erp_query_timeout: 'chat.transfer.resultUnknown',
|
||||
external_query_timeout: 'chat.transfer.resultUnknown',
|
||||
result_unknown: 'chat.transfer.resultUnknown',
|
||||
};
|
||||
return map[result] ?? 'chat.transfer.resultBlocked';
|
||||
}
|
||||
|
||||
/** 阻断原因悬浮文案:已知结果码走 i18n 本地化;带明细后缀(如查询失败的底层原因)原样保留追加。 */
|
||||
const REASON_I18N_KEYS: Record<string, string> = {
|
||||
blocked_quantity_mismatch: 'chat.transfer.reasonQuantityMismatch',
|
||||
blocked_inventory_not_found: 'chat.transfer.reasonInventoryNotFound',
|
||||
blocked_external_query_failed: 'chat.transfer.reasonExternalQueryFailed',
|
||||
blocked_future_date: 'chat.transfer.reasonFutureDate',
|
||||
};
|
||||
|
||||
function reasonTitle(item: TransferPrecheckItem): string | undefined {
|
||||
if (!isBlocked(item) || !item.reason) return undefined;
|
||||
const key = REASON_I18N_KEYS[item.result];
|
||||
if (!key) return item.reason;
|
||||
const base = t(key);
|
||||
const marker = ': ';
|
||||
const detail = item.reason.includes(marker)
|
||||
? item.reason.slice(item.reason.indexOf(marker) + marker.length).trim()
|
||||
: '';
|
||||
return detail ? `${base}:${detail}` : base;
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -131,8 +160,8 @@ function resultLabel(result: string): string {
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedQuantity') }}</div>
|
||||
</div>
|
||||
<div class="rounded-lg bg-surface-soft p-2 text-center">
|
||||
<div class="text-lg font-black text-brand-600">{{ summary.estimated_erp_write_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedErpWrites') }}</div>
|
||||
<div class="text-lg font-black text-brand-600">{{ summary.estimated_external_write_count }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedExternalWrites') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -164,11 +193,11 @@ function resultLabel(result: string): string {
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 bg-brand-50 px-3 py-1 text-xs font-bold text-brand-700 transition hover:bg-brand-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:disabled="props.requeryBusy || selectedBlockedCount === 0"
|
||||
:disabled="props.requeryBusy || selectedRequeryableCount === 0"
|
||||
data-testid="transfer-precheck-requery-selected"
|
||||
@click="requerySelected"
|
||||
>
|
||||
{{ $t('chat.transfer.requerySelected') }}{{ selectedBlockedCount ? `(${selectedBlockedCount})` : '' }}
|
||||
{{ $t('chat.transfer.requerySelected') }}{{ selectedRequeryableCount ? `(${selectedRequeryableCount})` : '' }}
|
||||
</button>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
@@ -224,26 +253,31 @@ function resultLabel(result: string): string {
|
||||
<td class="p-2">{{ item.to_warehouse }}</td>
|
||||
<td class="p-2">{{ item.to_quantity }}</td>
|
||||
<td class="p-2">
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-bold"
|
||||
:class="{
|
||||
'bg-emerald-50 text-emerald-700': item.result === 'executable',
|
||||
'bg-amber-50 text-amber-700': item.result === 'not_matured',
|
||||
'bg-red-50 text-red-700': !isSelectable(item) && item.result !== 'not_matured',
|
||||
}"
|
||||
>
|
||||
{{ $t(resultLabel(item.result)) }}
|
||||
</span>
|
||||
<button
|
||||
v-if="isBlocked(item)"
|
||||
type="button"
|
||||
class="ml-1 rounded border border-brand-200 px-1 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
|
||||
:disabled="props.requeryBusy"
|
||||
:data-testid="`transfer-requery-${item.invoice_no}`"
|
||||
@click="emit('requery', [item.invoice_no])"
|
||||
>
|
||||
{{ $t('chat.transfer.requeryRow') }}
|
||||
</button>
|
||||
<div class="flex items-center gap-1">
|
||||
<!-- 阻断原因经悬浮提示(title)透出:不占行高;可执行行也提供重查入口 -->
|
||||
<span
|
||||
class="rounded-full px-2 py-0.5 font-bold"
|
||||
:class="{
|
||||
'bg-emerald-50 text-emerald-700': item.result === 'executable',
|
||||
'bg-amber-50 text-amber-700': item.result === 'not_matured',
|
||||
'bg-red-50 text-red-700': !isSelectable(item) && item.result !== 'not_matured',
|
||||
}"
|
||||
:title="reasonTitle(item)"
|
||||
data-testid="transfer-item-result"
|
||||
>
|
||||
{{ $t(resultLabel(item.result)) }}
|
||||
</span>
|
||||
<button
|
||||
v-if="isRequeryable(item)"
|
||||
type="button"
|
||||
class="ml-1 rounded border border-brand-200 px-1 text-[10px] font-bold text-brand-700 transition hover:bg-brand-50 disabled:opacity-40"
|
||||
:disabled="props.requeryBusy"
|
||||
:data-testid="`transfer-requery-${item.invoice_no}`"
|
||||
@click="emit('requery', [item.invoice_no])"
|
||||
>
|
||||
{{ $t('chat.transfer.requeryRow') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -253,7 +287,7 @@ function resultLabel(result: string): string {
|
||||
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
|
||||
<span class="text-xs text-muted">
|
||||
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
|
||||
{{ $t('chat.transfer.estimatedErpWrites') }}:{{ summary.estimated_erp_write_count }}
|
||||
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ summary.estimated_external_write_count }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -39,9 +39,9 @@ function reasonLabel(reason: string): string {
|
||||
</div>
|
||||
|
||||
<!-- 已生成 ERP 单据:按单号聚合 + 可展开物料明细 -->
|
||||
<div v-if="run.result.erp_documents.length" class="flex flex-col gap-2">
|
||||
<div v-if="run.result.external_documents.length" class="flex flex-col gap-2">
|
||||
<details
|
||||
v-for="doc in run.result.erp_documents"
|
||||
v-for="doc in run.result.external_documents"
|
||||
:key="doc.document_no"
|
||||
class="rounded-lg border border-default"
|
||||
data-testid="transfer-erp-document"
|
||||
|
||||
@@ -58,7 +58,7 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('“清空”清空已选实例', async () => {
|
||||
it('“清空选择”清空已选实例', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-clear"]').trigger('click');
|
||||
@@ -66,6 +66,28 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('选中后上下文操作条原位替换选择辅助区,清空选择后还原', async () => {
|
||||
// [断言意图] 未选中零死按钮(仅辅助区);有选中时批量操作条同槽位出现并带计数;
|
||||
// 清空选择后还原辅助区——Gmail/Linear 式批量操作栏切换行为。
|
||||
const wrapper = mountCard();
|
||||
expect(wrapper.find('[data-testid="transfer-source-aids"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="transfer-source-action-bar"]').exists()).toBe(false);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
expect(wrapper.find('[data-testid="transfer-source-aids"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="transfer-source-action-bar"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="transfer-source-action-bar"]').text()).toContain('已选 1');
|
||||
await wrapper.find('[data-testid="transfer-source-clear"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-aids"]').exists()).toBe(true);
|
||||
expect(wrapper.find('[data-testid="transfer-source-action-bar"]').exists()).toBe(false);
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('D+1 规则提示收进 ⓘ 悬浮(title),不再平铺占宽', () => {
|
||||
// [断言意图] 长规则文案通过原生 title 渐进披露,紧凑日期行不换行错位。
|
||||
const wrapper = mountCard();
|
||||
expect(wrapper.find('[data-testid="transfer-source-date-hint"]').attributes('title')).toBe('截止不超出 D+1 规则(业务日期前一天)');
|
||||
});
|
||||
|
||||
it('“只选可重试”勾选无文件/失败来源', async () => {
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-retryable"]').trigger('click');
|
||||
@@ -86,4 +108,33 @@ describe('TransferSourceSelectCard', () => {
|
||||
await wrapper.find('[data-testid="transfer-source-batch-retry"]').trigger('click');
|
||||
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSSG']);
|
||||
});
|
||||
|
||||
it('已过期来源显示「文件已过期」徽标且可重试', async () => {
|
||||
// [断言意图] 保留期已到的来源不得误报就绪(has_ready_file=false);
|
||||
// expired 状态与 none/failed 一样允许重新触发收料 RPA。
|
||||
const wrapper = mountCard({}, [
|
||||
{ source_code: 'CRANE-EXP', display_name: '过期在途仓', platform: 'crane', enabled: true, has_ready_file: false, file_status: 'expired' },
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="transfer-source-status-CRANE-EXP"]').text()).toBe('文件已过期');
|
||||
expect((wrapper.find('[data-testid="transfer-source-retry-CRANE-EXP"]').element as HTMLButtonElement).disabled).toBe(false);
|
||||
await wrapper.find('[data-testid="transfer-source-option-CRANE-EXP"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-batch-retry"]').trigger('click');
|
||||
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['CRANE-EXP']);
|
||||
});
|
||||
|
||||
it('确认默认携带调拨类型 in_transit_to_hub', async () => {
|
||||
// [断言意图] 类型 1 为缺省选中值,确认事件第三参回传类型。
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][2]).toBe('in_transit_to_hub');
|
||||
});
|
||||
|
||||
it('调拨类型 2/3 占位禁用且不可选中', async () => {
|
||||
// [断言意图] 一期仅开放类型 1;占位类型按钮 disabled,防止发起未支持链路。
|
||||
const wrapper = mountCard();
|
||||
expect((wrapper.find('[data-testid="transfer-type-option-hub_repair_out"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((wrapper.find('[data-testid="transfer-type-option-hub_to_hub"]').element as HTMLButtonElement).disabled).toBe(true);
|
||||
expect((wrapper.find('[data-testid="transfer-type-option-in_transit_to_hub"]').element as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,19 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferSourceSelectCard.vue
|
||||
用途:来源实例选择卡(决策 2/3/4:手工两步第一步)——按平台 DBS/Crane 分组勾选实例,
|
||||
“确认范围并预检”发起预检。
|
||||
选择调拨类型后“确认范围并预检”发起预检。
|
||||
依赖:props.sources、i18n chat.transfer.*。
|
||||
逻辑:平台仅分组不可直接执行;未选任何实例时确认按钮禁用。
|
||||
逻辑:预检参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
|
||||
(有选中时原位替换辅助区,承载批量重试/下载/清空选择)→ 平台分组来源列表
|
||||
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并预检」(未选禁用);
|
||||
调拨类型决定收料数据范围(类型 1 仅纳入 INVOICE 前缀 HOM/HOX/WTP),
|
||||
类型 2/3 一期占位(禁用,后端同样 fail-closed)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import type { TransferSourceOption } from '../../types/transfer.types';
|
||||
import type { TransferSourceOption, TransferType } from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
sources: TransferSourceOption[];
|
||||
@@ -19,7 +23,7 @@ const props = defineProps<{
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [sourceCodes: string[], dateRange?: { from?: string; to?: string }];
|
||||
confirm: [sourceCodes: string[], dateRange?: { from?: string; to?: string }, transferType?: TransferType];
|
||||
/** 批量重试收料 RPA:传来源编码列表 */
|
||||
retry: [sourceCodes: string[]];
|
||||
download: [sourceCodes: string[]];
|
||||
@@ -32,13 +36,26 @@ const selected = ref<Set<string>>(new Set());
|
||||
/** 收料日期范围(预检查询范围);截止不得超出 D+1 规则(后端卡控)。 */
|
||||
const dateFrom = ref('');
|
||||
const dateTo = ref('');
|
||||
/** 调拨业务类型:决定本次预检纳入哪些收料数据;一期仅类型 1 开放。 */
|
||||
const transferType = ref<TransferType>('in_transit_to_hub');
|
||||
|
||||
/** 类型选项元数据;enabled=false 为占位类型(UI 禁用 + 后端 fail-closed 双保险)。 */
|
||||
const transferTypeOptions: Array<{ value: TransferType; enabled: boolean }> = [
|
||||
{ value: 'in_transit_to_hub', enabled: true },
|
||||
{ value: 'hub_repair_out', enabled: false },
|
||||
{ value: 'hub_to_hub', enabled: false },
|
||||
];
|
||||
|
||||
function transferTypeLabel(value: TransferType): string {
|
||||
return t(`chat.transfer.transferType.${value}`);
|
||||
}
|
||||
|
||||
const platforms = computed(() => [...new Set(props.sources.map((source) => source.platform))]);
|
||||
const selectedCount = computed(() => selected.value.size);
|
||||
|
||||
/** 可重试判定:仅 待抓取(none) / 抓取失败(failed) 的来源可重试(ready/fetching 不重复触发)。 */
|
||||
/** 可重试判定:仅 待抓取(none) / 抓取失败(failed) / 已过期(expired) 的来源可重试(ready/fetching 不重复触发)。 */
|
||||
function isRetryable(source: TransferSourceOption): boolean {
|
||||
return source.file_status === 'none' || source.file_status === 'failed';
|
||||
return source.file_status === 'none' || source.file_status === 'failed' || source.file_status === 'expired';
|
||||
}
|
||||
|
||||
/** 全部可重试来源。 */
|
||||
@@ -117,7 +134,7 @@ function confirm() {
|
||||
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
emit('confirm', [...selected.value], { from: dateFrom.value || undefined, to: dateTo.value || undefined });
|
||||
emit('confirm', [...selected.value], { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -126,7 +143,54 @@ function confirm() {
|
||||
<h3 class="mb-1 text-sm font-bold text-primary">{{ $t('chat.transfer.sourceSelectTitle') }}</h3>
|
||||
<p class="mb-3 text-xs text-muted">{{ $t('chat.transfer.sourceSelectHint') }}</p>
|
||||
|
||||
<div class="mb-3 flex flex-wrap items-center gap-2">
|
||||
<!-- [ZONE 1] 预检参数区:调拨类型 + 收料日期同组(确认预检时一并提交,参数先行定范围)。 -->
|
||||
<div class="mb-3 rounded-lg border border-subtle p-3" data-testid="transfer-source-params">
|
||||
<p class="mb-2 text-[11px] font-bold text-muted">{{ $t('chat.transfer.precheckParams') }}</p>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs font-bold text-secondary">{{ $t('chat.transfer.transferTypeLabel') }}</span>
|
||||
<button
|
||||
v-for="option in transferTypeOptions"
|
||||
:key="option.value"
|
||||
type="button"
|
||||
class="rounded-full border px-3 py-1 text-xs font-bold disabled:cursor-not-allowed disabled:opacity-40"
|
||||
:class="transferType === option.value
|
||||
? 'border-brand-600 bg-brand-600 text-white hover:bg-brand-700'
|
||||
: 'border-brand-200 text-brand-700 hover:bg-brand-50'"
|
||||
:disabled="busy || !option.enabled"
|
||||
:title="option.enabled ? undefined : t('chat.transfer.transferTypeComingSoon')"
|
||||
:data-testid="`transfer-type-option-${option.value}`"
|
||||
@click="transferType = option.value"
|
||||
>
|
||||
{{ transferTypeLabel(option.value) }}
|
||||
<span v-if="!option.enabled" class="ml-1 font-normal opacity-70">{{ t('chat.transfer.transferTypeComingSoon') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs font-bold text-secondary">{{ $t('chat.transfer.receiptDateLabel') }}</span>
|
||||
<input
|
||||
v-model="dateFrom"
|
||||
type="date"
|
||||
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
|
||||
data-testid="transfer-source-date-from"
|
||||
/>
|
||||
<span class="text-xs text-muted">~</span>
|
||||
<input
|
||||
v-model="dateTo"
|
||||
type="date"
|
||||
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
|
||||
data-testid="transfer-source-date-to"
|
||||
/>
|
||||
<!-- D+1 规则属低频说明:收进原生 title 悬浮(渐进披露),避免长文案挤压布局。 -->
|
||||
<span
|
||||
class="cursor-help text-xs text-muted"
|
||||
:title="$t('chat.transfer.receiptDateHint')"
|
||||
data-testid="transfer-source-date-hint"
|
||||
>ⓘ</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- [ZONE 2] 选择辅助/上下文操作条:有选中时原位替换辅助区(批量操作惯例),未选中零死按钮。 -->
|
||||
<div v-if="selectedCount === 0" class="mb-3 flex flex-wrap items-center gap-2" data-testid="transfer-source-aids">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
@@ -145,58 +209,45 @@ function confirm() {
|
||||
>
|
||||
{{ $t('chat.transfer.selectRetryable') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-3 py-1.5 text-xs font-bold text-white hover:bg-brand-700 disabled:opacity-50"
|
||||
:disabled="batchRetryDisabled"
|
||||
data-testid="transfer-source-batch-retry"
|
||||
@click="batchRetry"
|
||||
>
|
||||
{{ $t('chat.transfer.batchRetry') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
|
||||
:disabled="busy || downloadDisabled"
|
||||
data-testid="transfer-source-download"
|
||||
@click="downloadSelected"
|
||||
>
|
||||
{{ $t('chat.transfer.downloadFiles') }}
|
||||
</button>
|
||||
<div class="ml-auto flex flex-wrap items-center gap-2">
|
||||
<label class="flex items-center gap-1 text-xs text-secondary">
|
||||
<span>{{ $t('chat.transfer.receiptDateFrom') }}</span>
|
||||
<input
|
||||
v-model="dateFrom"
|
||||
type="date"
|
||||
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
|
||||
data-testid="transfer-source-date-from"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex items-center gap-1 text-xs text-secondary">
|
||||
<span>~</span>
|
||||
<input
|
||||
v-model="dateTo"
|
||||
type="date"
|
||||
class="rounded-lg border border-default bg-surface px-2 py-1 text-xs text-primary"
|
||||
data-testid="transfer-source-date-to"
|
||||
/>
|
||||
</label>
|
||||
<span class="text-xs text-muted">{{ $t('chat.transfer.receiptDateHint') }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-source-clear"
|
||||
@click="clearSelected"
|
||||
>
|
||||
{{ $t('chat.transfer.clearSources') }}
|
||||
</button>
|
||||
<span class="ml-auto text-xs text-muted">
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="mb-3 flex flex-wrap items-center gap-2 rounded-lg border border-brand-200 bg-brand-50 px-3 py-2"
|
||||
data-testid="transfer-source-action-bar"
|
||||
>
|
||||
<span class="text-xs font-bold text-secondary">
|
||||
{{ $t('chat.transfer.selectedSourceCount', { count: selectedCount }) }}
|
||||
<span v-if="selectedRetryableCount > 0" class="text-amber-600"> · {{ $t('chat.transfer.selectedRetryableCount', { count: selectedRetryableCount }) }}</span>
|
||||
</span>
|
||||
<span class="ml-auto flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-brand-200 px-3 py-1.5 text-xs font-bold text-brand-700 hover:bg-brand-50 disabled:opacity-50"
|
||||
:disabled="batchRetryDisabled"
|
||||
data-testid="transfer-source-batch-retry"
|
||||
@click="batchRetry"
|
||||
>
|
||||
{{ $t('chat.transfer.batchRetry') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
|
||||
:disabled="busy || downloadDisabled"
|
||||
data-testid="transfer-source-download"
|
||||
@click="downloadSelected"
|
||||
>
|
||||
{{ $t('chat.transfer.downloadFiles') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft disabled:opacity-50"
|
||||
:disabled="busy"
|
||||
data-testid="transfer-source-clear"
|
||||
@click="clearSelected"
|
||||
>
|
||||
{{ $t('chat.transfer.clearSources') }}
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
|
||||
@@ -250,6 +301,13 @@ function confirm() {
|
||||
>
|
||||
{{ t('chat.transfer.fileFailed') }}
|
||||
</span>
|
||||
<span
|
||||
v-else-if="source.file_status === 'expired'"
|
||||
class="inline-flex items-center gap-1 rounded-full bg-orange-50 px-2 py-0.5 text-[10px] font-bold text-orange-700"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileExpired') }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex items-center gap-1 rounded-full bg-surface-strong px-2 py-0.5 text-[10px] font-bold text-muted"
|
||||
@@ -272,8 +330,7 @@ function confirm() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end gap-3 border-t border-subtle pt-3">
|
||||
<span class="text-xs text-muted">{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }}</span>
|
||||
<div class="flex items-center justify-end border-t border-subtle pt-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-4 py-1.5 text-sm font-bold text-white hover:bg-brand-700 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
|
||||
@@ -23,7 +23,7 @@ const summary = {
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '2400',
|
||||
estimated_erp_write_count: 2,
|
||||
estimated_external_write_count: 2,
|
||||
precheck_hash: 'sha256:x',
|
||||
};
|
||||
|
||||
@@ -110,7 +110,7 @@ describe('TransferResultCard', () => {
|
||||
run_no: 'RUN-1',
|
||||
status: 'partial_failed',
|
||||
result: {
|
||||
erp_documents: [{
|
||||
external_documents: [{
|
||||
document_no: 'TRF-10001',
|
||||
from_warehouse: 'DBS-TRANSIT',
|
||||
to_warehouse: 'HUB-CN01',
|
||||
|
||||
@@ -31,7 +31,7 @@ const summary = {
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 2, not_matured_count: 0, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '2400',
|
||||
estimated_erp_write_count: 2,
|
||||
estimated_external_write_count: 2,
|
||||
precheck_hash: 'sha256:abc',
|
||||
};
|
||||
|
||||
@@ -54,7 +54,7 @@ describe('useChatTransfer', () => {
|
||||
api.getTransferRun.mockResolvedValue({
|
||||
run_no: 'RUN-20260806-1',
|
||||
status: 'success',
|
||||
result: { erp_documents: [], exceptions: [] },
|
||||
result: { external_documents: [], exceptions: [] },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import type {
|
||||
TransferRunResult,
|
||||
TransferSourceOption,
|
||||
TransferSourceProgress,
|
||||
TransferType,
|
||||
} from '../types/transfer.types';
|
||||
|
||||
export function useChatTransfer() {
|
||||
@@ -59,11 +60,12 @@ export function useChatTransfer() {
|
||||
const selectedCount = computed(() => selected.value.size);
|
||||
const estimatedQuantity = computed(() => precheck.value?.estimated_transfer_quantity ?? '0');
|
||||
|
||||
/** 创建预检(缺文件时来源级阶段展示等待/失败) */
|
||||
/** 创建预检(缺文件时来源级阶段展示等待/失败);transferType 决定收料数据范围,缺省在途仓至HUB仓 */
|
||||
async function createPrecheck(
|
||||
sourceCodes: string[],
|
||||
businessDate?: string,
|
||||
dateRange?: { from?: string; to?: string },
|
||||
transferType?: TransferType,
|
||||
) {
|
||||
busy.value = true;
|
||||
error.value = '';
|
||||
@@ -73,6 +75,7 @@ export function useChatTransfer() {
|
||||
business_date: businessDate,
|
||||
receipt_date_from: dateRange?.from,
|
||||
receipt_date_to: dateRange?.to,
|
||||
transfer_type: transferType,
|
||||
});
|
||||
precheckId.value = summary.precheck_id;
|
||||
await refreshPrecheck();
|
||||
@@ -174,7 +177,7 @@ export function useChatTransfer() {
|
||||
async function downloadErpInventory() {
|
||||
if (!runNo.value) return null;
|
||||
const result = await downloadTransferErpInventory(runNo.value);
|
||||
saveBlob(result.blob, result.filename ?? `erp-inventory-${runNo.value}.csv`);
|
||||
saveBlob(result.blob, result.filename ?? `external-inventory-${runNo.value}.csv`);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ const detail: TransferPrecheckDetail = {
|
||||
expires_at: '',
|
||||
counts: { file_invoice_count: 3, not_matured_count: 1, prechecked_count: 2, executable_count: 2, blocked_count: 0 },
|
||||
estimated_transfer_quantity: '2400',
|
||||
estimated_erp_write_count: 2,
|
||||
estimated_external_write_count: 2,
|
||||
precheck_hash: 'sha256:abc',
|
||||
},
|
||||
sources: [{ source_code: 'DBS-AWSBI', stage: 'file_ready', file_no: 'REC-1', file_version: 'v3' }],
|
||||
@@ -49,7 +49,7 @@ const runResult = {
|
||||
run_no: 'RUN-20260806-001',
|
||||
status: 'success',
|
||||
result: {
|
||||
erp_documents: [{
|
||||
external_documents: [{
|
||||
document_no: 'TRF-10001',
|
||||
from_warehouse: 'DBS-TRANSIT',
|
||||
to_warehouse: 'HUB-CN01',
|
||||
@@ -85,7 +85,7 @@ describe('in-transit-transfer e2e contract', () => {
|
||||
transfer.toggleSelect('INV-002', false);
|
||||
await transfer.execute();
|
||||
expect(api.executeTransferPrecheck).toHaveBeenCalledWith('TPC-20260806-001', ['INV-001']);
|
||||
expect(transfer.run.value?.result.erp_documents[0].document_no).toBe('TRF-10001');
|
||||
expect(transfer.run.value?.result.external_documents[0].document_no).toBe('TRF-10001');
|
||||
});
|
||||
|
||||
it('刷新恢复:重建 composable 后按 run_no 恢复最终结果(决策 17)', async () => {
|
||||
@@ -93,7 +93,7 @@ describe('in-transit-transfer e2e contract', () => {
|
||||
transfer.runNo.value = 'RUN-20260806-001';
|
||||
await transfer.refreshRun();
|
||||
expect(transfer.run.value?.status).toBe('success');
|
||||
expect(transfer.run.value?.result.erp_documents[0].material_count).toBe(2);
|
||||
expect(transfer.run.value?.result.external_documents[0].material_count).toBe(2);
|
||||
});
|
||||
|
||||
it('下载:收料来源文件与 ERP 库存表(决策 21/22 前端入口)', async () => {
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
* 逻辑:卡片/组合式函数只消费这些稳定类型;状态与后端 13 状态集对齐。
|
||||
*/
|
||||
|
||||
/** 调拨业务类型(与后端 TransferType 枚举一致;类型 2/3 一期占位未开放) */
|
||||
export type TransferType = 'in_transit_to_hub' | 'hub_repair_out' | 'hub_to_hub';
|
||||
|
||||
/** 预检计数 */
|
||||
export interface TransferPrecheckCounts {
|
||||
file_invoice_count: number;
|
||||
@@ -30,7 +33,7 @@ export interface TransferPrecheckSummary {
|
||||
expires_at: string;
|
||||
counts: TransferPrecheckCounts;
|
||||
estimated_transfer_quantity: string;
|
||||
estimated_erp_write_count: number;
|
||||
estimated_external_write_count: number;
|
||||
precheck_hash: string;
|
||||
}
|
||||
|
||||
@@ -105,7 +108,7 @@ export interface TransferRunResult {
|
||||
run_no: string;
|
||||
status: string;
|
||||
result: {
|
||||
erp_documents: ErpDocument[];
|
||||
external_documents: ErpDocument[];
|
||||
exceptions: TransferExceptionItem[];
|
||||
};
|
||||
}
|
||||
@@ -157,8 +160,8 @@ export interface TransferSourceOption {
|
||||
display_name: string;
|
||||
platform: string;
|
||||
enabled: boolean;
|
||||
/** 收料文件状态:ready / fetching / failed / none(只读投影货代收料事实) */
|
||||
file_status?: 'ready' | 'fetching' | 'failed' | 'none';
|
||||
/** 收料文件状态:ready / fetching / failed / expired / none(只读投影货代收料事实) */
|
||||
file_status?: 'ready' | 'fetching' | 'failed' | 'expired' | 'none';
|
||||
/** 是否已有当前可用的收料文件(门禁:无 ready 文件禁止确认预检) */
|
||||
has_ready_file?: boolean;
|
||||
file_no?: string | null;
|
||||
@@ -168,7 +171,7 @@ export interface TransferSourceOption {
|
||||
/** 来源收料文件状态(门禁 + 状态标识 + 重试返回) */
|
||||
export interface TransferSourceFileStatus {
|
||||
source_code: string;
|
||||
file_status: 'ready' | 'fetching' | 'failed' | 'none';
|
||||
file_status: 'ready' | 'fetching' | 'failed' | 'expired' | 'none';
|
||||
has_ready_file: boolean;
|
||||
file_no?: string | null;
|
||||
file_sha256?: string | null;
|
||||
|
||||
Reference in new issue
Block a user