Merge branch 'hugo-auto-transfer' into dev
This commit is contained in:
commit
d95c4dc086
88 files changed
+5345
-406
No files matched your search
@@ -793,6 +793,32 @@ def retry_source_rpa_api(source_code: str):
|
||||
}, status=202)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/sources/retry-rpa-batch", methods=["POST"])
|
||||
@require_transfer_permission
|
||||
def retry_sources_rpa_batch_api():
|
||||
"""批量重试多来源收料 RPA:全部有效来源合并写**一个** batch trigger(一文件 N units)。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
逐来源调用单来源端点会产生 N 个 trigger 文件,Worker 每文件开/关一次浏览器;
|
||||
合并单文件后 Worker 单次登录串行导出全部来源(与收料排程路径同效率)。
|
||||
|
||||
请求体:{"source_codes": ["DSV360_AWSBI", ...]}。逐来源解析失败分层与
|
||||
fail-closed 语义同单来源端点;单源配置缺失跳过并记录,不阻断其余来源。
|
||||
"""
|
||||
payload = request.get_json(silent=True) or {}
|
||||
source_codes = [str(code).strip() for code in (payload.get("source_codes") or []) if str(code).strip()]
|
||||
if not source_codes:
|
||||
raise ValidationError("source_codes is required")
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa_batch
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=source_codes,
|
||||
business_date=str(business_date_now()),
|
||||
reason="transfer_retry_receipt",
|
||||
)
|
||||
return _ok(outcome)
|
||||
|
||||
|
||||
@in_transit_transfer_bp.route("/backlog", methods=["GET"])
|
||||
@require_transfer_permission
|
||||
def backlog_api():
|
||||
|
||||
@@ -104,6 +104,9 @@ class ShippingNoticeLineInventoryMatch(Base):
|
||||
required_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
shortage_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
|
||||
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
|
||||
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
unit: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
|
||||
@@ -97,7 +97,12 @@ def raise_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
)
|
||||
if 'invalid or expired casdoor state' in lowered_raw:
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s', context, data)
|
||||
# [STEP 2] 未识别错误必须保留原始异常堆栈,否则本地换票后的崩溃会被吞成一行 payload={}。
|
||||
current_app.logger.warning(
|
||||
'[casdoor] unmapped auth error context=%s payload=%s source=%r',
|
||||
context, data, source,
|
||||
exc_info=source if isinstance(source, BaseException) else None,
|
||||
)
|
||||
raise AppError(
|
||||
code='CASDOOR_AUTH_FAILED',
|
||||
message='Authentication failed, please try again',
|
||||
|
||||
@@ -32,6 +32,8 @@ class AutoTransferOutcome:
|
||||
def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
source_codes: list[str] | None = None,
|
||||
recover_history: bool = True,
|
||||
receipt_date_from: str | None = None,
|
||||
receipt_date_to: str | None = None,
|
||||
sender: WeComSender | None = None,
|
||||
recipients: list[str] | None = None) -> AutoTransferOutcome:
|
||||
"""执行一次自动调拨排程。
|
||||
@@ -44,6 +46,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
deps: 注入依赖。
|
||||
source_codes: 来源实例列表(缺省全部启用来源)。
|
||||
recover_history: 是否执行历史恢复。
|
||||
receipt_date_from / receipt_date_to: 可选收料日期范围(测试/排障缩小
|
||||
匹配面;留空=全部成熟积压;非法范围由匹配层抛 ValidationError)。
|
||||
sender / recipients: 企微通知(None 则跳过通知;run_no 为空时不发送)。
|
||||
Returns:
|
||||
AutoTransferOutcome;空数据日时 run_no/run_status 均为 None 且 errors 为空。
|
||||
@@ -59,6 +63,8 @@ def run_auto_transfer(*, business_date: str, deps: TransferDeps,
|
||||
source_codes=source_codes or [],
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
)
|
||||
# [STEP 2] 空数据日跳过执行:匹配后无可执行行(含恢复后仍为 0)时不建票、
|
||||
# 不写 ERP、不通知(产品决策 C5);该日仅留痕 Run/Matching,不视作失败。
|
||||
|
||||
@@ -112,17 +112,26 @@ class MatchingItemDTO:
|
||||
# 不参与匹配身份与 Hash 快照;空值行在匹配阶段落 blocked_missing_unit。
|
||||
unit: str = ""
|
||||
# 行装饰字段(restore 按 scope 实时视图时填齐;run_matching 快照路径保持缺省):
|
||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行评估时间(updated_at);
|
||||
# stale=评估时间距今超过确认 TTL;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||
# item_id=行主键(批量操作/待处理池回链);checked_at=行库存查得时刻(见 _item_dto);
|
||||
# stale=距库存取数超过展示阈值;file_current=行评估版本戳仍是该来源当前可用文件。
|
||||
item_id: int = 0
|
||||
checked_at: str | None = None
|
||||
stale: bool = False
|
||||
file_current: bool = False
|
||||
# [2026-10-12 单据数口径修正] 执行建单五元组首键:路由解析所得外部组织
|
||||
# (execution_service.prepare_execution 同款 .strip() 口径)。匹配评估路径填齐,
|
||||
# 供「预计 ERP 单据数」按五元组去重与前端勾选行预估;restore 视图路径缺省 ""。
|
||||
external_org: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MatchingSummaryDTO:
|
||||
"""匹配摘要(含预计调拨数量、预计 外部系统 写入数与匹配 Hash)。"""
|
||||
"""匹配摘要(含预计调拨数量、预计 ERP 单据数与匹配 Hash)。
|
||||
|
||||
estimated_external_write_count(2026-10-12 口径修正):可执行行按执行建单
|
||||
五元组 (external_org, source_code, receipt_date, from_warehouse, to_warehouse)
|
||||
去重后的单据数,非可执行行数——同组多行在执行期合并一张 ERP 单。
|
||||
"""
|
||||
|
||||
matching_id: str
|
||||
status: str
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any, Iterable, Mapping
|
||||
|
||||
from app.core.errors import AppError
|
||||
@@ -59,16 +59,26 @@ def _fail(rows: list[dict[str, Any]], *, row_no: Any, reason: str) -> None:
|
||||
rows.append({"row_no": row_no, "reason": reason})
|
||||
|
||||
|
||||
def _is_unreceived_row(date_value: Any) -> bool:
|
||||
"""判断是否为"无收料事实的在途行":无异动日期即跳过。
|
||||
def _is_unusable_receipt_row(date_value: Any, quantity_raw: Any) -> bool:
|
||||
"""判断是否为"非可用收料事实"的行:跳过,不参与匹配,也不阻断整文件。
|
||||
|
||||
WMS 异动报告会携带两类无日期行,均不是可用的收料事实:
|
||||
WMS 异动报告会携带三类非可用收料行,均不是可用的收料事实:
|
||||
① 未收料在途 ASN(Date Received 空、Qty Received 0);
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章)。
|
||||
收料日期是匹配身份与成熟过滤的必要字段,缺失即无法参与匹配;
|
||||
跳过后由下次排程抓取补齐(ASN 完成时盖章日期),不得整文件阻断。
|
||||
② 收料执行中(ASN Status=Executing,Qty Received 已计数但收料日期未盖章);
|
||||
③ 零数量收料行(Date Received 已盖章但 Qty Received = 0;2026-10-08 CRANE
|
||||
WTP26082227 实测——扫码收货数量记在他行/收货取消的占位行)。
|
||||
收料日期与正数量是行级匹配身份与成熟过滤的必要字段;此类行跳过后由下次排程
|
||||
抓取补齐(WMS 补数量/盖章后自然带出),不得整文件阻断。
|
||||
"""
|
||||
return not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip())
|
||||
if not (isinstance(date_value, (date, datetime)) or str(date_value or "").strip()):
|
||||
return True
|
||||
try:
|
||||
# 只跳过恰好为 0 的零收料行;负数属数据损坏,交由 validate_receipt_quantity 阻断。
|
||||
return Decimal(str(quantity_raw)) == 0
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
# 数量缺失/空:日期已盖章但无数量,同为零收料家族;非数字垃圾交由
|
||||
# validate_receipt_quantity 按非法数量阻断,不在此吞掉。
|
||||
return not str(quantity_raw or "").strip()
|
||||
|
||||
|
||||
def parse_movement_rows(*, source_code: str, rows: Iterable[Mapping[str, Any]]) -> list[ParsedReceiptRow]:
|
||||
@@ -174,7 +184,7 @@ def _parse_rows(
|
||||
if row_source and row_source.upper() != str(source_code).upper():
|
||||
_fail(errors, row_no=row_no, reason=f"source_identity_mismatch: {row_source}")
|
||||
continue
|
||||
if _is_unreceived_row(receipt_date_value):
|
||||
if _is_unusable_receipt_row(receipt_date_value, quantity_raw):
|
||||
continue
|
||||
try:
|
||||
receipt_date = parse_date(receipt_date_value)
|
||||
@@ -202,5 +212,8 @@ def _parse_rows(
|
||||
unit=str(row.get("unit") or "").strip(),
|
||||
))
|
||||
if errors:
|
||||
raise ReceiptFileSchemaError(rows=errors)
|
||||
# 诊断落库:消息携带前 3 条行级明细(行号+原因),随 parse_error_message
|
||||
# 落库自描述(2026-10-08 CRANE 零数量行事故:此前只有通用消息、无法定位)。
|
||||
summary = '; '.join(f"row {r.get('row_no')}: {r.get('reason')}" for r in errors[:3])
|
||||
raise ReceiptFileSchemaError(f"receipt file schema invalid: {summary}", rows=errors)
|
||||
return parsed
|
||||
@@ -389,6 +389,23 @@ def run_matching(
|
||||
estimated_quantity = sum(
|
||||
(item.to_quantity for item in items if item.result == RESULT_EXECUTABLE), Decimal("0")
|
||||
)
|
||||
# [2026-10-12 单据数口径修正] 预计 ERP 单据数 ≠ 可执行行数:执行建单按五元组
|
||||
# (external_org, source_code, receipt_date, from_warehouse, to_warehouse) 分组,
|
||||
# 同组多行合并一张 ERP 单(execution_service.prepare_execution 同键同 .strip()
|
||||
# 规范化)。本值 = 可执行行按同款五元组去重后的组数;行上 external_org 由
|
||||
# 匹配评估随路由解析填齐(_matching_rows 评估分支)。原「= executable_count」
|
||||
# 口径在多行同组时高估单据数,误导用户。
|
||||
estimated_document_keys = {
|
||||
(
|
||||
item.external_org,
|
||||
str(item.source_code or "").strip(),
|
||||
str(item.receipt_date or "").strip(),
|
||||
str(item.from_warehouse or "").strip(),
|
||||
str(item.to_warehouse or "").strip(),
|
||||
)
|
||||
for item in items
|
||||
if item.result == RESULT_EXECUTABLE
|
||||
}
|
||||
snapshot = {
|
||||
"scope": sorted(set(source_codes)),
|
||||
"business_date": business_date,
|
||||
@@ -433,7 +450,7 @@ def run_matching(
|
||||
expires_at="",
|
||||
counts=counts,
|
||||
estimated_transfer_quantity=str(estimated_quantity),
|
||||
estimated_external_write_count=counts.executable_count,
|
||||
estimated_external_write_count=len(estimated_document_keys),
|
||||
matching_hash=matching_hash,
|
||||
)
|
||||
return MatchingRunResult(summary=summary, items=tuple(items), sources=sources_tuple)
|
||||
@@ -621,8 +638,11 @@ def _matching_rows(
|
||||
row.result_code = match
|
||||
row.result_message = "strict quantity mismatch"
|
||||
row.updated_at = now
|
||||
# 本行已完成路由解析:external_org 随行透出(执行建单五元组首键,
|
||||
# 2026-10-12 单据数口径修正——预计单据数按五元组去重依赖本字段)。
|
||||
output.append(_item_dto(row, file_snapshot.get(row.source_code) or {}, now,
|
||||
int(deps.strategy.inventory_stale_ttl_seconds)))
|
||||
int(deps.strategy.inventory_stale_ttl_seconds),
|
||||
external_org=str(route.external_org or "").strip()))
|
||||
return output, pending_count
|
||||
|
||||
|
||||
@@ -944,6 +964,7 @@ def _item_dto(
|
||||
latest: dict,
|
||||
moment: datetime,
|
||||
inventory_stale_ttl_seconds: int,
|
||||
external_org: str = "",
|
||||
) -> MatchingItemDTO:
|
||||
"""把 InvoiceItem 装饰为前端行 DTO(restore 视图与可调拨明细队列共用)。
|
||||
|
||||
@@ -953,8 +974,10 @@ def _item_dto(
|
||||
moment: 新鲜度判定基准时间。
|
||||
inventory_stale_ttl_seconds: stale 展示阈值(strategy.inventory_stale_ttl_seconds;
|
||||
仅驱动 stale 徽标提示,不阻断执行——2026-09-25 TTL 门禁退役)。
|
||||
external_org: 路由解析所得外部组织(执行建单五元组首键,2026-10-12 单据数
|
||||
口径修正);仅匹配评估路径可填,restore 视图路径缺省 ""。
|
||||
Returns:
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current)。
|
||||
MatchingItemDTO(含 item_id / checked_at / stale / file_current / external_org)。
|
||||
"""
|
||||
evaluated_sha = _item_evaluated_sha(item)
|
||||
inventory_checked_at = item.inventory_checked_at
|
||||
@@ -1002,6 +1025,7 @@ def _item_dto(
|
||||
stale=bool(inventory_checked_at)
|
||||
and (moment - inventory_checked_at).total_seconds() > inventory_stale_ttl_seconds,
|
||||
file_current=bool(evaluated_sha) and evaluated_sha == latest.get("file_sha256"),
|
||||
external_org=external_org,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨真实收料 RPA 触发服务。
|
||||
|
||||
用途:为单个来源触发一次收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
||||
用途:为单个或多个来源触发收料/异动 RPA 抓取(复用货代收料 trigger 链路),不创建排程。
|
||||
按来源取 ShippingInventorySource + ShippingReceiptReportConfig + rpa_profile,
|
||||
先落 ShippingReceiptRpaUnitRun(awaiting_rpa,回调按 callback_id 查库可达),
|
||||
再装配收料 trigger unit 并调用 write_receipt_export_batch_trigger 原子写 trigger。
|
||||
@@ -8,11 +8,14 @@
|
||||
逻辑:list_receipt_capable_source_codes 供排程 source_codes 留空时的缺省范围;
|
||||
一源一单元,query_parameters 原样下发;来源停用/收料配置缺失/rpa_profile 缺失时
|
||||
fail-closed;写 trigger 失败把单元行标 failed 并 commit。
|
||||
trigger_receipt_rpa_batch(2026-10-09)把多来源合并为一个 batch trigger 文件:
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话,避免逐来源开/关浏览器。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
@@ -151,3 +154,117 @@ def trigger_receipt_rpa(
|
||||
unit.trigger_snapshot_json = unit_payload
|
||||
db.session.commit()
|
||||
return {"ok": True, "callback_id": unit_payload['callback_id'], "trigger_path": path}
|
||||
|
||||
|
||||
def trigger_receipt_rpa_batch(
|
||||
*,
|
||||
source_codes: list[str],
|
||||
business_date: str,
|
||||
reason: str = 'transfer_retry_receipt',
|
||||
writer: RouteTriggerWriter | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""批量触发多来源收料 RPA:全部有效来源合并写**一个** batch trigger 文件。
|
||||
|
||||
【AI 触发时机】聊天侧「批量重试 RPA」按钮提交多个来源编码时调用;
|
||||
行级单来源重试仍走 trigger_receipt_rpa(一源一文件语义不变)。
|
||||
|
||||
核心逻辑:逐来源装配 unit(来源级隔离——配置缺失/停用跳过并记录,不炸整批;
|
||||
parse_failed 先本地重解析,恢复 ready 则不触发 RPA),有效 units 先各落一行
|
||||
ShippingReceiptRpaUnitRun 再一次性 write_receipt_export_batch_trigger 原子落盘。
|
||||
Worker 对单文件按 profile 分组共享一次浏览器会话串行导出,避免逐来源开/关浏览器。
|
||||
|
||||
Args:
|
||||
source_codes: 来源实例编码列表(去重保序;空串自动剔除)。
|
||||
business_date: 业务日期。
|
||||
reason: 触发原因(写入 trigger payload)。
|
||||
writer: 触发写者;缺省复用 write_receipt_export_batch_trigger。
|
||||
|
||||
Returns:
|
||||
{"ok": True/False, "triggered": bool, "results": [...], "trigger_path"?/「error_code」?}。
|
||||
ok=本次请求产生了主效果(写盘成功,或无需写盘且全部来源经本地重解析恢复);
|
||||
triggered=是否写了 batch trigger;results 逐来源携带真实结果
|
||||
(触发:{source_code, ok: true};重解析:{..., reparsed: true, file_status};
|
||||
跳过:{source_code, ok: false, error_code, error_message})。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.services.in_transit_transfer.evidence_sync import sync_and_commit_for_callback
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
codes = list(dict.fromkeys(str(code).strip() for code in source_codes if str(code).strip()))
|
||||
results: list[dict[str, Any]] = []
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
unit_payloads: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] 解析失败分层(对齐单来源端点)+ 逐来源装配 unit;单源失败跳过不阻断整批。
|
||||
for code in codes:
|
||||
status = resolve_source_file_status(source_code=code)
|
||||
if status.get('file_status') == 'parse_failed' and status.get('file_sha256'):
|
||||
sync_and_commit_for_callback(
|
||||
source_code=code, business_date=business_date, now=datetime.utcnow(),
|
||||
)
|
||||
status = resolve_source_file_status(source_code=code)
|
||||
results.append({
|
||||
'source_code': code,
|
||||
'ok': status.get('file_status') == 'ready',
|
||||
'reparsed': True,
|
||||
'file_status': status.get('file_status'),
|
||||
})
|
||||
continue
|
||||
try:
|
||||
unit_payloads.append(_build_trigger_unit(source_code=code, business_date=business_date, reason=reason))
|
||||
except RuntimeError as exc:
|
||||
results.append({
|
||||
'source_code': code, 'ok': False,
|
||||
'error_code': 'RPA_RECEIPT_CONFIG_MISSING', 'error_message': str(exc),
|
||||
})
|
||||
|
||||
if not unit_payloads:
|
||||
# 无可触发来源:全部经重解析恢复 → 请求已达成目的;否则如实报无可用来源。
|
||||
reparse_recovered = any(item.get('reparsed') and item.get('ok') for item in results)
|
||||
db.session.commit()
|
||||
if reparse_recovered:
|
||||
return {"ok": True, "triggered": False, "results": results}
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_NO_TRIGGERABLE_SOURCE", "results": results}
|
||||
|
||||
# [STEP 2] 先落可审计单元行并 flush 取 id——回调入口按 callback_id 查库(与单来源同模式)。
|
||||
for payload in unit_payloads:
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
inventory_source_id=payload['inventory_source_id'],
|
||||
source_code=payload['source_code'],
|
||||
connector_type=payload['connector_type'],
|
||||
warehouse_id=payload.get('warehouse_id'),
|
||||
callback_id=payload['callback_id'],
|
||||
status='awaiting_rpa',
|
||||
config_snapshot_json=dict(payload['config_snapshot']),
|
||||
)
|
||||
db.session.add(unit)
|
||||
units.append(unit)
|
||||
db.session.flush()
|
||||
for unit, payload in zip(units, unit_payloads):
|
||||
payload['unit_run_id'] = unit.id
|
||||
|
||||
# [STEP 3] 一个 batch trigger 原子落盘;目录不可用则本批单元全部标 failed(不留永久 awaiting)。
|
||||
run_no = f"TRIG-BATCH-{uuid.uuid4().hex[:8].upper()}"
|
||||
writer_fn = writer or write_receipt_export_batch_trigger
|
||||
path = writer_fn(run_no, unit_payloads, payload={
|
||||
'schema_version': 'shipping_receipt_rpa.v1',
|
||||
'action': 'receipt_export_batch',
|
||||
'business_date': business_date,
|
||||
'reason': reason,
|
||||
'source_codes': [payload['source_code'] for payload in unit_payloads],
|
||||
})
|
||||
if not path:
|
||||
for unit in units:
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
unit.error_message = 'receipt trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return {"ok": False, "triggered": False, "error_code": "RPA_RECEIPT_TRIGGER_UNAVAILABLE", "results": results}
|
||||
|
||||
# [STEP 4] 冻结快照供审计;commit 必须先于返回——Worker 拿到文件即可能回调。
|
||||
for unit, payload in zip(units, unit_payloads):
|
||||
unit.trigger_snapshot_json = payload
|
||||
results.append({'source_code': unit.source_code, 'ok': True})
|
||||
db.session.commit()
|
||||
return {"ok": True, "triggered": True, "trigger_path": path, "results": results}
|
||||
@@ -81,6 +81,9 @@ def serialize_item(item) -> dict[str, Any]:
|
||||
"to_quantity": str(item.to_quantity),
|
||||
# 交易单位原值透传(movement 契约第 11 字段 unit,T7 交接:序列化缺口补齐)。
|
||||
"unit": item.unit,
|
||||
# [2026-10-12 单据数口径修正] 执行建单五元组首键透传:前端按勾选行
|
||||
# 预估 ERP 单据数与后端同口径分组(匹配评估路径填齐,历史回放缺省 "")。
|
||||
"external_org": item.external_org,
|
||||
"result": item.result,
|
||||
"reason": item.reason,
|
||||
"raw_lines": [
|
||||
|
||||
@@ -26,7 +26,10 @@ from app.services.in_transit_transfer.receipt_file_gate import (
|
||||
)
|
||||
|
||||
RUNNING_UNIT_STATUSES = ('queued', 'awaiting_rpa', 'processing')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'empty', 'cancelled')
|
||||
FAILED_UNIT_STATUSES = ('failed', 'cancelled')
|
||||
# 空数据(no_receipt_data):抓取成功但当日无收料记录,属业务结果而非故障,
|
||||
# 独立投影 no_data 供前端如实展示(2026-10-08:曾误并入 failed 致无法分辨真失败)。
|
||||
NO_DATA_UNIT_STATUSES = ('empty',)
|
||||
|
||||
|
||||
def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
@@ -37,7 +40,7 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
|
||||
Returns:
|
||||
{"file_status": ..., "has_ready_file": bool, "file_no": ..., "file_sha256": ...},
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'expired', 'none'};
|
||||
file_status ∈ {'ready', 'parse_failed', 'fetching', 'failed', 'no_data', 'expired', 'none'};
|
||||
parse_failed 表示文件仍可用但解析失败:has_ready_file=False,
|
||||
仍带 file_no/file_sha256 便于诊断与前端提示。
|
||||
"""
|
||||
@@ -84,6 +87,9 @@ def resolve_source_file_status(*, source_code: str) -> dict:
|
||||
.order_by(ShippingReceiptRpaUnitRun.id.desc())
|
||||
.first()
|
||||
)
|
||||
if latest_unit is not None and latest_unit.status in NO_DATA_UNIT_STATUSES:
|
||||
# 空数据:抓取成功但当日无收料记录——如实投影 no_data,不得与抓取失败混淆。
|
||||
return {'file_status': 'no_data', 'has_ready_file': False, 'file_no': None, 'file_sha256': None}
|
||||
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}
|
||||
|
||||
|
||||
@@ -344,8 +344,10 @@ def _register_headers_from_config() -> None:
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import register_inventory_rpa_excel_headers
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import register_receipt_rpa_excel_headers
|
||||
|
||||
register_inventory_rpa_excel_headers()
|
||||
register_receipt_rpa_excel_headers()
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
|
||||
@@ -9,16 +9,83 @@ backend/app/services/schedule/freight_receipt_rpa_finalize.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
from app.services.schedule import normalize_platform_api_path, register_schedule_header, resolve_schedule_header
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
_RECEIPT_RPA_HEADER_ORDER = [
|
||||
"source_code",
|
||||
"warehouse_id",
|
||||
"connector_type",
|
||||
"receipt_file_count",
|
||||
"export_status",
|
||||
"skip_reason",
|
||||
"error_message",
|
||||
]
|
||||
_RECEIPT_RPA_HEADER_LABELS = {
|
||||
"source_code": "收料源",
|
||||
"warehouse_id": "仓库",
|
||||
"connector_type": "连接器",
|
||||
"receipt_file_count": "归档文件数",
|
||||
"export_status": "导出状态",
|
||||
"skip_reason": "跳过原因",
|
||||
"error_message": "错误原因",
|
||||
}
|
||||
|
||||
|
||||
def register_receipt_rpa_excel_headers() -> None:
|
||||
"""
|
||||
注册货代收料 RPA 排程 Excel 列头(幂等)。
|
||||
核心逻辑:由 schedule.__init__._register_headers_from_config 在 reload 后调用,避免被 clear 冲掉。
|
||||
"""
|
||||
register_schedule_header(
|
||||
RECEIPT_RPA_JOB_KEY,
|
||||
_RECEIPT_RPA_HEADER_ORDER,
|
||||
_RECEIPT_RPA_HEADER_LABELS,
|
||||
)
|
||||
|
||||
|
||||
def _build_receipt_finalize_details(units: list[ShippingReceiptRpaUnitRun]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
收料单元 → 排程 Excel 明细行(对齐库存 finalize 的行结构)。
|
||||
|
||||
核心逻辑:empty 归一为 skipped、cancelled 归一为 failed,与卡片 计数口径一致;
|
||||
归档文件数便于与原始收料包内 {序号}_{source_code}.xlsx 条目对账。
|
||||
|
||||
Args:
|
||||
units: 该 run 的全部收料单元(已全部终态)。
|
||||
|
||||
Returns:
|
||||
list[dict]: 按 unit.id 升序的明细行。
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
for unit in sorted(units, key=lambda item: item.id):
|
||||
status = unit.status
|
||||
if status == 'empty':
|
||||
export_status = 'skipped'
|
||||
elif status == 'cancelled':
|
||||
export_status = 'failed'
|
||||
else:
|
||||
export_status = status
|
||||
rows.append({
|
||||
'source_code': unit.source_code,
|
||||
'warehouse_id': unit.warehouse_id or '',
|
||||
'connector_type': unit.connector_type or '',
|
||||
'receipt_file_count': len(unit.files or []),
|
||||
'export_status': export_status,
|
||||
'skip_reason': str(unit.error_code or '') if export_status == 'skipped' else '',
|
||||
'error_message': str(unit.error_message or '')[:500] if export_status == 'failed' else '',
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
|
||||
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
||||
@@ -213,6 +280,44 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
|
||||
# [STEP] 对齐库存 finalize:终态前生成收料汇总 Excel,企微在 textcard+ZIP 之外多发一条 [文件] 消息。
|
||||
register_receipt_rpa_excel_headers()
|
||||
header_order, header_labels = resolve_schedule_header(RECEIPT_RPA_JOB_KEY)
|
||||
excel_export_ok = True
|
||||
excel_data, excel_name, excel_size = None, None, 0
|
||||
try:
|
||||
excel_data, _excel_name, excel_size = export_schedule_result_excel(
|
||||
run_no=run.run_no,
|
||||
summary={
|
||||
'status': run.status,
|
||||
'total_count': len(units),
|
||||
'success_count': success_count,
|
||||
'skipped_count': skipped_count,
|
||||
'failed_count': failed_count,
|
||||
'duration_ms': run.duration_ms,
|
||||
},
|
||||
details=_build_receipt_finalize_details(units),
|
||||
header_order=header_order,
|
||||
header_labels=header_labels,
|
||||
)
|
||||
except Exception as excel_exc:
|
||||
excel_export_ok = False
|
||||
current_app.logger.error(
|
||||
'[schedule-run] receipt RPA excel export failed for run %s: %s', run.run_no, excel_exc,
|
||||
)
|
||||
# 对齐库存:全成功批次的 Excel 失败要降级,不得让收件人误以为一切正常。
|
||||
if run.status == 'success':
|
||||
run.status = 'partial_failed'
|
||||
run.error_message = '; '.join(filter(None, [run.error_message, f'Excel导出失败: {excel_exc}']))[:2000]
|
||||
else:
|
||||
# 企微/下载展示名:收料RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||
from app.services.schedule.shipping_receipt_rpa_archive import receipt_rpa_result_excel_name
|
||||
|
||||
excel_name = receipt_rpa_result_excel_name(run)
|
||||
run.excel_file_data = excel_data
|
||||
run.excel_file_name = excel_name if excel_data else None
|
||||
run.excel_file_size = excel_size or 0
|
||||
|
||||
# [STEP] 对齐库存:终态前预生成原始收料 ZIP,企微只发一个包。
|
||||
archive_summary = {
|
||||
'raw_receipt_zip_available': False,
|
||||
@@ -237,6 +342,8 @@ def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
'success_count': success_count,
|
||||
'empty_count': skipped_count,
|
||||
'failed_count': failed_count,
|
||||
'excel_export_status': 'ok' if excel_export_ok else 'failed',
|
||||
'excel_failed': not excel_export_ok,
|
||||
**archive_summary,
|
||||
}
|
||||
db.session.commit()
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
"""自动调拨排程。
|
||||
|
||||
用途:自动处理当日新成熟可调拨项与历史可恢复异常,并发送一次企微汇总通知。
|
||||
依赖:auto_transfer、transfer deps、wecom_sender、job_registry.ScheduleExecuteResult、
|
||||
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)。
|
||||
用途:自动处理当日新成熟可调拨项与历史可恢复异常;执行结果通知统一走
|
||||
排程「启用通知」通用企微通知,本任务不自建领域通知。
|
||||
依赖:auto_transfer、transfer deps、job_registry.ScheduleExecuteResult、
|
||||
receipt_trigger_service.list_receipt_capable_source_codes(缺省来源口径)、
|
||||
date_policy(业务日与日期解析)。
|
||||
逻辑:文件就绪保障内建于自动调拨匹配管道(就绪复用,缺失自动触发收料 RPA),
|
||||
不依赖其他排程成功;来源留空兜底为全部启用收料来源;有通知人时构造
|
||||
sender,仅在有 run_no 或空数据日(无 errors)后置 domain_notification_managed
|
||||
抑制框架卡;硬失败不置标记以便框架兜底。
|
||||
不依赖其他排程成功;来源留空兜底为全部启用收料来源;可选收料日期范围
|
||||
以「T−N 偏移天数」配置,执行时按当日业务日换算为具体日期透传匹配层;
|
||||
空数据日(无 run_no 且无 errors)置 domain_notification_managed 保持
|
||||
静默(C5),有 Run 或硬失败交由框架完成卡按排程「启用通知」发送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.in_transit_transfer import deps as transfer_deps
|
||||
from app.services.in_transit_transfer.auto_transfer import AutoTransferOutcome, run_auto_transfer
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now
|
||||
from app.services.in_transit_transfer.date_policy import business_date_now, parse_date
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import list_receipt_capable_source_codes
|
||||
from app.services.in_transit_transfer.wecom_sender import WecomSummarySender
|
||||
from app.services.schedule.job_registry import ScheduleExecuteResult
|
||||
|
||||
|
||||
@@ -45,41 +48,77 @@ def _wanted_source_codes(task: ScheduleTask) -> list[str]:
|
||||
return codes
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行 + 企微汇总通知。
|
||||
|
||||
核心逻辑:有通知人时构造 WecomSummarySender 传入 run_auto_transfer;
|
||||
仅在返回后按结果决定是否置 domain_notification_managed——有 run_no
|
||||
(成功/部分失败领域卡路径)或无 errors(空数据日 C5)时抑制框架卡;
|
||||
硬失败(无 run_no 且有 errors)不置标记,允许框架完成卡兜底。
|
||||
def _offset_to_date(business_date: str, offset_days: Any, label: str, errors: list[str]) -> str | None:
|
||||
"""把「T−N 偏移天数」参数换算为执行日口径的具体收料日期(T−N)。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/notify_user_ids)。
|
||||
run: 排程执行批次(领域自管通知时写入 response_summary_json 标记)。
|
||||
business_date: 业务日期 T(YYYY-MM-DD)。
|
||||
offset_days: 偏移天数(须为非负整数;None/空视为未配置)。
|
||||
label: 参数中文名(写错误信息用)。
|
||||
errors: 错误累积列表(非法配置写入后返回 None,由调用方快速失败)。
|
||||
Returns:
|
||||
'YYYY-MM-DD';未配置或非法时为 None(非法同时落错误)。
|
||||
"""
|
||||
if offset_days is None or offset_days == "":
|
||||
return None
|
||||
try:
|
||||
days = int(offset_days)
|
||||
except (TypeError, ValueError):
|
||||
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
|
||||
return None
|
||||
if days < 0 or float(offset_days) != days:
|
||||
errors.append(f"{label}须为非负整数(当前值 {offset_days!r})")
|
||||
return None
|
||||
return (parse_date(business_date) - timedelta(days=days)).isoformat()
|
||||
|
||||
|
||||
def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""自动调拨:恢复 + 匹配(严格相等)+ 执行;通知统一走排程「启用通知」。
|
||||
|
||||
核心逻辑:不自建领域汇总通知(任务级通知人参数已移除,收件人取排程表单
|
||||
底部「启用通知」配置);仅在空数据日(无 run_no 且无 errors)置
|
||||
domain_notification_managed 抑制框架完成卡(C5 空数据日静默);
|
||||
有 run_no(成功/部分失败)或硬失败时框架卡照常发送/兜底。
|
||||
可选收料日期范围以「T−N 偏移天数」配置(receipt_from/to_offset_days),
|
||||
执行时按当日业务日换算为具体日期透传匹配层,供测试/排障缩小本轮处理面;
|
||||
偏移非法(负数/小数/非数字)快速失败不执行;范围越界由匹配层
|
||||
ValidationError 落 errors 走硬失败路径。
|
||||
|
||||
Args:
|
||||
task: 排程任务(job_params: source_codes/recover_history/
|
||||
receipt_from_offset_days/receipt_to_offset_days)。
|
||||
run: 排程执行批次(空数据日写入 response_summary_json 标记)。
|
||||
Returns:
|
||||
ScheduleExecuteResult 七元组;空数据日 total=0 且不记 error(C5)。
|
||||
"""
|
||||
params = _task_params(task)
|
||||
source_codes = _wanted_source_codes(task)
|
||||
recover_history = bool(params.get("recover_history", True))
|
||||
recipients = [str(item).strip() for item in (params.get("notify_user_ids") or []) if str(item).strip()]
|
||||
business_date = str(business_date_now())
|
||||
|
||||
# 有通知人时构造 sender 传入领域层;是否抑制框架卡见下方按 outcome 判定。
|
||||
sender = WecomSummarySender() if recipients else None
|
||||
# [STEP] T−N 偏移换算:非法配置快速失败(不执行、交框架失败通知),
|
||||
# 防止坏参数被静默忽略后退化成全量积压处理。
|
||||
param_errors: list[str] = []
|
||||
receipt_date_from = _offset_to_date(
|
||||
business_date, params.get("receipt_from_offset_days"), "收料日期起点", param_errors)
|
||||
receipt_date_to = _offset_to_date(
|
||||
business_date, params.get("receipt_to_offset_days"), "收料日期终点", param_errors)
|
||||
if param_errors:
|
||||
return (0, 0, 0, 0, [], [f"sources={len(source_codes)}"], param_errors)
|
||||
|
||||
deps = transfer_deps.get_transfer_dependencies()
|
||||
outcome = run_auto_transfer(
|
||||
business_date=str(business_date_now()),
|
||||
business_date=business_date,
|
||||
deps=deps,
|
||||
source_codes=source_codes,
|
||||
recover_history=recover_history,
|
||||
sender=sender,
|
||||
recipients=recipients,
|
||||
receipt_date_from=receipt_date_from,
|
||||
receipt_date_to=receipt_date_to,
|
||||
)
|
||||
|
||||
# [STEP] 领域自管通知门禁:仅在领域卡已发出(有 run_no)或空数据日
|
||||
# (无 errors,C5 静默)时置标记;硬失败让框架完成卡兜底。
|
||||
if recipients and (outcome.run_no or not outcome.errors):
|
||||
# [STEP] 空数据日静默门禁:无 run 且无错误(匹配后无可执行行,C5)时置
|
||||
# 标记抑制框架完成卡;有 run 或硬失败时框架卡照常通知/兜底。
|
||||
if not outcome.run_no and not outcome.errors:
|
||||
run.response_summary_json = {
|
||||
**(run.response_summary_json or {}),
|
||||
"domain_notification_managed": True,
|
||||
@@ -94,7 +133,6 @@ def run_in_transit_transfer_schedule(task: ScheduleTask, run: ScheduleRun) -> Sc
|
||||
results.append({
|
||||
"run_no": outcome.run_no,
|
||||
"status": outcome.run_status,
|
||||
"notification_status": outcome.notification_status,
|
||||
})
|
||||
elif not outcome.errors:
|
||||
# 空数据日:匹配后无可执行行,执行与通知按 C5 跳过,不记失败。
|
||||
|
||||
@@ -584,10 +584,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
label="在途自动调拨",
|
||||
handler=run_in_transit_transfer_schedule,
|
||||
description=(
|
||||
"自动处理可调拨项与历史可恢复异常:调拨前确保各来源当日收料文件就绪"
|
||||
"(就绪复用,缺失自动触发收料 RPA),数量严格相等匹配后自动生成 ERP 调拨单;"
|
||||
"每非空 Run 发送一条企微汇总通知,通知失败不改变 ERP 结果。"
|
||||
"执行时间由排程配置决定,建议配置在业务期望的调拨时点之前。"
|
||||
"自动匹配可调拨项并生成 ERP 调拨单,含历史可恢复异常复核;"
|
||||
"缺收料文件时自动触发收料 RPA。执行时间建议配置在期望调拨时点之前。"
|
||||
),
|
||||
category="platform",
|
||||
params_schema=(
|
||||
@@ -609,16 +607,23 @@ def _register_builtin_platform_jobs() -> None:
|
||||
"default": True,
|
||||
},
|
||||
{
|
||||
"key": "notify_user_ids",
|
||||
"type": "multi_select",
|
||||
"label": "通知人",
|
||||
"label_key": "admin.schedule.form.transferNotifyUsers",
|
||||
"key": "receipt_from_offset_days",
|
||||
"type": "number",
|
||||
"label": "收料日期起(T-N)",
|
||||
"label_key": "admin.schedule.form.transferReceiptDateFrom",
|
||||
"required": False,
|
||||
"default": [],
|
||||
"options_source": "users",
|
||||
"help": "填天数 N,按执行日换算收料日期下限 T−N;例:4=从 T−4 起。留空=全部成熟积压(默认 ≤ T-2)。",
|
||||
},
|
||||
{
|
||||
"key": "receipt_to_offset_days",
|
||||
"type": "number",
|
||||
"label": "收料日期止(T-N)",
|
||||
"label_key": "admin.schedule.form.transferReceiptDateTo",
|
||||
"required": False,
|
||||
"help": "填天数 N,按执行日换算收料日期上限 T−N;例:起4止2=只处理 T−4~T−2。不得晚于成熟上限(默认 T-2)。",
|
||||
},
|
||||
),
|
||||
defaults={"source_codes": [], "recover_history": True, "notify_user_ids": []},
|
||||
defaults={"source_codes": [], "recover_history": True},
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -110,6 +110,11 @@ def receipt_raw_zip_download_name(run: ScheduleRun) -> str:
|
||||
return f'{receipt_rpa_attachment_stem(run)}-收料.zip'
|
||||
|
||||
|
||||
def receipt_rpa_result_excel_name(run: ScheduleRun) -> str:
|
||||
"""收料 RPA 结果 Excel 的企微/下载展示名(对齐库存 inventory_rpa_result_excel_name)。"""
|
||||
return f'{receipt_rpa_attachment_stem(run)}-结果.xlsx'
|
||||
|
||||
|
||||
def _receipt_raw_zip_archive_path(run_no: str) -> Path:
|
||||
"""磁盘归档路径:<archive_dir>/<run_no>.zip。"""
|
||||
return Path(get_receipt_archive_dir()) / f'{run_no}.zip'
|
||||
|
||||
@@ -1277,6 +1277,14 @@ def match_inventory_line(payload: dict[str, Any], *, line_no: int) -> dict[str,
|
||||
)
|
||||
# 行级匹配只持久化当前 LineMatch;OT 不再保存库存匹配聚合列或行结果缓存。
|
||||
_merge_line_inventory_resolutions(task, match_payload, snapshot_line_id=int(snapshot.lines[orig_idx].id) if snapshot is not None and orig_idx < len(snapshot.lines) else None)
|
||||
# [BE-料号兜底自动放行] 行事实落库后、聚合重算【前】执行(与 match_inventory 同款钩子):
|
||||
# 料号总量满足需求的缺口行由系统自动放行,使下方聚合重算把放行行计入满足、
|
||||
# 行级重匹配可直接落 MATCHED_FULFILLABLE;重入安全性说明见 match_inventory 钩子注释。
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
auto_release_part_fallback_shortages(task)
|
||||
|
||||
line_results = list(match_payload.get('line_results') or [])
|
||||
from app.services.shipping_notice.reservation_service import record_inventory_verification
|
||||
@@ -1778,6 +1786,17 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
inventory_snapshot_id=active_inventory_file_for_task(task).id if active_inventory_file_for_task(task) else None,
|
||||
matching_rule_version='stp_line_v2',
|
||||
)
|
||||
# [BE-料号兜底自动放行] 行事实落库后、聚合与 match_completed 判定【前】执行:
|
||||
# 料号总量满足需求的缺口行由系统自动放行(满足即放行,非仅可放行),使随后的
|
||||
# 聚合重算与满足性判定把放行行计入满足、任务可直接落 MATCHED_FULFILLABLE。
|
||||
# 重入安全:匹配跑在 AutoProgress Gate 执行器事务内时,submit_auto_progress 按
|
||||
# 「任务唯一活动 Job + 活动 Attempt 复用」幂等,不会重复入队或自触发;auto fulfill
|
||||
# Job 重复入队由协调器 eligible+幂等键吸收(与既有匹配路径的多入队行为一致)。
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
auto_release_part_fallback_shortages(task)
|
||||
# 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
|
||||
# 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
|
||||
match_status, shortages = _recompute_task_match_aggregate(task)
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_persistence.py
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
|
||||
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
|
||||
新快照新增行并切换 is_current;不覆盖历史快照事实。
|
||||
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
|
||||
供后续投影层与自动放行服务读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -277,6 +279,12 @@ def persist_line_inventory_match_facts(
|
||||
required_qty=str(required) if required is not None else None,
|
||||
available_qty=str(available) if available is not None else None,
|
||||
shortage_qty=str(shortage) if shortage is not None else None,
|
||||
# 料号兜底总量(Task 1 匹配器下发):字符串化落列;无键/None → NULL,
|
||||
# BE-5 / not_found 分支不篡改,直接取匹配器原值。
|
||||
part_available_qty=(
|
||||
str(result['part_available_qty'])
|
||||
if result.get('part_available_qty') is not None else None
|
||||
),
|
||||
reservation_id=rsv,
|
||||
part_number=pn,
|
||||
unit=unit_value,
|
||||
@@ -342,6 +350,11 @@ def persist_line_inventory_match_facts(
|
||||
existing.required_qty = str(required) if required is not None else None
|
||||
existing.available_qty = str(available) if available is not None else None
|
||||
existing.shortage_qty = str(shortage) if shortage is not None else None
|
||||
# 更新分支同样以最新匹配结果刷新兜底总量;键缺失 → NULL,不残留旧值。
|
||||
existing.part_available_qty = (
|
||||
str(result['part_available_qty'])
|
||||
if result.get('part_available_qty') is not None else None
|
||||
)
|
||||
existing.reservation_id = rsv
|
||||
existing.part_number = pn
|
||||
existing.unit = unit_value
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/line_inventory_match_projection.py
|
||||
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
|
||||
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
|
||||
ready+not_found→available=0;result_missing 不得转 0;
|
||||
part_available_qty(料号兜底总量)仅 inventory_status==ready 时透出,否则 None,
|
||||
不派生「可兜底放行」布尔(自动放行判定在 Task 7 服务内基于行事实现算);
|
||||
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
|
||||
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
|
||||
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
|
||||
@@ -562,6 +564,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
|
||||
'required_qty': row.required_qty,
|
||||
'available_qty': row.available_qty,
|
||||
'shortage_qty': row.shortage_qty,
|
||||
'part_available_qty': getattr(row, 'part_available_qty', None),
|
||||
'reservation_id': row.reservation_id,
|
||||
'part_number': row.part_number,
|
||||
'unit': row.unit,
|
||||
@@ -661,6 +664,7 @@ def project_line_inventory_view(
|
||||
'inventory_status': None,
|
||||
'match_result': None,
|
||||
'available_qty': None,
|
||||
'part_available_qty': None,
|
||||
'shortage_qty': None,
|
||||
'is_shortage': False,
|
||||
'display_available': 'pending',
|
||||
@@ -699,6 +703,12 @@ def project_line_inventory_view(
|
||||
required_qty=required_qty if required_qty is not None else fact.get('required_qty'),
|
||||
available_qty=fact.get('available_qty'),
|
||||
)
|
||||
# [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控);
|
||||
# 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。
|
||||
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||
part_available_value = (
|
||||
str(part_total) if inventory_status == STATUS_READY and part_total is not None else None
|
||||
)
|
||||
user_status = project_user_line_status(
|
||||
inventory_status=inventory_status,
|
||||
match_result=match_result,
|
||||
@@ -770,6 +780,7 @@ def project_line_inventory_view(
|
||||
'inventory_status': inventory_status,
|
||||
'match_result': match_result,
|
||||
'available_qty': qty['available_qty'],
|
||||
'part_available_qty': part_available_value,
|
||||
'shortage_qty': qty['shortage_qty'],
|
||||
'is_shortage': bool(qty['is_shortage']),
|
||||
'display_available': qty['display_available'],
|
||||
|
||||
+408
-90
@@ -30,6 +30,9 @@ from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
resolve_review_case_for_task,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
assert_case_is_current_workflow_version,
|
||||
)
|
||||
@@ -317,8 +320,14 @@ def _shortage_release_required_fields(
|
||||
line_index: int | None,
|
||||
inventory_snapshot_id: int | None,
|
||||
inventory_source_code: str | None,
|
||||
) -> list[dict[str, str]]:
|
||||
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。"""
|
||||
) -> tuple[list[dict[str, Any]], str]:
|
||||
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。
|
||||
|
||||
Returns:
|
||||
(fields, evidence_scope) 元组:fields 为模板库存字段投影(快照唯一值只读,
|
||||
其余 requires_manual);evidence_scope ∈ {'inventory_snapshot', 'part_fallback'},
|
||||
'part_fallback' 表示预约键在库存快照 0 行命中、已按料号键重筛带出(审计口径)。
|
||||
"""
|
||||
if line_index is None:
|
||||
raise ConflictError(
|
||||
'Current line inventory evidence is unavailable',
|
||||
@@ -371,7 +380,8 @@ def _shortage_release_required_fields(
|
||||
and str(item.get('source_key') or '').strip().isdigit()
|
||||
}
|
||||
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
|
||||
# 无快照即无库存证据:全部模板库存字段人工补录,证据范围维持快照口径。
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels), 'inventory_snapshot'
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
|
||||
expected = [
|
||||
@@ -395,6 +405,24 @@ def _shortage_release_required_fields(
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
]
|
||||
evidence_scope = 'inventory_snapshot'
|
||||
if not candidates:
|
||||
# [STEP] 料号兜底(2026-10 需求):预约键在库存快照 0 行命中时,按料号键重筛证据行,
|
||||
# 能唯一取值的字段不再要求人工手填。仅识别 field_code='part_number' 的匹配键;
|
||||
# 匹配方案不含料号键则维持空候选(全人工补录,fail-closed)。
|
||||
part_field_ids = {
|
||||
int(field_id) for field_id, _value in expected
|
||||
if str(field_id).strip().isdigit()
|
||||
and str(getattr(db.session.get(ShippingInventoryField, int(field_id)), 'field_code', '') or '') == 'part_number'
|
||||
}
|
||||
if part_field_ids:
|
||||
candidates = [
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(str(field_id))) == value
|
||||
for field_id, value in expected if int(field_id) in part_field_ids)
|
||||
]
|
||||
if candidates:
|
||||
evidence_scope = 'part_fallback'
|
||||
field_ids = {
|
||||
int(str(item.get('source_key') or '').strip())
|
||||
for item in mappings
|
||||
@@ -411,7 +439,7 @@ def _shortage_release_required_fields(
|
||||
mappings=mappings,
|
||||
candidates=candidates,
|
||||
field_labels=labels,
|
||||
)
|
||||
), evidence_scope
|
||||
|
||||
|
||||
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
|
||||
@@ -429,7 +457,7 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
|
||||
def _sync_confirmed_task_fulfillment_gates(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
actor_id: int,
|
||||
actor_id: int | None,
|
||||
trigger: str = 'inventory_shortage_released',
|
||||
) -> None:
|
||||
"""
|
||||
@@ -924,7 +952,8 @@ def project_review_case_line_decisions(
|
||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||
if release_line_index is None:
|
||||
release_line_index = draft_line.get('_line_index')
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
# scope 仅在 decide 落库时写入审计快照;投影契约本期不新增字段。
|
||||
release_template_fields, _evidence_scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=release_snapshot_id,
|
||||
@@ -1076,6 +1105,185 @@ def build_inventory_issue_fallback(
|
||||
}
|
||||
|
||||
|
||||
def _apply_shortage_line_release(
|
||||
task: ShippingNotice,
|
||||
line_index: int,
|
||||
release_field_values: dict[str, Any],
|
||||
*,
|
||||
evidence_scope: str | None = None,
|
||||
actor_type: str = 'user',
|
||||
actor_id: int | None = None,
|
||||
auto_release: bool = False,
|
||||
case: ShippingOrderReviewCase | None = None,
|
||||
reason: str | None = None,
|
||||
) -> ShippingOrderReviewLineDecision:
|
||||
"""
|
||||
人工 decide 与缺口自动放行共用的短缺放行执行体:解析证据字段、校验补录、
|
||||
版本化落库、同步正式 OT 门禁并写审计。
|
||||
|
||||
核心逻辑:从 decide_review_line_fulfillment 放行分支原样提取(行为不变)。
|
||||
证据字段按行事实快照解析(预约键命中 → inventory_snapshot;预约键 0 行命中
|
||||
按料号键重筛 → part_fallback);落库快照 release_field_values 为「自动带出 +
|
||||
人工补录」全量字段值字典(导出覆盖唯一来源);落库后立即重算任务履约态并
|
||||
同步门禁/自动履约入队,与人工放行完全一致。终态/已决定行必须由调用方先跳过,
|
||||
本执行体不重复校验放行资格。
|
||||
|
||||
Args:
|
||||
task: 正式 OT 聚合根(含 order_snapshot_id;自动放行来自匹配钩子,
|
||||
人工 decide 来自 case.confirmed_task_id)。
|
||||
line_index: 目标行号(0-based,与行匹配事实 line_index 同口径)。
|
||||
release_field_values: 人工补录值(decide)或自动带出全量值(自动放行);
|
||||
校验后与模板字段合并为全量值字典落库。
|
||||
evidence_scope: 调用方已解析的证据范围;None 时按行事实重新解析
|
||||
(人工 decide 路径,由本执行体统一解析避免双重查询语义分叉)。
|
||||
actor_type: 决定来源('user' 人工 / 'system' 自动放行),写入 decision_source。
|
||||
actor_id: 操作人(人工为操作用户;自动为触发匹配的用户,可为 None)。
|
||||
auto_release: True 时在决定与审计快照标记 auto_release(系统自动放行溯源)。
|
||||
case: 可选;人工 decide 已加载的可写 Case。缺省时按 confirmed_task_id 反查。
|
||||
reason: 可选人工放行原因;自动放行为 None。
|
||||
|
||||
Returns:
|
||||
新建的 ShippingOrderReviewLineDecision(已 flush、含主键)。
|
||||
|
||||
Raises:
|
||||
ConflictError: Case/草稿行缺失、证据不可解析或人工必填字段缺失。
|
||||
"""
|
||||
release_case = case if case is not None else resolve_review_case_for_task(task)
|
||||
if release_case is None or getattr(release_case, 'id', None) is None:
|
||||
raise ConflictError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
draft_line_by_index = {
|
||||
int(row.get('_line_index')): (key, row)
|
||||
for key, row in _draft_line_map(release_case).items()
|
||||
if row.get('_line_index') is not None
|
||||
}
|
||||
pair = draft_line_by_index.get(int(line_index))
|
||||
if pair is None:
|
||||
raise ConflictError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
key, draft_line = pair
|
||||
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_index=int(line_index), is_current=True)
|
||||
.first()
|
||||
if getattr(task, 'id', None) is not None else None
|
||||
)
|
||||
release_line_index = getattr(fact, 'line_index', None) if fact is not None else int(line_index)
|
||||
release_template_fields, resolved_scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
||||
)
|
||||
release_evidence_scope = str(evidence_scope or resolved_scope or 'inventory_snapshot')
|
||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||
release_values = _validate_inventory_shortage_release_fields(
|
||||
required_fields=release_required_fields,
|
||||
supplied_values=release_field_values or {},
|
||||
)
|
||||
# [STEP] 落库为「自动带出 + 人工补录」全量模板字段值字典:人工提交值覆盖自动带出值
|
||||
# (校验白名单仅用于必填校验,不再裁剪落库字典)。export.release_overrides_by_source_line
|
||||
# 只读本字典——若仍落仅人工项,料号兜底/预约命中自动带出的字段在 Excel 证据列将为空。
|
||||
manual_field_ids = {str(field.get('field_id') or '') for field in release_required_fields}
|
||||
release_values = {
|
||||
str(field.get('field_id') or ''): (
|
||||
release_values[str(field.get('field_id') or '')]
|
||||
if str(field.get('field_id') or '') in manual_field_ids
|
||||
else (None if field.get('value') is None else str(field.get('value')))
|
||||
)
|
||||
for field in release_template_fields
|
||||
}
|
||||
|
||||
projections = _line_projection_map(release_case)
|
||||
proj = projections.get(key) or {}
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
schema_fields_from_case,
|
||||
)
|
||||
|
||||
schema_fields = schema_fields_from_case(release_case)
|
||||
req_qty = _parse_qty(_line_required_qty(draft_line, proj, schema_fields=schema_fields))
|
||||
avail_qty = _parse_qty(proj.get('available_qty'))
|
||||
|
||||
current = _active_decision(release_case, key)
|
||||
# [STEP 1] 停用旧活动决定(放行资格与终态校验由调用方完成)。
|
||||
if current is not None:
|
||||
current.is_active = False
|
||||
current.updated_at = datetime.utcnow()
|
||||
|
||||
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(release_case.id),
|
||||
draft_line_id=key,
|
||||
line_index=draft_line.get('_line_index'),
|
||||
decision_version=_next_version(release_case, key),
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
decision_source=actor_type,
|
||||
line_status=status,
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
required_qty=str(req_qty) if req_qty is not None else None,
|
||||
available_qty=str(avail_qty) if avail_qty is not None else (
|
||||
str(proj.get('available_qty') or '').strip() or None
|
||||
),
|
||||
reservation_id=_line_reservation_id(draft_line, proj),
|
||||
part_number=_line_part_number(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
actor_user_id=int(actor_id) if actor_id is not None else None,
|
||||
snapshot_json={
|
||||
'decision_code': DECISION_RELEASE_SHORTAGE,
|
||||
'decision_source': actor_type,
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'draft_line_id': key,
|
||||
'release_field_values': release_values,
|
||||
'release_required_fields': release_required_fields,
|
||||
# 审计口径:放行证据来自预约匹配快照(inventory_snapshot)还是料号兜底重筛(part_fallback)。
|
||||
'release_evidence_scope': release_evidence_scope,
|
||||
**({'auto_release': True} if auto_release else {}),
|
||||
},
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
# [BE-结案-豁免] 放行是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=release_case,
|
||||
actor_id=actor_id,
|
||||
trigger='inventory_shortage_released',
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='review_line_fulfillment_decided',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(release_case.case_no),
|
||||
action=DECISION_RELEASE_SHORTAGE,
|
||||
actor_type=actor_type,
|
||||
actor_id=int(actor_id) if actor_id is not None else None,
|
||||
review_case_no=str(release_case.case_no),
|
||||
run_no=str(release_case.run.run_no) if release_case.run is not None else None,
|
||||
metadata={
|
||||
'draft_line_id': key,
|
||||
'decision_code': DECISION_RELEASE_SHORTAGE,
|
||||
'decision_version': int(row.decision_version),
|
||||
'line_status': status,
|
||||
'release_field_count': len(release_values),
|
||||
**({'auto_release': True} if auto_release else {}),
|
||||
},
|
||||
before=_serialize_decision(current) if current is not None else None,
|
||||
after=_serialize_decision(row),
|
||||
source='order_review_fulfillment_decision',
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def decide_review_line_fulfillment(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -1100,7 +1308,9 @@ def decide_review_line_fulfillment(
|
||||
draft_line_id: 草稿行键。
|
||||
decision_code: 决定码。
|
||||
reason: 关闭/重开必填原因;短缺放行可选(人工放行事实由审计链记录)。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值;落库快照
|
||||
release_field_values 为「自动带出 + 人工补录」全量字段值字典(导出覆盖唯一来源),
|
||||
release_evidence_scope 记录证据范围(inventory_snapshot / part_fallback)。
|
||||
expected_draft_version: 可选草稿乐观锁。
|
||||
actor_is_admin: 是否管理员(重开授权)。
|
||||
|
||||
@@ -1200,93 +1410,94 @@ def decide_review_line_fulfillment(
|
||||
details={'draft_line_id': key},
|
||||
)
|
||||
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
|
||||
) if task is not None else []
|
||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||
release_values = _validate_inventory_shortage_release_fields(
|
||||
required_fields=release_required_fields,
|
||||
supplied_values=release_field_values or {},
|
||||
)
|
||||
else:
|
||||
release_required_fields = []
|
||||
release_values = {}
|
||||
|
||||
# [STEP 1] 停用旧活动决定
|
||||
if current is not None:
|
||||
current.is_active = False
|
||||
current.updated_at = datetime.utcnow()
|
||||
|
||||
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
draft_line_id=key,
|
||||
line_index=draft_line.get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
decision_code=code,
|
||||
decision_source='user',
|
||||
line_status=status,
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
required_qty=str(req_qty) if req_qty is not None else None,
|
||||
available_qty=str(avail_qty) if avail_qty is not None else (
|
||||
str(proj.get('available_qty') or '').strip() or None
|
||||
),
|
||||
reservation_id=_line_reservation_id(draft_line, proj),
|
||||
part_number=_line_part_number(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
actor_user_id=int(user_id),
|
||||
snapshot_json={
|
||||
'decision_code': code,
|
||||
'decision_source': 'user',
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'draft_line_id': key,
|
||||
'release_field_values': release_values,
|
||||
'release_required_fields': release_required_fields,
|
||||
},
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code in {DECISION_RELEASE_SHORTAGE, DECISION_CLOSE}:
|
||||
# [BE-结案-豁免] 结案与放行同为库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=case,
|
||||
# [STEP] 短缺放行统一走共享执行体:证据字段解析、全量字段落库、停用旧决定、
|
||||
# 门禁同步与审计均在 _apply_shortage_line_release 内完成(人工与系统自动放行
|
||||
# 同一条链路,行为不变)。无 task 时上方放行资格校验已拒绝(无事实且无 RPA
|
||||
# 终态失败豁免),不会到达此处。
|
||||
row = _apply_shortage_line_release(
|
||||
task,
|
||||
release_line_index,
|
||||
release_field_values or {},
|
||||
actor_type='user',
|
||||
actor_id=int(user_id),
|
||||
trigger='inventory_shortage_released' if code == DECISION_RELEASE_SHORTAGE else 'line_fulfillment_closed',
|
||||
case=case,
|
||||
reason=reason,
|
||||
)
|
||||
status = _STATUS_BY_DECISION[DECISION_RELEASE_SHORTAGE]
|
||||
else:
|
||||
# [STEP 1] 停用旧活动决定
|
||||
if current is not None:
|
||||
current.is_active = False
|
||||
current.updated_at = datetime.utcnow()
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
|
||||
row = ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
draft_line_id=key,
|
||||
line_index=draft_line.get('_line_index'),
|
||||
decision_version=_next_version(case, key),
|
||||
decision_code=code,
|
||||
decision_source='user',
|
||||
line_status=status,
|
||||
is_active=True,
|
||||
reason=str(reason or '').strip()[:2000] or None,
|
||||
required_qty=str(req_qty) if req_qty is not None else None,
|
||||
available_qty=str(avail_qty) if avail_qty is not None else (
|
||||
str(proj.get('available_qty') or '').strip() or None
|
||||
),
|
||||
reservation_id=_line_reservation_id(draft_line, proj),
|
||||
part_number=_line_part_number(
|
||||
draft_line,
|
||||
proj,
|
||||
schema_fields=schema_fields,
|
||||
),
|
||||
actor_user_id=int(user_id),
|
||||
snapshot_json={
|
||||
'decision_code': code,
|
||||
'decision_source': 'user',
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'draft_line_id': key,
|
||||
'release_field_values': {},
|
||||
'release_required_fields': [],
|
||||
'release_evidence_scope': None,
|
||||
},
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code == DECISION_CLOSE:
|
||||
# [BE-结案-豁免] 结案是库存充分性 Gate 的受控事实:决定落库后立即重算并触发编排。
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=case,
|
||||
actor_id=int(user_id),
|
||||
trigger='line_fulfillment_closed',
|
||||
)
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action=code,
|
||||
actor_type='user',
|
||||
actor_id=int(user_id),
|
||||
review_case_no=str(case.case_no),
|
||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||
metadata={
|
||||
'draft_line_id': key,
|
||||
'decision_code': code,
|
||||
'decision_version': int(row.decision_version),
|
||||
'line_status': status,
|
||||
'release_field_count': len(release_values),
|
||||
},
|
||||
before=_serialize_decision(current) if current is not None else None,
|
||||
after=_serialize_decision(row),
|
||||
source='order_review_fulfillment_decision',
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='review_line_fulfillment_reopened' if code == DECISION_REOPEN else 'review_line_fulfillment_decided',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=str(case.case_no),
|
||||
action=code,
|
||||
actor_type='user',
|
||||
actor_id=int(user_id),
|
||||
review_case_no=str(case.case_no),
|
||||
run_no=str(case.run.run_no) if case.run is not None else None,
|
||||
metadata={
|
||||
'draft_line_id': key,
|
||||
'decision_code': code,
|
||||
'decision_version': int(row.decision_version),
|
||||
'line_status': status,
|
||||
'release_field_count': 0,
|
||||
},
|
||||
before=_serialize_decision(current) if current is not None else None,
|
||||
after=_serialize_decision(row),
|
||||
source='order_review_fulfillment_decision',
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.order_review_resume_service import (
|
||||
attach_resume_outcome,
|
||||
@@ -1311,6 +1522,113 @@ def decide_review_line_fulfillment(
|
||||
return attach_resume_outcome(payload, resume)
|
||||
|
||||
|
||||
def _active_decision_line_indexes(task: ShippingNotice) -> set[int]:
|
||||
"""读取当前任务全部活动行决定的 line_index(含 release/close/fulfill 等一切决定)。
|
||||
|
||||
核心逻辑:自动放行只处理「无任何活动决定」的行——已放行、已结案、已入波次或
|
||||
已有其他人工决定的行一律跳过,保证幂等且绝不自动撤销既有决定(与
|
||||
``_released_snapshot_line_ids_for_task`` 同款 Case 反查口径)。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
if getattr(task, 'id', None) is None:
|
||||
return set()
|
||||
rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.line_index.isnot(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return {int(row.line_index) for row in rows}
|
||||
|
||||
|
||||
def auto_release_part_fallback_shortages(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
) -> list[int]:
|
||||
"""
|
||||
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
|
||||
|
||||
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
|
||||
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
|
||||
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
|
||||
履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证,不自动撤销
|
||||
既有放行。注意:行匹配事实以 snapshot_line_id 为键,行号取自 fact['line_index']。
|
||||
|
||||
Args:
|
||||
task: 正式任务聚合根(OT 或正式 Notice,须含 id 与 order_snapshot_id)。
|
||||
actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。
|
||||
|
||||
Returns:
|
||||
自动放行的 line_index 列表(按行号升序)。
|
||||
"""
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
load_current_match_facts_by_task,
|
||||
)
|
||||
|
||||
task_id = getattr(task, 'id', None)
|
||||
if task_id is None:
|
||||
return []
|
||||
facts = load_current_match_facts_by_task(int(task_id))
|
||||
if not facts:
|
||||
return []
|
||||
decided_indexes = _active_decision_line_indexes(task)
|
||||
ordered_facts = sorted(
|
||||
(fact for fact in facts.values() if fact.get('line_index') is not None),
|
||||
key=lambda fact: int(fact['line_index']),
|
||||
)
|
||||
released: list[int] = []
|
||||
for fact in ordered_facts:
|
||||
line_index = int(fact['line_index'])
|
||||
try:
|
||||
if line_index in decided_indexes:
|
||||
continue
|
||||
if not _is_shortage_match_fact(fact):
|
||||
continue
|
||||
required = _parse_qty(fact.get('required_qty'))
|
||||
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||
if required is None or part_total is None or part_total < required:
|
||||
# 料号兜底量缺失或不足 → 维持人工待处置(不得任取部分数量放行)。
|
||||
continue
|
||||
fields, evidence_scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=line_index,
|
||||
inventory_snapshot_id=fact.get('inventory_snapshot_id'),
|
||||
inventory_source_code=fact.get('inventory_source_code'),
|
||||
)
|
||||
if any(bool(field.get('requires_manual')) for field in fields):
|
||||
# 证据字段无法唯一取值(requires_manual 残留)→ 降级人工放行,补录要求保留。
|
||||
continue
|
||||
auto_values = {
|
||||
str(field.get('field_id') or ''): (
|
||||
None if field.get('value') is None else str(field.get('value'))
|
||||
)
|
||||
for field in fields
|
||||
}
|
||||
_apply_shortage_line_release(
|
||||
task,
|
||||
line_index,
|
||||
auto_values,
|
||||
evidence_scope=evidence_scope,
|
||||
actor_type='system',
|
||||
actor_id=actor_id,
|
||||
auto_release=True,
|
||||
)
|
||||
released.append(line_index)
|
||||
except ConflictError:
|
||||
# 证据不可解析(无源/模板未发布/无快照/草稿行缺失)→ 维持人工路径,不中断其余行。
|
||||
continue
|
||||
return released
|
||||
|
||||
|
||||
def close_remaining_fulfillment(
|
||||
*,
|
||||
user_id: int,
|
||||
|
||||
@@ -478,17 +478,22 @@ def inventory_preparation_primary_action(
|
||||
"""裁决库存准备 Gate 面向业务用户的主动作。
|
||||
|
||||
单源合并(用户拍板):库存失败只保留 2 个按钮 ——
|
||||
``retry_inventory_preparation``(直接重跑 RPA)与 ``retry_inventory_matching``
|
||||
(优先复用已有快照并重匹配;无快照时 match_inventory 内部经 ensure_inventory 回退 RPA)。
|
||||
``retry_inventory_preparation``(显式重跑 RPA)与 ``retry_inventory_matching``
|
||||
(复用已抓取库存与字段映射并重匹配,不重抓,见 execute_stage_capability_rematch)。
|
||||
已下线的 ``reload_inventory_result``(只重读)不再独立成主动作,其「复用快照」行为已并入
|
||||
``retry_inventory_matching``。
|
||||
边界(STP 多候选,ensure_inventory auto 模式):缺快照停人工待处理、不隐式触发 RPA。
|
||||
因此获取库存未成功(无行级匹配结果)时,``retry_inventory_matching`` 由阶段能力禁用
|
||||
(disabled_reason=no_match_result,见 ui_state._stage_capabilities_for_task),
|
||||
重抓必须走显式的 ``retry_inventory_preparation``;本函数只裁决按钮位次,不禁用按钮。
|
||||
"""
|
||||
normalized_status = str(status or '').strip().lower()
|
||||
normalized_reason = str(blocking_reason_code or '').strip().lower()
|
||||
if normalized_status == 'waiting_external':
|
||||
return 'poll_inventory_preparation'
|
||||
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
|
||||
# [MERGE] 超时/耗尽:优先复用已有快照重匹配,无则回退 RPA(retry_inventory_matching 自含)。
|
||||
# [MERGE] 超时/耗尽:优先复用已有快照重匹配;无匹配结果时该按钮由阶段能力
|
||||
# 禁用(no_match_result),显式重抓走侧路 retry_inventory_preparation。
|
||||
return 'retry_inventory_matching'
|
||||
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
|
||||
return 'retry_inventory_preparation'
|
||||
|
||||
@@ -352,6 +352,13 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
continue
|
||||
current = gate
|
||||
break
|
||||
facts_before = (
|
||||
execution.last_passed_gate_code,
|
||||
execution.current_gate_code,
|
||||
execution.primary_next_action_code,
|
||||
execution.responsible_party,
|
||||
execution.status,
|
||||
)
|
||||
execution.last_passed_gate_code = last_passed
|
||||
if current is None:
|
||||
execution.current_gate_code = None
|
||||
@@ -359,7 +366,16 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
execution.responsible_party = None
|
||||
if execution.status not in {'cancelled', 'failed'}:
|
||||
execution.status = 'completed'
|
||||
_sync_order_task_stage_after_gate_refresh(execution)
|
||||
_sync_order_task_stage_after_gate_refresh(
|
||||
execution,
|
||||
facts_changed=facts_before != (
|
||||
execution.last_passed_gate_code,
|
||||
execution.current_gate_code,
|
||||
execution.primary_next_action_code,
|
||||
execution.responsible_party,
|
||||
execution.status,
|
||||
),
|
||||
)
|
||||
return
|
||||
execution.current_gate_code = current.gate_code
|
||||
execution.primary_next_action_code = current.next_action_code
|
||||
@@ -376,10 +392,23 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
|
||||
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
|
||||
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
|
||||
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
|
||||
_sync_order_task_stage_after_gate_refresh(execution)
|
||||
_sync_order_task_stage_after_gate_refresh(
|
||||
execution,
|
||||
facts_changed=facts_before != (
|
||||
execution.last_passed_gate_code,
|
||||
execution.current_gate_code,
|
||||
execution.primary_next_action_code,
|
||||
execution.responsible_party,
|
||||
execution.status,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
|
||||
def _sync_order_task_stage_after_gate_refresh(
|
||||
execution: ShippingProcessExecution,
|
||||
*,
|
||||
facts_changed: bool = False,
|
||||
) -> None:
|
||||
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
|
||||
if getattr(execution, 'task_id', None) is None:
|
||||
return
|
||||
@@ -397,10 +426,38 @@ def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecutio
|
||||
if task is not None else None
|
||||
)
|
||||
if notice is not None:
|
||||
version_before = int(getattr(task, 'progress_version', 0) or 0)
|
||||
sync_order_task_stage_for_notice(notice, order_task=task)
|
||||
# 库存缺口/文件就绪等 Gate 事实变化但映射后 stage/status 未变时,仍须推进
|
||||
# progress_version:工作台以该版本变化触发 [REFRESH_ON_CHANGE] 重拉任务详情,
|
||||
# 版本冻结会让行级可用数量/缺口停留在上一次快照。
|
||||
if (
|
||||
facts_changed
|
||||
and task is not None
|
||||
and int(getattr(task, 'progress_version', 0) or 0) == version_before
|
||||
):
|
||||
_bump_order_task_progress_version(task)
|
||||
elif task is not None:
|
||||
# Notice 生成前只维护 OT 自身阶段;不能调用 Notice 专属映射。
|
||||
task.stage = task.stage or 'notification_preparation'
|
||||
# 无 Notice 绑定(通知准备/库存匹配常态)时上方 Notice 映射不存在,Gate 每次真实
|
||||
# 推进都必须经中央写入口递增 progress_version,否则统一投影版本冻结,
|
||||
# 前端轮询只更新右卡门禁、任务详情表格永不刷新。
|
||||
if facts_changed:
|
||||
_bump_order_task_progress_version(task)
|
||||
|
||||
|
||||
def _bump_order_task_progress_version(task: ShippingOrderTask) -> None:
|
||||
"""Gate 事实已变化但 stage/status 无值可变时,经中央写入口强制递增进度版本。"""
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
|
||||
sync_order_task_processing_state(
|
||||
task,
|
||||
bump_progress=True,
|
||||
force_progress_bump=True,
|
||||
reason_code='gate_facts_advanced',
|
||||
source='process_gate_service',
|
||||
)
|
||||
|
||||
|
||||
def ensure_execution_for_workflow_version(
|
||||
|
||||
@@ -812,6 +812,11 @@ def apply_user_projection_fields(
|
||||
return 'waiting_human'
|
||||
if unverified_upload_terminal:
|
||||
return 'waiting_human'
|
||||
if gate_status in {'queued', 'running', 'waiting_external'}:
|
||||
# Gate/Execution 在途 = 系统处理中:Notice 生成前 OT.status 会停留在建单前
|
||||
# 的 waiting_review,不得据此把 RPA 自动推进误报成待人工——前端把
|
||||
# waiting_human 视为终态并停止投影轮询,回调完成将永远无法被感知。
|
||||
return 'running'
|
||||
# 1) 终态短路:old_status completed/cancelled/failed
|
||||
if old_status == 'completed':
|
||||
return 'completed'
|
||||
|
||||
@@ -8,6 +8,7 @@ services/shipping_notice/stp_line_inventory_match.py
|
||||
__source_code(源已在选源/载入 Excel 时确定);多文件命中为冲突;唯一命中且数量充足则冻结
|
||||
resolved 源与行证据;多源可履约行暂停 Excel(step_payload 标记);人工指定源后
|
||||
forced_match_source_code 过滤库存行再匹配;结果写入 step_payload / line_results_json。
|
||||
行结果另含料号兜底总量 part_available_qty(允许源内、忽略预约号与单位的二次汇总)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -77,6 +78,37 @@ def _inventory_row_qty(row: dict[str, Any]) -> Decimal:
|
||||
return Decimal('0')
|
||||
|
||||
|
||||
def _part_total_available_qty(
|
||||
buckets: dict[tuple[str, str, str, str], dict[str, Any]],
|
||||
*,
|
||||
part: str,
|
||||
allowed_source_codes: list[str],
|
||||
has_candidate_scope: bool,
|
||||
) -> Decimal | None:
|
||||
"""
|
||||
按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。
|
||||
|
||||
Args:
|
||||
buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。
|
||||
part: 归一化料号;空串返回 None。
|
||||
allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。
|
||||
has_candidate_scope: 行是否携带候选源范围事实。
|
||||
|
||||
Returns:
|
||||
料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。
|
||||
"""
|
||||
if not part:
|
||||
return None
|
||||
total = Decimal('0')
|
||||
for key, bucket in buckets.items():
|
||||
if key[1] != part:
|
||||
continue
|
||||
if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes:
|
||||
continue
|
||||
total += bucket['available_qty']
|
||||
return total
|
||||
|
||||
|
||||
def snapshot_header_reservation_id(snapshot: ShippingOrderSnapshot | None) -> str | None:
|
||||
"""
|
||||
从冻结 Snapshot 读取 Header 级 reservation_id。
|
||||
@@ -275,6 +307,9 @@ def match_order_lines_across_candidates(
|
||||
|
||||
核心逻辑:匹配键是 Reservation + Part(单位可选);库存源在选源/载入 Excel 时已确定,
|
||||
库存行缺 ``__source_code`` 仍参与聚合。仅当行上显式带源码时,才用候选源范围过滤/判冲突。
|
||||
料号兜底:仅 not_found(预约不匹配)/ok/shortage 行额外下发
|
||||
``part_available_qty``(行允许源内、忽略预约号、不限单位的料号总可用量);
|
||||
缺料号、invalid(超出候选范围)、multi_file_conflict、缺预约行不写该键,由下游按缺失→None 处理。
|
||||
|
||||
Args:
|
||||
order_lines: 含 part_number / reservation_id / quantity(或 qty)/ uom 的订单行。
|
||||
@@ -348,6 +383,13 @@ def match_order_lines_across_candidates(
|
||||
else True
|
||||
)
|
||||
]
|
||||
# [STEP] 料号兜底总量:行允许源内、忽略预约号、不限单位,供预约不匹配/缺口行自动放行判断。
|
||||
part_total = _part_total_available_qty(
|
||||
buckets,
|
||||
part=part,
|
||||
allowed_source_codes=allowed_source_codes,
|
||||
has_candidate_scope=has_candidate_scope,
|
||||
)
|
||||
|
||||
if not effective or not part:
|
||||
disposition = 'not_found'
|
||||
@@ -408,6 +450,7 @@ def match_order_lines_across_candidates(
|
||||
'required_qty': float(required),
|
||||
'available_qty': 0.0,
|
||||
'shortage_qty': float(required),
|
||||
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||
'line_status': 'shortage',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': None,
|
||||
@@ -431,6 +474,7 @@ def match_order_lines_across_candidates(
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': 0.0,
|
||||
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||
'line_status': 'ok',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': resolved_source,
|
||||
@@ -453,6 +497,7 @@ def match_order_lines_across_candidates(
|
||||
'required_qty': float(required),
|
||||
'available_qty': float(available),
|
||||
'shortage_qty': float(max(required - available, Decimal('0'))),
|
||||
'part_available_qty': float(part_total) if part_total is not None else None,
|
||||
'line_status': 'partial' if available > 0 else 'shortage',
|
||||
'disposition': disposition,
|
||||
'resolved_inventory_source_code': resolved_source,
|
||||
|
||||
@@ -16,6 +16,7 @@ services/shipping_notice/ui_state.py
|
||||
+ 当前 Match 投影诚实反映最近一轮(Notice 经 order_task_id→OT),
|
||||
行级拆 selected_source_code(CandidateSet 取数目标)与 source_code(Match 正式源);
|
||||
短缺行复用放行模板字段;匹配成功无短缺下发 can_fulfill_complete_line;
|
||||
prep 行直透投影 part_available_qty(料号兜底总量,仅库存就绪时非空)供前端「可用数量」列;
|
||||
下发 source_options 与 capabilities(阶段能力,供右卡点击 stageCapabilityBypass);
|
||||
用户动作统一由 Gate 授权;build_task_ui_state 同请求内复用一次 Gate 摘要;
|
||||
project_notice_available_actions 供货代上传聚合行内菜单轻量消费。
|
||||
@@ -950,7 +951,8 @@ def _build_stage_context(
|
||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||
if release_line_index is None and getattr(snapshot_line, 'position', None) is not None:
|
||||
release_line_index = int(snapshot_line.position)
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
# scope 仅在 decide 落库时写入审计快照;prep 行投影契约本期不新增字段。
|
||||
release_template_fields, _evidence_scope = _shortage_release_required_fields(
|
||||
task=order_task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=release_snapshot_id,
|
||||
@@ -976,6 +978,7 @@ def _build_stage_context(
|
||||
'required_qty': required_qty,
|
||||
'available_qty': inv_view.get('available_qty'),
|
||||
'shortage_qty': inv_view.get('shortage_qty'),
|
||||
'part_available_qty': inv_view.get('part_available_qty'),
|
||||
'source_code': source_code,
|
||||
'selected_source_code': selected_source_code,
|
||||
'status': inv_view.get('user_line_status'),
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
"""add part_available_qty to shipping_notice_line_inventory_matches
|
||||
|
||||
Revision ID: 0a575f3afc32
|
||||
Revises: 9e5045511198
|
||||
Create Date: 2026-10-09 14:46:05.242283
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '0a575f3afc32'
|
||||
down_revision = '9e5045511198'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# 本迁移由 autogenerate 生成后人工裁剪:本地 dev 库与模型存在大量与本任务无关的
|
||||
# 结构漂移,仅保留目标表新列(料号维度总可用量),其余漂移由后续专项迁移处理。
|
||||
op.add_column('shipping_notice_line_inventory_matches', sa.Column('part_available_qty', sa.String(32), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('shipping_notice_line_inventory_matches', 'part_available_qty')
|
||||
@@ -122,7 +122,8 @@ def test_create_matching_returns_envelope_with_matching_id(app, client, admin_he
|
||||
data = body["data"]
|
||||
assert data["matching_id"].startswith("MTG-")
|
||||
assert data["matching_hash"].startswith("sha256:")
|
||||
assert data["estimated_external_write_count"] == 2
|
||||
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||
assert data["estimated_external_write_count"] == 1
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
@@ -625,6 +626,41 @@ def test_retry_rpa_parse_failed_still_failed_reports_not_ok(app, client, admin_h
|
||||
assert called["rpa"] == 0
|
||||
|
||||
|
||||
def test_retry_rpa_batch_requires_source_codes(app, client, admin_headers):
|
||||
"""空 source_codes → 400(批量端点参数卡控)。"""
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers, json={"source_codes": []},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_retry_rpa_batch_delegates_to_batch_trigger_service(app, client, admin_headers, monkeypatch):
|
||||
"""批量端点把 source_codes 原样交给 trigger_receipt_rpa_batch 并回传结果 envelope。"""
|
||||
captured: dict = {}
|
||||
|
||||
def fake_batch(*, source_codes, business_date, reason):
|
||||
captured.update(source_codes=source_codes, business_date=business_date, reason=reason)
|
||||
return {
|
||||
"ok": True, "triggered": True, "trigger_path": "/tmp/trigger.json",
|
||||
"results": [{"source_code": code, "ok": True} for code in source_codes],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"app.services.in_transit_transfer.receipt_trigger_service.trigger_receipt_rpa_batch", fake_batch,
|
||||
)
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/sources/retry-rpa-batch", headers=admin_headers,
|
||||
json={"source_codes": ["DSV360_AWSDU", "DSV360_AWSSG"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()["data"]
|
||||
# [断言意图] 端点只做参数卡控与转发:来源列表原样下传、reason 固定业务语义。
|
||||
assert captured["source_codes"] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||
assert captured["reason"] == "transfer_retry_receipt"
|
||||
assert body["ok"] is True and body["triggered"] is True
|
||||
assert [item["source_code"] for item in body["results"]] == ["DSV360_AWSDU", "DSV360_AWSSG"]
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
|
||||
@@ -64,3 +64,29 @@ def test_executes_and_propagates_result_when_executable(monkeypatch):
|
||||
assert outcome.run_no == "RUN-20260928-XYZ789"
|
||||
assert outcome.run_status == "success"
|
||||
assert outcome.errors == []
|
||||
|
||||
|
||||
def test_passes_receipt_date_range_to_matching(monkeypatch):
|
||||
"""可选收料日期范围透传匹配层;缺省时为 None(=全部成熟积压)。"""
|
||||
captured = {}
|
||||
|
||||
def _fake_create(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return _summary(0)
|
||||
|
||||
monkeypatch.setattr(at, "create_matching", _fake_create)
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
receipt_date_from="2026-09-01", receipt_date_to="2026-09-05",
|
||||
)
|
||||
# 断言:显式范围原样透传(成熟上限/起止合法性由匹配层 ValidationError 卡控)。
|
||||
assert captured["receipt_date_from"] == "2026-09-01"
|
||||
assert captured["receipt_date_to"] == "2026-09-05"
|
||||
|
||||
at.run_auto_transfer(
|
||||
business_date="2026-09-28", deps=None, source_codes=["CRANE_SGP"], recover_history=False,
|
||||
)
|
||||
# 断言:缺省(留空)不缩小匹配面,范围参数为 None。
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
@@ -85,7 +85,8 @@ def test_matching_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
assert event.data["message_type"] == "transfer-match"
|
||||
payload = event.data["payload"]
|
||||
assert payload["kind"] == "match"
|
||||
assert payload["summary"]["estimated_external_write_count"] == 2
|
||||
# [2026-10-12 单据数口径修正] HOM-001/HOX-002 同五元组合并 1 张(原口径=行数 2)。
|
||||
assert payload["summary"]["estimated_external_write_count"] == 1
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-002"}
|
||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
@@ -57,7 +57,9 @@ 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.matching_hash.startswith("sha256:")
|
||||
assert summary.estimated_external_write_count == 3
|
||||
# [2026-10-12 单据数口径修正] 3 行可执行按执行建单五元组去重:DBS 两行
|
||||
# 同(org,source,date,from,to)合并 1 张 + CRANE 1 行 1 张 = 2(原口径=行数 3)。
|
||||
assert summary.estimated_external_write_count == 2
|
||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
||||
@@ -66,6 +68,61 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
|
||||
|
||||
def test_estimated_document_count_merges_same_group(dbs_ready_file):
|
||||
"""[2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
|
||||
|
||||
场景:同源同日两张 Invoice,五元组(org, source, receipt_date, from, to)
|
||||
全同 → 执行期合并一张 ERP 单,预估数 = 1 而非可执行行数 2;
|
||||
并断言 DTO external_org 随路由解析透出(前端勾选行预估的分组输入)。
|
||||
"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
# HOM-001 与 HOX-002 同(HX-CN01, DBS-AWSBI, 2026-08-05, DBS-TRANSIT, HUB-CN01)。
|
||||
assert result.summary.estimated_external_write_count == 1
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["HOM-001"].external_org == "HX-CN01"
|
||||
assert items["HOX-002"].external_org == "HX-CN01"
|
||||
|
||||
|
||||
def test_estimated_document_count_splits_by_receipt_date():
|
||||
"""[2026-10-12 单据数口径修正] 同源同仓库但收料日期不同 → 五元组不同,预估 = 2。
|
||||
|
||||
锁定分组的日期维度:execution_service.prepare_execution 以 receipt_date 入键,
|
||||
跨日行不合并单(预估数与执行建单数一致,不给用户错误预期)。
|
||||
"""
|
||||
deps, erp, _ = _deps({
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_no": "REC-20260806-009",
|
||||
"file_version": "v9",
|
||||
"checksum": "e" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 1, "doc_no": "HOM-A", "lot_no": "LOT-A",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-04", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 2, "doc_no": "HOM-B", "lot_no": "LOT-B",
|
||||
"material_code": "MAT-001", "material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"movement_date": "2026-08-05", "quantity": "600", "unit": "个", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
})
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-A", "600")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-B", "600")
|
||||
seed_rows_from_file("DBS-AWSBI", deps, "2026-08-06")
|
||||
result = run_matching(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
assert result.summary.estimated_external_write_count == 2
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
|
||||
@@ -75,10 +75,22 @@ def test_invalid_quantity_rejected():
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
||||
|
||||
|
||||
def test_zero_quantity_rejected():
|
||||
"""0 数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
def test_zero_quantity_stamped_row_skipped():
|
||||
"""零数量收料行(日期已盖章、数量 0)为非可用收料事实:跳过不阻断(2026-10-08 CRANE WTP26082227 实测)。"""
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
assert parsed == []
|
||||
|
||||
|
||||
def test_zero_quantity_rows_mixed_with_valid_rows_only_valid_parsed():
|
||||
"""合法行与零数量行混排:只放行合法行,零数量行不阻断整文件。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=788, invoice_no="WTP26082227", receipt_quantity="0",
|
||||
receipt_date="2026-10-01 14:37:43"),
|
||||
dict(VALID_ROW, row_no=789, invoice_no="INV-002", receipt_quantity="120"),
|
||||
]
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
assert [row.row_no for row in parsed] == [789]
|
||||
assert parsed[0].invoice_no == "INV-002"
|
||||
|
||||
|
||||
def test_negative_quantity_rejected():
|
||||
@@ -121,3 +133,19 @@ def test_error_carries_row_details():
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
||||
details = excinfo.value.details
|
||||
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
||||
|
||||
|
||||
def test_schema_error_message_carries_row_details():
|
||||
"""诊断落库:schema 失败消息必须携带前几条行级明细(行号+原因),随 parse_error_message 落库自描述。"""
|
||||
rows = [
|
||||
dict(VALID_ROW, row_no=5, invoice_no=""),
|
||||
dict(VALID_ROW, row_no=9, receipt_quantity="abc"),
|
||||
]
|
||||
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
# [断言意图] 消息不再只是通用 "receipt file schema invalid",须含行号与原因;
|
||||
# 明细同时保留在 details.rows 供管理端展示。
|
||||
text = str(exc_info.value) or (exc_info.value.message or "")
|
||||
assert "row 5" in text and "missing_invoice_no" in text
|
||||
detail_rows = (exc_info.value.details or {}).get("rows") or []
|
||||
assert {"row_no": 5, "reason": "missing_invoice_no"} in detail_rows
|
||||
@@ -1,11 +1,13 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
||||
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
用途:验证 trigger_receipt_rpa / trigger_receipt_rpa_batch 按来源装配收料 trigger unit
|
||||
并调用写者;触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa(_batch)、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False;
|
||||
批量触发多来源合并一个 batch trigger 文件(单源失败跳过不炸整批,
|
||||
parse_failed 先本地重解析不触发 RPA)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,7 +15,10 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import (
|
||||
trigger_receipt_rpa,
|
||||
trigger_receipt_rpa_batch,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -170,3 +175,157 @@ def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, rec
|
||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 批量触发(trigger_receipt_rpa_batch):多来源合并一个 batch trigger 文件,
|
||||
# Worker 单次浏览器会话串行处理(2026-10-09 批量重试效率修复)。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def second_receipt_source(app):
|
||||
"""再造一个启用来源 + 收料配置(批量用例需要多来源);启用态必须绑定
|
||||
解析规则/Excel 模板(ck_shipping_inventory_sources_enabled_bindings),复用种子源绑定。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingRpaProfile, ShippingReceiptReportConfig
|
||||
|
||||
seed = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
profile = ShippingRpaProfile(
|
||||
profile_code='DBS_SG_TEST', display_name='DBS SG', connector_type='dbs',
|
||||
login_url='https://test.invalid/dbs-sg', login_config_json={'auth_mode': 'password'},
|
||||
)
|
||||
source = ShippingInventorySource(
|
||||
source_code='DSV360_AWSSG', display_name='DBS SG AWSSG', connector_type='dbs',
|
||||
rpa_profile=profile,
|
||||
parsing_profile=seed.parsing_profile, excel_template=seed.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='AWSSG',
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
enabled=True,
|
||||
)
|
||||
db.session.add_all([profile, source])
|
||||
db.session.flush() # 先取 source.id(新建对象 flush 前无主键)
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[],
|
||||
)
|
||||
db.session.add(config)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writes_one_trigger_for_all_units(app, receipt_source, second_receipt_source):
|
||||
"""多来源 → 只写一次 trigger(一个文件 N units),各单元独立 callback_id/unit_run_id。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
calls: list = []
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
calls.append({'run_no': run_no, 'units': units, 'payload': payload or {}})
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
reason='transfer_retry_receipt', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 合并单文件是本修复的核心:writer 恰好调用 1 次、units 装下全部来源。
|
||||
assert len(calls) == 1
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert calls[0]['run_no'].startswith('TRIG-BATCH-')
|
||||
assert [u['source_code'] for u in calls[0]['units']] == ['DSV360_AWSDU', 'DSV360_AWSSG']
|
||||
assert calls[0]['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
# 每单元独立回调身份,且单元行先落库(回调按 callback_id 可达)。
|
||||
callback_ids = {u['callback_id'] for u in calls[0]['units']}
|
||||
assert len(callback_ids) == 2
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'awaiting_rpa'}
|
||||
assert all(row.schedule_run_id is None for row in rows)
|
||||
assert {row.id for row in rows} == {u['unit_run_id'] for u in calls[0]['units']}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_skips_invalid_source(app, receipt_source):
|
||||
"""单源配置缺失 → 跳过该源并逐源记录 error_code,其余来源照常进 batch trigger。"""
|
||||
captured: dict = {}
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
captured['units'] = units
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 来源级隔离:坏源不炸整批,trigger 只含有效源;结果逐源如实分层。
|
||||
assert outcome['ok'] is True and outcome['triggered'] is True
|
||||
assert [u['source_code'] for u in captured['units']] == ['DSV360_AWSDU']
|
||||
by_code = {item['source_code']: item for item in outcome['results']}
|
||||
assert by_code['DSV360_AWSDU']['ok'] is True
|
||||
assert by_code['DSV360_NOPE']['ok'] is False
|
||||
assert by_code['DSV360_NOPE']['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_all_invalid_no_trigger(app):
|
||||
"""全部来源无效 → 不写 trigger,ok=False + RPA_RECEIPT_NO_TRIGGERABLE_SOURCE。"""
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_NOPE'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: (_ for _ in ()).throw(AssertionError('writer must not be called')),
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_NO_TRIGGERABLE_SOURCE'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_writer_unavailable_marks_all_failed(app, receipt_source, second_receipt_source):
|
||||
"""trigger 目录不可用 → 本批全部单元标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU', 'DSV360_AWSSG'], business_date='2026-10-09',
|
||||
writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome['ok'] is False and outcome['triggered'] is False
|
||||
assert outcome['error_code'] == 'RPA_RECEIPT_TRIGGER_UNAVAILABLE'
|
||||
rows = ShippingReceiptRpaUnitRun.query.filter(ShippingReceiptRpaUnitRun.source_code.in_(
|
||||
['DSV360_AWSDU', 'DSV360_AWSSG'])).all()
|
||||
assert {row.status for row in rows} == {'failed'}
|
||||
assert {row.error_code for row in rows} == {'RPA_RECEIPT_TRIGGER_UNAVAILABLE'}
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_batch_parse_failed_reparses_without_rpa(app, receipt_source, monkeypatch):
|
||||
"""parse_failed 来源先本地重解析(成功则不触发 RPA),与单来源端点分层语义一致。"""
|
||||
statuses = {
|
||||
'DSV360_AWSDU': [
|
||||
{'file_status': 'parse_failed', 'file_sha256': 'abc'},
|
||||
{'file_status': 'ready', 'file_sha256': 'abc'},
|
||||
],
|
||||
}
|
||||
|
||||
def fake_resolve(*, source_code):
|
||||
# [断言意图] 解析失败分层:首次投影 parse_failed 触发本地重解析,
|
||||
# sync 后再查投影回 ready——该来源不得进入 batch trigger。
|
||||
queue = statuses.get(source_code)
|
||||
if queue and len(queue) > 1:
|
||||
return queue.pop(0)
|
||||
return queue[0] if queue else {'file_status': 'none'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.in_transit_transfer.source_file_status.resolve_source_file_status', fake_resolve,
|
||||
)
|
||||
synced: list = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.in_transit_transfer.evidence_sync.sync_and_commit_for_callback',
|
||||
lambda *, source_code, business_date, now: synced.append(source_code) or True,
|
||||
)
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
raise AssertionError('reparsed source must not be triggered via RPA')
|
||||
|
||||
outcome = trigger_receipt_rpa_batch(
|
||||
source_codes=['DSV360_AWSDU'], business_date='2026-10-09', writer=fake_writer,
|
||||
)
|
||||
# [断言意图] 重解析恢复 ready → 无需写盘,整体 ok=True(请求已达成目的)。
|
||||
assert synced == ['DSV360_AWSDU']
|
||||
assert outcome['ok'] is True and outcome['triggered'] is False
|
||||
assert outcome['results'] == [{
|
||||
'source_code': 'DSV360_AWSDU', 'ok': True, 'reparsed': True, 'file_status': 'ready',
|
||||
}]
|
||||
@@ -29,7 +29,9 @@ def test_transfer_job_registered_with_schedule_defaults():
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history"} <= keys
|
||||
assert {"source_codes", "recover_history", "receipt_from_offset_days", "receipt_to_offset_days"} <= keys
|
||||
# 断言:任务级通知人已移除——通知统一走排程「启用通知」,防止参数回归。
|
||||
assert "notify_user_ids" not in keys
|
||||
assert not re.search(r"\d{2}:\d{2}", job.description), "描述禁止硬编码执行时刻"
|
||||
|
||||
|
||||
@@ -123,17 +125,8 @@ def test_wanted_source_codes_falls_back_when_empty(monkeypatch):
|
||||
assert _wanted_source_codes(string_param) == ["DBS_HUB"]
|
||||
|
||||
|
||||
class _FakeSender:
|
||||
"""记录实例化的发送器替身(断言 handler 接线,不发真实消息)。"""
|
||||
|
||||
instantiated = 0
|
||||
|
||||
def __init__(self):
|
||||
type(self).instantiated += 1
|
||||
|
||||
|
||||
def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
||||
"""配了通知人:构造 sender、置领域自管标记、recipients 透传。"""
|
||||
def test_handler_empty_data_day_stays_silent(monkeypatch):
|
||||
"""空数据日(无 run_no 且无 errors):不传领域通知参数,置静默标记抑制框架完成卡(C5)。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
@@ -147,28 +140,32 @@ def test_handler_wires_sender_and_domain_notification(monkeypatch):
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
class _FakeSenderInner:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
||||
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True, "notify_user_ids": ["7"]})
|
||||
task = ScheduleTask(job_params={"source_codes": [], "recover_history": True})
|
||||
run = ScheduleRun(run_no="RUNR-1", status="running")
|
||||
total, success, failed, skipped, results, warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
# 断言:领域通知接线已移除(不再透传 sender/recipients);空数据日置 C5 静默标记。
|
||||
assert "sender" not in captured
|
||||
assert "recipients" not in captured
|
||||
assert captured["receipt_date_from"] is None
|
||||
assert captured["receipt_date_to"] is None
|
||||
assert captured["source_codes"] == ["CRANE_SGP"]
|
||||
assert captured["recipients"] == ["7"]
|
||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
||||
assert captured["recover_history"] is True
|
||||
assert run.response_summary_json["domain_notification_managed"] is True
|
||||
assert (total, success, failed, skipped) == (0, 0, 0, 0)
|
||||
assert results == []
|
||||
assert any("no executable items" in w for w in warnings)
|
||||
|
||||
|
||||
def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
||||
"""未配通知人:sender=None、不置标记、落回框架通用通知(由框架按任务配置发送)。"""
|
||||
def test_handler_converts_t_minus_offsets(monkeypatch):
|
||||
"""T−N 偏移天数按执行日业务日换算为具体收料日期透传;留空为 None。"""
|
||||
from datetime import date
|
||||
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
monkeypatch.setattr(job_mod, "business_date_now", lambda: date(2026, 10, 12))
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
@@ -178,43 +175,91 @@ def test_handler_without_recipients_skips_domain_notification(monkeypatch):
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": 4, "receipt_to_offset_days": 2})
|
||||
run = ScheduleRun(run_no="RUNR-4", status="running")
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
# 断言:T=2026-10-12,起4止2 换算为 T−4~T−2 的具体日期透传匹配层。
|
||||
assert captured["business_date"] == "2026-10-12"
|
||||
assert captured["receipt_date_from"] == "2026-10-08"
|
||||
assert captured["receipt_date_to"] == "2026-10-10"
|
||||
|
||||
|
||||
def test_handler_rejects_invalid_offset_without_execution(monkeypatch):
|
||||
"""偏移非法(负数/非整数):快速失败不执行,错误走框架失败通知。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _must_not_run(**kwargs):
|
||||
raise AssertionError("run_auto_transfer must not run with invalid offsets")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _must_not_run)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
run = ScheduleRun(run_no="RUNR-5", status="running")
|
||||
task = ScheduleTask(job_params={"receipt_from_offset_days": -1})
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:负数偏移不执行、不置静默标记(框架卡照常告警),错误信息含参数名。
|
||||
assert results == []
|
||||
assert any("收料日期起点" in e for e in errors)
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
|
||||
task = ScheduleTask(job_params={"receipt_to_offset_days": 2.5})
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
# 断言:小数偏移同样快速失败。
|
||||
assert any("收料日期终点" in e for e in errors)
|
||||
|
||||
|
||||
def test_handler_run_day_uses_framework_notification(monkeypatch):
|
||||
"""有 Run(成功):不置静默标记,框架完成卡按排程「启用通知」照常发送。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
return job_mod.AutoTransferOutcome(run_no="TR-1", run_status="success")
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-2", status="running")
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
total, success, failed, skipped, results, _warnings, errors = job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
|
||||
assert captured["sender"] is None
|
||||
assert captured["recipients"] == []
|
||||
# 断言:有 run 不抑制框架通知;run_no 落入 results 供完成卡/留痕展示。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results and results[0]["run_no"] == "TR-1"
|
||||
assert (total, success, failed, skipped) == (1, 1, 0, 0)
|
||||
assert errors == []
|
||||
|
||||
|
||||
def test_handler_hard_failure_keeps_framework_notification(monkeypatch):
|
||||
"""硬失败(有通知人、无 run_no、有 errors):仍构造并传入 sender,但不置自管标记。"""
|
||||
"""硬失败(无 run_no、有 errors):不置静默标记,框架完成卡兜底告警。"""
|
||||
import app.services.schedule.in_transit_transfer_job as job_mod
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
|
||||
monkeypatch.setattr(job_mod, "list_receipt_capable_source_codes", lambda: ["CRANE_SGP"])
|
||||
captured = {}
|
||||
|
||||
def _fake_auto_transfer(**kwargs):
|
||||
captured.update(kwargs)
|
||||
return job_mod.AutoTransferOutcome(errors=["match pipeline boom"])
|
||||
|
||||
monkeypatch.setattr(job_mod, "run_auto_transfer", _fake_auto_transfer)
|
||||
monkeypatch.setattr(job_mod, "transfer_deps", SimpleNamespace(get_transfer_dependencies=lambda: None))
|
||||
|
||||
class _FakeSenderInner:
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(job_mod, "WecomSummarySender", _FakeSenderInner)
|
||||
|
||||
task = ScheduleTask(job_params={"notify_user_ids": ["7"]})
|
||||
task = ScheduleTask(job_params={})
|
||||
run = ScheduleRun(run_no="RUNR-3", status="running")
|
||||
_total, _success, _failed, _skipped, _results, _warnings, errors = (
|
||||
_total, _success, _failed, _skipped, results, _warnings, errors = (
|
||||
job_mod.run_in_transit_transfer_schedule(task, run)
|
||||
)
|
||||
|
||||
# 断言:sender 已构造并透传;硬失败不抑制框架完成卡。
|
||||
assert isinstance(captured["sender"], _FakeSenderInner)
|
||||
assert captured["recipients"] == ["7"]
|
||||
# 断言:硬失败不抑制框架完成卡(兜底告警),errors 原样上抛、无 results。
|
||||
assert not (run.response_summary_json or {}).get("domain_notification_managed")
|
||||
assert results == []
|
||||
assert errors == ["match pipeline boom"]
|
||||
@@ -207,3 +207,14 @@ def test_record_and_clear_parse_failure_roundtrip(app, receipt_unit_run):
|
||||
clear_receipt_parse_failure(report=report)
|
||||
db.session.commit()
|
||||
assert resolve_source_file_status(source_code=SOURCE_CODE)["file_status"] == "ready"
|
||||
|
||||
|
||||
def test_empty_unit_is_no_data(app, receipt_unit_run):
|
||||
"""空数据单元(抓取成功、当日无收料记录)→ no_data,不得与抓取失败混淆。"""
|
||||
from app import db
|
||||
|
||||
receipt_unit_run.status = 'empty'
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'no_data'
|
||||
assert status['has_ready_file'] is False
|
||||
@@ -448,3 +448,167 @@ def test_fill_multi_value_js_uses_entry_text_not_bare_text():
|
||||
# 禁止在 checkbox 循环里出现未绑定的 `text`(旧脚本 ReferenceError)。
|
||||
assert "desiredValues.includes(text" not in source
|
||||
assert "normalize(text)" not in source or "entryText" in source
|
||||
|
||||
|
||||
class _RecordingFrame:
|
||||
"""脚本化 frame:evaluate 返回预置结果或抛预置异常,并记录收到的 label。"""
|
||||
|
||||
def __init__(self, result=None, error: Exception | None = None):
|
||||
self._result = result
|
||||
self._error = error
|
||||
self.calls: list[str] = []
|
||||
|
||||
def evaluate(self, script: str, label: str):
|
||||
self.calls.append(label)
|
||||
if self._error is not None:
|
||||
raise self._error
|
||||
return self._result
|
||||
|
||||
|
||||
class _RecordingPage:
|
||||
def __init__(self, frames):
|
||||
self.frames = frames
|
||||
|
||||
|
||||
_STRUCTURAL_CONTROLS = {
|
||||
"text": "#ReportViewerMain_ctl08_ctl15_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl15_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl15_divDropDown",
|
||||
}
|
||||
|
||||
|
||||
def test_structural_resolver_hit_returns_controls_and_trims_label():
|
||||
"""命中 frame 返回三件套;label 先 trim 再传入页面脚本。"""
|
||||
module = _load_module()
|
||||
early = _RecordingFrame(result=None)
|
||||
hit = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([early, hit])
|
||||
|
||||
got = module.resolve_parameter_controls_structural(page, " Owner ")
|
||||
|
||||
assert got == _STRUCTURAL_CONTROLS
|
||||
assert hit.calls == ["Owner"]
|
||||
|
||||
|
||||
def test_structural_resolver_all_frames_miss_or_error_returns_none():
|
||||
"""全部 frame 未命中或探测异常(跨域/销毁帧):返回 None 交调用方回退。"""
|
||||
module = _load_module()
|
||||
page = _RecordingPage([
|
||||
_RecordingFrame(result=None),
|
||||
_RecordingFrame(error=RuntimeError("execution context destroyed")),
|
||||
_RecordingFrame(result=None),
|
||||
])
|
||||
assert module.resolve_parameter_controls_structural(page, "Owner") is None
|
||||
|
||||
|
||||
def test_structural_resolver_empty_label_short_circuits():
|
||||
"""空标签短路:不打扰任何 frame。"""
|
||||
module = _load_module()
|
||||
frame = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([frame])
|
||||
assert module.resolve_parameter_controls_structural(page, " ") is None
|
||||
assert frame.calls == []
|
||||
|
||||
|
||||
def test_structural_resolver_none_page_returns_none():
|
||||
"""无页面上下文(纯函数调用):直接返回 None。"""
|
||||
module = _load_module()
|
||||
assert module.resolve_parameter_controls_structural(None, "Owner") is None
|
||||
|
||||
|
||||
def test_fill_multi_select_template_miss_falls_back_to_structural(monkeypatch):
|
||||
"""接线:报表模板未命中 Owner 时,落到结构性解析并把三件套传入 multi_value 填充。
|
||||
|
||||
[断言意图] 2026-10-08 事故回归:Owner@Receipt Detail@AWSRTM 未登记 ctl15 模板时,
|
||||
不得静默失败弃填(导致全货主巨报表渲染超时),必须结构性解析后正常填充。
|
||||
"""
|
||||
module = _load_module()
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||
captured.update(config_override)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "resolve_parameter_controls", lambda *a, **k: {})
|
||||
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([probe])
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Owner", ["CRTM-0000000100"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert captured == {"control": "multi_value", **_STRUCTURAL_CONTROLS}
|
||||
assert probe.calls == ["Owner"]
|
||||
|
||||
|
||||
def test_fill_multi_select_structural_preferred_registry_is_fallback(monkeypatch):
|
||||
"""优先级:结构性解析优先(ctl 编号随渲染漂移,注册表 ctl 条目只作回退)。
|
||||
|
||||
[断言意图] 结构性命中时使用结构性三件套、注册表回退不被消费;
|
||||
结构性未命中时才回退注册表控件。
|
||||
"""
|
||||
module = _load_module()
|
||||
registry_controls = {
|
||||
"text": "#ReportViewerMain_ctl08_ctl29_txtValue",
|
||||
"toggle": "#ReportViewerMain_ctl08_ctl29_ctl01",
|
||||
"dropdown": "#ReportViewerMain_ctl08_ctl29_divDropDown",
|
||||
}
|
||||
resolve_calls: list[tuple] = []
|
||||
monkeypatch.setattr(
|
||||
module, "resolve_parameter_controls",
|
||||
lambda *a, **k: (resolve_calls.append(a), dict(registry_controls))[1],
|
||||
)
|
||||
probe = _RecordingFrame(result=dict(_STRUCTURAL_CONTROLS))
|
||||
page = _RecordingPage([probe])
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def _fake_fill(page, label, values, *, timeout_ms, config_override, select_all):
|
||||
captured.update(config_override)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(module, "_fill_multi_value_parameter", _fake_fill)
|
||||
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Warehouse", ["RTM"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
|
||||
assert ok is True
|
||||
assert captured.get("text") == _STRUCTURAL_CONTROLS["text"] # 结构性解析优先生效
|
||||
assert resolve_calls == [] # 结构性命中:注册表回退未被消费
|
||||
|
||||
# 结构性未命中 → 回退注册表控件
|
||||
probed = _RecordingFrame(result=None)
|
||||
page = _RecordingPage([probed])
|
||||
captured.clear()
|
||||
ok = module.fill_dsv_multi_select_parameter(
|
||||
page, "Warehouse", ["RTM"], select_all=False,
|
||||
browser_timeout_ms=lambda: 3_000,
|
||||
report_name="Receipt Detail", program_label="AWSRTM",
|
||||
)
|
||||
assert ok is True
|
||||
assert captured.get("text") == registry_controls["text"] # 回退到注册表
|
||||
assert probed.calls == ["Warehouse"]
|
||||
|
||||
|
||||
def test_multi_value_already_set_set_equality_not_substring():
|
||||
"""2026-10-08 Owner@AWSRTM 事故根因回归:SSRS 多选框默认全选,txtValue 恒为全量 CSV,
|
||||
目标值必为该 CSV 的子串——必须用集合相等判定,子串包含会恒误判"已设置"并跳过下拉勾选。"""
|
||||
module = _load_module()
|
||||
all_owners_csv = ",".join(f"CRTM-0000000{n:03d}" for n in range(5, 449))
|
||||
|
||||
# [断言意图] 目标值是全选 CSV 的"子串"但非"全集"——不得判已设置(旧 bug 行为)。
|
||||
assert module._multi_value_already_set(all_owners_csv, ["CRTM-0000000100"]) is False
|
||||
# 完全相等的选中集合才允许跳过。
|
||||
assert module._multi_value_already_set("CRTM-0000000100", ["CRTM-0000000100"]) is True
|
||||
assert module._multi_value_already_set("CRTM-0000000100, CRTM-0000000101",
|
||||
["CRTM-0000000101", "CRTM-0000000100"]) is True
|
||||
# 边界:空当前值/空目标不判已设置;大小写与空白不敏感。
|
||||
assert module._multi_value_already_set("", ["CRTM-0000000100"]) is False
|
||||
assert module._multi_value_already_set(all_owners_csv, []) is False
|
||||
assert module._multi_value_already_set(" crtm-0000000100 ", ["CRTM-0000000100"]) is True
|
||||
@@ -132,20 +132,68 @@ def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch, tmp_
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
# [断言意图] 一次性出口:单条 textcard + 单个收料 ZIP,与库存排程同通道同门禁。
|
||||
# [断言意图] 一次性出口:单条 textcard + 结果 Excel + 单个收料 ZIP,与库存排程同通道同门禁。
|
||||
assert outcome == {'finalized': True, 'status': 'success'}
|
||||
assert len(textcards) == 1
|
||||
assert '原始收料包:已随本通知发送' in textcards[0][1]
|
||||
assert len(media_uploads) == 1
|
||||
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-收料.zip')
|
||||
assert file_sends == ['media-1']
|
||||
assert len(media_uploads) == 2
|
||||
assert media_uploads[0].startswith('收料RPA-') and media_uploads[0].endswith('-结果.xlsx')
|
||||
assert media_uploads[1].startswith('收料RPA-') and media_uploads[1].endswith('-收料.zip')
|
||||
assert file_sends == ['media-1', 'media-2']
|
||||
assert run.wecom_notified is True
|
||||
assert run.response_summary_json.get('raw_receipt_zip_available') is True
|
||||
|
||||
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
|
||||
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
assert len(textcards) == 1 and len(file_sends) == 1
|
||||
assert len(textcards) == 1 and len(file_sends) == 2
|
||||
|
||||
|
||||
def test_receipt_finalize_generates_summary_excel(app, tmp_path):
|
||||
"""收料 finalize 生成汇总 Excel:行结构对齐库存、状态归一、展示名 收料RPA-*-结果.xlsx。"""
|
||||
from io import BytesIO
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
app.config['FREIGHT_RPA_RECEIPT_ARCHIVE_DIR'] = str(tmp_path / 'receipt-archives-excel')
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-EXCEL', name='Receipt excel', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-EXCEL', schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True})
|
||||
db.session.add(run); db.session.flush()
|
||||
unit_ok = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSDU', connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-excel-ok', status='success', config_snapshot_json={})
|
||||
unit_empty = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='DSV360_AWSCV', connector_type='dbs', warehouse_id='AWSCV', callback_id='receipt-excel-empty', status='empty', config_snapshot_json={})
|
||||
unit_fail = ShippingReceiptRpaUnitRun(schedule_run_id=run.id, inventory_source_id=source.id, source_code='CRANE_WH1', connector_type='crane', warehouse_id=None, callback_id='receipt-excel-fail', status='failed', error_code='RPA.RECEIPT_EXPORT_FAILED', error_message='download timeout', config_snapshot_json={})
|
||||
db.session.add_all([unit_ok, unit_empty, unit_fail]); db.session.flush()
|
||||
db.session.add(ShippingReceiptReportFile(unit_run_id=unit_ok.id, storage_provider='minio', storage_bucket='test', storage_key='receipt-excel-1.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='d' * 64))
|
||||
db.session.commit()
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
# [断言意图] finalize 生成汇总 Excel,并携带与库存同名的 summary 契约键。
|
||||
assert outcome == {'finalized': True, 'status': 'partial_failed'}
|
||||
assert run.excel_file_data
|
||||
assert run.excel_file_name.startswith('收料RPA-') and run.excel_file_name.endswith('-结果.xlsx')
|
||||
assert run.response_summary_json['excel_export_status'] == 'ok'
|
||||
assert run.response_summary_json['excel_failed'] is False
|
||||
|
||||
# [断言意图] 行结构对齐库存:中文表头 + empty→skipped / failed 保持 failed,与卡片计数口径一致。
|
||||
workbook = load_workbook(BytesIO(run.excel_file_data))
|
||||
sheet = workbook.active
|
||||
header = [cell.value for cell in sheet[1]]
|
||||
assert header[:2] == ['收料源', '仓库']
|
||||
rows = {row[0]: row for row in sheet.iter_rows(min_row=2, values_only=True)}
|
||||
assert rows['DSV360_AWSDU'][3] == 1 and rows['DSV360_AWSDU'][4] == 'success'
|
||||
assert rows['DSV360_AWSCV'][4] == 'skipped'
|
||||
assert rows['CRANE_WH1'][4] == 'failed' and rows['CRANE_WH1'][6] == 'download timeout'
|
||||
|
||||
|
||||
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
|
||||
|
||||
@@ -1909,8 +1909,10 @@ def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypat
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
# 2026-09-20 页面改版后 #lanNavSel 既是标签读取点也是下拉开关(先于旧 #kc_locale 点击),
|
||||
# 因此点击它须置 opened,模拟“点开语言菜单”。
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("label")
|
||||
return _FakeLocator("toggle")
|
||||
if selector == "#kc_locale":
|
||||
return _FakeLocator("toggle")
|
||||
if "中文简体" in selector:
|
||||
@@ -2123,6 +2125,292 @@ def test_wait_for_dsv_login_method_page_skips_human_check_when_not_detected(monk
|
||||
assert human_check_calls["value"] == 0
|
||||
|
||||
|
||||
def test_is_dsv_password_upgrade_redirect_accepts_auth_dsv_com_resume():
|
||||
"""auth.dsv.com 的 resume/authorization.ping 也必须识别为密码升级提示地址。
|
||||
|
||||
[2026-10-12 回归] PingFederate resume 链迁移至 auth.dsv.com 后,旧的单域硬编码
|
||||
返回 False,导致升级提示检测不到、登录卡死在“使用密码升级登录!”页不点「也许以后」。
|
||||
"""
|
||||
_load_freight_rpa_worker()
|
||||
import dsv_auth
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||
|
||||
assert dsv_auth._is_dsv_password_upgrade_redirect(_FakePage()) is True
|
||||
|
||||
|
||||
def test_is_dsv_oauth_handshake_and_ping_urls_accept_auth_dsv_com():
|
||||
"""OAuth 握手 / authorization.ping 判定须覆盖 auth.dsv.com 双认证域。"""
|
||||
_load_freight_rpa_worker()
|
||||
import dsv_auth
|
||||
|
||||
assert dsv_auth.is_dsv_oauth_handshake_url(
|
||||
"https://auth.dsv.com/as/mock/as/authorization.oauth2"
|
||||
) is True
|
||||
assert dsv_auth.is_dsv_auth_ping_url(
|
||||
"https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||
) is True
|
||||
assert dsv_auth.is_dsv_oauth_handshake_url("https://s360.dbschenker.com/main") is False
|
||||
assert dsv_auth.is_dsv_auth_ping_url("https://s360.dbschenker.com/main") is False
|
||||
|
||||
|
||||
def test_looks_like_dsv_identifier_chooser_matches_strong_markers_only():
|
||||
"""「选择登录方法」标题命中且无密码框 → 已记住标识页;用户名页不得误判。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.body = body
|
||||
self.first = self
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self.body
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def count(self) -> int:
|
||||
return 0
|
||||
|
||||
class _FakeFrame:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.body = body
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator(self.body)
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, body: str) -> None:
|
||||
self.frames = [_FakeFrame(body)]
|
||||
|
||||
chooser_body = (
|
||||
"欢迎\nhtcus@hoo-thai.com\n选择登录方法\n通行密钥\n使用此设备登录。\n"
|
||||
"移动应用程序 (iPhone 11)\n密码\n输入您的密码并登录。\n取消"
|
||||
)
|
||||
assert worker._looks_like_dsv_identifier_chooser(_FakePage(chooser_body)) is True
|
||||
|
||||
username_body = "电子邮件或SIMS ID或手机号\n继续\n忘记密码"
|
||||
assert worker._looks_like_dsv_identifier_chooser(_FakePage(username_body)) is False
|
||||
|
||||
|
||||
def test_has_dsv_password_upgrade_prompt_on_auth_dsv_com_upgrade_page():
|
||||
"""升级提示检测在 auth.dsv.com resume 页必须生效,否则不点「也许以后」直接卡死。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
upgrade_body = "使用密码升级登录!\n从密码和电子邮件中解脱出来。\n也许以后\n立即启用"
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return upgrade_body
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
url = "https://auth.dsv.com/as/TKVXR7dFI7/resume/as/authorization.ping"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
|
||||
|
||||
|
||||
def test_maybe_auto_login_dsv_chooser_first_skips_username_and_completes(monkeypatch):
|
||||
"""已记住标识:方法选择页预检命中 → 跳过用户名等待/继续点击,直进密码阶段完成登录。
|
||||
|
||||
[2026-10-12 回归] 首版实现 chooser 分支漏初始化 user_filled,命中即抛
|
||||
UnboundLocalError 导致整源失败;且选择页判定在用户名等待超时后才做,每源白等约 2 分钟。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
g = worker._maybe_auto_login_dsv.__globals__
|
||||
state = {
|
||||
"continue_clicked": False,
|
||||
"purge_called": False,
|
||||
"password_method_clicked": False,
|
||||
"submitted": False,
|
||||
"home_ready": False,
|
||||
"find_password_calls": 0,
|
||||
}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def fill(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
password_locator = _FakeLocator()
|
||||
|
||||
def fake_find_password(page, timeout_ms: int = 250):
|
||||
state["find_password_calls"] += 1
|
||||
return password_locator if state["find_password_calls"] >= 2 else None
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dsv.com/as/mock/resume/as/authorization.ping"
|
||||
frames: list = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setitem(
|
||||
g, "_env",
|
||||
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||
)
|
||||
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: True)
|
||||
monkeypatch.setitem(g, "_click_dsv_continue", lambda page, locator: state.__setitem__("continue_clicked", True))
|
||||
monkeypatch.setitem(
|
||||
g, "_retry_dsv_login_with_purged_cookies", lambda page, username: state.__setitem__("purge_called", True)
|
||||
)
|
||||
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||
monkeypatch.setitem(g, "_fill_dsv_password_page_fields", lambda page, username, password: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_login_method_page", lambda page, timeout_ms=None: True)
|
||||
monkeypatch.setitem(
|
||||
g, "_click_dsv_password_method",
|
||||
lambda page: (state.__setitem__("password_method_clicked", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(
|
||||
g, "_submit_dsv_password_form",
|
||||
lambda page: (state.__setitem__("submitted", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||
monkeypatch.setitem(
|
||||
g, "_wait_for_dsv_home_ready_after_login",
|
||||
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
ticks["value"] += 0.25
|
||||
return ticks["value"]
|
||||
|
||||
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||
|
||||
worker._maybe_auto_login_dsv(_FakePage())
|
||||
|
||||
assert state["continue_clicked"] is False, "chooser-first 不得点击继续按钮"
|
||||
assert state["purge_called"] is False, "chooser-first 不得触发 Cookie 清空兜底"
|
||||
assert state["password_method_clicked"] is True
|
||||
assert state["submitted"] is True
|
||||
assert state["home_ready"] is True
|
||||
|
||||
|
||||
def test_maybe_auto_login_dsv_generic_fill_reaches_continue_without_unbound(monkeypatch):
|
||||
"""无用户名选择器时走通用填装:username_locator=None 传给继续点击,不得抛 UnboundLocalError。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
g = worker._maybe_auto_login_dsv.__globals__
|
||||
state = {
|
||||
"continue_args": None,
|
||||
"submitted": False,
|
||||
"home_ready": False,
|
||||
"find_password_calls": 0,
|
||||
}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self) -> None:
|
||||
self.first = self
|
||||
|
||||
def is_visible(self, *args, **kwargs) -> bool:
|
||||
return False
|
||||
|
||||
def fill(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
password_locator = _FakeLocator()
|
||||
|
||||
def fake_find_password(page, timeout_ms: int = 250):
|
||||
state["find_password_calls"] += 1
|
||||
return password_locator
|
||||
|
||||
class _FakePage:
|
||||
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||
frames: list = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator()
|
||||
|
||||
def wait_for_load_state(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
monkeypatch.setitem(
|
||||
g, "_env",
|
||||
lambda name, default=None: {"FREIGHT_RPA_WORKER_DSV_USERNAME": "mock-user",
|
||||
"FREIGHT_RPA_WORKER_DSV_PASSWORD": "mock-pass"}.get(name, default),
|
||||
)
|
||||
monkeypatch.setitem(g, "_has_existing_dsv_portal_session", lambda page: False)
|
||||
monkeypatch.setitem(g, "_wait_for_visible_selector", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_wait_for_dsv_auth_page_ready", lambda page, **kwargs: True)
|
||||
monkeypatch.setitem(g, "_maybe_switch_dsv_locale_to_zh_cn", lambda page: False)
|
||||
monkeypatch.setitem(g, "_looks_like_dsv_identifier_chooser", lambda page: False)
|
||||
monkeypatch.setitem(g, "_fill_first_visible_text_input", lambda page, username: True)
|
||||
|
||||
def fake_click_continue(page, locator):
|
||||
state["continue_args"] = locator
|
||||
return True
|
||||
|
||||
monkeypatch.setitem(g, "_click_dsv_continue", fake_click_continue)
|
||||
monkeypatch.setitem(g, "_is_dsv_password_upgrade_redirect", lambda page: False)
|
||||
monkeypatch.setitem(g, "_has_dsv_password_upgrade_prompt", lambda page, **kwargs: False)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt", lambda page: None)
|
||||
monkeypatch.setitem(g, "_dismiss_dsv_password_upgrade_prompt_after_login_redirect", lambda page: None)
|
||||
monkeypatch.setitem(g, "_find_dsv_password_locator", fake_find_password)
|
||||
monkeypatch.setitem(g, "_has_dsv_human_check_prompt", lambda page: False)
|
||||
monkeypatch.setitem(
|
||||
g, "_submit_dsv_password_form",
|
||||
lambda page: (state.__setitem__("submitted", True) or True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_debug_dsv_stage", lambda page, *args, **kwargs: None)
|
||||
monkeypatch.setitem(
|
||||
g, "_wait_for_dsv_home_ready_after_login",
|
||||
lambda page, **kwargs: state.__setitem__("home_ready", True),
|
||||
)
|
||||
monkeypatch.setitem(g, "_report_dsv_chain_stage", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_report_debug_event", lambda *args, **kwargs: None)
|
||||
monkeypatch.setitem(g, "_collect_dsv_reports_probe", lambda page: {})
|
||||
monkeypatch.setattr(g["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
ticks["value"] += 0.25
|
||||
return ticks["value"]
|
||||
|
||||
monkeypatch.setattr(g["time"], "monotonic", fake_monotonic)
|
||||
|
||||
worker._maybe_auto_login_dsv(_FakePage())
|
||||
|
||||
assert state["continue_args"] is None, "通用填装路径 username_locator 应显式为 None"
|
||||
assert state["submitted"] is True
|
||||
assert state["home_ready"] is True
|
||||
|
||||
|
||||
def test_find_dsv_password_locator_returns_visible_locator():
|
||||
"""密码方式切换轮询应走轻量密码框探测,而不是长时间通用等待。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
@@ -29,6 +29,7 @@ _RPA_MODULE_PATHS = {
|
||||
"dsv_auth": "connectors/dsv/dsv_auth.py",
|
||||
"dsv_session": "connectors/dsv/dsv_session.py",
|
||||
"dsv_debug": "connectors/dsv/dsv_debug.py",
|
||||
"dsv_report_parameters": "connectors/dsv/dsv_report_parameters.py",
|
||||
}
|
||||
|
||||
|
||||
@@ -449,6 +450,7 @@ def test_dsv_navigation_emits_elapsed_stage_logs(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
|
||||
worker._navigate_dsv_to_report_form(
|
||||
page,
|
||||
@@ -581,6 +583,7 @@ def test_navigate_dsv_to_report_form_retries_once_with_home_reset(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||
@@ -608,6 +611,7 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
chain = MagicMock()
|
||||
@@ -630,6 +634,177 @@ def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
|
||||
assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list)
|
||||
|
||||
|
||||
def _fake_dsv_page_with_frames(*frames):
|
||||
page = MagicMock()
|
||||
page.frames = list(frames)
|
||||
return page
|
||||
|
||||
|
||||
def _fake_dsv_frame(url: str, body: str):
|
||||
frame = MagicMock()
|
||||
frame.url = url
|
||||
frame.locator.return_value.inner_text.return_value = body
|
||||
return frame
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_passes_for_expected_program():
|
||||
"""SSRS viewer 标题含 program_label 时应判定打开了目标报表,直接放行。"""
|
||||
worker = _load_dsv_report_export()
|
||||
viewer = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/S360Reports/SSRS/f26275b5?token=x&isLegacy=true",
|
||||
"On Hand Inventory By Location AWS > Moerdijk > AWSRTM favorite_border",
|
||||
)
|
||||
page = _fake_dsv_page_with_frames(viewer)
|
||||
|
||||
worker._assert_dsv_report_viewer_identity(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||
timeout_ms=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_raises_on_wrong_program():
|
||||
"""viewer 载入 Bison 3lv(AWS > Bison > AWSBI)时应报身份不匹配。
|
||||
|
||||
2026-10-09 AWSRTM 事故回归:portal 顶层 Recent Reports 文本同样含 AWSRTM,
|
||||
门禁只认 /s360reports/ssrs/ viewer frame,顶层的 AWSRTM 字样不得误判为匹配。
|
||||
"""
|
||||
worker = _load_dsv_report_export()
|
||||
portal = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/main/portal/frame/reports/x",
|
||||
"RECENT REPORTS On Hand Inventory By Location (Moerdijk > AWSRTM)",
|
||||
)
|
||||
viewer = _fake_dsv_frame(
|
||||
"https://s360.dbschenker.com/S360Reports/SSRS/d40ada0a?token=x&isLegacy=true",
|
||||
"On Hand Inventory By Location 3lv AWS > Bison > AWSBI favorite_border",
|
||||
)
|
||||
page = _fake_dsv_page_with_frames(portal, viewer)
|
||||
|
||||
import pytest
|
||||
|
||||
with pytest.raises(RuntimeError, match="identity mismatch"):
|
||||
worker._assert_dsv_report_viewer_identity(
|
||||
page,
|
||||
{"navigation": {"program_label": "AWSRTM", "report_name": "On Hand Inventory by Location"}},
|
||||
timeout_ms=1000,
|
||||
)
|
||||
|
||||
|
||||
def test_assert_dsv_report_viewer_identity_skips_without_program_label():
|
||||
"""配置缺 program_label 时应跳过身份校验(保持旧行为,不因无身份信息而失败)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = _fake_dsv_page_with_frames()
|
||||
|
||||
worker._assert_dsv_report_viewer_identity(page, {"navigation": {"report_name": "X"}}, timeout_ms=1000)
|
||||
|
||||
|
||||
def test_navigate_dsv_to_report_form_resets_home_when_viewer_identity_mismatch(monkeypatch):
|
||||
"""viewer 载错报表(身份不匹配)时应整页 reset 后重导一次(2026-10-09 AWSRTM 串报修复)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
page = MagicMock()
|
||||
monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
|
||||
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
|
||||
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
identity = MagicMock(side_effect=[RuntimeError("identity mismatch"), None])
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", identity)
|
||||
reset = MagicMock()
|
||||
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
|
||||
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
|
||||
|
||||
source = {
|
||||
"entry_url": "https://s360.dbschenker.com/main/portal",
|
||||
"navigation": {
|
||||
"program_group": "Moerdijk",
|
||||
"program_label": "AWSRTM",
|
||||
"report_group": "Inventory",
|
||||
"report_name": "On Hand Inventory by Location",
|
||||
},
|
||||
}
|
||||
assert worker._navigate_dsv_to_report_form(page, source) == "On Hand Inventory by Location"
|
||||
assert identity.call_count == 2
|
||||
reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal")
|
||||
|
||||
|
||||
def test_fill_dsv_filter_returns_false_when_all_paths_fail(monkeypatch):
|
||||
"""配置了值但 multi_value/select/脚本/fill 全部失败时应返回 False(FILL-FAIL-FAST 契约)。"""
|
||||
params = _load_rpa_module("dsv_report_parameters")
|
||||
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||
monkeypatch.setattr(params, "_probe_report_parameter_controls", lambda page: {})
|
||||
|
||||
result = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
assert result is False
|
||||
|
||||
|
||||
def test_fill_dsv_filter_returns_true_on_success_and_legitimate_skip(monkeypatch):
|
||||
"""填充成功或合法跳过(值为空)应返回 True,不得被包装层误判为失败。"""
|
||||
params = _load_rpa_module("dsv_report_parameters")
|
||||
# JDA 模板下 Warehouse 是 multi_value 控件:mock 主路径成功即可验证 True 契约。
|
||||
monkeypatch.setattr(params, "_fill_multi_value_parameter", MagicMock(return_value=True))
|
||||
monkeypatch.setattr(params, "_fill_select_parameter", MagicMock(return_value=False))
|
||||
monkeypatch.setattr(params, "_iter_dsv_report_roots", lambda page: [])
|
||||
monkeypatch.setattr(params, "_find_locator", lambda page, selector: (None, None))
|
||||
|
||||
filled = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
skipped = params.fill_dsv_filter_if_needed(
|
||||
MagicMock(),
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
None,
|
||||
env=lambda key, default=None: "",
|
||||
browser_timeout_ms=lambda: 1000,
|
||||
report_name="On Hand Inventory by Location",
|
||||
)
|
||||
assert filled is True
|
||||
assert skipped is True
|
||||
|
||||
|
||||
def test_fill_dsv_filter_wrapper_raises_on_fill_failure(monkeypatch):
|
||||
"""包装层在 fill 返回 False 时必须抛错中止本源(2026-10-09 静默吞掉曾连环误报)。"""
|
||||
worker = _load_dsv_report_export()
|
||||
fake_module = MagicMock()
|
||||
fake_module.fill_dsv_filter_if_needed.return_value = False
|
||||
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||
|
||||
import pytest
|
||||
|
||||
with pytest.raises(RuntimeError, match="fill failed"):
|
||||
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||
|
||||
|
||||
def test_fill_dsv_filter_wrapper_silent_on_fill_success(monkeypatch):
|
||||
"""fill 返回 True(已填充/合法跳过)时包装层不得抛错。"""
|
||||
worker = _load_dsv_report_export()
|
||||
fake_module = MagicMock()
|
||||
fake_module.fill_dsv_filter_if_needed.return_value = True
|
||||
monkeypatch.setattr(worker.importlib.util, "spec_from_file_location", lambda *a, **k: MagicMock())
|
||||
monkeypatch.setattr(worker.importlib.util, "module_from_spec", lambda *a, **k: fake_module)
|
||||
|
||||
worker._fill_dsv_filter_if_needed(MagicMock(), "ENV", "Warehouse", "RTM")
|
||||
|
||||
|
||||
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
|
||||
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
|
||||
worker = _load_dsv_report_export()
|
||||
@@ -696,6 +871,7 @@ def test_navigate_dsv_to_report_form_clicks_program_group_before_program_label(m
|
||||
lambda page_arg, text, *, next_text="": group_calls.append((text, next_text)),
|
||||
)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
|
||||
monkeypatch.setattr(worker, "_assert_dsv_report_viewer_identity", MagicMock())
|
||||
|
||||
source = {
|
||||
"navigation": {
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
"""
|
||||
tests/test_line_inventory_match_persistence.py
|
||||
|
||||
用途:锁定 disposition → match_result 映射与 not_found/invalid_key 语义。
|
||||
依赖:pytest、line_inventory_match_persistence。
|
||||
逻辑:纯单元;不写库。
|
||||
用途:锁定 disposition → match_result 映射、not_found/invalid_key 语义,
|
||||
及行级匹配事实落库契约(含料号兜底总量 part_available_qty)。
|
||||
依赖:pytest、line_inventory_match_persistence、app 夹具(persist 用例)。
|
||||
逻辑:映射用例纯单元;persist 用例写库(内存测试库),不触外部集成。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_persistence import (
|
||||
map_disposition_to_match_codes,
|
||||
persist_line_inventory_match_facts,
|
||||
)
|
||||
|
||||
|
||||
@@ -54,3 +56,134 @@ def test_ok_and_shortage_are_matched_ready():
|
||||
assert map_disposition_to_match_codes(
|
||||
disposition='shortage', part_number='A', reservation_id='B',
|
||||
) == ('matched', 'ready')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# persist_line_inventory_match_facts 落库契约(依赖 app 夹具,写内存测试库)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _make_snapshot_task(task_no: str):
|
||||
"""
|
||||
构造含两行冻结快照的 OT 任务,供 persist 落库测试复用。
|
||||
|
||||
核心逻辑:持久化按 order_snapshot_id → ShippingOrderSnapshot.lines 的 line_no
|
||||
解析 snapshot_line_id;第 1 行料号/预约号齐全,第 2 行缺料号
|
||||
(对齐匹配器「缺料号行不下发 part_available_qty 键」的真实产出,见
|
||||
test_shipping_stp_phase4_line_inventory_match.py 的兜底总量用例)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask
|
||||
|
||||
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=1,
|
||||
schema_version_id=1,
|
||||
order_data_version=1,
|
||||
rule_versions_json={},
|
||||
source_manifest_json={},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
lines = [
|
||||
{'line_no': 1, 'part_number': 'PN-1', 'reservation_id': '3000092917', 'qty': 8},
|
||||
{'line_no': 2, 'part_number': None, 'reservation_id': '3000092918', 'qty': 1},
|
||||
]
|
||||
for position, line in enumerate(lines):
|
||||
db.session.add(
|
||||
ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=position,
|
||||
line_no=line['line_no'],
|
||||
part_number=line['part_number'],
|
||||
reservation_id=line['reservation_id'],
|
||||
qty=line['qty'],
|
||||
field_values_json={},
|
||||
)
|
||||
)
|
||||
task.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _not_found_result(*, part_available_qty, line_index: int = 0) -> dict:
|
||||
"""
|
||||
构造 not_found 行结果桩。
|
||||
|
||||
核心逻辑:part_available_qty 传 None 时**不下发该键**(而非显式 None),
|
||||
对齐匹配器对 conflict/缺料号行「无键即无兜底」的契约;持久化必须按
|
||||
无键 → NULL 处理。
|
||||
"""
|
||||
result = {
|
||||
'line_index': line_index,
|
||||
'disposition': 'not_found',
|
||||
'part_number': 'PN-1',
|
||||
'reservation_id': '3000092917',
|
||||
'required_qty': 8.0,
|
||||
'available_qty': 0.0,
|
||||
}
|
||||
if part_available_qty is not None:
|
||||
result['part_available_qty'] = part_available_qty
|
||||
return result
|
||||
|
||||
|
||||
def test_persist_writes_part_available_qty_for_not_found_line(app):
|
||||
"""预约不匹配行的料号兜底总量必须随匹配事实落库。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-PART-AVAILABLE-NEW')
|
||||
match_payload = {
|
||||
'line_results': [
|
||||
_not_found_result(part_available_qty=8.0),
|
||||
_not_found_result(part_available_qty=None, line_index=1),
|
||||
],
|
||||
'resolutions': [],
|
||||
}
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload=match_payload,
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
# 断言意图:兜底总量字符串化落列
|
||||
assert str(rows[0].part_available_qty) == '8.0'
|
||||
# 断言意图:无键/None 时必须落 NULL 而非 'None'
|
||||
assert rows[1].part_available_qty is None
|
||||
|
||||
|
||||
def test_persist_updates_part_available_qty_on_existing_row(app):
|
||||
"""同快照幂等更新时,料号兜底总量必须以最新匹配结果为准。"""
|
||||
with app.app_context():
|
||||
task = _make_snapshot_task('OT-PART-AVAILABLE-UPDATE')
|
||||
persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=8.0)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=13.0)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
# 断言意图:更新分支同样把新兜底总量字符串化落列
|
||||
assert str(rows[0].part_available_qty) == '13.0'
|
||||
# 断言意图:更新时键缺失 → 回写 NULL,不得残留旧值或 'None'
|
||||
rows = persist_line_inventory_match_facts(
|
||||
task=task,
|
||||
match_payload={
|
||||
'line_results': [_not_found_result(part_available_qty=None)],
|
||||
'resolutions': [],
|
||||
},
|
||||
inventory_snapshot_id=None,
|
||||
)
|
||||
assert rows[0].part_available_qty is None
|
||||
# 断言意图:同快照幂等更新,始终只有一条 current 事实
|
||||
assert len(rows) == 1
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.line_inventory_match_projection import (
|
||||
ACTION_CLOSE,
|
||||
ACTION_RELEASE_SHORTAGE,
|
||||
ACTION_RETRY_MATCHING,
|
||||
ACTION_RETRY_PREPARATION,
|
||||
normalize_match_quantities,
|
||||
@@ -116,7 +117,9 @@ def test_shortage_actions_preparation_and_close_only():
|
||||
user_line_status='shortage',
|
||||
)
|
||||
assert inv == [ACTION_RETRY_PREPARATION]
|
||||
assert line == [ACTION_CLOSE]
|
||||
# 断言意图(既有用例修复):对齐已上线契约(eed1068ae)——短缺行除关闭外
|
||||
# 同时下发 release_inventory_shortage(填写原因放行),本用例原断言已过期。
|
||||
assert line == [ACTION_CLOSE, ACTION_RELEASE_SHORTAGE]
|
||||
|
||||
|
||||
def test_wave_created_hides_line_actions():
|
||||
@@ -204,3 +207,28 @@ def test_user_status_maps_closed_and_system_ready():
|
||||
stored_line_status='ready_to_fulfill',
|
||||
decision_source='system',
|
||||
) == 'auto_fulfilling'
|
||||
|
||||
|
||||
def test_view_exposes_part_available_qty_gated_by_ready():
|
||||
"""料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。"""
|
||||
base = {
|
||||
'match_result': 'not_found', 'inventory_status': 'ready',
|
||||
'required_qty': '8', 'available_qty': None,
|
||||
'inventory_snapshot_id': 1, 'matched_at': None,
|
||||
'inventory_source_code': 'DSV', 'detail_json': {},
|
||||
}
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。
|
||||
assert view['available_qty'] == '0'
|
||||
assert view['part_available_qty'] == '9'
|
||||
pending = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。
|
||||
assert pending['part_available_qty'] is None
|
||||
@@ -891,6 +891,31 @@ def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_read
|
||||
assert preparation["has_match_result"] is False
|
||||
|
||||
|
||||
def test_preparation_lines_carry_part_available_qty(app) -> None:
|
||||
"""prep 行必须下发料号兜底总量,供前端新增「可用数量」列。"""
|
||||
with app.app_context():
|
||||
task, line = _frozen_task_with_line(
|
||||
task_no="OT-UI-PART-AVAILABLE",
|
||||
reservation_id="RSV-PART-AVAIL",
|
||||
part_number="PN-PART-AVAIL",
|
||||
qty="8",
|
||||
)
|
||||
# 行 Match 事实:required '8'、part_available_qty='9'(允许源内、忽略预约号与单位的料号总可用量)。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
|
||||
match_result="matched", inventory_status="ready", required_qty="8",
|
||||
available_qty="9", matched_qty="9", shortage_qty="0", part_available_qty="9",
|
||||
reservation_id="RSV-PART-AVAIL", part_number="PN-PART-AVAIL",
|
||||
inventory_source_code="DBS_DUB", is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
state = build_task_ui_state(task, include_stage_context=True)
|
||||
prep_line = state["stage_context"]["preparation"]["lines"][0]
|
||||
# 断言意图:ui_state 单源直透投影值,前端不做二次推导;不下发任何派生布尔标志。
|
||||
assert prep_line["part_available_qty"] == "9"
|
||||
|
||||
|
||||
def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_path) -> None:
|
||||
"""库存文件下载只能读取当前任务 active link 指向的托管文件,禁止按库存源或订单猜测文件。"""
|
||||
from app.models import ShippingInventoryFile, ShippingTaskInventoryLink
|
||||
|
||||
@@ -459,6 +459,56 @@ def test_refresh_pointers_keeps_invalidated_when_downstream_still_passed(gate_ex
|
||||
assert gate_execution.status == 'blocked'
|
||||
|
||||
|
||||
def test_refresh_pointers_bumps_task_progress_version_without_notice(gate_execution):
|
||||
"""无 Notice 绑定时 Gate 指针事实变化必须递增 OT progress_version。
|
||||
|
||||
复现:通知准备/库存匹配阶段 Notice 尚未生成,历史实现只回填 stage、不推进版本;
|
||||
统一投影 progress_version 冻结导致工作台 [REFRESH_ON_CHANGE] 永不重拉任务详情,
|
||||
RPA 重取成功后行级可用数量/缺口停留在旧快照(界面显示「库存文件未准备」)。
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from app.services.shipping_notice import process_gate_service
|
||||
|
||||
task = db.session.get(ShippingOrderTask, int(gate_execution.task_id))
|
||||
version_before = int(task.progress_version or 1)
|
||||
|
||||
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
for gate in ShippingProcessGate.query.filter_by(execution_id=int(gate_execution.id)).all():
|
||||
if gate.gate_code in {
|
||||
'document_materialization', 'layout_parsing', 'document_profile_routing',
|
||||
'order_field_extraction', 'field_completeness', 'reservation_validation',
|
||||
'customer_resolution', 'duplicate_detection', 'field_conflict_resolution',
|
||||
'task_creation', 'order_freeze_readiness', 'inventory_source_routing',
|
||||
'inventory_preparation', 'inventory_field_mapping', 'inventory_matching',
|
||||
}:
|
||||
gate.status = 'passed'
|
||||
gate.passed_at = now
|
||||
elif gate.gate_code == 'inventory_sufficiency':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'inventory_shortage_review_required'
|
||||
gate.next_action_code = 'open_shortage_review'
|
||||
elif gate.gate_code == 'excel_readiness':
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'excel_not_ready'
|
||||
# 其余保持 pending
|
||||
db.session.flush()
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
# 关键断言:缺口落定属于真实事实变化,无 Notice 也必须经中央写入口推进版本。
|
||||
assert gate_execution.current_gate_code == 'inventory_sufficiency'
|
||||
assert gate_execution.status == 'blocked'
|
||||
assert int(task.progress_version or 1) == version_before + 1
|
||||
|
||||
process_gate_service._refresh_execution_pointers(gate_execution)
|
||||
db.session.flush()
|
||||
|
||||
# 关键断言:事实未变的重复刷新不得递增版本,避免轮询期被放大成详情刷新风暴。
|
||||
assert int(task.progress_version or 1) == version_before + 1
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -519,6 +519,29 @@ def test_waiting_human_without_reconcile_action_has_no_false_primary_action():
|
||||
assert payload['primary_action'] is None
|
||||
|
||||
|
||||
def test_in_flight_gate_projects_running_not_waiting_human():
|
||||
"""RPA 在途(Gate waiting_external)必须投影 running,不得误报待人工。
|
||||
|
||||
Notice 生成前 OT.status 停留在建单前的 waiting_review;若在途期被投影成
|
||||
waiting_human,前端会把任务当终态停止投影轮询,RPA 回调完成将永远无法被
|
||||
感知(库存匹配表格冻结在「库存文件未准备」)。与门禁契约
|
||||
GATE_STATUS_TO_USER_STATUS['waiting_external']=='running' 对齐。
|
||||
"""
|
||||
payload = apply_user_projection_fields({
|
||||
'status': 'waiting_review',
|
||||
'stage': 'inventory_preparation',
|
||||
'source_type': 'order_task',
|
||||
'current_gate': {
|
||||
'gate_code': 'inventory_preparation',
|
||||
'status': 'waiting_external',
|
||||
},
|
||||
'available_actions': [],
|
||||
})
|
||||
|
||||
# 关键断言:Gate 在途 = 系统处理中;待人工只属于 blocked_manual 等人工阻断。
|
||||
assert payload['user_status'] == 'running'
|
||||
|
||||
|
||||
def test_apply_user_projection_fields_fail_closes_inconsistent_projection():
|
||||
"""事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。"""
|
||||
payload = apply_user_projection_fields({
|
||||
|
||||
@@ -4,7 +4,9 @@ tests/test_shipping_review_line_fulfillment_decision.py
|
||||
用途:行级履约决定的库存安全、reopen 约束与审计参数契约测试。
|
||||
依赖:pytest、order_review_fulfillment_decision_service。
|
||||
逻辑:覆盖库存不足禁止先行、task_created 禁止 reopen、管理员重开边界、
|
||||
数量解析与评估助手;不依赖完整建单 Fixture。
|
||||
数量解析与评估助手;以及缺口放行证据字段按「预约号+料号」筛快照、
|
||||
预约键 0 行命中时按料号键兜底重筛(evidence_scope=part_fallback)与
|
||||
放行全量字段值落库契约;不依赖完整建单 Fixture。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,6 +30,7 @@ from app.services.shipping_notice.order_review_fulfillment_decision_service impo
|
||||
_release_template_system_fields,
|
||||
_release_fact_identity,
|
||||
_resolve_shortage_release_inventory_source,
|
||||
_shortage_release_required_fields,
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
_is_shortage_match_fact,
|
||||
_has_terminal_inventory_rpa_failure,
|
||||
@@ -616,3 +619,610 @@ def test_project_empty_case_without_draft(app):
|
||||
result = project_review_case_line_decisions(case)
|
||||
assert result['lines'] == []
|
||||
assert result['has_open_lines'] is False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [Task 6] 缺口料号兜底:放行证据字段按「预约号+料号」筛库存快照;预约键 0 行命中
|
||||
# 时按料号键重筛带出(evidence_scope=part_fallback,审计可见),并落全量模板字段值。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
*,
|
||||
inventory_rows: list[dict[str, str]] | None = None,
|
||||
order_reservation_id: str = 'R-ORDER',
|
||||
order_part_number: str = 'ODM-001',
|
||||
required_qty: str = '10',
|
||||
part_available_qty: str | None = None,
|
||||
):
|
||||
"""
|
||||
构造放行字段判定夹具:「预约号+料号」匹配方案 + 行级库存快照 + 模板消费 ODM 字段。
|
||||
|
||||
核心逻辑:复用 conftest 种子源 DSV360_AWSDU(profile.match_keys=part_number +
|
||||
reservation_id,订单键 test-order-part-number / test-order-reservation-id),
|
||||
订单行预约号默认 'R-ORDER';库存快照行预约号默认 'R-INV'(≠订单)以制造
|
||||
预约键 0 行命中、料号键可命中的兜底场景。同时落一条真实行匹配事实
|
||||
(not_found 且指向本快照),供 decide 放行分支走真实模型查询。
|
||||
|
||||
Args:
|
||||
inventory_rows: 库存快照行(语义键 part / reservation / odm);
|
||||
None 时默认单行且 odm 值唯一('ODM-VAL')。
|
||||
required_qty: 行需求量(默认 '10' 保持 Task 6 口径)。
|
||||
part_available_qty: 匹配器下发的料号兜底总量;None 时不落列
|
||||
(自动放行服务视为不可判定并跳过,Task 7 使用)。
|
||||
|
||||
Returns:
|
||||
(task, inventory_file, odm_field)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventorySource,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
|
||||
part_field = ShippingInventoryField.query.filter_by(field_code='part_number').one()
|
||||
reservation_field = ShippingInventoryField.query.filter_by(field_code='reservation_id').one()
|
||||
odm_field = ShippingInventoryField.query.filter_by(field_code='odm_id').one()
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
template = db.session.get(ShippingExcelTemplate, int(source.excel_template_id))
|
||||
assert template is not None
|
||||
# 发货模板只消费 ODM 字段:该字段在快照行上的唯一值即放行自动带出的证据值。
|
||||
template.definition_json = {
|
||||
'mappings': [
|
||||
{'row_mode': 'line', 'source_kind': 'inventory_field', 'source_key': str(odm_field.id)},
|
||||
],
|
||||
}
|
||||
|
||||
user = User(username='part-fallback', email='part-fallback@example.com')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema(schema_code='PART_FALLBACK', display_name='Part Fallback')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
schema_version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
definition_json={'fields': []},
|
||||
)
|
||||
db.session.add(schema_version)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-PART-FALLBACK',
|
||||
user_id=user.id,
|
||||
stage='inventory_matching',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=1,
|
||||
schema_version_id=schema_version.id,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
# 订单行 match-key 值必须写入 field_values_json(键 = match_keys.order_field_id)。
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
reservation_id=order_reservation_id,
|
||||
part_number=order_part_number,
|
||||
qty=required_qty,
|
||||
field_values_json={
|
||||
'test-order-part-number': order_part_number,
|
||||
'test-order-reservation-id': order_reservation_id,
|
||||
},
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
|
||||
rows = [
|
||||
{
|
||||
str(part_field.id): str(row.get('part') or ''),
|
||||
str(reservation_field.id): str(row.get('reservation') or ''),
|
||||
str(odm_field.id): str(row.get('odm') or ''),
|
||||
}
|
||||
for row in (inventory_rows if inventory_rows is not None else [
|
||||
{'part': order_part_number, 'reservation': 'R-INV', 'odm': 'ODM-VAL'},
|
||||
])
|
||||
]
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-PART-FALLBACK',
|
||||
storage_path='test/part-fallback.xlsx',
|
||||
source_file_name='part-fallback.xlsx',
|
||||
source_code='DSV360_AWSDU',
|
||||
snapshot_status='ready',
|
||||
inventory_lines_json=rows,
|
||||
line_count=len(rows),
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
|
||||
# 放行资格走真实模型查询:行匹配事实 = not_found(库存不足),指向本快照与本库存源。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
match_result='not_found',
|
||||
inventory_status='ready',
|
||||
required_qty=required_qty,
|
||||
available_qty='0',
|
||||
matched_qty='0',
|
||||
shortage_qty=required_qty,
|
||||
part_available_qty=part_available_qty,
|
||||
reservation_id=order_reservation_id,
|
||||
part_number=order_part_number,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.commit()
|
||||
return task, inventory_file, odm_field
|
||||
|
||||
|
||||
def _decide_release_with_captured_snapshot(app, monkeypatch, *, task):
|
||||
"""
|
||||
经 decide_review_line_fulfillment 公开路径提交放行(预约不匹配场景),捕获落库快照。
|
||||
|
||||
核心逻辑:Case/草稿/决定行为进程内替身;放行分支真实执行(真实行匹配事实 +
|
||||
真实 _shortage_release_required_fields + 真实校验),Gate 重算、审计写库与
|
||||
resume/投影替身化,隔离外部副作用。提交 release_field_values={},
|
||||
用于证明自动带出值无须人工输入即可落库。
|
||||
|
||||
Returns:
|
||||
captured:决定行构造 kwargs(含 snapshot_json 全量内容)。
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice import order_review_fulfillment_decision_service as svc
|
||||
|
||||
draft = SimpleNamespace(
|
||||
draft_version=1,
|
||||
lines_json=[{
|
||||
'draft_line_id': 'L1',
|
||||
'qty': '10',
|
||||
'reservation_id': 'R-ORDER',
|
||||
'part_number': 'ODM-001',
|
||||
}],
|
||||
validation_result_json={'line_projections': [{'draft_line_id': 'L1', 'available_qty': '0'}]},
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
id=1,
|
||||
case_no='CASE-PART-FALLBACK',
|
||||
status='ready',
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='RUN-1'),
|
||||
confirmed_task_id=int(task.id),
|
||||
)
|
||||
row = SimpleNamespace(
|
||||
id=None,
|
||||
draft_line_id='L1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
decision_source='user',
|
||||
line_status='released_shortage',
|
||||
is_active=True,
|
||||
reason=None,
|
||||
required_qty='10',
|
||||
available_qty='0',
|
||||
reservation_id='R-ORDER',
|
||||
part_number='ODM-001',
|
||||
task_id=None,
|
||||
wave_no=None,
|
||||
actor_user_id=1,
|
||||
snapshot_json={},
|
||||
created_at=None,
|
||||
updated_at=None,
|
||||
)
|
||||
captured = {}
|
||||
|
||||
monkeypatch.setattr(svc, '_load_writable_case', lambda **kwargs: case)
|
||||
monkeypatch.setattr(svc, '_active_decision', lambda *args, **kwargs: None)
|
||||
monkeypatch.setattr(svc, '_next_version', lambda *args, **kwargs: 1)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'ShippingOrderReviewLineDecision',
|
||||
lambda **kwargs: (captured.update(kwargs), row)[1],
|
||||
)
|
||||
monkeypatch.setattr(svc.db.session, 'add', lambda value: None)
|
||||
monkeypatch.setattr(svc.db.session, 'flush', lambda: setattr(row, 'id', 42))
|
||||
# [STEP] 放行后 Gate 同步会重算任务履约态;测试中替身化重算与审计/resume/投影副作用。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||
lambda task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.resume_after_review_change',
|
||||
lambda **kwargs: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_resume_service.attach_resume_outcome',
|
||||
lambda payload, resume: payload,
|
||||
)
|
||||
monkeypatch.setattr(svc, '_get_soft_loader', lambda: (lambda **kwargs: case))
|
||||
monkeypatch.setattr(svc, 'project_review_case_line_decisions', lambda value: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_review_projection.serialize_review_case',
|
||||
lambda value: {},
|
||||
)
|
||||
|
||||
result = svc.decide_review_line_fulfillment(
|
||||
user_id=1,
|
||||
case_no=case.case_no,
|
||||
draft_line_id='L1',
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
reason='库存缺口按料号兜底放行',
|
||||
expected_draft_version=1,
|
||||
release_field_values={},
|
||||
)
|
||||
# 断言意图:决定行已分配主键并完成落库流程(flush 替身回填)。
|
||||
assert result['decision']['id'] == 42
|
||||
return captured
|
||||
|
||||
|
||||
def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses(app):
|
||||
"""预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual),
|
||||
# 且证据范围显式标记为 part_fallback(审计可见)。
|
||||
assert scope == 'part_fallback'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': 'ODM-VAL',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_part_fallback_still_manual_when_values_ambiguous(app):
|
||||
"""料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:scope 仍标记 part_fallback(确按料号重筛),但分歧字段禁止任取值,
|
||||
# 必须回退为人工必填、值为空。
|
||||
assert scope == 'part_fallback'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': None,
|
||||
'value_source': 'manual_required',
|
||||
'requires_manual': True,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_reservation_hit_keeps_inventory_snapshot_scope(app):
|
||||
"""预约号+料号同时命中时不得误标兜底,证据范围必须保持 inventory_snapshot。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-ORDER', 'odm': 'ODM-VAL'},
|
||||
],
|
||||
)
|
||||
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=0,
|
||||
inventory_snapshot_id=inventory_file.id,
|
||||
inventory_source_code='DSV360_AWSDU',
|
||||
)
|
||||
|
||||
# 断言意图:预约命中场景 scope 恒为 inventory_snapshot,字段照常自动带值。
|
||||
assert scope == 'inventory_snapshot'
|
||||
assert fields == [{
|
||||
'field_id': str(odm_field.id),
|
||||
'display_name': 'ODM 编号',
|
||||
'value': 'ODM-VAL',
|
||||
'value_source': 'inventory_snapshot',
|
||||
'requires_manual': False,
|
||||
}]
|
||||
|
||||
|
||||
def test_shortage_release_decision_records_part_fallback_scope(app, monkeypatch):
|
||||
"""放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」——scope 落在
|
||||
# 决定审计快照 snapshot_json['release_evidence_scope'](导出/审计同源读取)。
|
||||
assert captured['snapshot_json']['release_evidence_scope'] == 'part_fallback'
|
||||
|
||||
|
||||
def test_shortage_release_persists_full_template_field_values(app, monkeypatch):
|
||||
"""落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(app)
|
||||
captured = _decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读
|
||||
# snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空;
|
||||
# 全部字段自动带出时人工必填清单为空、人工提交为空 dict 仍可放行。
|
||||
assert captured['snapshot_json']['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||
assert captured['snapshot_json']['release_required_fields'] == []
|
||||
|
||||
|
||||
def test_shortage_release_part_fallback_still_requires_manual_fill_on_decide(app, monkeypatch):
|
||||
"""料号兜底分歧字段未人工补录时,公开 decide 路径仍必须 409(fail-closed 不回退)。"""
|
||||
with app.app_context():
|
||||
task, inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-A', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': 'R-INV-B', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
_decide_release_with_captured_snapshot(app, monkeypatch, task=task)
|
||||
|
||||
# 断言意图:兜底只解决「能唯一取值」的补录;分歧字段缺失人工补录仍按原契约拒绝。
|
||||
assert exc.value.code == 'SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [Task 7] 料号兜底自动放行:料号总量满足需求时,匹配完成后缺口行由系统自动放行
|
||||
# (decision_source='system'、snapshot.auto_release=True、scope=part_fallback);
|
||||
# 量不足 / 证据分歧 / 已有活动决定一律跳过并维持人工路径(fail-closed)。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_auto_release_fixture(
|
||||
app,
|
||||
*,
|
||||
required_qty: str = '8',
|
||||
part_available_qty: str = '9',
|
||||
inventory_rows: list[dict[str, str]] | None = None,
|
||||
):
|
||||
"""
|
||||
构造自动放行端到端夹具:真实 OT/快照行/行事实(part_available_qty)/复核 Case+草稿。
|
||||
|
||||
核心逻辑:复用 Task 6 seed(预约号改用 10 位纯数字域契约值;订单预约号与库存行
|
||||
预约号不同 → 预约键 0 行命中、料号键命中),再落一条真实 Review Case 与草稿
|
||||
(与既有投影测试同构:run/unit/document 用悬挂占位 ID),使自动放行可走真实的
|
||||
Case 反查、草稿行定位、决定落库与门禁满足性查询。
|
||||
|
||||
Returns:
|
||||
(task, case, odm_field)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderSnapshot
|
||||
|
||||
task, _inventory_file, odm_field = _seed_part_fallback_release_fixture(
|
||||
app,
|
||||
inventory_rows=inventory_rows,
|
||||
order_reservation_id='3000112934',
|
||||
required_qty=required_qty,
|
||||
part_available_qty=part_available_qty,
|
||||
)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='CASE-AUTO-RELEASE', run_id=921, unit_id=922, document_id=923,
|
||||
owner_user_id=int(task.user_id), status='confirmed', confirmed_task_id=task.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=int(snapshot.schema_version_id),
|
||||
header_values_json={},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'line-1',
|
||||
'qty': required_qty,
|
||||
'reservation_id': '3000112934',
|
||||
'part_number': 'ODM-001',
|
||||
}],
|
||||
validation_result_json={'line_projections': [
|
||||
{'draft_line_id': 'line-1', 'available_qty': '0'},
|
||||
]},
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
db.session.commit()
|
||||
return task, case, odm_field
|
||||
|
||||
|
||||
def _patch_auto_release_side_effects(monkeypatch, *, stub_recompute: bool = True) -> list[dict]:
|
||||
"""
|
||||
替身化自动放行的编排副作用(与 Task 6 decide 测试同口径)。
|
||||
|
||||
Args:
|
||||
stub_recompute: True 时替身化任务履约态重算;False 保留真实重算
|
||||
(供门禁满足性测试走完整「放行→重算→sufficiency 放行」链路)。
|
||||
|
||||
Returns:
|
||||
auto_fulfill_jobs:enqueue_post_ot_auto_fulfill_job 捕获列表。
|
||||
"""
|
||||
if stub_recompute:
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.recompute_task_fulfillment_state',
|
||||
lambda task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit',
|
||||
lambda **kwargs: None,
|
||||
)
|
||||
auto_fulfill_jobs: list[dict] = []
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||
lambda **kwargs: auto_fulfill_jobs.append(kwargs),
|
||||
)
|
||||
return auto_fulfill_jobs
|
||||
|
||||
|
||||
def _active_auto_release_decisions(case):
|
||||
"""读取该 Case 活动的 release_inventory_shortage 决定(真实模型查询)。"""
|
||||
from app.models import ShippingOrderReviewLineDecision
|
||||
|
||||
return (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.filter_by(
|
||||
review_case_id=int(case.id),
|
||||
decision_code=DECISION_RELEASE_SHORTAGE,
|
||||
is_active=True,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def test_auto_release_runs_after_match_when_part_total_satisfies(app, monkeypatch):
|
||||
"""料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、
|
||||
# 模板字段(ODM)可由料号命中的快照行唯一取值。
|
||||
task, case, odm_field = _seed_auto_release_fixture(app)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。
|
||||
assert released == [0]
|
||||
decisions = _active_auto_release_decisions(case)
|
||||
assert len(decisions) == 1
|
||||
decision = decisions[0]
|
||||
assert decision.decision_source == 'system'
|
||||
assert decision.snapshot_json['auto_release'] is True
|
||||
assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback'
|
||||
# 自动带出值必须落库(导出覆盖唯一来源),与人工 decide 放行同契约。
|
||||
assert decision.snapshot_json['release_field_values'] == {str(odm_field.id): 'ODM-VAL'}
|
||||
assert decision.snapshot_json['release_required_fields'] == []
|
||||
|
||||
|
||||
def test_auto_release_skips_when_part_total_below_required(app, monkeypatch):
|
||||
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 同上构造,但料号总量改为 3(< 8)。
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app, part_available_qty='3')
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。
|
||||
assert released == []
|
||||
assert _active_auto_release_decisions(case) == []
|
||||
|
||||
|
||||
def test_auto_release_skips_when_evidence_field_ambiguous(app, monkeypatch):
|
||||
"""证据字段无法唯一取值(requires_manual 残留)时不得自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
# 同上构造,但两条同料号快照行在模板字段(ODM)上取值不同。
|
||||
task, case, _odm_field = _seed_auto_release_fixture(
|
||||
app,
|
||||
inventory_rows=[
|
||||
{'part': 'ODM-001', 'reservation': '3000420001', 'odm': 'ODM-V1'},
|
||||
{'part': 'ODM-001', 'reservation': '3000420002', 'odm': 'ODM-V2'},
|
||||
],
|
||||
)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:降级为人工放行(补录要求保留),不产生自动决定。
|
||||
assert released == []
|
||||
assert _active_auto_release_decisions(case) == []
|
||||
|
||||
|
||||
def test_auto_release_does_not_duplicate_existing_decision(app, monkeypatch):
|
||||
"""已有人工放行/结案决定(或已放行)的行不得重复自动放行。"""
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task, case, _odm_field = _seed_auto_release_fixture(app)
|
||||
_patch_auto_release_side_effects(monkeypatch)
|
||||
|
||||
first = auto_release_part_fallback_shortages(task)
|
||||
second = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:幂等——不新建第二个活动决定,原决定保持不变。
|
||||
assert first == [0]
|
||||
assert second == []
|
||||
assert len(_active_auto_release_decisions(case)) == 1
|
||||
|
||||
|
||||
def test_auto_release_counted_in_sufficiency_and_gate_releases(app, monkeypatch):
|
||||
"""自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。"""
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_recompute_task_match_aggregate,
|
||||
match_completed,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
with app.app_context():
|
||||
task, _case, _odm_field = _seed_auto_release_fixture(app)
|
||||
# 保留真实 recompute:完整走「放行落库 → 任务履约态重算 → 满足性门禁」链路。
|
||||
_patch_auto_release_side_effects(monkeypatch, stub_recompute=False)
|
||||
|
||||
# 放行前:缺口行未放行 → 整单不满足。
|
||||
assert match_completed(task) is False
|
||||
|
||||
released = auto_release_part_fallback_shortages(task)
|
||||
|
||||
# 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过,
|
||||
# inventory_sufficiency 不再因该行 blocked_manual。
|
||||
assert released == [0]
|
||||
assert match_completed(task) is True
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
line_results = task.step_payload_json['current_match_projection']['line_results']
|
||||
assert line_results[0]['line_status'] == 'released'
|
||||
@@ -236,3 +236,55 @@ def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monke
|
||||
assert task.review_status == 'shortage_review'
|
||||
assert task.pending_human_reason == 'shortage'
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'shortage'
|
||||
|
||||
|
||||
def test_system_auto_release_decision_counts_as_released(app):
|
||||
"""系统自动放行(decision_source='system')的活动决定必须被满足性门禁按放行读取。
|
||||
|
||||
核心逻辑:料号兜底自动放行(Task 7)落库的 release_inventory_shortage 决定
|
||||
decision_source='system';``_released_snapshot_line_ids_for_task`` 的真实查询
|
||||
(不经测试 seam)必须同等识别,match_completed / 聚合重算才能把放行行计入满足。
|
||||
"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewDraft, ShippingOrderReviewLineDecision
|
||||
from app.services.shipping_notice.fulfillment_workflow import _recompute_task_match_aggregate
|
||||
|
||||
with app.app_context():
|
||||
task = _task_with_current_matches(
|
||||
task_no='SN-AUTO-RELEASE-GATE',
|
||||
rows=[{'match_result': 'not_found', 'shortage_qty': '1'}],
|
||||
)
|
||||
# 放行前:缺口行未放行 → 整单不满足。
|
||||
assert match_completed(task) is False
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-AUTO-RELEASE-GATE', run_id=931, unit_id=932, document_id=933,
|
||||
owner_user_id=task.user_id, status='confirmed', confirmed_task_id=task.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=1,
|
||||
header_values_json={},
|
||||
lines_json=[{'draft_line_id': 'line-1', 'qty': '1', 'reservation_id': '3000112934'}],
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=int(case.id),
|
||||
draft_line_id='line-1',
|
||||
line_index=0,
|
||||
decision_version=1,
|
||||
decision_code='release_inventory_shortage',
|
||||
decision_source='system',
|
||||
line_status='released_shortage',
|
||||
is_active=True,
|
||||
snapshot_json={'auto_release': True, 'release_evidence_scope': 'part_fallback'},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
# 系统自动放行决定落库后走真实放行查询(不打 seam 补丁)必须满足。
|
||||
assert match_completed(task) is True
|
||||
status, shortages = _recompute_task_match_aggregate(task)
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
assert task.step_payload_json['current_match_projection']['line_results'][0]['line_status'] == 'released'
|
||||
@@ -215,6 +215,92 @@ def test_allowed_system_facts_use_notice_line_no_not_export_sequence():
|
||||
assert 'export_sequence' not in ALLOWED_SYSTEM_FACTS
|
||||
|
||||
|
||||
def test_part_fallback_total_aggregates_across_reservations_within_allowed_source():
|
||||
"""预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。"""
|
||||
# Reservation 契约只接受 5/10 位纯数字(validated_reservation_id),
|
||||
# 故用互不相同的数字预约号表达「订单预约号 vs 其它预约号」。
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines,
|
||||
inventory_lines=inventory_lines,
|
||||
header_reservation_id=None,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:订单预约号无库存桶 → not_found;料号兜底总量 0+5+3=8 必须随行结果下发。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['available_qty'] == 0.0
|
||||
assert result['part_available_qty'] == 8.0
|
||||
|
||||
|
||||
def test_part_fallback_total_respects_allowed_source_and_ignores_unit():
|
||||
"""料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。"""
|
||||
order_lines = [{
|
||||
'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8,
|
||||
'allowed_source_codes': ['DSV'], 'candidate_line_id': 1,
|
||||
}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092919', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'},
|
||||
{'reservation_id': '3000092920', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['part_available_qty'] == 105.0
|
||||
|
||||
|
||||
def test_part_fallback_total_absent_for_conflict_and_missing_part():
|
||||
"""multi_file_conflict / 缺料号 / invalid(超出候选范围)行不下发料号总量,避免误导用户。"""
|
||||
order_lines = [
|
||||
{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 1,
|
||||
'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1},
|
||||
{'line_no': 2, 'reservation_id': '3000092918', 'quantity': 1,
|
||||
'allowed_source_codes': ['A'], 'candidate_line_id': 2},
|
||||
{'line_no': 3, 'part_number': 'P-2', 'reservation_id': '1380000000', 'quantity': 1,
|
||||
'allowed_source_codes': ['A'], 'candidate_line_id': 3},
|
||||
]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'},
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'},
|
||||
{'reservation_id': '1380000000', 'part_number': 'P-2', 'qty': 5, '__source_code': 'B'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
# 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。
|
||||
assert 'part_available_qty' not in payload['line_results'][0]
|
||||
assert 'part_available_qty' not in payload['line_results'][1]
|
||||
# 断言意图:命中仅存在于候选范围外源(invalid)的行同样不写键,不得误导放行判断。
|
||||
assert payload['line_results'][2]['disposition'] == 'invalid'
|
||||
assert 'part_available_qty' not in payload['line_results'][2]
|
||||
|
||||
|
||||
def test_part_fallback_total_on_shortage_line_sums_other_reservations():
|
||||
"""预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。"""
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': '3000092917', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': '3000092917', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'},
|
||||
{'reservation_id': '3000092918', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。
|
||||
assert result['disposition'] == 'shortage'
|
||||
assert result['available_qty'] == 2.0
|
||||
assert result['shortage_qty'] == 6.0
|
||||
assert result['part_available_qty'] == 9.0
|
||||
|
||||
|
||||
def test_permanent_audit_events_have_no_retention_expiry(app):
|
||||
"""货代统一审计账本新写入事件永久保留(retention_expires_at 为空)。"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
@@ -460,6 +460,8 @@
|
||||
- 人工上传是 RPA 的受控降级:业务人员仅按 `business_no` 确认已上传,不上传截图、回执或 PDF;服务端仍通过该 Notice 的受控 Attempt 与状态机记录成功事实。
|
||||
- 上传以 Excel Artifact 为边界:每次 RPA 或人工操作均创建独立 Attempt,trigger 和回调必须携带 `artifact_id`、`attempt_id` 与幂等 `callback_id`。相同回调只生效一次;网络失败只能重试原 Artifact,只有货代明确拒绝并经授权才可作废 Artifact、释放未上传预约单;Task 上传字段仅为 Artifact/Attempt 的聚合投影。
|
||||
|
||||
- **缺口放行规则变化(2026-10-09,料号兜底自动放行,已实现)**:预约单号匹配出缺口的行,若该料号在行允许库存源内的总可用数量 ≥ 需求数量、且放行证据字段可全部自动取值,系统在库存匹配落库后自动创建 `release_inventory_shortage` 放行决定(系统来源、快照记 `auto_release` 与证据范围),不再要求人工逐字段补录;证据带出优先级为「预约号+料号精确命中 → 库存无该预约单号时按料号重筛 → 人工补录」,自动带出与人工补录合并保存并作为导出 Excel 证据的唯一来源。料号总量不足、证据无法自动取值或已有放行决定时一律保持人工放行,系统不自动撤销。出单条件不变:仍由用户人工勾选波次触发,放行行可勾选资格规则与既有口径一致;工作台匹配表原「可用数量」列改「预约数量」(预约匹配口径),新增「可用数量」列展示料号口径总量(与明细表/聊天卡同名列是否统一待产品定)。
|
||||
|
||||
### 3.1 本期范围
|
||||
|
||||
- 查询员工本人假期余额
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
| --- | --- | --- |
|
||||
| POST | `/matchings` | 创建/复用一次调拨匹配(只读,不写 ERP;body `source_codes` 必填,可选 `business_date`/`receipt_date_from`/`receipt_date_to`/`transfer_type`,缺省 `in_transit_to_hub`;响应含 matching_id/hash/计数/来源进度) |
|
||||
| GET | `/items/executable` | 可调拨明细:全局 ready_to_execute 行队列(业务稳定排序=收料日期→数据源→Invoice→created_at,2026-09-29 与待处理池/匹配卡视图统一为同一口径;行含 item_id/checked_at/stale/file_current),勾选后 POST `/items/execute` 按行生成调拨单 |
|
||||
| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`,counts 实时聚合) |
|
||||
| GET | `/matchings/{id}` | 按 scope 实时视图恢复匹配进度(行含 `item_id`/`checked_at`/`stale`/`file_current`/`external_org`(执行建单五元组首键,2026-10-12 起),counts 实时聚合) |
|
||||
| POST | `/matchings/{no}/items/requery` | 批量重查 ERP 库存——圈行口径=匹配 scope(与匹配卡实时视图同源谓词,行归属 matching_id 不参与;2026-09-24 修复:旧按 matching_id 圈行致历史行重查不可达);body 可选 `invoice_nos` 限定范围;库存查询按组织批量(2026-09-29:每组织一次 `query_stock`,N 行=N 组织内 1 次调用,行级评估/Attempt/审计保持单行粒度) |
|
||||
| POST | `/sources/receipt-files` | 按选中来源打包下载各自最新归档收料文件 zip(下载留审计) |
|
||||
| GET | `/runs/{run_no}` | Run 结果(`orders` 调拨单清单=进度=结果,逐单八键/行六键含 reason;+ 按 ERP 单号聚合 external_documents + 未落单异常 exceptions) |
|
||||
@@ -69,6 +69,7 @@
|
||||
| GET | `/metrics` | 调拨运营指标(成功率/失败类型/待处理老化/通知失败) |
|
||||
| GET | `/sources` | 来源实例列表(附收料文件状态 ready/parse_failed/fetching/failed/expired/none + has_ready_file,供前端门禁;2026-09-29 起 `parse_failed`=当日文件在但 movement 解析失败(`has_ready_file=false`),路由失败仅行内 `blocked_route_not_resolved`、不抬升来源顶栏) |
|
||||
| POST | `/sources/{source_code}/retry-rpa` | 来源收料重试(2026-09-29 起分层:parse_failed 且有当日可用文件时优先本地重解析——成功 ready / 仍失败 parse_failed,200 `reparsed=true`,不触发 RPA;否则原样重新触发一次收料 RPA 抓取,202+fetching,配置缺失 fail-closed ok=False) |
|
||||
| POST | `/sources/retry-rpa-batch` | 批量来源收料重试(body `source_codes`;2026-10-09 起多来源合并写**一个** batch trigger 文件——Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;逐来源分层与 fail-closed 语义同单来源端点,单源配置缺失跳过并记录不阻断整批,响应 `triggered`+逐源 `results`) |
|
||||
| GET | `/backlog` | 待处理异常列表(可恢复/已关闭/结果未知 + 老化等级;查看留审计) |
|
||||
| GET | `/backlog/summary` | 待处理异常汇总(含 3/5/7 天老化分级) |
|
||||
|
||||
@@ -188,6 +189,7 @@ cd backend && flask db upgrade
|
||||
- 端到端场景清单(前端实施后落 Playwright/Vitest 契约):人工执行主路径、自动排程、异常恢复、刷新恢复、权限越权、ERP 沙箱真实单据(创建/审核/过账/作废)。
|
||||
- 本期功能验收项(2026-09-24 ERP 建单写路径,配置见 §10):
|
||||
- **五元组建单**:按五元组(external_org / source_code / 收料日期 / 拨出库位 / 拨入库位,全 .strip() 规范化)聚合明细建一张单,单号 `HX-<org>-OR-*`;同组失败单复用单号/时间戳全量重跑、result_unknown/executing 单阻断新行(group_ticket_unresolved)。
|
||||
- **预计 ERP 单据数口径(2026-10-12 修正)**:匹配摘要 `estimated_external_write_count` = 可执行行按同款五元组去重后的组数(同组多行合并一张,原「=可执行行数」口径高估);匹配卡上该数(计数卡=全部可执行行、生成按钮旁=勾选可执行行,随勾选联动)由前端按行上 `external_org` 实时分组计算,历史快照中旧口径持久值不再上屏。
|
||||
- **融合卡**:`GET /runs/{run_no}` orders 逐单亮态(成功/失败/未知三态+ERP 单号回显),202 提交后 4s 轮询至严格终态;retrigger 受理窗口不误停轮询。
|
||||
- **retrigger**:result_unknown 单复用 doc_no/submit_timestamp 只触发末步,ERP 幂等回原单号;非 result_unknown 400。
|
||||
- **关闭单**:business_failed/technical_failed 人工关闭(原因必填),单 cancelled、行脱离回可执行、组锁释放可另开新单;result_unknown 无关闭入口(SOP 红线 §10.8)。
|
||||
|
||||
@@ -745,3 +745,42 @@ A:可以。现在推荐按**一次业务委托一个 Agent 会话**处理;
|
||||
|
||||
- Excel 一旦生成,头字段、行字段、行源全部转为**只读**;页面按后端 `edit_window` 禁用对应输入。
|
||||
- 若已确认信息有误,只能走既有的撤销 / 人工纠错流程(D12:编辑窗只覆盖「确认后、Excel 前」;客户侧订单变更仍走重新上传/重新解析;上传货代后的纠错仍须人工撤销)。
|
||||
|
||||
---
|
||||
|
||||
## 17. 缺口放行(料号兜底自动放行)
|
||||
|
||||
> 针对预约单号匹配出缺口、但同料号在库存中还有其他预约号余量的场景。系统会按料号维度自动核对总量,满足条件时**直接替您完成放行**,不再要求逐字段补录放行证据;不满足时仍回到人工放行,流程更省但不放松管控。
|
||||
|
||||
### 17.1 什么时候系统会自动放行
|
||||
|
||||
匹配完成后,同时满足以下条件的缺口行由系统自动放行(无需您确认):
|
||||
|
||||
- 该行按「预约单号 + 料号」匹配存在缺口(含库存中查不到该预约单号的情况);
|
||||
- 该料号在本行允许的库存源内的**总可用数量 ≥ 需求数量**(忽略预约号、不限单位的料号口径);
|
||||
- 放行需要的证据字段(库存数量、批次等)都能从库存中**自动取到唯一值**。
|
||||
|
||||
### 17.2 什么时候降级为人工放行
|
||||
|
||||
以下任一情况系统不会自动放行,该行保持原人工流程(由您补录证据后放行):
|
||||
|
||||
- 料号总可用数量不足(差多少都不行,系统不会拿部分数量放行);
|
||||
- 放行证据字段无法自动取值或取值存在分歧;
|
||||
- 该行已有放行决定时,系统不会自动撤销或改写,仍以已有人工决定为准。
|
||||
|
||||
### 17.3 放行证据从哪里来(带出优先级)
|
||||
|
||||
1. 优先按「预约单号 + 料号」精确命中取值;
|
||||
2. 库存中查不到该预约单号时,按料号重新筛选库存取值;
|
||||
3. 仍取不到的字段由人工补录。自动带出与人工补录的字段值会合并保存,作为生成发货 Excel 时证据列的唯一来源。
|
||||
|
||||
### 17.4 Excel 出单条件不变
|
||||
|
||||
- 出单仍由您**人工勾选波次**触发,系统不会因自动放行而自动出单;
|
||||
- 放行行的可勾选资格规则与之前完全一致(已满足行 + 已放行行可勾选),缺货且未放行行仍不能进入本轮 Excel。
|
||||
|
||||
### 17.5 页面上的数量列
|
||||
|
||||
- 库存匹配表中,原「可用数量」列更名为「**预约数量**」(按预约单号匹配到的数量);
|
||||
- 新增「**可用数量**」列,显示该料号在允许库存源内的总可用量(料号口径),供您判断能否放行;
|
||||
- 注意:订单明细表、聊天匹配卡中的「可用数量」仍是预约匹配口径,与工作台新列同名不同义,是否统一名称待产品确认。
|
||||
@@ -2396,7 +2396,7 @@ volumes:
|
||||
|
||||
同一 Windows 用户通过两个独立计划任务同时运行 test/prod。每个任务调用 `start_rpa_worker.ps1`,只给对应 Worker 子进程注入环境变量;Secret 使用当前用户 DPAPI 文件保存,不写入用户级或机器级环境变量。
|
||||
|
||||
库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`FREIGHT_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`(旧参数 `-ReuseDsvSession` 已于 2026-09-18 移除)。
|
||||
库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`FREIGHT_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程——登录链路须能自愈重登录而非判死(2026-10-12 加固):①认证态判定统一走 `on_dsv_auth_domain` 双域(`auth.dbschenker.com` / `auth.dsv.com`,后者为 PingFederate resume 链迁移后的新认证域),单域硬编码漏判会导致升级提示不点「也许以后」、「选择登录方法」页误判等卡死;②「已记住标识」的 PingID 选择登录方法页(无用户名框,`looks_like_dsv_identifier_chooser` 强特征判定)跳过邮箱/继续直进密码阶段;③用户名步骤走不通时清空 Cookie 从 portal 重新发起登录(`_retry_dsv_login_with_purged_cookies`),仍失败才抛错交由批内重试。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`(旧参数 `-ReuseDsvSession` 已于 2026-09-18 移除)。
|
||||
|
||||
Worker 本机磁盘保留(`FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。
|
||||
|
||||
@@ -3064,7 +3064,7 @@ FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS=900
|
||||
|
||||
- 收料文件在回调时**原样上传 MinIO**(`shipping/receipt-reports/{年}/{月}/{单元}/{sha256}.xlsx`),保留三年;MinIO 不可用时该单元回调失败,不落成功态。
|
||||
- 到期对象由平台排程任务 **货代收料归档到期清理**(`freight-receipt-rpa-retention`)删除,建议在排程管理配置每日一次;它只删除过期对象,不删除运行、文件事实与审计记录。
|
||||
- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。
|
||||
- 企微通知与库存排程**同一出口同一门禁**(`scheduler_service._notify_schedule_run_wecom`,2026-09-21 统一;2026-09-28 起附件改为 ZIP):收料 run 全部单元终态归集后**一次性**发送 textcard 汇总(`schedule_completed` 事件)+ **汇总结果 Excel** `收料RPA-{yyyyMMdd}-{HHmm}-结果.xlsx`(2026-10-12 对齐库存补齐;列头 收料源/仓库/连接器/归档文件数/导出状态/跳过原因/错误原因,`empty→skipped`、`cancelled→failed` 与卡片计数同口径,导出失败降级 success→partial_failed 并记 `excel_export_status/excel_failed`)+ **一个**原始收料包 `收料RPA-{yyyyMMdd}-{HHmm}-收料.zip`(包内 `{序号}_{source_code}.xlsx` + `manifest.json`,磁盘键 `{run_no}.zip`);不再逐文件推送。Worker 落盘名为 `receipt_{batch_run_no}_{source_code}_{warehouse_or_NA}_{stamp}.xlsx`。接收人取排程任务的 `notify_user_ids` + `notify_enabled`,且必须已完成企微绑定;排障查 `schedule_runs.wecom_notified / wecom_notify_error`。管理员重发(`/receipt-report-files/{id}/resend`)保留为补偿通道,不触发 RPA,投递失败记 `WECOM_USER_UNBOUND`。
|
||||
|
||||
排程创建:管理端「排程管理」新增平台任务 **货代收料 RPA**(`freight-receipt-rpa`),可选参数 `source_codes` 留空则执行全部已启用站点中已配置收料的站点,按需配置 Cron 与接收人。收料排程与库存排程相互独立(站点、Cron、接收人分别选择)。收料触发前执行**与库存同口径**的 Worker 在线 fail-fast 检查(`assert_receipt_rpa_worker_ready`:心跳 TTL + 收料 trigger 目录哨兵 + scope 匹配,2026-09-30 起对齐):Worker 离线、哨兵缺失(含漏配 `FREIGHT_RPA_SHARED_SCOPE_ID`)或 scope 不符时排程立即 failed(`RPA.WORKER_OFFLINE`),不再空等 `FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。上线后仍应按 `1.9.4` 验收并保留 `data\freight_rpa\receipt\logs\worker.log` 巡检。
|
||||
|
||||
@@ -3907,3 +3907,64 @@ inventory_preparation Gate
|
||||
- 预检触发守卫(`_DefaultRpaTrigger`):收料配置存在但未绑/规则未发布/用途不符 → `RPA_RECEIPT_MOVEMENT_PROFILE_MISSING`,不写 trigger(防徒劳抓取循环);无收料配置仍走既有 `RPA_RECEIPT_CONFIG_MISSING`。
|
||||
- 站点库存解析绑定(`ShippingInventorySource.parsing_profile_id`,站点表单与批量绑定弹窗)只列 `purpose==='inventory'` 的已发布规则,防止误绑异动规则。
|
||||
- `movement_file_repository.latest_ready_file` 复用条件不变:归档文件存在且绑定规则就绪;无排程按需触发的单元行 `schedule_run_id` 为 NULL(FK 禁止 0 占位)。
|
||||
|
||||
## 通知准备阶段进度版本推进契约修复(2026-10-09)
|
||||
|
||||
> 背景:单笔「重新获取库存(RPA)」成功并检出库存缺口后,工作台「库存匹配」表格的可用数量/缺口/匹配状态停留在旧快照(显示「库存文件未准备」),仅右卡门禁更新。根因有两处,均在后端投影契约,前端 `[REFRESH_ON_CHANGE]`(progressVersion 变化 → 重拉任务详情)机制本身无缺陷。
|
||||
|
||||
### 缺陷 1:无 Notice 绑定期 Gate 推进不递增 progress_version
|
||||
|
||||
- `ShippingNotice` 生成前(通知准备/库存匹配常态),`process_gate_service._sync_order_task_stage_after_gate_refresh` 的无 Notice 分支只回填 `task.stage`,从不写 status、从不递增 `progress_version`。实测 OT-20260919-97A7EB0C 自 9/19 建单后版本冻结在 20,10/9 的 RPA 重取→匹配→缺口全链路零递增。
|
||||
- 修复:`_refresh_execution_pointers` 捕获指针事实(last_passed/current_gate/primary_next_action/responsible_party/status)前后差异得 `facts_changed`;无 Notice 分支在事实变化时经 `sync_order_task_processing_state(force_progress_bump=True, reason_code='gate_facts_advanced')` 强制递增(保留 BE-06 中央审计);有 Notice 分支在映射后 stage/status 未变但事实已变化时同样补递增。事实未变的重复刷新不递增,避免轮询期刷新风暴。
|
||||
|
||||
### 缺陷 2:RPA 在途被投影成 waiting_human 导致前端轮询提前自停
|
||||
|
||||
- Notice 生成前 `OT.status` 停留在建单前的 `waiting_review`;`processing_projection_invariants._compute_user_status` 在 Gate `waiting_external`(系统等 Worker)时会落到 `waiting_review → waiting_human` 分支,前端把该用户态视为终态并停止投影轮询,回调完成永远无法被感知。
|
||||
- 修复:在 `blocked_manual`/未证实上传终态判定之后新增「Gate 在途(queued/running/waiting_external)→ running」短路,与既有门禁契约 `GATE_STATUS_TO_USER_STATUS['waiting_external']=='running'` 对齐;`blocked_manual` 等人工阻断判定优先级不变。
|
||||
|
||||
### 回归与影响面
|
||||
|
||||
- 新增测试:`test_shipping_process_gate_service.py::test_refresh_pointers_bumps_task_progress_version_without_notice`(事实变化递增一次、未变化不递增)、`test_shipping_processing_projection_invariants.py::test_in_flight_gate_projects_running_not_waiting_human`。
|
||||
- 修复后闭环:提交重取(waiting_external,版本+1,轮询存活)→ Worker 回调/AutoProgress 重评(匹配落库缺口、Gate blocked_manual,版本+1)→ 前端轮询感知终态并重拉任务详情,行级可用数量/缺口/匹配状态即时刷新。
|
||||
|
||||
---
|
||||
|
||||
## 料号兜底自动放行与数量列(2026-10-09)
|
||||
|
||||
> 背景:预约单号匹配缺口行,在「同料号库存尚有其他预约号余量」时仍需人工逐字段补录放行证据。本节记录已实现并过评审的「料号兜底自动放行」与料号维度可用数量列,均为追加能力,不改既有缺口判定与出单条件。
|
||||
|
||||
### 匹配器:part_available_qty(料号兜底总量)
|
||||
|
||||
- 缺口判定不变:仍按「预约单号 + 料号」主键匹配(`backend/app/services/shipping_notice/stp_line_inventory_match.py` 的 `match_order_lines_across_candidates`)。
|
||||
- 行结果新增 `part_available_qty`:口径 = 行允许源内、忽略预约号、不限单位的料号总可用量(对行允许源快照按料号键二次汇总);跨源不合并(多源行只汇总该行允许源,不做全库合计)。
|
||||
- 下发范围:仅 `not_found`(预约不匹配)/ `ok` / `shortage` 行下发;`multi_file_conflict` / `invalid` / 缺料号 / 缺预约行不下发。
|
||||
|
||||
### 存储:新列与回填策略
|
||||
|
||||
- 新列 `shipping_notice_line_inventory_matches.part_available_qty`(`String(32)` 可空),迁移 `0a575f3afc32`(`backend/migrations/versions/0a575f3afc32_add_part_available_qty_to_shipping_.py`)。
|
||||
- 落库:`line_inventory_match_persistence` 在匹配落库(新建与更新路径)时随行事实字符串化写列。
|
||||
- 存量行 NULL 不回填,重新匹配后回填。
|
||||
|
||||
### 投影与前端数量列
|
||||
|
||||
- 投影:`line_inventory_match_projection.serialize_match_fact` 与 view 透出 `part_available_qty`(仅库存就绪时非空,否则 None);`ui_state.py` preparation 行直透该数量。
|
||||
- 前端库存匹配表:原「可用数量」列改「预约数量」(`lifecycle.prepare.reservedQty`,仍为预约匹配语义),新增「可用数量」列(`lifecycle.prepare.partAvailableQty`,数据源为料号兜底总量);四语言已补齐。
|
||||
|
||||
### 自动放行:auto_release_part_fallback_shortages
|
||||
|
||||
- 位置:`backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py` 的 `auto_release_part_fallback_shortages`,在库存匹配落库后调用。
|
||||
- 触发条件(全部满足才由系统放行):行为缺口行 + 该行料号兜底总量 `part_available_qty` ≥ 需求数量 + 放行证据字段全部可自动取值(无 `requires_manual` 残留)。
|
||||
- 放行写路径:复用 `_apply_shortage_line_release`,由系统创建 `release_inventory_shortage` 决定,`decision_source='system'`、`actor_type='system'`;决定快照记 `auto_release: true` 与 `release_evidence_scope`(`inventory_snapshot` / `part_fallback`)供审计。审计/门禁同步/自动履约入队与人工放行完全一致;幂等由「无活动决定的行才处理」保证。
|
||||
- 降级人工:证据不可解析(ConflictError)、字段分歧或料号总量不足时一律跳过该行并保持人工放行路径(fail-closed),不中断其余行。
|
||||
- 不自动撤销:自动放行只创建决定,不撤销/重开任何既有放行。
|
||||
|
||||
### 放行证据带出优先级与 release_field_values
|
||||
|
||||
- 带出优先级:预约号 + 料号精确命中优先 → 库存中无该预约单号时按料号键重筛(`release_evidence_scope=part_fallback`)→ 剩余字段人工补录。
|
||||
- `release_field_values` 落库为「自动带出 + 人工补录」全量字段值字典,是导出 Excel 证据覆盖的唯一来源。
|
||||
|
||||
### 不变项与边界备忘
|
||||
|
||||
- Excel/波次条件零改动:出单仍需人工勾选波次,放行行可勾选资格规则不变(`export.py` / wave 服务 / 满足性聚合未改动)。
|
||||
- 同名不同义:订单明细表 / 聊天匹配卡的「可用数量」仍是预约匹配语义;prep 工作台新「可用数量」列是料号兜底总量,两处是否统一待产品定。
|
||||
- 存量 canonical-only 快照行料号兜底不生效(与基线一致)。
|
||||
+3
-1
@@ -228,6 +228,7 @@
|
||||
| **确认后订单编辑窗谓词(二期 T10)** | 已实现 | `order_edit_window_service.editable_scope`(header=订单任一通知无 Excel 且无活动 Attempt;行=所属通知无 Excel 且无活动 Attempt,未入波次行不受首单 Excel 限制)+ `order_has_active_attempt`;`ui_state` 下发 `edit_window`;测试通过。设计 §3.1。 |
|
||||
| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 |
|
||||
| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 |
|
||||
| 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 |
|
||||
|
||||
### 排程平台任务契约中心(schedule)
|
||||
|
||||
@@ -802,7 +803,7 @@
|
||||
| 领域模型/状态机/DTO/审计/迁移 | 后端已实现 | backend/app/models/in_transit_transfer.py(Run/SourceJob/Matching/InvoiceItem/Attempt/AuditEvent/Archive)+ 迁移 it1a2b3c4d5e / rn1a2b3c4d5e6(precheck→match 术语改名);13 状态服务端门禁(services/in_transit_transfer/status.py) |
|
||||
| 收料文件准备与只读匹配(原"预检") | 后端已实现 | 收料文件落地即同步待办行(RPA 回调桥 → evidence_sync 三分类写入:新行待查/证据变化刷新重置/缺席行存续只换戳);匹配=证据对齐兜底(align_scope_rows,sha 一致直通零解析)+ 按组织批量查库存 + 严格数量比对;缺文件按来源触发收料 RPA/来源隔离/字段校验/T+lag 成熟(默认 T+2)/Invoice 多行汇总+原始行追溯/匹配快照 Hash/进度恢复 |
|
||||
| 可调拨清单勾选与 ERP 原子调拨 | 后端已实现 | 可调拨明细队列勾选按行提交执行 Run/写前复查/Invoice 幂等/duplicate_success/result_unknown 隔离/单项失败不阻断/按票聚合结果(写路径已接线,见下行「ERP 建单写路径」) |
|
||||
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;每非空 Run 一条企微通知(失败不改 ERP 结果) |
|
||||
| 排程/恢复/异常/通知 | 后端已实现 | 08:00 收料文件与 09:00 自动调拨 platform job;任务参数=来源实例/历史可恢复异常复核/可选收料日期起止(T-N 偏移天数,执行日换算,测试/排障缩小匹配面;留空=全部成熟积压;非法偏移快速失败,越界由匹配层卡控成熟上限);待处理池 3/5/7 天老化;人工重试/关闭;七 Sheet 异常 Excel;执行结果通知统一走排程「启用通知」通用执行结果通知(空数据日静默,失败不改 ERP 结果;2026-10-12 移除任务级通知人参数) |
|
||||
| 调拨业务类型 | 后端已实现(类型2/3占位) | 三类型:在途仓至HUB仓(一期开放,仅纳入 INVOICE 前缀 HOM/HOX/WTP 的票)/HUB仓维修出(占位,规则 ODM ID=HoxinRMA 待文件层支持 odm_id)/HUB仓间调拨(占位);类型随 Run 落库并入匹配 Hash,占位类型 fail-closed;前端来源选择卡选择(占位类型禁用) |
|
||||
| 生产硬化 | 后端已实现 | MinIO 归档+Hash 复核;Worker 崩溃/陈旧执行恢复;运营指标;越权 403;下载访问审计;性能测试;运维手册 docs/features/in-transit-transfer/technical.md |
|
||||
| 可调拨明细与待办看板首页 | 已实现 | 首页上区「库存匹配」动作卡 + 待办看板四队列:可调拨明细(GET /items/executable 全局可执行行,勾选按行生成调拨单)/待恢复异常/已人工关闭/结果未知;「最近匹配」(原"最近预检")已移除(行不迁移后匹配卡=范围实时视图,多份同 scope 匹配属重复窗口) |
|
||||
@@ -810,6 +811,7 @@
|
||||
| 按行执行与执行门禁 | 已实现 | execute(item_ids) **202 异步**:API 两道门禁(存在可执行 + 文件版本对账,fail-closed)通过即建 queued Run + 五元组分组建票 + 一次入队,worker 逐票执行(文件对账复核 + 写前路由/库存复查——库存复查仅全量重跑路径,final_only 续跑不复查);Run 留痕不绑匹配;进度/结果无状态回读(GET /runs 轮询票清单);行级新鲜度 TTL 门禁与 ITEMS_STALE 错误码退役,TTL 降为 stale 徽标展示阈值(2026-09-25 定稿,见 features/in-transit-transfer/technical.md §6.3) |
|
||||
| ERP 建单写路径(票级顺序引擎,2026-09-24) | 已实现 | 写路径经集成连接器统一出口:`database` 连接器(oracle/mysql/sqlserver/postgresql 四库直连,SQL 接口 identifiers 白名单替换)+ `create_transfer` 绑定一对多有序步骤(steps_json:写 ERP 中间表 → 触发 WS);顺序引擎四规则(resume 跳过非末步/非末步失败即中止/末步映射+裁决钩子/末步超时 result_unknown);融合卡「票清单=进度=结果」、result_unknown retrigger(D11 唯一出口,禁关闭重建)、失败票人工关票(D18 行脱离回可执行)、首页「已执行」票维护区块;管理端配置配方/SOP/UAT 确认项/已知限制统一见 [features/in-transit-transfer/technical.md](features/in-transit-transfer/technical.md) §10(含 SOP 红线 §10.8;交付说明:新增依赖 pymysql/pymssql,psycopg2-binary 既有;本期零新增环境变量) |
|
||||
| 收料日期默认与输入期限制 | 已实现 | 来源选择卡收料日期默认 T+lag 成熟规则(默认业务日 T-2,可配 IN_TRANSIT_TRANSFER_MATURITY_LAG_DAYS);日期输入 max/min 即时限制 + 起止非法行内提示禁用确认(后端 RECEIPT_DATE_RANGE_INVALID 卡控保留双保险);「直接生成调拨单」改名「生成调拨单」 |
|
||||
| 来源重试合并触发与知情范围确认(2026-10-09) | 已实现 | 批量重试 RPA 合并写**单个** batch trigger(POST `/sources/retry-rpa-batch`,Worker 单次浏览器会话按 profile 分组串行导出,替代逐来源 N 个 trigger/N 次开浏览器;单源失败跳过不阻断整批,parse_failed 仍先本地重解析);来源选择卡混合选择(含非就绪项)确认前先披露范围(可匹配/暂不可匹配计数+按状态分组明细),显式确认后提交 ready-only,全就绪直达(知情部分确认,替代静默剔除;其余来源就绪后可重新匹配增量补入) |
|
||||
| 前端 Chat 卡片/结果页与四语言 | 已实现 | `frontend/src/features/chat/` 卡片(文件进度/匹配/结果/待处理)与 admin 模块已按计划实施(结果=融合卡:202 提交后 4s 轮询票清单至严格终态) |
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,937 @@
|
||||
# 库存缺口料号兜底放行 + 数量列改造 实施计划
|
||||
|
||||
> **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:** 库存缺口仍按「预约单号+料号」判定;当料号维度总库存满足需求时,缺口行由**系统自动放行**(无需人工确认,证据字段按预约优先→料号兜底自动带出);Excel/波次生成条件不变;前端「库存匹配」表原「可用数量」列改为「预约数量」,其后新增「可用数量」(料号总库存)列。
|
||||
|
||||
**Architecture:** 匹配器在现有 `(reservation, part, unit, source)` 聚合桶上按料号二次汇总出 `part_available_qty`,随行级匹配事实持久化(新列+迁移);匹配完成后由自动放行服务对「料号总量≥需求且放行证据可全部自动取值」的缺口行创建系统放行决定(复用人工放行的同一落库/审计/门禁同步/自动履约链路),其余缺口行维持人工放行(证据预约优先→料号兜底);导出消费的放行字段值扩展为「自动带出+人工补录」全量字典。前端新增料号可用数量列,自动放行行沿用既有「已放行」状态展示。
|
||||
|
||||
**Tech Stack:** Flask + SQLAlchemy 2.0 + Alembic(后端);Vue 3 + TypeScript + Vue I18n 四语言(前端)。
|
||||
|
||||
**Spec:** 本计划顶部「需求与假设」节即规格;执行者须连同本节一起阅读。
|
||||
|
||||
## 需求与假设(评审重点,与用户确认过的口径)
|
||||
|
||||
1. **缺口判定公式不变**:`match_order_lines_across_candidates` 的预约号+料号匹配、`available_qty`/`shortage_qty`/`match_result` 计算与持久化语义完全不变。料号兜底**不**改变缺口判定(否则会改变 Excel 条件,违反需求)。
|
||||
2. **料号总库存口径(用户已确认 2026-10-09)**:在该行允许的库存源范围内(`allowed_source_codes`,无候选范围时不过滤)、**不限单位**、**忽略预约号**汇总库存行 `available_qty`。跨库存源不合并(与 `multi_file_conflict` 人工选源语义一致);`multi_file_conflict`/`invalid`(超出候选范围)行不下发料号总量(显示 —,需先选源)。
|
||||
3. **自动放行规则(用户确认 2026-10-09:料号总库存满足 = 自动放行,不是仅"可放行")**:匹配落库后,对同时满足以下全部条件的缺口行,由系统(actor_type='system')自动创建 `release_inventory_shortage` 行决定:
|
||||
- 行为缺口(`inventory_status='ready'` 且 shortage/not_found);
|
||||
- `part_available_qty >= required_qty`(料号兜底量满足);
|
||||
- 无活动决定(未放行/未结案)且行非终态(未入波次/未履约);
|
||||
- 放行模板字段**全部**可自动取值(证据行按「预约号+料号」优先、库存中无该预约单号时按料号键重筛;任一字段无法唯一取值 → 不自动放行,降级为现有人工放行并保留补录要求);
|
||||
- 证据解析本身失败(无源/模板未发布/无快照等 ConflictError 场景)→ 不自动放行,维持现状。
|
||||
自动放行复用人工放行的同一内部落库函数(审计、门禁同步、自动履约入队不变),决策快照记 `auto_release: true` 与 `release_evidence_scope`。**不自动撤销**:已放行行不因后续重匹配总量变化而回退(与人工放行一致,撤销走既有流程)。
|
||||
4. **放行字段值持久化扩展**:导出侧的放行证据覆盖(`release_overrides_by_source_line`)只读 `decision.snapshot_json['release_field_values']`,而现行该字典经白名单只存人工补录项。自动放行没有人工输入,故 decide/自动放行落库时把「自动带出 + 人工补录」的**全量**模板字段值写入 `release_field_values`(校验逻辑不变:人工必填项缺失仍 409)。
|
||||
4. **Excel/波次条件不变**:`exportable_snapshot_line_ids` / `current_available_snapshot_line_ids` / `create_post_ot_fulfillment_wave` / `excel_gate_error` / `can_fulfill_complete_line` 一律不改。放行过的缺口行按既有规则获得出单资格。
|
||||
5. **前端范围**:仅改「订单生命周期工作台 → 通知准备 → 库存匹配」表(ui_state `preparation.lines` 单源)。订单明细表(draft lines,`fulfillmentDecision.availableQty` 键)与聊天匹配卡(`ShippingMatchLineResult`)**本期不动**,键值文案同为「可用数量」但语义仍是预约匹配量——已在文档任务中注明,若需统一由用户后续决定。
|
||||
6. **存量数据**:历史 Match 行 `part_available_qty` 为 NULL(前端显示 —),不回填;用户点「重新匹配库存 / 重新获取库存」后自动补齐。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 🧬 新增数据库列必须配套 Alembic 迁移(`flask db migrate -m "..."` → 检查 → `flask db upgrade`),禁止只改模型。
|
||||
- 🌍 前端新增文案必须同时补 `zh-CN / zh-TW / en / th` 四语言;禁止硬编码中文。`chat.json` 的 `lifecycle.prepare` 块是**单行 JSON**,编辑用精确子串替换(Edit 工具)或 python io,禁用 PowerShell Get-Content/Set-Content。
|
||||
- 🚫 不做 git commit;每个任务以 `git add <具体文件>` 收尾(用户批准后统一提交)。
|
||||
- ⚠️ Excel/波次/满足性聚合行为不变:Task 10 的守护测试必须全绿(`test_post_ot_fulfillment_wave_p0.py`、`test_shipping_rolling_fulfillment.py`、`test_shipping_stp_match_completed_gate.py`)。
|
||||
- 📝 新函数必须有含 Args/Returns 的 docstring;测试断言必须有断言意图注释(§5.4)。
|
||||
- 后端测试命令:`cd backend && ./.venv/Scripts/python.exe -m pytest <file> -q`。
|
||||
|
||||
## File Structure(改动全景)
|
||||
|
||||
| 文件 | 动作 | 职责 |
|
||||
| --- | --- | --- |
|
||||
| `backend/app/services/shipping_notice/stp_line_inventory_match.py` | 修改 | 匹配器按料号二次聚合,产出 `part_available_qty` |
|
||||
| `backend/app/models/shipping_notice_line_inventory_match.py` | 修改 | 新列 `part_available_qty`(String(32) nullable) |
|
||||
| `backend/migrations/versions/<rev>_add_part_available_qty_to_line_inventory_matches.py` | 新建 | 加列迁移 |
|
||||
| `backend/app/services/shipping_notice/line_inventory_match_persistence.py` | 修改 | 新建/更新两分支写入新列 |
|
||||
| `backend/app/services/shipping_notice/line_inventory_match_projection.py` | 修改 | serialize/view 透出新列 `part_available_qty`(ready 门控) |
|
||||
| `backend/app/services/shipping_notice/ui_state.py` | 修改 | prep 行下发两个新字段 |
|
||||
| `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py` | 修改 | 放行补录字段按料号兜底重筛;decide/自动放行落库全量字段值;自动放行共享内部函数 |
|
||||
| `backend/app/services/shipping_notice/fulfillment_workflow.py` | 修改 | `match_inventory`/`match_inventory_line` 落库后挂自动放行钩子 |
|
||||
| `frontend/src/features/chat/types/shipping.api.types.ts` | 修改 | prep 行 / Case 行类型加可选新字段 |
|
||||
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | 修改 | `lifecycle.prepare` 加 `reservedQty`、`partAvailableQty` |
|
||||
| `frontend/src/features/chat/views/ShippingOrderReviewView.vue` | 修改 | 表头/单元格/colspan/格式化 |
|
||||
| `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts` | 修改 | i18n mock + 列渲染断言 |
|
||||
| `backend/tests/test_shipping_stp_phase4_line_inventory_match.py` | 修改 | 匹配器新用例 |
|
||||
| `backend/tests/test_line_inventory_match_persistence.py` | 修改 | 持久化断言 |
|
||||
| `backend/tests/test_line_inventory_match_projection.py` | 修改 | 投影派生断言 |
|
||||
| `backend/tests/test_shipping_notice_ui_state.py` | 修改 | prep 行字段断言 |
|
||||
| `backend/tests/test_shipping_review_line_fulfillment_decision.py` | 修改 | 放行兜底 evidence 用例 |
|
||||
| `docs/features/shipping-notice/technical.md`、`business.md`、`docs/funclist.md`、`docs/demand.md` | 修改 | 文档同步 |
|
||||
|
||||
**不动清单(明确不改)**:`export.py`、`reservation_service.current_available_snapshot_line_ids`、`post_ot_fulfillment_wave_service.py`、`fulfillment_workflow.match_completed/_recompute_task_match_aggregate/excel_gate_error`、`process_gate_bridge.py` sufficiency 评估、`ShippingMatchResultCard.vue`、任务中心。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 匹配器按料号聚合总可用量
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/stp_line_inventory_match.py`(桶聚合在 :289-300,行循环 :314 起,各 disposition 分支 :347-461)
|
||||
- Test: `backend/tests/test_shipping_stp_phase4_line_inventory_match.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 现有 `buckets: dict[(reservation, part, unit, source) -> {'available_qty': Decimal, 'sample_row', 'source_code'}]`、`allowed_source_codes: list[str]`、`has_candidate_scope: bool`、`part: str`。
|
||||
- Produces: 每个 `line_results[i]`(disposition ∈ `not_found`(预约不匹配/预约缺失但有料号)、`ok`、`shortage`)新增键 `part_available_qty: float | None`;`multi_file_conflict`/`invalid`/缺料号行**不写该键**(后续按缺失处理)。口径:行允许源内、忽略预约号、**不限单位**。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_shipping_stp_phase4_line_inventory_match.py` 追加(沿用该文件现有的订单行/库存行构造 helper,若 helper 名不同以文件内现名为准):
|
||||
|
||||
```python
|
||||
def test_part_fallback_total_aggregates_across_reservations_within_allowed_source():
|
||||
"""预约号不匹配但同料号在其它预约号下总量足够时,必须下发料号总可用量。"""
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-ORDER', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': 'R-ORDER', 'part_number': 'P-1', 'qty': 0, '__source_code': 'DSV'},
|
||||
{'reservation_id': 'R-OTHER-A', 'part_number': 'P-1', 'qty': 5, '__source_code': 'DSV'},
|
||||
{'reservation_id': 'R-OTHER-B', 'part_number': 'P-1', 'qty': 3, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines,
|
||||
inventory_lines=inventory_lines,
|
||||
header_reservation_id=None,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:预约桶 0 → not_found;料号兜底总量 5+3=8 必须随行结果下发。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['available_qty'] == 0.0
|
||||
assert result['part_available_qty'] == 8.0
|
||||
|
||||
|
||||
def test_part_fallback_total_respects_allowed_source_and_ignores_unit():
|
||||
"""料号兜底汇总受候选源范围约束,但不限定单位(用户确认口径 2026-10-09)。"""
|
||||
order_lines = [{
|
||||
'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-ORDER', 'quantity': 8,
|
||||
'allowed_source_codes': ['DSV'], 'candidate_line_id': 1,
|
||||
}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': 'R-A', 'part_number': 'P-1', 'qty': 6, '__source_code': 'DSV'},
|
||||
{'reservation_id': 'R-B', 'part_number': 'P-1', 'qty': 10, '__source_code': 'OTHER'},
|
||||
{'reservation_id': 'R-C', 'part_number': 'P-1', 'qty': 99, '__source_code': 'DSV', 'uom': 'BOX'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:范围外源(OTHER)不得计入;异单位(BOX)行**必须计入**(不限单位),总量 6+99=105。
|
||||
assert result['disposition'] == 'not_found'
|
||||
assert result['part_available_qty'] == 105.0
|
||||
|
||||
|
||||
def test_part_fallback_total_absent_for_conflict_and_missing_part():
|
||||
"""multi_file_conflict 与缺料号行不下发料号总量,避免误导用户。"""
|
||||
order_lines = [
|
||||
{'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-1', 'quantity': 1,
|
||||
'allowed_source_codes': ['A', 'B'], 'candidate_line_id': 1},
|
||||
{'line_no': 2, 'reservation_id': 'R-2', 'quantity': 1,
|
||||
'allowed_source_codes': ['A'], 'candidate_line_id': 2},
|
||||
]
|
||||
inventory_lines = [
|
||||
{'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 5, '__source_code': 'A'},
|
||||
{'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 5, '__source_code': 'B'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
# 断言意图:冲突行与缺料号行均无 part_available_qty 键(持久化/投影按缺失→None)。
|
||||
assert 'part_available_qty' not in payload['line_results'][0]
|
||||
assert 'part_available_qty' not in payload['line_results'][1]
|
||||
|
||||
|
||||
def test_part_fallback_total_on_shortage_line_sums_other_reservations():
|
||||
"""预约命中但不足(shortage)时,料号总量同样跨预约号合计下发。"""
|
||||
order_lines = [{'line_no': 1, 'part_number': 'P-1', 'reservation_id': 'R-1', 'quantity': 8}]
|
||||
inventory_lines = [
|
||||
{'reservation_id': 'R-1', 'part_number': 'P-1', 'qty': 2, '__source_code': 'DSV'},
|
||||
{'reservation_id': 'R-9', 'part_number': 'P-1', 'qty': 7, '__source_code': 'DSV'},
|
||||
]
|
||||
payload = match_order_lines_across_candidates(
|
||||
order_lines=order_lines, inventory_lines=inventory_lines,
|
||||
)
|
||||
result = payload['line_results'][0]
|
||||
# 断言意图:缺口判定不变(available=2/shortage=6);兜底总量=2+7=9。
|
||||
assert result['disposition'] == 'shortage'
|
||||
assert result['available_qty'] == 2.0
|
||||
assert result['shortage_qty'] == 6.0
|
||||
assert result['part_available_qty'] == 9.0
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py -q -k part_fallback`
|
||||
Expected: FAIL(`KeyError: 'part_available_qty'`)
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
在 `stp_line_inventory_match.py` 的模块级 helper 区(`_inventory_row_qty` 之后,约 :78)新增:
|
||||
|
||||
```python
|
||||
def _part_total_available_qty(
|
||||
buckets: dict[tuple[str, str, str, str], dict[str, Any]],
|
||||
*,
|
||||
part: str,
|
||||
allowed_source_codes: list[str],
|
||||
has_candidate_scope: bool,
|
||||
) -> Decimal | None:
|
||||
"""
|
||||
按料号(忽略预约号、不限单位)在该行允许源范围内汇总库存总可用量(料号兜底口径)。
|
||||
|
||||
Args:
|
||||
buckets: (reservation, part, unit, source) 聚合桶;unit 维度不参与过滤。
|
||||
part: 归一化料号;空串返回 None。
|
||||
allowed_source_codes: 该行冻结的候选源;仅 has_candidate_scope 时约束。
|
||||
has_candidate_scope: 行是否携带候选源范围事实。
|
||||
|
||||
Returns:
|
||||
料号总可用量(Decimal);缺料号返回 None。跨源不合并(multi_file_conflict 语义)。
|
||||
"""
|
||||
if not part:
|
||||
return None
|
||||
total = Decimal('0')
|
||||
for key, bucket in buckets.items():
|
||||
if key[1] != part:
|
||||
continue
|
||||
if has_candidate_scope and bucket['source_code'] and bucket['source_code'] not in allowed_source_codes:
|
||||
continue
|
||||
total += bucket['available_qty']
|
||||
return total
|
||||
```
|
||||
|
||||
在行循环内、`all_source_hits` 计算之后(约 :350)加:
|
||||
|
||||
```python
|
||||
part_total = _part_total_available_qty(
|
||||
buckets,
|
||||
part=part,
|
||||
allowed_source_codes=allowed_source_codes,
|
||||
has_candidate_scope=has_candidate_scope,
|
||||
)
|
||||
```
|
||||
|
||||
各 disposition 分支的 `result` dict 增补(`invalid`、`multi_file_conflict`、`not part` 的 not_found 三个分支**不加**):
|
||||
|
||||
- `elif not source_hits:` 的 not_found 分支(预约不匹配):`'part_available_qty': float(part_total) if part_total is not None else None,`
|
||||
- `ok` 分支与 `shortage` 分支:同上键。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py -q`
|
||||
Expected: 全部 PASS(含既有用例,证明缺口判定未变)
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/stp_line_inventory_match.py backend/tests/test_shipping_stp_phase4_line_inventory_match.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 模型新列 + Alembic 迁移
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/models/shipping_notice_line_inventory_match.py:104-106`(数量列区)
|
||||
- Create: `backend/migrations/versions/<head-rev>_add_part_available_qty_to_line_matches.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `ShippingNoticeLineInventoryMatch.part_available_qty: Mapped[Optional[str]]`(String(32) nullable,与 `available_qty` 同风格——数量以字符串化 Decimal 持久化)。
|
||||
|
||||
- [ ] **Step 1: 改模型**
|
||||
|
||||
在 `shortage_qty` 列(:106)之后加:
|
||||
|
||||
```python
|
||||
# 料号维度总可用量(忽略预约号、行允许源内汇总);预约号不匹配行的放行兜底依据。
|
||||
# 历史行与无快照行为 NULL,前端显示占位符;重新匹配后回填。
|
||||
part_available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 生成迁移**
|
||||
|
||||
```bash
|
||||
cd backend && ./.venv/Scripts/python.exe -m flask db migrate -m "add part_available_qty to shipping_notice_line_inventory_matches"
|
||||
```
|
||||
|
||||
检查生成的迁移文件:仅含 `op.add_column('shipping_notice_line_inventory_matches', sa.Column('part_available_qty', sa.String(32), nullable=True))` 与对应 `drop_column`;确认 `down_revision` 指向当前 head(`flask db heads` 核对单头)。
|
||||
|
||||
- [ ] **Step 3: 升级并验证**
|
||||
|
||||
```bash
|
||||
cd backend && ./.venv/Scripts/python.exe -m flask db upgrade && ./.venv/Scripts/python.exe -m flask db downgrade && ./.venv/Scripts/python.exe -m flask db upgrade
|
||||
```
|
||||
|
||||
Expected: upgrade/downgrade/upgrade 均无错误(本地 dev 库)。
|
||||
|
||||
- [ ] **Step 4: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/models/shipping_notice_line_inventory_match.py backend/migrations/versions/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: 持久化写入 part_available_qty
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/line_inventory_match_persistence.py`(新建行分支约 :266-305;更新分支约 :352-382)
|
||||
- Test: `backend/tests/test_line_inventory_match_persistence.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 的 `line_results[i]['part_available_qty']`。
|
||||
- Produces: `ShippingNoticeLineInventoryMatch.part_available_qty`(`str(qty)` 或 None)。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_line_inventory_match_persistence.py` 追加(复用该文件既有夹具构造 task/snapshot/match_payload):
|
||||
|
||||
```python
|
||||
def test_persist_writes_part_available_qty_for_not_found_line():
|
||||
"""预约不匹配行的料号兜底总量必须随匹配事实落库。"""
|
||||
# 复用文件内既有 persist 测试夹具(task + inventory snapshot + 冻结候选),
|
||||
# match_payload 的 line_results[0] 使用 disposition='not_found' 并附
|
||||
# 'part_available_qty': 8.0(构造方式对齐文件内首个 not_found 用例)。
|
||||
rows = persist_line_inventory_match_facts(task=task, match_payload=match_payload)
|
||||
# 断言意图:兜底总量字符串化落列;无键/None 时必须落 NULL 而非 'None'。
|
||||
assert str(rows[0].part_available_qty) == '8.0'
|
||||
```
|
||||
|
||||
(执行者按该文件现有用例的夹具名补齐构造代码;断言语义必须保留本注释所述两点。)
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_persistence.py -q -k part_available`
|
||||
Expected: FAIL(AttributeError: part_available_qty)
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
新建行分支(`row = ShippingNoticeLineInventoryMatch(...)`)在 `shortage_qty=...` 之后加:
|
||||
|
||||
```python
|
||||
part_available_qty=(
|
||||
str(result['part_available_qty'])
|
||||
if result.get('part_available_qty') is not None else None
|
||||
),
|
||||
```
|
||||
|
||||
更新分支(`existing.xxx = ...` 区)对应加:
|
||||
|
||||
```python
|
||||
existing.part_available_qty = (
|
||||
str(result['part_available_qty'])
|
||||
if result.get('part_available_qty') is not None else None
|
||||
)
|
||||
```
|
||||
|
||||
注意:BE-5 守卫(`snap_id is None` → result_missing)与 `not_found 强制 available=0` 分支不需改——`part_available_qty` 直接取匹配器原值;`snap_id is None` 时匹配器本身无库存行、值为 None,天然一致。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_persistence.py -q`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/line_inventory_match_persistence.py backend/tests/test_line_inventory_match_persistence.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 投影层透出料号总可用量
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/line_inventory_match_projection.py`(`serialize_match_fact` :544-590;`project_line_inventory_view` :597-798)
|
||||
- Test: `backend/tests/test_line_inventory_match_projection.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Match 行列 `part_available_qty`(Task 3)。
|
||||
- Produces:
|
||||
- `serialize_match_fact(row)['part_available_qty'] -> str | None`(Task 7 自动放行服务经 `load_current_match_facts_by_task` 消费)
|
||||
- `project_line_inventory_view(...)['part_available_qty'] -> str | None`(仅 `inventory_status=='ready'` 时有值,否则 None;Task 5 ui_state 消费)
|
||||
- 不做的事:不派生「可兜底放行」布尔字段——自动放行判定在 Task 7 服务内基于行事实现算,投影层无人消费该标志(YAGNI)。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_line_inventory_match_projection.py` 追加:
|
||||
|
||||
```python
|
||||
def test_view_exposes_part_available_qty_gated_by_ready():
|
||||
"""料号兜底总量必须随投影透出,且非 ready 一律 None(与 available_qty 同门控)。"""
|
||||
base = {
|
||||
'match_result': 'not_found', 'inventory_status': 'ready',
|
||||
'required_qty': '8', 'available_qty': None,
|
||||
'inventory_snapshot_id': 1, 'matched_at': None,
|
||||
'inventory_source_code': 'DSV', 'detail_json': {},
|
||||
}
|
||||
view = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:not_found 行 available 规范为 0,兜底量原样透出(前端新列数据源)。
|
||||
assert view['available_qty'] == '0'
|
||||
assert view['part_available_qty'] == '9'
|
||||
pending = project_line_inventory_view(
|
||||
has_formal_ot=True, fact={**base, 'inventory_status': 'preparing', 'part_available_qty': '9'},
|
||||
required_qty='8', stored_line_status=None, decision_source=None,
|
||||
can_fulfill_complete_line=False,
|
||||
)
|
||||
# 断言意图:非 ready 一律 pending,兜底量同样不下发,避免半就绪状态误导。
|
||||
assert pending['part_available_qty'] is None
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_projection.py -q -k part_available`
|
||||
Expected: FAIL(KeyError)
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
`serialize_match_fact` 返回 dict 加(`'shortage_qty': row.shortage_qty,` 之后):
|
||||
|
||||
```python
|
||||
'part_available_qty': getattr(row, 'part_available_qty', None),
|
||||
```
|
||||
|
||||
`project_line_inventory_view`:
|
||||
|
||||
1. 在 `qty = normalize_match_quantities(...)` 之后加:
|
||||
|
||||
```python
|
||||
# [STEP] 料号兜底口径:仅库存就绪时透出料号总可用量(与 available_qty 同门控);
|
||||
# 「是否可兜底放行」的判定由自动放行服务基于行事实现算,投影层不下发派生布尔。
|
||||
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||
part_available_value = (
|
||||
str(part_total) if inventory_status == STATUS_READY and part_total is not None else None
|
||||
)
|
||||
```
|
||||
|
||||
2. `has_formal_ot` 为 False 的早退 return 增加形状一致性键:`'part_available_qty': None,`。
|
||||
3. 主 return 增加:`'part_available_qty': part_available_value,`
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_line_inventory_match_projection.py tests/test_line_inventory_allowed_actions.py -q`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/line_inventory_match_projection.py backend/tests/test_line_inventory_match_projection.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: ui_state prep 行下发新字段
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/ui_state.py`(preparation_lines 组装 :966-997)
|
||||
- Test: `backend/tests/test_shipping_notice_ui_state.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 4 的 `inv_view['part_available_qty']`。
|
||||
- Produces: `ui_state.stage_context.preparation.lines[i].part_available_qty: str | None`(前端 Task 9 新列消费;不加派生布尔——自动放行由 Task 7 服务判定,UI 只展示「已放行」结果状态)。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_shipping_notice_ui_state.py` 现有 preparation 投影用例(`test_stage_context_preparation_*` 系列旁)追加,夹具对齐同文件现有 prep 用例:
|
||||
|
||||
```python
|
||||
def test_preparation_lines_carry_part_available_qty():
|
||||
"""prep 行必须下发料号兜底总量,供前端新增「可用数量」列。"""
|
||||
# 复用文件内 prep stage_context 夹具;行 Match 事实 part_available_qty='9'、required '8'。
|
||||
line = state['stage_context']['preparation']['lines'][0]
|
||||
# 断言意图:ui_state 单源直透投影值,前端不做二次推导。
|
||||
assert line['part_available_qty'] == '9'
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_notice_ui_state.py -q -k part_available`
|
||||
Expected: FAIL(KeyError: 'part_available_qty')
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
`preparation_lines.append({...})` 在 `'shortage_qty': inv_view.get('shortage_qty'),` 之后加:
|
||||
|
||||
```python
|
||||
'part_available_qty': inv_view.get('part_available_qty'),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_notice_ui_state.py -q`
|
||||
Expected: PASS
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/ui_state.py backend/tests/test_shipping_notice_ui_state.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: 放行补录字段按料号兜底带出
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py`(`_shortage_release_required_fields` :314-414;调用点:本文件 :918-922(Case 投影)、`decide_review_line_fulfillment` 内校验/落库区 :1117-1256;`backend/app/services/shipping_notice/ui_state.py:946-960` 的调用点)
|
||||
- Test: `backend/tests/test_shipping_review_line_fulfillment_decision.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `ShippingInventoryField.field_code`(`'part_number'` / `'reservation_id'`)、`read_inventory_file_lines(snapshot)` 行 dict(含 field_id 键与 canonical 键)。
|
||||
- Produces:
|
||||
- `_shortage_release_required_fields(...) -> tuple[list[dict[str, Any]], str]`——`(fields, evidence_scope)`,`evidence_scope ∈ {'inventory_snapshot', 'part_fallback'}`;
|
||||
- `decide_review_line_fulfillment` 落库 `snapshot_json['release_field_values']` 从「仅人工补录项」扩展为「自动带出 + 人工补录」**全量**模板字段值字典(导出覆盖读取该字典,见需求假设 4);`snapshot_json['release_evidence_scope']` 记录证据范围。
|
||||
- 放行资格校验(`_is_shortage_match_fact` 409)**不变**;`_validate_inventory_shortage_release_fields` 的必填校验**不变**(人工必填项缺失仍 409),仅其返回值不再是落库字典的唯一来源。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_shipping_review_line_fulfillment_decision.py` 追加(夹具对齐该文件 `test_shortage_release_requires_template_inventory_field_when_snapshot_value_is_ambiguous`——同一套 source/template/profile/快照行构造,把快照行的预约号改为与订单行不同、料号相同):
|
||||
|
||||
```python
|
||||
def test_shortage_release_fields_fall_back_to_part_key_when_reservation_misses():
|
||||
"""预约号在库存中不存在但料号存在时,补录字段必须按料号键带出快照值。"""
|
||||
# 构造:profile.match_keys=[reservation_id, part_number];快照行预约号 'R-INV' ≠ 订单行 'R-ORDER',
|
||||
# 料号相同;模板消费的库存字段在该行有唯一值。
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task, line_index=line_index,
|
||||
inventory_snapshot_id=snapshot.id, inventory_source_code='DSV',
|
||||
)
|
||||
# 断言意图:预约键筛空 → 料号键重筛命中 → 字段自动带值(不再 requires_manual),
|
||||
# 且证据范围显式标记为 part_fallback(审计可见)。
|
||||
assert scope == 'part_fallback'
|
||||
assert all(not field['requires_manual'] for field in fields)
|
||||
|
||||
|
||||
def test_shortage_release_part_fallback_still_manual_when_values_ambiguous():
|
||||
"""料号命中多行且字段值不一致时,该字段必须维持人工必填(fail-closed)。"""
|
||||
# 构造同上,但两条同料号快照行在该模板字段上取值不同。
|
||||
fields, scope = _shortage_release_required_fields(
|
||||
task=task, line_index=line_index,
|
||||
inventory_snapshot_id=snapshot.id, inventory_source_code='DSV',
|
||||
)
|
||||
# 断言意图:scope 仍标记 part_fallback,但分歧字段 requires_manual=True。
|
||||
assert scope == 'part_fallback'
|
||||
assert any(field['requires_manual'] for field in fields)
|
||||
```
|
||||
|
||||
再补一条 decide 集成断言(复用既有 `test_shortage_release_syncs_gate_and_enqueues_auto_fulfill_without_mutating_inventory_fact` 的场景,把快照行预约号改不匹配):
|
||||
|
||||
```python
|
||||
def test_shortage_release_decision_records_part_fallback_scope():
|
||||
"""放行决定的审计快照必须记录证据来源范围(release_evidence_scope)。"""
|
||||
# ...复用既有放行 decide 流程断言,另断言:
|
||||
# 断言意图:审计可回答「放行证据来自预约匹配还是料号兜底」。
|
||||
assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback'
|
||||
|
||||
|
||||
def test_shortage_release_persists_full_template_field_values():
|
||||
"""落库的 release_field_values 必须包含自动带出字段(导出覆盖的唯一来源)。"""
|
||||
# 复用上面预约不匹配场景(字段全部自动带出、无人工补录项),提交放行时
|
||||
# release_field_values 传空 dict:
|
||||
# 断言意图:自动带出值必须落库——export.release_overrides_by_source_line 只读
|
||||
# snapshot_json['release_field_values'],不落库导出 Excel 证据列将为空。
|
||||
assert decision.snapshot_json['release_field_values'] == {'102': 'ODM-001'} # field_id→值,按夹具实际字段
|
||||
```
|
||||
|
||||
> ⚠ 既有用例若断言 `release_field_values` 只含人工提交项(如 `test_shortage_release_rejects_missing_template_inventory_override`),其「缺失仍 409」断言必须保留通过;仅「落库字典内容」断言按全量语义更新。
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py -q -k part_fallback`
|
||||
Expected: FAIL
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
1. `_shortage_release_required_fields` 改为返回 `tuple`。候选行筛选段(现 :388-391)替换为:
|
||||
|
||||
```python
|
||||
candidates = [
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
]
|
||||
evidence_scope = 'inventory_snapshot'
|
||||
if not candidates:
|
||||
# [STEP] 料号兜底(2026-10 需求):预约键在库存中无命中时,按料号键重筛证据行。
|
||||
# 仅识别 field_code='part_number' 的匹配键;识别不到则维持空候选(全人工补录,fail-closed)。
|
||||
part_field_ids = {
|
||||
int(field_id) for field_id, _value in expected
|
||||
if str(getattr(ShippingInventoryField.query.get(int(field_id)), 'field_code', '') or '') == 'part_number'
|
||||
}
|
||||
if part_field_ids:
|
||||
candidates = [
|
||||
dict(row) for row in inventory_lines
|
||||
if all(_match_text(row.get(str(field_id))) == value
|
||||
for field_id, value in expected if int(field_id) in part_field_ids)
|
||||
]
|
||||
if candidates:
|
||||
evidence_scope = 'part_fallback'
|
||||
```
|
||||
|
||||
函数末尾 `return _release_template_inventory_fields(...)` 改为 `return _release_template_inventory_fields(...), evidence_scope`(`snapshot is None` 的早退分支返回 `([...], 'inventory_snapshot')`)。
|
||||
|
||||
2. 更新两个调用点接收元组(**只取 fields,scope 不进投影契约**——前端本期不消费,避免死字段;scope 仅在 3 的决策快照落值):
|
||||
- Case 投影(本文件 :918-922):`fields, _scope = _shortage_release_required_fields(...)`,行投影结构不变。
|
||||
- `ui_state.py:946-960`:同样 `fields, _scope = ...`,prep 行结构不变。
|
||||
3. `decide_review_line_fulfillment`:放行分支调用处解包,并把 `'release_evidence_scope': evidence_scope` 写入 `snapshot_json`(现 :1223-1256 的 dict 字面量)。
|
||||
4. `release_field_values` 落库改为**全量**模板字段值:`{field['field_id']: (人工提交值 if field_id in 人工必填 else field['value']) for field in fields}`——即以自动带出值为底、人工提交值覆盖;`_validate_inventory_shortage_release_fields` 的必填校验与白名单校验保持原样(人工必填缺失仍 409),仅落库字典不再经白名单裁剪。
|
||||
|
||||
- [ ] **Step 4: 运行确认通过**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py tests/test_shipping_notice_ui_state.py -q`
|
||||
Expected: PASS(既有放行用例不回归——预约命中场景 scope 恒为 'inventory_snapshot')
|
||||
|
||||
- [ ] **Step 5: 守护 Excel 不变**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py tests/test_shipping_stp_match_completed_gate.py -q`
|
||||
Expected: 全绿(未改任何导出/波次/聚合代码的证明)
|
||||
|
||||
- [ ] **Step 6: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/app/services/shipping_notice/ui_state.py backend/tests/test_shipping_review_line_fulfillment_decision.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: 料号兜底自动放行服务
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py`(从 `decide_review_line_fulfillment` 放行分支提取共享内部函数;新增 `auto_release_part_fallback_shortages`)
|
||||
- Modify: `backend/app/services/shipping_notice/fulfillment_workflow.py`(`match_inventory` :1775-1870 尾部、`match_inventory_line` :1272 附近落库后挂钩子)
|
||||
- Test: `backend/tests/test_shipping_review_line_fulfillment_decision.py`、`backend/tests/test_shipping_stp_match_completed_gate.py`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 4 的行事实(`part_available_qty`,经 `load_current_match_facts_by_task`)、Task 6 的证据解析(`_shortage_release_required_fields` 全自动取值)。
|
||||
- Produces:
|
||||
- `_apply_shortage_line_release(task, line_index, release_field_values, *, evidence_scope, actor_type, actor_id, auto_release: bool) -> ShippingOrderReviewLineDecision`——人工 decide 与自动放行共用的落库+审计+`_sync_confirmed_task_fulfillment_gates` 执行体(从现 :1117-1256 放行分支原样提取,行为不变);
|
||||
- `auto_release_part_fallback_shortages(task, *, actor_id=None) -> list[int]`——返回自动放行的 line_index 列表;单行异常捕获记审计,不中断整批。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
在 `backend/tests/test_shipping_review_line_fulfillment_decision.py` 追加(复用既有放行夹具 + Task 6 的预约不匹配快照行构造;匹配夹具对齐 `test_shipping_stp_match_completed_gate.py` 的 match 构造):
|
||||
|
||||
```python
|
||||
def test_auto_release_runs_after_match_when_part_total_satisfies():
|
||||
"""料号兜底量满足且证据全自动取值时,匹配完成后必须系统自动放行。"""
|
||||
# 构造:订单行需求 8、预约不匹配(not_found)、同料号允许源内总量 9、
|
||||
# 模板字段全部可由料号命中的快照行唯一取值。执行 match_inventory(...)。
|
||||
decision = 活动放行决定(task) # 按文件内既有 helper 读取活动 release_inventory_shortage 决定
|
||||
# 断言意图:无需任何人工动作,缺口行已被系统放行且标记来源。
|
||||
assert decision is not None
|
||||
assert decision.snapshot_json['auto_release'] is True
|
||||
assert decision.snapshot_json['release_evidence_scope'] == 'part_fallback'
|
||||
|
||||
|
||||
def test_auto_release_skips_when_part_total_below_required():
|
||||
"""料号兜底量不足时不得自动放行,行保持人工待处置。"""
|
||||
# 同上构造,但料号总量改为 3(< 8)。
|
||||
# 断言意图:不足行维持 shortage 等人工;聚合仍为 shortage。
|
||||
assert 活动放行决定(task) is None
|
||||
|
||||
|
||||
def test_auto_release_skips_when_evidence_field_ambiguous():
|
||||
"""证据字段无法唯一取值(requires_manual 残留)时不得自动放行。"""
|
||||
# 同上构造,但两条同料号快照行在模板字段上取值不同。
|
||||
# 断言意图:降级为人工放行(补录要求保留),不产生自动决定。
|
||||
assert 活动放行决定(task) is None
|
||||
|
||||
|
||||
def test_auto_release_does_not_duplicate_existing_decision():
|
||||
"""已有人工放行/结案决定(或已放行)的行不得重复自动放行。"""
|
||||
# 先人工放行该行,再重跑 match_inventory。
|
||||
# 断言意图:幂等——不新建第二个活动决定,原决定保持不变。
|
||||
assert 活动决定数量(task, 'release_inventory_shortage') == 1
|
||||
|
||||
|
||||
def test_auto_release_counted_in_sufficiency_and_gate_releases():
|
||||
"""自动放行后聚合满足、sufficiency 门禁放行(复用既有 released 语义)。"""
|
||||
# 断言意图:自动放行走同一聚合/门禁链路——match_completed 通过,
|
||||
# inventory_sufficiency 不再因该行 blocked_manual。
|
||||
assert match_completed(task) is True
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 运行确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py -q -k auto_release`
|
||||
Expected: FAIL(无自动放行行为)
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
1. **提取共享执行体**:把 `decide_review_line_fulfillment` 放行分支的落库段(创建/激活 `ShippingOrderReviewLineDecision`、`_validate_inventory_shortage_release_fields` 调用、`_sync_confirmed_task_fulfillment_gates`、审计)原样提取为 `_apply_shortage_line_release(...)`(签名见 Interfaces);decide 分支改为调用它(行为零变化,既有用例守护)。
|
||||
2. **自动放行服务**(同文件新增):
|
||||
|
||||
```python
|
||||
def auto_release_part_fallback_shortages(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
actor_id: int | None = None,
|
||||
) -> list[int]:
|
||||
"""
|
||||
匹配落库后按料号兜底自动放行缺口行(用户确认语义:满足即自动放行,非仅可放行)。
|
||||
|
||||
核心逻辑:仅处理「ready + 缺口 + 料号总量≥需求 + 无活动决定 + 证据字段全部可
|
||||
自动取值」的行;任一条件不满足(含证据解析 ConflictError)一律跳过并保持人工
|
||||
路径,fail-closed 不变。复用 _apply_shortage_line_release,审计/门禁同步/自动
|
||||
履约入队与人工放行完全一致;幂等由「已放行行跳过」保证,不自动撤销既有放行。
|
||||
|
||||
Args:
|
||||
task: 正式任务聚合根。
|
||||
actor_id: 触发匹配的用户(审计归属);自动决定本身 actor_type='system'。
|
||||
|
||||
Returns:
|
||||
自动放行的 line_index 列表。
|
||||
"""
|
||||
released: list[int] = []
|
||||
facts = load_current_match_facts_by_task(getattr(task, 'id', None))
|
||||
decided_indexes = 活动决定行索引集合(task) # 复用既有查询:release/close 活动决定的 line_index
|
||||
for line_index, fact in sorted(facts.items()):
|
||||
try:
|
||||
required = _parse_qty(fact.get('required_qty'))
|
||||
part_total = _parse_qty(fact.get('part_available_qty'))
|
||||
if line_index in decided_indexes:
|
||||
continue
|
||||
if not _is_shortage_match_fact(fact):
|
||||
continue
|
||||
if part_total is None or required is None or part_total < required:
|
||||
continue
|
||||
fields, evidence_scope = _shortage_release_required_fields(
|
||||
task=task, line_index=line_index,
|
||||
inventory_snapshot_id=fact.get('inventory_snapshot_id'),
|
||||
inventory_source_code=fact.get('inventory_source_code'),
|
||||
)
|
||||
if any(bool(field.get('requires_manual')) for field in fields):
|
||||
continue
|
||||
auto_values = {
|
||||
str(field['field_id']): field.get('value')
|
||||
for field in fields
|
||||
}
|
||||
_apply_shortage_line_release(
|
||||
task, line_index, auto_values,
|
||||
evidence_scope=evidence_scope, actor_type='system', actor_id=actor_id,
|
||||
auto_release=True,
|
||||
)
|
||||
released.append(line_index)
|
||||
except ConflictError:
|
||||
# 证据不可解析(无源/模板未发布/无快照)→ 维持人工路径,不中断其余行。
|
||||
continue
|
||||
return released
|
||||
```
|
||||
|
||||
(`_parse_qty` 从 `line_inventory_match_projection` 复用;`活动决定行索引集合`/`活动放行决定` 按文件内既有查询 helper 落地。)
|
||||
|
||||
3. **匹配钩子**:`fulfillment_workflow.py` 的 `match_inventory`(持久化与聚合重算完成、return 之前)与 `match_inventory_line`(行持久化之后)加:
|
||||
|
||||
```python
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
auto_release_part_fallback_shortages,
|
||||
)
|
||||
|
||||
auto_released = auto_release_part_fallback_shortages(task)
|
||||
if auto_released:
|
||||
# 自动放行内部已重算聚合并同步门禁/自动履约;此处仅在审计上记录匹配触发的放行。
|
||||
...
|
||||
```
|
||||
|
||||
(`match_inventory` 末尾的 `match_completed` 判定放在钩子**之后**执行,使放行行计入满足、任务可直接落 `MATCHED_FULFILLABLE`;`match_inventory_line` 同理在其聚合重算前挂钩子。若提取后顺序约束冲突,以「先钩子后聚合判定」为准并加注释说明。)
|
||||
|
||||
- [ ] **Step 4: 运行确认通过 + 守护不变**
|
||||
|
||||
```bash
|
||||
cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_review_line_fulfillment_decision.py tests/test_shipping_stp_match_completed_gate.py tests/test_shipping_line_scoped_inventory_retry.py tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py -q
|
||||
```
|
||||
|
||||
Expected: 全绿。特别核对:`test_match_completed_rejects_partial`(未达兜底的 partial 行仍阻断)、波次用例(出单仍需人工勾选,自动放行只是让行获得可勾选资格)。
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py backend/app/services/shipping_notice/fulfillment_workflow.py backend/tests/test_shipping_review_line_fulfillment_decision.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: 前端 i18n 四语言新增键
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/locales/zh-CN/chat.json`、`zh-TW/chat.json`、`en/chat.json`、`th/chat.json`(`shippingOrderReview.lifecycle.prepare` 块,zh-CN 约 :1721-1737;**该块为单行 JSON**,用 Edit 工具精确子串替换)
|
||||
|
||||
**Interfaces:**
|
||||
- Produces: `chat.shippingOrderReview.lifecycle.prepare.reservedQty`、`.partAvailableQty`,Task 9 模板消费。
|
||||
|
||||
- [ ] **Step 1: 四语言各加两键**
|
||||
|
||||
在每语言 `lifecycle.prepare` 对象内 `"requiredQty"` 键旁插入(保持键序:`requiredQty` 之后):
|
||||
|
||||
| 键 | zh-CN | zh-TW | en | th |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `reservedQty` | `预约数量` | `預約數量` | `Reserved qty` | `จำนวนตามใบจอง` |
|
||||
| `partAvailableQty` | `可用数量` | `可用數量` | `Available qty` | `จำนวนที่ใช้ได้` |
|
||||
|
||||
示例(zh-CN,`"requiredQty": "需求数量",` 后插入):
|
||||
|
||||
```json
|
||||
"reservedQty": "预约数量", "partAvailableQty": "可用数量",
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 校验 JSON 合法**
|
||||
|
||||
```bash
|
||||
cd frontend && node -e "['zh-CN','zh-TW','en','th'].forEach(l=>{JSON.parse(require('fs').readFileSync('src/locales/'+l+'/chat.json','utf8'));console.log(l+' ok')})"
|
||||
```
|
||||
|
||||
Expected: 四行 ok
|
||||
|
||||
- [ ] **Step 3: Stage**
|
||||
|
||||
```bash
|
||||
git add frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 9: 前端类型 + 库存匹配表列改造 + spec
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/types/shipping.api.types.ts`(prep 行匿名类型 :1522-1545)
|
||||
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(表头 :5332、单元格 :5333、`formalPreparationLines` :2565-2573、releaseBar colspan :5333 内 `colspan="12"`)
|
||||
- Test: `frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts`
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: 后端 prep 行 `part_available_qty`(Task 5)、i18n 键(Task 8)。
|
||||
- Produces: 表格列序 `… 需求数量 | 库存源 | 预约数量 | 可用数量 | 缺口 | 匹配状态 …`。
|
||||
|
||||
- [ ] **Step 1: 类型扩展**
|
||||
|
||||
仅 prep 行匿名类型(:1531 `available_qty` 旁)加:
|
||||
|
||||
```typescript
|
||||
/** 料号维度总可用量(忽略预约号、行允许源内汇总);无快照/未就绪为 null。 */
|
||||
part_available_qty?: string | null;
|
||||
```
|
||||
|
||||
(不动 `ShippingOrderReviewLineFulfillmentLine`——Case 行投影本期不下发该字段,不加备用字段。)
|
||||
|
||||
- [ ] **Step 2: 更新 spec 断言(先写失败测试)**
|
||||
|
||||
`ShippingOrderReviewView.spec.ts`:
|
||||
|
||||
1. i18n mock(:648 附近 `fulfillmentDecision` 同级或 `prepare` mock 块)补 `reservedQty: '预约数量', partAvailableQty: '可用数量'`(对齐该 mock 的组织方式)。
|
||||
2. 在既有 prep workspace 用例(:2689 附近 prep line mock `available_qty: null` 处)给 prep 行加 `part_available_qty: '9'`,并新增断言:
|
||||
|
||||
```typescript
|
||||
// 断言意图:原可用数量列头改由 reservedQty 键渲染(预约数量),
|
||||
// 新增料号总库存列紧随其后,值来自 part_available_qty。
|
||||
const headers = Array.from(workspace.querySelectorAll('thead th')).map((th) => th.textContent);
|
||||
expect(headers).toContain('预约数量');
|
||||
expect(headers.indexOf('可用数量')).toBe(headers.indexOf('预约数量') + 1);
|
||||
expect(workspace.textContent).toContain('9');
|
||||
```
|
||||
|
||||
(挂载/查询方式对齐该用例现有写法。)
|
||||
|
||||
- [ ] **Step 3: 运行确认失败**
|
||||
|
||||
Run: `cd frontend && npx vitest run src/features/chat/views/ShippingOrderReviewView.spec.ts`(若 vitest 环境仍损坏——node:crypto 问题——则跳过本步与 Step 6,以 `npm run build` + 人工核对代替,并在任务备注中说明)
|
||||
|
||||
Expected: FAIL
|
||||
|
||||
- [ ] **Step 4: 视图改造**
|
||||
|
||||
1. `formalPreparationLines`(:2565-2573)的映射对象加:
|
||||
|
||||
```typescript
|
||||
part_available_qty:
|
||||
line.part_available_qty == null ? null : displayDecimalQty(line.part_available_qty),
|
||||
```
|
||||
|
||||
2. 表头(:5332)把 `<th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th>` 替换为:
|
||||
|
||||
```html
|
||||
<th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.reservedQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.partAvailableQty') }}</th>
|
||||
```
|
||||
|
||||
3. 单元格(:5333)把 `<td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td>` 替换为:
|
||||
|
||||
```html
|
||||
<td class="whitespace-nowrap px-3 py-2">{{ line.available_qty ?? '—' }}</td><td class="whitespace-nowrap px-3 py-2">{{ line.part_available_qty ?? '—' }}</td>
|
||||
```
|
||||
|
||||
(原绑定保留=预约数量列;新列取 `part_available_qty`。pending 态后端已下发 null,无需前端再判。)
|
||||
|
||||
4. 同一单元格行内的 releaseBar 展开行 `<td :colspan="12"` 改为 `<td :colspan="13"`(新增一列)。
|
||||
5. **不改**:`formalPreparationLineStatusLabel`、行背景 class、`releaseBarHasFields`(仍以 `shortage_qty>0` 为准)、`preparationWaveSelectableLines`、`linesTableColumnCount`(那是订单明细表 colspan,明细表不动)。
|
||||
|
||||
- [ ] **Step 5: 构建 + 测试**
|
||||
|
||||
```bash
|
||||
cd frontend && npm run build
|
||||
```
|
||||
|
||||
Expected: 构建通过(vitest 环境损坏期间的替代验收,见 docs 记忆「vitest 环境损坏」)。
|
||||
|
||||
- [ ] **Step 6: Stage**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/chat/types/shipping.api.types.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 10: 文档同步
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/features/shipping-notice/technical.md`(文末追加章节)
|
||||
- Modify: `docs/features/shipping-notice/business.md`(追加业务规则节)
|
||||
- Modify: `docs/funclist.md`(shipping-notice 表追加 1-2 行)
|
||||
- Modify: `docs/demand.md`(缺口放行规则变化说明)
|
||||
|
||||
- [ ] **Step 1: technical.md 追加「料号兜底自动放行与数量列(2026-10-09)」**
|
||||
|
||||
要点(只追加不改史):缺口判定仍按预约+料号;匹配器下发 `part_available_qty`(口径=行允许源内、忽略预约号、不限单位;跨源不合并;conflict/invalid/缺料号不下发);新列 `shipping_notice_line_inventory_matches.part_available_qty`(迁移),投影/ui_state 仅透出该数量;**自动放行**:匹配落库后对「缺口+料号总量≥需求+证据字段全部自动取值」的行由系统创建放行决定(`auto_release: true`、`release_evidence_scope` 审计;证据不可解析/字段分歧/总量不足时降级人工;不自动撤销);`release_field_values` 扩展为全量字段值(导出覆盖来源);Excel/波次条件不变(出单仍需人工勾选波次,放行行可勾选资格不变);存量行为 NULL 不回填。并注明:明细表/聊天匹配卡的「可用数量」仍是预约匹配语义,与 prep 表新「可用数量」(料号总量)同名不同义,是否统一待产品定。
|
||||
|
||||
- [ ] **Step 2: business.md / demand.md / funclist.md**
|
||||
|
||||
- business.md:新增「缺口放行(料号兜底自动放行)」小节:料号总库存满足需求时系统自动放行(无需人工确认),放行证据带出优先级(预约匹配 → 料号兜底);证据无法自动取值或料号总量不足时降级为人工放行;Excel 出单条件表述不变(出单仍由用户勾选触发)。
|
||||
- demand.md:在库存缺口/放行相关需求条目下补充该规则变化。
|
||||
- funclist.md:shipping-notice 表加行「库存匹配料号兜底自动放行与料号维度可用数量展示(已实现)」。
|
||||
|
||||
- [ ] **Step 3: Stage**
|
||||
|
||||
```bash
|
||||
git add docs/features/shipping-notice/technical.md docs/features/shipping-notice/business.md docs/funclist.md docs/demand.md
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 11: 全量回归
|
||||
|
||||
- [ ] **Step 1: 后端定向回归**
|
||||
|
||||
```bash
|
||||
cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_shipping_stp_phase4_line_inventory_match.py tests/test_line_inventory_match_persistence.py tests/test_line_inventory_match_projection.py tests/test_line_inventory_allowed_actions.py tests/test_shipping_notice_ui_state.py tests/test_shipping_review_line_fulfillment_decision.py tests/test_post_ot_fulfillment_wave_p0.py tests/test_shipping_rolling_fulfillment.py tests/test_shipping_stp_match_completed_gate.py tests/test_shipping_line_scoped_inventory_retry.py -q
|
||||
```
|
||||
|
||||
Expected: 全绿(既有 6 个已知 WIP 失败不在上述文件中;若出现需先比对 HEAD 判断归属)。
|
||||
|
||||
- [ ] **Step 2: 前端构建**
|
||||
|
||||
```bash
|
||||
cd frontend && npm run build
|
||||
```
|
||||
|
||||
Expected: 通过。
|
||||
|
||||
- [ ] **Step 3: 人工冒烟清单(test 环境部署后)**
|
||||
|
||||
1. 通知准备存在「预约不匹配但料号总量足够」的行:重取库存/重新匹配后**行自动变为「已放行」**(无需人工点击),表格显示 预约数量 0 / 可用数量(料号总量)≥需求。
|
||||
2. 自动放行行获得出单资格:勾选生成 Excel 行数计入;导出 Excel 中该行证据列有值(来自料号命中行)。
|
||||
3. 料号总量也不足的行:可用数量显示不足值,行保持「库存不足」,人工放行时补录字段按预约优先→料号兜底带出,剩余项人工必填。
|
||||
4. 证据字段存在分歧(同料号多行值不一致)的行:不自动放行,维持人工补录。
|
||||
5. 「重新匹配库存 / 重新获取库存」后历史 NULL 行回填新列;已自动放行的行重匹配后不重复建决定、不撤销。
|
||||
|
||||
---
|
||||
|
||||
## Self-Review 记录
|
||||
|
||||
- 规格覆盖:需求点 1(列改名)→ Task 8/9;需求点 2(新增料号可用数量列)→ Task 1-5/8/9;料号兜底**自动放行** → Task 6(证据全量带出+落库)+ Task 7(自动放行服务与匹配钩子);Excel/波次条件不变 → 全局不动清单 + Task 6/7 守护步骤;文档 → Task 10。
|
||||
- 占位符扫描:Task 3/5/6/7 的测试步骤要求执行者对齐既有夹具(夹具构造依赖运行时数据库对象,不适合在本计划内伪写完整代码),已给出断言语义注释与对齐用例名,属可执行指引而非 TODO;Task 7 服务实现中的 `活动决定行索引集合`/`活动放行决定` 为既有查询 helper 的语义占位,执行者按文件内现有决定查询落地。
|
||||
- 类型一致性:`part_available_qty` 链路 float(匹配器)→ String(32) 列(持久化)→ str(serialize/投影/ui_state)→ `string | null`(TS)一致;`evidence_scope` 在 Task 6/7 流转并在决策快照落值;自动放行复用 `_apply_shortage_line_release` 单一执行体,无平行落库路径。
|
||||
@@ -261,7 +261,7 @@ watch(
|
||||
type="date"
|
||||
:value="params[field.key] ?? ''"
|
||||
class="input-field w-full !text-sm !leading-5"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value)"
|
||||
@input="setField(field.key, ($event.target as HTMLInputElement).value === '' ? null : ($event.target as HTMLInputElement).value)"
|
||||
/>
|
||||
<input
|
||||
v-else-if="field.type === 'datetime'"
|
||||
@@ -341,7 +341,7 @@ watch(
|
||||
v-model="multiSearch[field.key]"
|
||||
type="text"
|
||||
class="mb-1 w-full rounded-lg border border-default px-2 py-1.5 text-sm outline-none focus:border-blue-500"
|
||||
:placeholder="$t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
|
||||
:placeholder="resolveText(field.placeholder_key, field.placeholder) || $t('admin.schedule.form.dynamicParamsSearchPlaceholder')"
|
||||
/>
|
||||
<p v-if="optionsLoading[field.options_source || '']" class="px-2 py-1 text-xs text-muted">
|
||||
{{ $t('admin.schedule.form.dynamicParamsOptionsLoading') }}
|
||||
|
||||
+3
-2
@@ -877,7 +877,6 @@ onMounted(() => {
|
||||
}
|
||||
.edit-card .input-field, .impact-dialog .input-field, .impact-dialog .select-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }
|
||||
.actions, .impact-dialog footer { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.impact-dialog footer { justify-content: flex-end; }
|
||||
.link-list, .plain-list { margin: 0; padding-left: 1.1rem; color: #475569; font-size: 13px; }
|
||||
.adoption-link { color: #0369a1; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.adoption-link:hover { color: #0c4a6e; }
|
||||
@@ -924,10 +923,12 @@ onMounted(() => {
|
||||
background: var(--overlay-soft); padding: 24px;
|
||||
}
|
||||
.impact-dialog {
|
||||
display: grid; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow: auto;
|
||||
display: grid; grid-auto-rows: max-content; width: min(520px, 96vw); max-height: 82vh; gap: 14px; overflow-y: auto;
|
||||
border-radius: 12px; background: #fff; padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24);
|
||||
}
|
||||
.impact-dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
/* footer 用 sticky 钉在对话框可视底部:内容超高时确认/取消始终可见,不随表单或影响列表滚动消失(负 margin 抵消对话框 padding 实现通栏) */
|
||||
.impact-dialog footer { position: sticky; bottom: -18px; justify-content: flex-end; margin: 4px -18px -18px; border-top: 1px solid var(--border-default); background: #fff; padding: 12px 18px; }
|
||||
.impact-dialog h2, .impact-dialog p { margin: 0; }
|
||||
.impact-summary {
|
||||
display: grid; gap: 8px; border: 1px solid #fecaca; border-radius: 8px;
|
||||
|
||||
+13
-11
@@ -316,14 +316,15 @@ onMounted(() => { void load(); });
|
||||
.identity-hero h1 { margin: 0; }
|
||||
.identity-hero p { max-width: 760px; }
|
||||
.identity-hero__meta { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; justify-content: flex-end; }
|
||||
.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bfe7f8; border-radius: 999px; background: #effaff; color: #087aaa; font-size: .78rem; font-weight: 700; white-space: nowrap; }
|
||||
.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #18b17c; box-shadow: 0 0 0 4px #dff8ed; }.identity-pulse--draft { background: #e09b22; box-shadow: 0 0 0 4px #fff2d5; }
|
||||
/* 状态/品牌色统一 Tailwind 标准语义值(brand=sky 系 #0284c7、启用=green、草稿=amber),不再使用自造蓝绿 */
|
||||
.identity-hero__status { display: inline-flex; align-items: center; gap: .48rem; padding: .5rem .75rem; border: 1px solid #bae6fd; border-radius: 999px; background: #f0f9ff; color: #0369a1; font-size: .78rem; font-weight: 700; white-space: nowrap; }
|
||||
.identity-pulse { width: .5rem; height: .5rem; border-radius: 50%; background: #10b981; box-shadow: 0 0 0 4px #d1fae5; }.identity-pulse--draft { background: #f59e0b; box-shadow: 0 0 0 4px #fef3c7; }
|
||||
.identity-hero__link { display: inline-flex; align-items: center; gap: .35rem; white-space: nowrap; }
|
||||
.identity-flow { position: relative; display: grid; grid-template-columns: repeat(3, 1fr); gap: .6rem; padding: 1rem; overflow: hidden; border: 1px solid #dce9f2; border-radius: 1rem; background: linear-gradient(105deg, #f4fbff, #fff); }
|
||||
.identity-flow__rail { position: absolute; top: 1.84rem; left: 12%; right: 12%; height: 1px; background: #cce5f2; }
|
||||
.identity-flow__step { position: relative; z-index: 1; display: flex; gap: .75rem; align-items: flex-start; min-width: 0; }
|
||||
.identity-flow__step > span { display: grid; place-items: center; flex: 0 0 1.65rem; height: 1.65rem; border: 1px solid #b9d8e8; border-radius: 50%; background: #fff; color: #6b8298; font-size: .66rem; font-weight: 800; }
|
||||
.identity-flow__step--active > span { border-color: #0d93cf; background: #0d93cf; color: #fff; box-shadow: 0 0 0 4px #dff4fc; }
|
||||
.identity-flow__step--active > span { border-color: #0284c7; background: #0284c7; color: #fff; box-shadow: 0 0 0 4px #e0f2fe; }
|
||||
.identity-flow strong { display: block; color: #193652; font-size: .82rem; font-weight: 800; }
|
||||
.identity-flow small { display: -webkit-box; overflow: hidden; margin-top: .15rem; color: #7a8fa6; font-size: .72rem; line-height: 1.45; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
|
||||
.identity-loading { display: flex; align-items: center; gap: .5rem; padding: 2rem; color: #6f839b; font-size: .9rem; }
|
||||
@@ -336,12 +337,12 @@ onMounted(() => { void load(); });
|
||||
.identity-definition-list { display: grid; }
|
||||
.identity-definition-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto auto; gap: .75rem; align-items: center; padding: .78rem 1.35rem; border-bottom: 1px solid #edf3f7; transition: background .18s ease; }
|
||||
.identity-definition-row:hover { background: #f7fbfd; }
|
||||
.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #e9f7fd; color: #0b90cc; }
|
||||
.identity-definition-row__icon { display: grid; place-items: center; width: 2rem; height: 2rem; border-radius: .6rem; background: #f0f9ff; color: #0284c7; }
|
||||
.identity-definition-row strong { color: #1a3856; font-size: .86rem; font-weight: 750; }
|
||||
.identity-definition-row p { overflow: hidden; margin-top: .18rem; color: #8194a8; font-size: .72rem; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.identity-target, .identity-automation { padding: .32rem .52rem; border-radius: 999px; background: #f1f5f8; color: #677f98; font-size: .7rem; white-space: nowrap; }
|
||||
.identity-automation-select { border: 1px solid #dce8ef; cursor: pointer; }
|
||||
.identity-automation--enabled { background: #e4f8ef; color: #12865c; }
|
||||
.identity-automation--enabled { background: #dcfce7; color: #15803d; }
|
||||
.identity-empty { display: flex; align-items: center; gap: .55rem; min-height: 5.5rem; padding: 1.2rem 1.35rem; color: #7c91a7; font-size: .82rem; }
|
||||
.identity-definition-form { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: .85rem; padding: 1.1rem 1.35rem 1.35rem; background: linear-gradient(135deg, #f7fbfd 0%, #f3f9fc 100%); }
|
||||
.identity-form-title { grid-column: 1 / -1; display: flex; align-items: center; gap: .42rem; color: #173857; font-size: .85rem; }
|
||||
@@ -349,13 +350,13 @@ onMounted(() => { void load(); });
|
||||
.identity-definition-form label { display: grid; gap: .35rem; color: #667f99; font-size: .72rem; font-weight: 700; }
|
||||
.identity-label-with-tip { display: inline-flex; align-items: center; gap: .28rem; }
|
||||
.identity-label-tip { width: .9rem; height: .9rem; color: #7d93a8; cursor: help; }
|
||||
.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7cc7eb; outline-offset: 2px; }
|
||||
.identity-label-tip:focus-visible { border-radius: 50%; outline: 2px solid #7dd3fc; outline-offset: 2px; }
|
||||
.identity-definition-form label small { color: #8295a8; font-size: .67rem; font-weight: 500; line-height: 1.35; }
|
||||
.identity-definition-form .input-field, .identity-static-field { box-sizing: border-box; min-width: 0; height: 2.75rem; padding: 0 .8rem; border-color: #d9e7ef; background: #fff; font-size: .83rem; line-height: 1.25; }
|
||||
.identity-definition-form select.input-field { padding-top: 0; padding-bottom: 0; line-height: 2.75rem; }
|
||||
.identity-static-field { display: flex; align-items: center; padding: 0 .8rem; border: 1px solid #d9e7ef; border-radius: .65rem; color: #5f7893; }
|
||||
.identity-source-help { display: grid; align-content: center; gap: .12rem; min-height: 2.75rem; padding: .48rem .7rem; border: 1px solid #d6eaf5; border-radius: .65rem; background: #edf8fe; color: #537189; font-size: .69rem; line-height: 1.35; }
|
||||
.identity-source-help strong { color: #187eae; font-size: .72rem; }.identity-source-help small { color: #2e9068; font-size: .68rem; }
|
||||
.identity-source-help strong { color: #0369a1; font-size: .72rem; }.identity-source-help small { color: #16a34a; font-size: .68rem; }
|
||||
.identity-definition-form__submit { display: inline-flex; align-items: center; justify-content: center; gap: .4rem; align-self: end; min-height: 2.5rem; }
|
||||
.identity-panel--publication { position: sticky; top: 1rem; padding: 1.25rem; }
|
||||
.identity-publication__header { display: flex; align-items: center; justify-content: space-between; gap: .75rem; }
|
||||
@@ -363,7 +364,7 @@ onMounted(() => { void load(); });
|
||||
.identity-publication__hint { margin: .75rem 0 1rem; color: #75899f; font-size: .78rem; line-height: 1.6; }
|
||||
.identity-version-list { display: flex; flex-wrap: wrap; gap: .5rem; padding-bottom: 1rem; border-bottom: 1px solid #e9f0f4; }
|
||||
.identity-version { display: inline-flex; align-items: center; gap: .35rem; padding: .46rem .6rem; border: 1px solid #dbe7ee; border-radius: .6rem; background: #fff; color: #668099; font-size: .73rem; transition: all .18s ease; }
|
||||
.identity-version:hover, .identity-version--selected { border-color: #0b91cd; background: #eefaff; color: #087cae; }
|
||||
.identity-version:hover, .identity-version--selected { border-color: #0284c7; background: #f0f9ff; color: #0369a1; }
|
||||
.identity-version span { font-weight: 800; }.identity-version small { font-size: .68rem; }
|
||||
.identity-selection { margin: 1rem 0; }
|
||||
.identity-published-definitions { margin: 1rem 0; }
|
||||
@@ -374,12 +375,13 @@ onMounted(() => { void load(); });
|
||||
.identity-published-definition small { margin-top: .15rem; color: #8194a8; font-size: .68rem; }
|
||||
.identity-published-empty { margin: 0; color: #8194a8; font-size: .76rem; }
|
||||
.identity-selection__heading { display: flex; justify-content: space-between; margin-bottom: .6rem; color: #274563; font-size: .78rem; font-weight: 750; }
|
||||
.identity-selection__heading strong { color: #0a8bc4; }
|
||||
.identity-selection__heading strong { color: #0284c7; }
|
||||
.identity-check-row { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: .5rem; padding: .54rem 0; border-bottom: 1px dashed #e2ebf1; color: #37516c; font-size: .78rem; }
|
||||
.identity-check-row input { accent-color: #0c94ce; }.identity-check-row small { color: #8496a8; font-size: .68rem; }
|
||||
/* @tailwindcss/forms 接管原生 checkbox 后 accent-color 无效:勾选填充取 currentColor,用 color 指定选中蓝 */
|
||||
.identity-check-row input { color: #0284c7; }.identity-check-row small { color: #8496a8; font-size: .68rem; }
|
||||
.identity-publication__actions { display: grid; grid-template-columns: 1fr 1fr; gap: .65rem; padding-top: 1rem; }
|
||||
.identity-publication__actions .btn-primary, .identity-publication__actions .btn-ghost { min-width: 0; font-size: .79rem; }
|
||||
.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #eaf9f0; color: #16895e; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #56826f; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.identity-published { grid-column: 1 / -1; display: grid; grid-template-columns: auto auto minmax(0, 1fr); align-items: center; gap: .45rem; padding: .7rem; border-radius: .65rem; background: #dcfce7; color: #15803d; font-size: .78rem; font-weight: 700; }.identity-published code { overflow: hidden; color: #16a34a; font-size: .67rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@media (max-width: 980px) { .identity-workbench { grid-template-columns: 1fr; }.identity-panel--publication { position: static; }.identity-hero { align-items: flex-start; flex-direction: column; gap: .85rem; }.identity-hero__meta { justify-content: flex-start; }.identity-flow__rail { display: none; } }
|
||||
@media (max-width: 700px) { .identity-rules-page { gap: 1rem; }.identity-flow { grid-template-columns: 1fr; }.identity-definition-form { grid-template-columns: 1fr; }.identity-definition-row { grid-template-columns: auto minmax(0, 1fr); }.identity-target, .identity-automation { justify-self: start; }.identity-panel__heading { align-items: flex-start; flex-direction: column; }.identity-panel__heading > p { text-align: left; }.identity-definition-row__icon { grid-row: span 2; }.identity-publication__actions { grid-template-columns: 1fr; } }
|
||||
@media (prefers-reduced-motion: reduce) { .identity-definition-row, .identity-version { transition: none; } }
|
||||
|
||||
@@ -146,8 +146,8 @@
|
||||
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
|
||||
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
|
||||
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<button type="button" class="btn-danger btn-sm" @click="source.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
@@ -172,8 +172,8 @@
|
||||
<input v-model="parameter.name" class="input-field" :placeholder="t('admin.shippingInventory.parameterName')">
|
||||
<select v-model="parameter.mode" class="select-field"><option value="single">{{ t('admin.shippingInventory.single') }}</option><option value="multi_text">{{ t('admin.shippingInventory.multiText') }}</option><option value="multi_select">{{ t('admin.shippingInventory.multiSelect') }}</option></select>
|
||||
<input class="input-field" :value="parameter.values.join(', ')" :placeholder="t('admin.shippingInventory.parameterValues')" @input="parameter.values = splitValues(($event.target as HTMLInputElement).value)">
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.required" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.required') }}</label>
|
||||
<label class="inline-check"><input v-model="parameter.select_all" type="checkbox" class="admin-checkbox">{{ t('admin.shippingInventory.selectAll') }}</label>
|
||||
<button type="button" class="btn-danger btn-sm" @click="receiptConfig.query_parameters_json.splice(index, 1)">{{ t('admin.delete') }}</button>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm full" @click="addReceiptParameter">{{ t('admin.shippingInventory.addParameter') }}</button>
|
||||
@@ -356,7 +356,8 @@
|
||||
<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>
|
||||
</template>
|
||||
|
||||
<div v-if="isEditableTab" class="form-actions full">
|
||||
</form>
|
||||
<div v-if="isEditableTab" class="form-actions">
|
||||
<div
|
||||
v-if="activeTab === 'sources' && selectedId"
|
||||
class="source-enabled-footer"
|
||||
@@ -385,7 +386,7 @@
|
||||
}}</small>
|
||||
</div>
|
||||
<div class="form-actions-buttons">
|
||||
<button v-if="!parsingReadOnly" type="submit" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
|
||||
<button v-if="!parsingReadOnly" type="button" class="btn-primary" :disabled="saving || ruleReadOnly || templateReadOnly || inventoryFieldReadOnly" @click="saveCurrent">{{ saving ? t('admin.shippingInventory.saving') : t('admin.save') }}</button>
|
||||
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentRule">{{ t('admin.shippingInventory.publish') }}</button>
|
||||
<button v-if="activeTab === 'rules' && selectedId && selectedRuleStatus === 'published'" type="button" class="btn-secondary btn-sm" @click="retireCurrentRule">{{ t('admin.shippingInventory.retire') }}</button>
|
||||
<button v-if="activeTab === 'templates' && selectedId && selectedTemplateStatus === 'draft'" type="button" class="btn-secondary btn-sm" @click="publishCurrentTemplate">{{ t('admin.shippingInventory.publishTemplate') }}</button>
|
||||
@@ -399,7 +400,6 @@
|
||||
<button type="button" class="btn-ghost btn-sm" @click="closeDrawer">{{ t('admin.cancel') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1653,23 +1653,28 @@ onMounted(load);
|
||||
.row-secondary { color: #94a3b8; font-size: 11px; }
|
||||
.status-dot { position: absolute; top: 18px; right: 12px; width: 7px; height: 7px; border-radius: 50%; }
|
||||
.status-dot.on { background: #22c55e; }
|
||||
.status-dot.off { background: #b2bdc9; }
|
||||
.status-dot.off { background: #94a3b8; }
|
||||
.drawer-mask { position: fixed; z-index: 40; inset: 0; display: flex; justify-content: flex-end; background: var(--overlay-soft); }
|
||||
.workbench-actions { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.clone-template-mask { z-index: 80; align-items: center; justify-content: center; padding: 20px; }
|
||||
.clone-template-dialog { width: min(480px, 100%); border-radius: 10px; background: #fff; box-shadow: 0 18px 48px rgb(15 23 42 / 25%); }
|
||||
.clone-template-header { display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid #e2e8f0; padding: 18px 20px; }.clone-template-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.clone-template-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; }
|
||||
.clone-template-form { display: grid; gap: 14px; padding: 20px; }.clone-template-form label { display: grid; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.clone-template-form .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.clone-template-form small { color: #94a3b8; font-size: 11px; line-height: 1.45; }.clone-template-actions { display: flex; justify-content: flex-end; gap: 10px; border-top: 1px solid #edf2f7; padding-top: 14px; }
|
||||
.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }.batch-source-option input { margin: 3px 0 0; accent-color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; }
|
||||
.editor-drawer { width: min(760px, 100vw); height: 100%; overflow-y: auto; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); }
|
||||
.drawer-header { position: sticky; z-index: 1; top: 0; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; }
|
||||
.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #f2d3cd; border-radius: 999px; background: #fff4f1; padding: 3px 7px; color: #a53f30; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #c7e7d0; background: #eefaf1; color: #247442; }
|
||||
.batch-validation-dialog { display: grid; width: min(780px, 100%); max-height: min(720px, calc(100vh - 40px)); grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border-radius: 12px; background: #fff; box-shadow: 0 20px 56px rgb(15 23 42 / 28%); }.batch-selection, .batch-progress { display: grid; min-height: 0; gap: 14px; padding: 18px 20px; }.batch-selection { grid-template-rows: auto minmax(0, 1fr) auto; }.batch-selection-toolbar { display: flex; align-items: end; justify-content: space-between; gap: 14px; }.batch-selection-toolbar label { display: grid; flex: 1; gap: 5px; color: #62788a; font-size: 11px; font-weight: 700; }.batch-selection-toolbar .input-field { min-width: 0; padding: 8px 9px; font: inherit; font-size: 13px; }.batch-selection-actions { display: flex; align-items: center; gap: 8px; }.batch-selection-actions > b { flex: 0 0 auto; border-radius: 999px; background: #e9f7fd; padding: 6px 9px; color: #13759d; font-size: 11px; white-space: nowrap; }.batch-selection-actions .btn-ghost { padding: 6px 8px; white-space: nowrap; }.batch-source-list, .batch-run-list { min-height: 0; overflow-y: auto; border: 1px solid #dce8ef; border-radius: 8px; background: #fbfdfe; }.batch-source-list { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-content: start; gap: 1px; background: #e3edf3; }.batch-source-option { display: flex; min-width: 0; align-items: flex-start; gap: 9px; background: #fff; padding: 10px 11px; cursor: pointer; }.batch-source-option:hover { background: #f4fbfe; }/* accent-color 在 @tailwindcss/forms 接管的原生 checkbox 上无效:勾选填充取 currentColor,用 color 指定选中蓝色 */
|
||||
.batch-source-option input { margin: 3px 0 0; color: #168ebc; }.batch-source-option span { display: grid; min-width: 0; gap: 3px; }.batch-source-option b { overflow: hidden; color: #344b60; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.batch-source-option small { overflow: hidden; color: #8a9aab; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-empty { grid-column: 1 / -1; margin: 0; padding: 28px 12px; color: #8797a7; font-size: 12px; text-align: center; }.batch-progress { grid-template-rows: auto auto auto minmax(0, 1fr) auto; }.batch-progress-heading { display: flex; align-items: end; justify-content: space-between; gap: 16px; }.batch-progress-heading > div { display: grid; gap: 3px; }.batch-progress-heading span { color: #16759f; font-size: 11px; font-weight: 800; }.batch-progress-heading strong { color: #334c60; font-size: 13px; }.batch-progress-heading > b { color: #1c6f96; font-size: 18px; font-variant-numeric: tabular-nums; }.batch-progress-bar { height: 7px; overflow: hidden; border-radius: 999px; background: #e8f0f5; }.batch-progress-bar i { display: block; height: 100%; border-radius: inherit; background: linear-gradient(90deg, #22a1c7, #4bb8d7); transition: width .25s ease; }.batch-stat-grid { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 6px; }.batch-stat-grid button { display: grid; gap: 2px; border: 1px solid #e0eaf0; border-radius: 7px; background: #fff; padding: 8px; color: #708393; font: inherit; text-align: left; cursor: pointer; }.batch-stat-grid button:hover, .batch-stat-grid button.active { border-color: #8fd0e7; background: #eef9fd; }.batch-stat-grid b { color: #314b60; font-size: 16px; font-variant-numeric: tabular-nums; }.batch-stat-grid span { overflow: hidden; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }.batch-run-list { display: grid; align-content: start; }.batch-run { display: grid; grid-template-columns: 9px minmax(0, 1fr) minmax(0, .9fr); align-items: center; gap: 9px; border-bottom: 1px solid #e8eff3; padding: 9px 11px; }.batch-run:last-child { border-bottom: 0; }.batch-run-marker { width: 7px; height: 7px; border-radius: 50%; background: #a9b8c5; }.batch-run > div { display: grid; min-width: 0; gap: 2px; }.batch-run b, .batch-run small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.batch-run b { color: #385166; font-size: 12px; }.batch-run > div small { color: #8a9baa; font-size: 10px; }.batch-run-error { color: #ae493b; font-size: 10px; }.batch-run.is-completed .batch-run-marker { background: #32a665; }.batch-run.is-completed_empty .batch-run-marker { background: #e7a628; }.batch-run.is-failed .batch-run-marker { background: #db6552; }
|
||||
/* 抽屉为 flex 三段式:头部/底部操作栏固定,.editor-form 独占剩余高度并内部滚动,操作栏位置不受内容增减影响 */
|
||||
.editor-drawer { display: flex; flex-direction: column; width: min(760px, 100vw); height: 100%; overflow: hidden; border-left: 1px solid var(--border-default); background: var(--bg-surface); box-shadow: -12px 0 32px rgb(15 23 42 / 18%); }
|
||||
.drawer-header { flex: 0 0 auto; display: flex; justify-content: space-between; gap: 16px; border-bottom: 1px solid var(--border-default); background: var(--bg-surface); padding: 18px 20px; }
|
||||
/* 状态徽标统一 Tailwind 标准语义色:未启用=rose(与 components-ds 危险态一致)、启用=green(与 .status-switch 一致),不再用自造色值 */
|
||||
.drawer-title-row { display: flex; align-items: center; gap: 9px; }.drawer-header h3 { margin: 0; color: #1e293b; font-size: 16px; font-weight: 600; }.source-run-status { flex: 0 0 auto; border: 1px solid #fecdd3; border-radius: 999px; background: #fff1f2; padding: 3px 7px; color: #be123c; font-size: 11px; font-weight: 700; }.source-run-status.enabled { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
|
||||
.drawer-header p { margin: 5px 0 0; color: #64748b; font-size: 12px; line-height: 1.5; }
|
||||
.drawer-close { width: 30px; height: 30px; border: 0; border-radius: 6px; background: transparent; color: #64748b; font-size: 24px; line-height: 1; cursor: pointer; }
|
||||
.drawer-close:hover { background: #f1f5f9; color: #334155; }
|
||||
.editor-form { display: grid; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; }
|
||||
/* grid-auto-rows 必须 max-content:本表单是受限高度的滚动网格,Chrome 会把包含 overflow:hidden 子项(.path-card)的隐式 auto 行压缩到远小于内容的高度,裁掉查询条件/按钮;显式 max-content 强制行高按内容 sizing */
|
||||
.editor-form { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; align-content: start; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; padding: 20px; }
|
||||
.editor-form label { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }
|
||||
.editor-form input, .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; }
|
||||
/* checkbox/radio 必须排除:此处的 color 与 background 简写优先级更高,会覆盖 @tailwindcss/forms 的 :checked 样式(填充取 currentColor + 白色对钩背景图),导致勾选态与未勾选态渲染完全一致、无法分辨 */
|
||||
.editor-form input:not([type='checkbox']):not([type='radio']), .editor-form select { min-width: 0; border: 1px solid var(--border-default); border-radius: 6px; background: var(--bg-surface); padding: 8px 9px; color: var(--text-secondary); font: inherit; font-size: 13px; font-weight: 400; }
|
||||
.editor-form small { color: #94a3b8; font-size: 11px; font-weight: 400; line-height: 1.45; }
|
||||
.inventory-mapping-tabs { display: flex; gap: 4px; margin: 0 0 14px; border-bottom: 1px solid #e2e8f0; }
|
||||
.inventory-mapping-tabs button { border: 0; border-bottom: 2px solid transparent; background: transparent; padding: 8px 12px; color: #64748b; font: inherit; font-size: 13px; cursor: pointer; }
|
||||
@@ -1698,7 +1703,7 @@ onMounted(load);
|
||||
.path-card { display: grid; grid-column: 1 / -1; border: 1px solid #dbe8ee; border-radius: 10px; background: #fff; overflow: hidden; }
|
||||
.path-card-header { display: flex; align-items: center; gap: 10px; border: 0; background: #f7fbfd; padding: 10px 12px; cursor: pointer; font: inherit; text-align: left; }.path-card-header:hover { background: #eff7fa; }
|
||||
.path-card-title { display: grid; flex: 1 1 auto; min-width: 0; gap: 2px; }.path-card-title b { color: #145f5a; font-size: 12px; font-weight: 800; }.path-card-title small { color: #94a3b8; font-size: 11px; font-weight: 400; }
|
||||
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #eef2f5; padding: 3px 8px; color: #7b8998; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #e6f6ec; color: #19703a; }
|
||||
.path-badge { flex: 0 0 auto; border-radius: 999px; background: #f1f5f9; padding: 3px 8px; color: #64748b; font-size: 11px; font-weight: 700; }.path-card.configured .path-badge.on { background: #dcfce7; color: #15803d; }
|
||||
.path-card-toggle { flex: 0 0 auto; color: #4d849f; font-size: 14px; line-height: 1; }
|
||||
.path-card-body { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; border-top: 1px solid #e6eef4; padding: 14px 12px; }.path-card-body .full { grid-column: 1 / -1; }
|
||||
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
|
||||
@@ -1727,7 +1732,8 @@ onMounted(load);
|
||||
.condition-empty { color: #8190a0; font-size: 12px; }
|
||||
.inline-check { flex-direction: row !important; align-items: center; gap: 4px !important; white-space: nowrap; font-size: 11px !important; }
|
||||
.switch-field { display: flex; flex-direction: column; gap: 6px; color: #64748b; font-size: 12px; font-weight: 500; }.status-switch { display: inline-flex; width: fit-content; align-items: center; gap: 7px; border: 0; background: transparent; padding: 2px 0; color: #94a3b8; font: inherit; font-size: 12px; cursor: pointer; }.status-switch i { position: relative; width: 34px; height: 20px; border-radius: 999px; background: #cbd5e1; transition: background .18s; }.status-switch i::after { position: absolute; top: 3px; left: 3px; width: 14px; height: 14px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px rgb(15 23 42 / 25%); content: ''; transition: transform .18s; }.status-switch.on { color: #15803d; }.status-switch.on i { background: #22c55e; }.status-switch.on i::after { transform: translateX(14px); }.status-switch b { font-weight: 500; }
|
||||
.form-actions { position: sticky; z-index: 2; bottom: 0; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; grid-column: 1 / -1; margin: 6px -20px -20px; border-top: 1px solid #dce6ef; background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); }
|
||||
/* 底部操作栏是抽屉 flex 布局的独立层级:固定在抽屉底部,不随表单内容滚动/折叠区展开移动。模板中该栏位于 </form> 之后(不在 form 内),保存按钮为 type=button 显式 click 调用 saveCurrent,输入框回车提交仍走 form @submit */
|
||||
.form-actions { flex: 0 0 auto; display: flex; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: 10px; border-top: 1px solid var(--border-default); background: rgb(255 255 255 / 96%); box-shadow: 0 -8px 18px rgb(15 23 42 / 7%); padding: 14px 20px; backdrop-filter: blur(8px); }
|
||||
.source-enabled-footer { display: flex; margin-right: auto; min-width: 0; align-items: center; gap: 10px; }
|
||||
.source-enabled-label { flex: 0 0 auto; color: #475569; font-size: 13px; font-weight: 600; }
|
||||
.source-enabled-hint { overflow: hidden; color: #94a3b8; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }
|
||||
@@ -1741,7 +1747,7 @@ onMounted(load);
|
||||
.audit-table td strong, .audit-table td small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }.audit-table td strong { color: #263850; font-weight: 600; }.audit-table td small { margin-top: 4px; color: #94a3b8; }
|
||||
.audit-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.audit-status { display: inline-flex; border-radius: 999px; padding: 3px 8px; font-size: 11px; white-space: nowrap; }.audit-status.ready { background: #dcfce7; color: #15803d; }.audit-status.failed { background: #fef2f2; color: #b91c1c; }.audit-status.neutral { background: #f1f5f9; color: #64748b; }
|
||||
.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
|
||||
.audit-detail dl { flex: 1 1 auto; min-height: 0; overflow-y: auto; display: grid; grid-auto-rows: max-content; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
|
||||
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
|
||||
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
|
||||
@media (max-width: 980px) { .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
|
||||
|
||||
+2
-2
@@ -206,8 +206,8 @@ onBeforeUnmount(stopSampleRefresh);
|
||||
.wizard-page { min-height: 100%; padding: 24px; background: #f6f8fc; }
|
||||
.wizard-shell { width: 100%; }
|
||||
.wizard-heading { margin-bottom: 28px; }.wizard-heading h1, .wizard-heading p { margin: 0; }
|
||||
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }.stepper li.active { color: #1677d2; }.stepper li.complete { color: #0f8a65; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #0f8a65; background: #0f8a65; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
|
||||
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #1677d2; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
|
||||
.stepper { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0; margin: 0 0 18px; padding: 0; list-style: none; }.stepper li { display: flex; align-items: center; gap: 10px; color: #94a3b8; font-size: .86rem; font-weight: 650; }.stepper li:not(:last-child)::after { width: 100%; height: 1px; margin-left: 10px; background: #dbe4f0; content: ''; }/* 步骤状态色统一 Tailwind 标准值:激活=brand-600、完成=green-600 */.stepper li.active { color: #0284c7; }.stepper li.complete { color: #16a34a; }.stepper-icon { display: inline-grid; flex: 0 0 auto; width: 32px; height: 32px; place-items: center; border: 1px solid currentColor; border-radius: 50%; background: #fff; }.stepper .complete .stepper-icon { color: #fff; border-color: #16a34a; background: #16a34a; }.stepper small { display: block; margin-bottom: 1px; color: #94a3b8; font-size: .68rem; font-weight: 700; text-transform: uppercase; }
|
||||
.wizard-card { min-height: 360px; padding: clamp(24px, 4vw, 44px); border: 1px solid #e1e8f2; border-radius: 12px; background: #fff; box-shadow: 0 8px 24px rgb(15 23 42 / .06); }.wizard-card__heading { margin-bottom: 28px; padding-bottom: 18px; border-bottom: 1px solid #edf1f7; }.wizard-card__heading span { color: #0284c7; font-size: .76rem; font-weight: 750; letter-spacing: .06em; text-transform: uppercase; }.wizard-card__heading h2 { margin: 6px 0 0; color: #1e293b; font-size: 1.25rem; }
|
||||
.wizard-actions { display: flex; align-items: center; gap: 10px; margin-top: 18px; }.wizard-actions__spacer { flex: 1; }
|
||||
@media (max-width: 640px) { .wizard-page { padding: 24px 16px; }.stepper { grid-template-columns: 1fr; gap: 10px; }.stepper li:not(:last-child)::after { display: none; }.wizard-card { min-height: 300px; border-radius: 14px; }.wizard-actions { flex-wrap: wrap; }.wizard-actions__spacer { display: none; }.btn-secondary:first-child { margin-right: auto; } }
|
||||
</style>
|
||||
+1
-1
@@ -353,7 +353,7 @@ ul { margin: 8px 0; padding-left: 20px; color: #b91c1c; font-size: 13px; }
|
||||
.metrics div { display: grid; gap: 4px; }
|
||||
.metrics dt { color: #64748b; font-size: 12px; }
|
||||
.metrics dd { margin: 0; color: #1e293b; font-size: 14px; font-weight: 600; }
|
||||
.conflict-card { border: 1px solid #fecaca; background: #fff7f7; border-radius: 8px; padding: 12px; margin-top: 10px; }
|
||||
.conflict-card { border: 1px solid #fecaca; background: #fef2f2; border-radius: 8px; padding: 12px; margin-top: 10px; }
|
||||
.conflict-card strong { color: #991b1b; font-size: 13px; }
|
||||
.conflict-card .reasons { color: #b45309; font-size: 12px; }
|
||||
@media (max-width: 767px) {
|
||||
|
||||
+3
-2
@@ -688,8 +688,9 @@ watch(
|
||||
}
|
||||
|
||||
.migration-backdrop { position: fixed; z-index: 30; inset: 0; display: grid; place-items: center; padding: 1rem; background: rgb(15 23 42 / 45%); }
|
||||
.migration-dialog { display: grid; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
|
||||
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }.migration-dialog footer { display: flex; justify-content: flex-end; gap: .5rem; }
|
||||
.migration-dialog { display: grid; grid-auto-rows: max-content; width: min(100%, 42rem); max-height: min(44rem, calc(100vh - 2rem)); gap: 1rem; overflow-y: auto; padding: 1.5rem; border-radius: 1rem; background: var(--bg-surface); box-shadow: 0 20px 40px rgb(15 23 42 / 25%); }
|
||||
.migration-dialog h2,.migration-dialog p { margin: 0; }.migration-note { color: var(--text-muted); font-size: .875rem; }.migration-changes { display: grid; gap: .75rem; }.migration-changes article { display: grid; gap: .45rem; padding: .85rem; border: 1px solid var(--border-default); border-radius: .75rem; }.migration-changes span { color: var(--text-muted); font-size: .8125rem; }.migration-changes label { display: grid; gap: .3rem; color: var(--text-secondary); font-size: .8125rem; font-weight: 600; }.migration-changes select { min-height: 2.25rem; border: 1px solid var(--border-default); border-radius: .5rem; background: var(--bg-surface); color: var(--text-primary); font: inherit; }/* footer 用 sticky 钉在对话框可视底部:breaking changes 列表长时取消/确认迁移按钮始终可见,不需滚回底部 */
|
||||
.migration-dialog footer { position: sticky; bottom: -1.5rem; display: flex; justify-content: flex-end; gap: .5rem; margin: 0 -1.5rem -1.5rem; border-top: 1px solid var(--border-default); background: var(--bg-surface); padding: 1rem 1.5rem 1.25rem; }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.header-main,
|
||||
|
||||
+1
-1
@@ -127,5 +127,5 @@ onBeforeUnmount(stopPolling);
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #1677d2; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
|
||||
.sample-step { display: grid; gap: 18px; max-width: 640px; }.upload-panel,.reuse-panel,.parse-status,.selected-sample { border: 1px solid var(--border-default); border-radius: 12px; background: var(--bg-surface); }.upload-panel { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; padding: 18px; background: var(--bg-surface-soft); }.upload-panel__icon { display: grid; width: 42px; height: 42px; place-items: center; border-radius: 10px; color: var(--status-info-fg); background: var(--status-info-bg); }.upload-panel h3,.reuse-panel h3,.parse-status p,.selected-sample span { margin: 0; }.upload-panel h3,.reuse-panel h3 { color: var(--text-primary); font-size: 1rem; }.upload-panel p,.reuse-panel p { margin: 5px 0 0; color: var(--text-muted); font-size: .84rem; }.upload-action { display: inline-flex; min-height: 38px; align-items: center; border-radius: 8px; padding: 0 13px; color: #fff; background: #0284c7; font-weight: 700; cursor: pointer; }.upload-action input { position: absolute; width: 1px; height: 1px; overflow: hidden; opacity: 0; }.parse-status,.selected-sample { display: flex; gap: 10px; align-items: center; padding: 13px 15px; color: var(--status-info-fg); background: var(--status-info-bg); }.parse-status strong,.selected-sample strong { display: block; color: var(--text-primary); }.parse-status p,.selected-sample span { display: block; margin-top: 3px; color: var(--text-muted); font-size: .83rem; }.refresh-status { margin-top: 6px; padding: 0; border: 0; color: inherit; background: transparent; font: inherit; font-size: .8rem; font-weight: 700; cursor: pointer; text-decoration: underline; }.parse-status.failed { color: var(--status-error-fg); border-color: var(--status-error-border); background: var(--status-error-bg); }.parse-status.failed > span { display: grid; width: 19px; height: 19px; place-items: center; border-radius: 50%; color: #fff; background: var(--status-error-fg); font-weight: 800; }.selected-sample { color: var(--status-success-fg); border-color: var(--status-success-border); background: var(--status-success-bg); }.reuse-panel { padding: 18px; }.reuse-panel__heading { margin-bottom: 14px; }.field { display: grid; gap: 7px; color: var(--text-secondary); font-size: .88rem; font-weight: 700; }.field .select-field { min-height: 44px; font: inherit; } @media (max-width: 640px) { .upload-panel { grid-template-columns: auto 1fr; }.upload-action { grid-column: 1 / -1; justify-content: center; } }
|
||||
</style>
|
||||
+3
-1
@@ -1419,8 +1419,10 @@ onMounted(async () => {
|
||||
<style scoped>
|
||||
.compact-button { padding: 6px 10px; font-size: 12px; }
|
||||
.impact-overlay { position: fixed; z-index: 60; inset: 0; display: grid; place-items: center; background: var(--overlay-soft); padding: 24px; }
|
||||
.impact-dialog { display: grid; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow: hidden; border-radius: 12px; background: var(--bg-surface); padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
|
||||
.impact-dialog { display: grid; grid-auto-rows: max-content; width: min(720px, 96vw); max-height: 82vh; gap: 14px; overflow-y: auto; border-radius: 12px; background: var(--bg-surface); padding: 18px; box-shadow: 0 24px 64px rgb(15 23 42 / .24); }
|
||||
.impact-dialog header, .impact-dialog footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
/* footer 用 sticky 钉在对话框可视底部:发布影响列表等长内容滚动时,确认/取消按钮始终可见(原 overflow:hidden 会把 footer 整条裁掉) */
|
||||
.impact-dialog footer { position: sticky; bottom: -18px; margin: 4px -18px -18px; border-top: 1px solid var(--border-default); background: var(--bg-surface); padding: 12px 18px; }
|
||||
.impact-dialog h2, .impact-dialog p { margin: 0; }
|
||||
.impact-list { display: grid; gap: 8px; overflow: auto; }
|
||||
.impact-list article { border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px 12px; }
|
||||
|
||||
@@ -236,3 +236,27 @@ export const retryTransferSourceRpa = (sourceCode: string) =>
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
});
|
||||
|
||||
/** 批量来源重试响应:triggered=是否写了 batch trigger;results 逐来源真实结果 */
|
||||
export interface TransferRetryRpaBatchResult {
|
||||
ok: boolean;
|
||||
triggered: boolean;
|
||||
trigger_path?: string;
|
||||
error_code?: string;
|
||||
results: Array<{
|
||||
source_code: string;
|
||||
ok: boolean;
|
||||
reparsed?: boolean;
|
||||
file_status?: string;
|
||||
error_code?: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/** 批量重试(2026-10-09):多来源合并写一个 batch trigger 文件,
|
||||
* Worker 单次浏览器会话串行导出全部来源(逐来源单文件会开/关 N 次浏览器) */
|
||||
export const retryTransferSourcesRpaBatch = (sourceCodes: string[]) =>
|
||||
requestJson<TransferRetryRpaBatchResult>(`${BASE}/sources/retry-rpa-batch`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(),
|
||||
body: JSON.stringify({ source_codes: sourceCodes }),
|
||||
});
|
||||
@@ -1,12 +1,14 @@
|
||||
<!--
|
||||
features/chat/components/messages/TransferBacklogSummaryCard.vue
|
||||
用途:待处理异常卡(可恢复/已关闭/结果未知三组)——列与匹配窗口一致,
|
||||
支持关键字/结果筛选、多选批量操作(重查/恢复处理/标记无需处理)与行级快捷操作。
|
||||
支持关键字/结果筛选、多选批量操作(重查/恢复/关闭)与行级快捷操作。
|
||||
依赖:props.items、i18n chat.transfer.*、transferBatch.deriveBatchNo、transferFormat.formatQuantity。
|
||||
逻辑:仅 blocked_recoverable 可勾选与操作;result_unknown / manually_closed 只读;
|
||||
可恢复行按 result_code 细分徽标(blocked_file_removed=文件已移除);
|
||||
blocked_file_removed 行行内仅留「标记无需继续处理」(重查不可恢复——消失证据
|
||||
blocked_file_removed 行行内仅留「关闭」(重查不可恢复——消失证据
|
||||
无法由重查翻回,唯一出口=人工关闭或等文件重新同步);
|
||||
批量按钮与行内按钮同用短文案键(重查/恢复/关闭,2026-10-12 文案一致化,
|
||||
完整语义经 title 悬浮),勾选计数保留;
|
||||
勾选集合为卡片本地态,操作经 emit 交父组件调用批量端点并刷新。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -157,18 +159,22 @@ function resultLabelKey(item: TransferBacklogItem): string {
|
||||
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"
|
||||
data-testid="transfer-backlog-batch-resume"
|
||||
:disabled="busy"
|
||||
:title="$t('chat.transfer.resumeAction')"
|
||||
@click="emit('resume', selectedActionableIds)"
|
||||
>
|
||||
{{ $t('chat.transfer.resumeAction') }}({{ selectedActionableIds.length }})
|
||||
<!-- [2026-10-12 文案一致化] 批量按钮与行内按钮同用短文案键(恢复/关闭),
|
||||
勾选计数保留;完整语义经 title 悬浮透出(与行内按钮同模式) -->
|
||||
{{ $t('chat.transfer.resumeActionShort') }}({{ selectedActionableIds.length }})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-red-200 bg-red-50 px-3 py-1 text-xs font-bold text-red-600 transition hover:bg-red-100 disabled:cursor-not-allowed disabled:opacity-40"
|
||||
data-testid="transfer-backlog-batch-close"
|
||||
:disabled="busy"
|
||||
:title="$t('chat.transfer.manualClose')"
|
||||
@click="emit('batchClose', selectedActionableIds)"
|
||||
>
|
||||
{{ $t('chat.transfer.manualClose') }}({{ selectedActionableIds.length }})
|
||||
{{ $t('chat.transfer.manualCloseShort') }}({{ selectedActionableIds.length }})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import { computed, ref } from 'vue';
|
||||
import { deriveBatchNo } from './transferBatch';
|
||||
import { formatQuantity } from './transferFormat';
|
||||
import { parseApiUtcDate } from '@/shared/utils/dateTime';
|
||||
import type { TransferMatchingItem } from '../../types/transfer.types';
|
||||
|
||||
const props = defineProps<{
|
||||
@@ -71,10 +72,11 @@ function rowKey(item: TransferMatchingItem): string {
|
||||
return `${item.item_id ?? 'na'}|${item.invoice_no}`;
|
||||
}
|
||||
|
||||
/** 查询时刻展示(HH:mm);无 checked_at 不渲染。 */
|
||||
/** 查询时刻展示(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
|
||||
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);无 checked_at 不渲染。 */
|
||||
function checkedTime(item: TransferMatchingItem): string {
|
||||
if (!item.checked_at) return '';
|
||||
const date = new Date(item.checked_at);
|
||||
const date = parseApiUtcDate(item.checked_at);
|
||||
return Number.isNaN(date.getTime()) ? '' : date.toTimeString().slice(0, 5);
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -10,7 +10,7 @@ import { mount } from '@vue/test-utils';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import i18n from '@/i18n';
|
||||
import TransferMatchCard from './TransferMatchCard.vue';
|
||||
import type { TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
|
||||
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
|
||||
|
||||
/** 最小合法匹配摘要(TransferMatchingSummary 全必填字段齐备,计数为 0) */
|
||||
function buildSummary(): TransferMatchingSummary {
|
||||
@@ -70,3 +70,81 @@ describe('TransferMatchCard 来源失败顶栏', () => {
|
||||
expect(wrapper.find('[data-testid="transfer-match-failed-sources"]').exists()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
/** [2026-10-12 单据数口径修正] 预计 ERP 单据数按执行建单五元组去重。
|
||||
* 行分组键 = (external_org, source_code, receipt_date, from_warehouse,
|
||||
* to_warehouse),与后端 execution_service.prepare_execution 同口径:
|
||||
* 同组多行执行期合并一张 ERP 单,预估数不得等于可执行行数。 */
|
||||
function buildItem(overrides: Partial<TransferMatchingItem>): TransferMatchingItem {
|
||||
return {
|
||||
item_id: 1,
|
||||
source_code: 'DBS-AWSBI',
|
||||
material_no: 'MAT-001',
|
||||
material_name: '连接器组件',
|
||||
specification: 'A 型',
|
||||
invoice_no: 'HOM-001',
|
||||
receipt_date: '2026-08-05',
|
||||
from_warehouse: 'DBS-TRANSIT',
|
||||
from_quantity: '100',
|
||||
to_warehouse: 'HUB-CN01',
|
||||
to_quantity: '100',
|
||||
result: 'executable',
|
||||
external_org: 'HX-CN01',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** 计数卡第 5 格 = 预计 ERP 单据(可执行/未成熟/阻断/数量/单据/待查/失效)。 */
|
||||
function estimateCardText(wrapper: ReturnType<typeof mount>): string {
|
||||
const cells = wrapper.find('[data-testid="transfer-match-counts"]').findAll('div.rounded-lg');
|
||||
return cells[4]?.text() ?? '';
|
||||
}
|
||||
|
||||
describe('TransferMatchCard 预计 ERP 单据数(五元组去重)', () => {
|
||||
const sameGroupA = buildItem({ item_id: 1, invoice_no: 'HOM-001' });
|
||||
const sameGroupB = buildItem({ item_id: 2, invoice_no: 'HOX-002' });
|
||||
const crossDate = buildItem({ item_id: 3, invoice_no: 'HOM-003', receipt_date: '2026-08-04' });
|
||||
|
||||
it('计数卡:同组两行 + 跨日一行 → 预估 2(不等于可执行行数 3)', () => {
|
||||
// [断言意图] 锁定五元组去重口径:receipt_date 入键,同组合并、跨组拆分,
|
||||
// 历史快照旧口径(=行数)持久值不再上屏。
|
||||
const wrapper = mount(TransferMatchCard, {
|
||||
props: {
|
||||
summary: buildSummary(),
|
||||
items: [sameGroupA, sameGroupB, crossDate],
|
||||
selected: new Set<number>(),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(estimateCardText(wrapper).replace(/\D/g, '')).toBe('2');
|
||||
});
|
||||
|
||||
it('生成按钮旁预估随勾选联动:勾选同组两行仍为 1,跨组勾选后为 2', async () => {
|
||||
// [断言意图] 底部预估回答「点生成会出几张单」:仅统计勾选的可执行行并
|
||||
// 按五元组分组;同组两行勾选=1 张(合并),追加跨日行勾选=2 张。
|
||||
const wrapper = mount(TransferMatchCard, {
|
||||
props: {
|
||||
summary: buildSummary(),
|
||||
items: [sameGroupA, sameGroupB, crossDate],
|
||||
selected: new Set<number>([1, 2]),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
|
||||
await wrapper.setProps({ selected: new Set<number>([1, 2, 3]) });
|
||||
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':2');
|
||||
});
|
||||
|
||||
it('阻断行不参与预估:勾选阻断行不改变单据数', () => {
|
||||
const blocked = buildItem({ item_id: 4, invoice_no: 'HOM-BLOCKED', result: 'blocked_quantity_mismatch' });
|
||||
const wrapper = mount(TransferMatchCard, {
|
||||
props: {
|
||||
summary: buildSummary(),
|
||||
items: [sameGroupA, blocked],
|
||||
selected: new Set<number>([1, 4]),
|
||||
},
|
||||
global: { plugins: [i18n] },
|
||||
});
|
||||
expect(wrapper.find('[data-testid="transfer-estimate-selected"]').text()).toContain(':1');
|
||||
});
|
||||
});
|
||||
@@ -15,13 +15,19 @@
|
||||
emit execute(itemIds);来源级解析/文件失败经 sources.error_code 透出
|
||||
(防"安静全 0"),但路由未解析失败(TRANSFER.ROUTE_NOT_RESOLVED)不进顶栏
|
||||
——路由失败保持行级(result=blocked_route_not_resolved 行内展示),
|
||||
顶栏按 error_code 客户端排除,历史卡片回放同样生效。
|
||||
顶栏按 error_code 客户端排除,历史卡片回放同样生效;
|
||||
[2026-10-12 单据数口径修正] 预计 ERP 单据数(计数卡=全部可执行行、
|
||||
生成按钮旁=勾选可执行行)按执行建单五元组 (external_org, source_code,
|
||||
receipt_date, from_warehouse, to_warehouse) 去重实时计算(与后端
|
||||
execution_service 同键),同组多行合并一张单——原「=可执行行数」口径
|
||||
高估单据数误导用户。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { deriveBatchNo } from './transferBatch';
|
||||
import { formatQuantity } from './transferFormat';
|
||||
import { parseApiUtcDate } from '@/shared/utils/dateTime';
|
||||
import type { TransferMatchingItem, TransferMatchingSummary, TransferSourceProgress } from '../../types/transfer.types';
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -143,13 +149,43 @@ const executableCheckedItemIds = computed(() =>
|
||||
props.items.filter((item) => isSelectable(item) && isChecked(item)).map((item) => item.item_id as number),
|
||||
);
|
||||
|
||||
/** [2026-10-12 单据数口径修正] 执行建单五元组键(与后端 execution_service.
|
||||
* prepare_execution 分组建单同键同 .trim() 规范化):(external_org, source_code,
|
||||
* receipt_date, from_warehouse, to_warehouse),同组多行执行期合并一张 ERP 单。
|
||||
* 老卡片行缺 external_org 按 '' 参与(分组退化为四元组,仅跨组织同仓库配置下有差异)。 */
|
||||
function documentGroupKey(item: TransferMatchingItem): string {
|
||||
return [
|
||||
(item.external_org ?? '').trim(),
|
||||
(item.source_code ?? '').trim(),
|
||||
(item.receipt_date ?? '').trim(),
|
||||
(item.from_warehouse ?? '').trim(),
|
||||
(item.to_warehouse ?? '').trim(),
|
||||
].join('\u001f');
|
||||
}
|
||||
|
||||
/** 预计 ERP 单据数(计数卡):全部可执行行按五元组去重的组数。客户端实时计算,
|
||||
* 使历史快照中旧口径(=可执行行数)的持久化估计值不再上屏误导。 */
|
||||
const estimatedDocumentCountAll = computed(
|
||||
() => new Set(props.items.filter((item) => item.result === 'executable').map(documentGroupKey)).size,
|
||||
);
|
||||
|
||||
/** 预计 ERP 单据数(生成按钮旁):按当前勾选的可执行行分组计数,回答
|
||||
* 「点生成会出几张单」;未勾选为 0。 */
|
||||
const estimatedDocumentCountSelected = computed(
|
||||
() => new Set(
|
||||
props.items.filter((item) => item.result === 'executable' && isChecked(item)).map(documentGroupKey),
|
||||
).size,
|
||||
);
|
||||
|
||||
/**
|
||||
* 库存查询时刻小字(HH:mm);无效/缺省 checked_at 返回 null 不渲染。
|
||||
* 库存查询时刻小字(HH:mm);后端 naive ISO 按 UTC 解析后转浏览器本地时区
|
||||
* (仓库约定 parseApiUtcDate,2026-09-29 修复 UTC+8 展示异常);
|
||||
* 无效/缺省 checked_at 返回 null 不渲染。
|
||||
* @param item 匹配明细行;checked_at 为后端 ISO 时间
|
||||
*/
|
||||
function checkedAtLabel(item: TransferMatchingItem): string | null {
|
||||
if (!item.checked_at) return null;
|
||||
const date = new Date(item.checked_at);
|
||||
const date = parseApiUtcDate(item.checked_at);
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
const hh = String(date.getHours()).padStart(2, '0');
|
||||
const mm = String(date.getMinutes()).padStart(2, '0');
|
||||
@@ -217,7 +253,9 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
|
||||
<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_external_write_count }}</div>
|
||||
<!-- [2026-10-12 单据数口径修正] 按执行建单五元组去重(客户端计算),
|
||||
不再透传旧口径持久值(=可执行行数)——同组多行合并一张 ERP 单 -->
|
||||
<div class="text-lg font-black text-brand-600">{{ estimatedDocumentCountAll }}</div>
|
||||
<div class="text-[11px] text-muted">{{ $t('chat.transfer.estimatedExternalWrites') }}</div>
|
||||
</div>
|
||||
<!-- 待查库存:文件已落地、尚未查过 ERP 库存的行数(历史回放缺省 0) -->
|
||||
@@ -390,9 +428,10 @@ function reasonTitle(item: TransferMatchingItem): string | undefined {
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex items-center justify-end gap-3 border-t border-subtle pt-3">
|
||||
<span class="text-xs text-muted">
|
||||
<span class="text-xs text-muted" data-testid="transfer-estimate-selected">
|
||||
{{ $t('chat.transfer.selectedCount', { count: selectedCount }) }} ·
|
||||
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ summary.estimated_external_write_count }}
|
||||
<!-- [2026-10-12 单据数口径修正] 随勾选联动:按勾选可执行行五元组分组计数 -->
|
||||
{{ $t('chat.transfer.estimatedExternalWrites') }}:{{ estimatedDocumentCountSelected }}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -385,9 +385,13 @@ async function onSourceRetry(sourceCodes: string[]) {
|
||||
const codes = Array.isArray(sourceCodes) ? sourceCodes : [sourceCodes];
|
||||
retryingSource.value = new Set([...retryingSource.value, ...codes]);
|
||||
try {
|
||||
// 逐来源触发,避免一次并发 EPR/RPA 竞态;失败中断剩余。
|
||||
for (const code of codes) {
|
||||
await transfer.retrySourceRpa(code);
|
||||
// 多来源一次批量端点(合并单 batch trigger,Worker 单次浏览器会话串行导出);
|
||||
// 单来源沿用原接口(行级 ↻ 一源一文件语义不变)。
|
||||
const [first, ...rest] = codes;
|
||||
if (rest.length > 0) {
|
||||
await transfer.retrySourcesRpaBatch(codes);
|
||||
} else if (first !== undefined) {
|
||||
await transfer.retrySourceRpa(first);
|
||||
}
|
||||
} catch (e) {
|
||||
reportError(e);
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
* 确认提交、重试收料 RPA。
|
||||
* 依赖:@vue/test-utils、i18n。
|
||||
* 逻辑:平台 DBS/Crane 仅分组;实例为选择与执行边界(决策 2/3/4);
|
||||
* 确认需至少一个 has_ready_file(兜底告警),提交范围静默过滤为 ready-only
|
||||
* (无 ready 文件的勾选项不进匹配,2026-09-29 来源错误分层);
|
||||
* 确认需至少一个 has_ready_file(兜底告警);混合选择(含非就绪项)先披露范围
|
||||
* 再确认(知情部分确认 2026-10-09,替代历史静默剔除),提交范围 ready-only;
|
||||
* 重试门禁=仅 fetching 在途不可重试(ready 亦可强制重抓,2026-09-29 去管控)。
|
||||
*/
|
||||
import { mount } from '@vue/test-utils';
|
||||
@@ -54,18 +54,21 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('“全选可见”勾选全部启用实例,确认时静默剔除无 ready 文件来源', async () => {
|
||||
// [断言意图] 门禁新语义:有 ready 文件的勾选项照常放行,无 ready 文件的勾选项
|
||||
// (DBS-AWSSG none)静默剔除——确认范围只含可执行来源,不再整包提交。
|
||||
it('“全选可见”勾选全部启用实例,混合选择先披露再确认 ready-only', async () => {
|
||||
// [断言意图] 知情部分确认(2026-10-09):混合选择(2 ready + 1 none)点确认先出现
|
||||
// 披露条且不提交;披露后确认只携带具备 ready 文件的来源码。
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-select-visible"]').trigger('click');
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('勾选 ready+parse_failed 确认时只提交 ready 来源', async () => {
|
||||
it('勾选 ready+parse_failed 先披露,披露后确认只提交 ready 来源', async () => {
|
||||
// [断言意图] 解析失败来源(has_ready_file=false)勾选后不阻断确认,
|
||||
// 但确认事件只携带具备 ready 文件的来源码。
|
||||
// 但须经披露条确认,确认事件只携带具备 ready 文件的来源码。
|
||||
const sources = [
|
||||
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
|
||||
{ source_code: 'DSV-BAD', display_name: 'bad', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'parse_failed' as const },
|
||||
@@ -74,9 +77,64 @@ describe('TransferSourceSelectCard', () => {
|
||||
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DSV-BAD"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
await wrapper.find('[data-testid="transfer-source-partial-proceed"]').trigger('click');
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DSV-OK']);
|
||||
});
|
||||
|
||||
it('混合选择披露条展示可匹配/暂不可匹配计数与状态分组', async () => {
|
||||
// [断言意图] 披露必须让「抓取中」与「真失败」可区分:摘要含三段计数,
|
||||
// 分组明细含「抓取中 1」——用户知情后再决定是否仅匹配就绪来源。
|
||||
const sources = [
|
||||
{ source_code: 'DSV-OK', display_name: 'ok', platform: 'dbs', enabled: true, has_ready_file: true, file_status: 'ready' as const },
|
||||
{ source_code: 'DSV-FETCH', display_name: 'fetching', platform: 'dbs', enabled: true, has_ready_file: false, file_status: 'fetching' as const },
|
||||
];
|
||||
const wrapper = mountCard({}, sources);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DSV-OK"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DSV-FETCH"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
const summary = wrapper.find('[data-testid="transfer-source-partial-summary"]').text();
|
||||
expect(summary).toContain('可匹配 1 个');
|
||||
expect(summary).toContain('暂不可匹配 1 个');
|
||||
expect(summary).toContain('抓取中 1');
|
||||
});
|
||||
|
||||
it('披露后「取消」收回披露条且不提交,确认按钮还原', async () => {
|
||||
// [断言意图] 披露是可退出的确认步:取消后回到选择状态、零副作用。
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="transfer-source-partial-cancel"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.find('[data-testid="transfer-source-confirm"]').exists()).toBe(true);
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('披露展示期间调整勾选即收回披露(旧口径失效)', async () => {
|
||||
// [断言意图] 披露基于确认瞬间的选择快照:勾选变化后旧披露必须失效收回,
|
||||
// 防止按过期口径提交。
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSSG"] input').setValue(false);
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.emitted('confirm')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('全就绪选择不出现披露,确认直达提交', async () => {
|
||||
// [断言意图] 知情披露只在混合状态出现:全部就绪时确认一步直达(常态零额外点击)。
|
||||
const wrapper = mountCard();
|
||||
await wrapper.find('[data-testid="transfer-source-option-DBS-AWSBI"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-option-CRANE-SZ"] input').setValue(true);
|
||||
await wrapper.find('[data-testid="transfer-source-confirm"]').trigger('click');
|
||||
expect(wrapper.find('[data-testid="transfer-source-partial-confirm"]').exists()).toBe(false);
|
||||
expect(wrapper.emitted('confirm')?.[0][0]).toEqual(['DBS-AWSBI', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('parse_failed 显示解析失败徽标且可重试', async () => {
|
||||
// [断言意图] 当日收料文件解析失败(file_status=parse_failed)不得误报就绪;
|
||||
// 与 none/failed/expired 一样允许重新触发收料 RPA。
|
||||
@@ -180,6 +238,16 @@ describe('TransferSourceSelectCard', () => {
|
||||
expect(wrapper.emitted('retry')?.[0][0]).toEqual(['DBS-AWSBI', 'DBS-AWSSG', 'CRANE-SZ']);
|
||||
});
|
||||
|
||||
it('空数据来源显示「无收料数据」徽标而非抓取失败', async () => {
|
||||
// [断言意图] 抓取成功但当日无收料记录(file_status=no_data)属业务结果,
|
||||
// 必须如实展示"无收料数据",不得与"抓取失败"混淆(2026-10-08 PRD01 误标事故)。
|
||||
const wrapper = mountCard({}, [
|
||||
{ source_code: 'CRANE-NODATA', display_name: '空数据在途仓', platform: 'crane', enabled: true, has_ready_file: false, file_status: 'no_data' },
|
||||
]);
|
||||
expect(wrapper.find('[data-testid="transfer-source-status-CRANE-NODATA"]').text()).toBe('无收料数据');
|
||||
expect((wrapper.find('[data-testid="transfer-source-retry-CRANE-NODATA"]').element as HTMLButtonElement).disabled).toBe(false);
|
||||
});
|
||||
|
||||
it('已过期来源显示「文件已过期」徽标且可重试', async () => {
|
||||
// [断言意图] 保留期已到的来源不得误报就绪(has_ready_file=false);
|
||||
// expired 状态与 none/failed 一样允许重新触发收料 RPA。
|
||||
|
||||
@@ -6,14 +6,15 @@
|
||||
逻辑:匹配参数区(调拨类型 + 收料日期,确认时一并提交)→ 选择辅助/上下文操作条
|
||||
(有选中时原位替换辅助区,承载批量重试/下载/清空选择)→ 平台分组来源列表
|
||||
(平台仅分组不可直接执行)→ 底部唯一实心主按钮「确认范围并匹配」(未选禁用);
|
||||
确认只提交具备 ready 文件的来源(勾选的无 ready 项如 parse_failed/none 静默剔除,
|
||||
门禁「至少一 ready」保留为兜底告警);重试除抓取中(fetching)外均可触发
|
||||
确认只提交具备 ready 文件的来源:混合选择(含非就绪项)先披露范围再确认
|
||||
(知情部分确认 2026-10-09,替代历史静默剔除),全就绪直达;
|
||||
门禁「至少一 ready」保留为兜底告警;重试除抓取中(fetching)外均可触发
|
||||
(ready 亦可强制重抓,2026-09-29 去管控),徽标独立文案;
|
||||
调拨类型决定收料数据范围(类型 1 仅纳入 INVOICE 前缀 HOM/HOX/WTP),
|
||||
类型 2/3 一期占位(禁用,后端同样 fail-closed)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { useMessage } from '@/shared/composables/useMessage';
|
||||
import { eligibleReceiptDateTo } from './transferDate';
|
||||
@@ -89,6 +90,37 @@ const confirmDisabled = computed(() =>
|
||||
);
|
||||
const downloadDisabled = computed(() => props.busy || !selectedHasReadyFile.value);
|
||||
|
||||
// ---- [知情部分确认 2026-10-09] 混合选择(含非就绪项)先披露范围再确认,替代历史静默剔除 ----
|
||||
/** 披露条可见性:仅在「已选含就绪 + 非就绪」混合状态点确认后出现。 */
|
||||
const showPartialConfirm = ref(false);
|
||||
/** 已选来源中具备 ready 文件的数量。 */
|
||||
const selectedReadyCount = computed(() =>
|
||||
[...selected.value].filter((code) => props.sources.find((s) => s.source_code === code)?.has_ready_file).length,
|
||||
);
|
||||
const selectedUnreadyCount = computed(() => selectedCount.value - selectedReadyCount.value);
|
||||
/** 非就绪状态分组展示顺序:先在途(fetching)后终态。 */
|
||||
const unreadyStatusOrder = ['fetching', 'failed', 'parse_failed', 'no_data', 'expired', 'none'] as const;
|
||||
/** 非就绪状态 → 徽标文案 key(复用既有状态徽标词汇,披露条逐组计数)。 */
|
||||
const UNREADY_STATUS_LABEL_KEYS: Record<(typeof unreadyStatusOrder)[number], string> = {
|
||||
fetching: 'chat.transfer.fileFetching',
|
||||
failed: 'chat.transfer.fileFailed',
|
||||
parse_failed: 'chat.transfer.fileParseFailed',
|
||||
no_data: 'chat.transfer.fileNoData',
|
||||
expired: 'chat.transfer.fileExpired',
|
||||
none: 'chat.transfer.fileNone',
|
||||
};
|
||||
/** 非就绪来源按状态分组计数(固定顺序),让「抓取中」与「真失败」可区分。 */
|
||||
const unreadyBreakdownText = computed(() => unreadyStatusOrder
|
||||
.map((status) => ({
|
||||
status,
|
||||
count: [...selected.value].filter(
|
||||
(code) => props.sources.find((s) => s.source_code === code)?.file_status === status,
|
||||
).length,
|
||||
}))
|
||||
.filter((item) => item.count > 0)
|
||||
.map((item) => `${t(UNREADY_STATUS_LABEL_KEYS[item.status])} ${item.count}`)
|
||||
.join(' · '));
|
||||
|
||||
function toggle(sourceCode: string, checked: boolean) {
|
||||
const next = new Set(selected.value);
|
||||
if (checked) next.add(sourceCode);
|
||||
@@ -141,23 +173,49 @@ function downloadSelected(): void {
|
||||
if (codes.length) emit('download', codes);
|
||||
}
|
||||
|
||||
/** 确认范围并匹配:只提交具备 ready 文件的来源;无 ready 文件的勾选项(如 parse_failed/none)
|
||||
* 静默剔除(历史上是「至少一 ready 则整包提交」,会把不可执行来源带进匹配);
|
||||
* 「至少一 ready」门禁保留为兜底告警(全部无 ready 时拦截)。 */
|
||||
/** 确认范围并匹配:只提交具备 ready 文件的来源。混合选择(含非就绪项)先展示披露条
|
||||
* (知情部分确认 2026-10-09,替代历史「至少一 ready 则静默剔除整包」),用户确认后
|
||||
* 才提交 ready-only;全就绪直达。「至少一 ready」门禁保留为兜底告警。 */
|
||||
function confirm() {
|
||||
if (selectedCount.value === 0) {
|
||||
notifyWarning(t('chat.transfer.needSelectSource'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
const readyCodes = [...selected.value].filter(
|
||||
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
|
||||
);
|
||||
const readyCodes = selectedReadyCodes();
|
||||
if (readyCodes.length === 0) {
|
||||
notifyWarning(t('chat.transfer.needReadyFile'), t('chat.transfer.sourceSelectTitle'));
|
||||
return;
|
||||
}
|
||||
if (selectedUnreadyCount.value > 0) {
|
||||
showPartialConfirm.value = true;
|
||||
return;
|
||||
}
|
||||
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
|
||||
}
|
||||
|
||||
/** 已选来源中的 ready 来源码(每次 emit 时现算,避免披露期间勾选变化导致口径过期)。 */
|
||||
function selectedReadyCodes(): string[] {
|
||||
return [...selected.value].filter(
|
||||
(code) => props.sources.find((s) => s.source_code === code)?.has_ready_file,
|
||||
);
|
||||
}
|
||||
|
||||
/** 披露后确认:仅提交就绪来源(其余来源就绪后可重新匹配补入,后端增量圈行不破坏已有行)。 */
|
||||
function proceedPartialConfirm() {
|
||||
const readyCodes = selectedReadyCodes();
|
||||
showPartialConfirm.value = false;
|
||||
emit('confirm', readyCodes, { from: dateFrom.value || undefined, to: dateTo.value || undefined }, transferType.value);
|
||||
}
|
||||
|
||||
/** 披露后取消:收回披露条,可调整勾选或等待其余来源就绪。 */
|
||||
function cancelPartialConfirm() {
|
||||
showPartialConfirm.value = false;
|
||||
}
|
||||
|
||||
// 勾选变化即收回披露:用户在调整范围,旧披露口径已失效。
|
||||
watch(selected, () => {
|
||||
showPartialConfirm.value = false;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -278,7 +336,10 @@ function confirm() {
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-for="platform in platforms" :key="platform" class="mb-3 rounded-lg border border-subtle">
|
||||
<!-- [ZONE 3] 来源列表:上限随视口伸缩(60vh)而非固定值——来源多时列表尽量占满可用高度再内部滚动,
|
||||
避免固定小限高把列表压成几行+卡片下方大量留白;来源少时卡片自然收缩不受影响 -->
|
||||
<div class="max-h-[60vh] space-y-3 overflow-y-auto" data-testid="transfer-source-list">
|
||||
<div v-for="platform in platforms" :key="platform" class="rounded-lg border border-subtle">
|
||||
<div class="flex items-center justify-between rounded-t-lg bg-surface-soft px-3 py-1.5">
|
||||
<b class="text-xs text-secondary">{{ platform.toUpperCase() }}</b>
|
||||
<label class="text-[11px] text-muted">
|
||||
@@ -329,6 +390,14 @@ function confirm() {
|
||||
>
|
||||
{{ t('chat.transfer.fileFailed') }}
|
||||
</span>
|
||||
<!-- 无收料数据(no_data):抓取成功但当日无收料记录,属业务结果而非故障;当日稍后到货可重抓补数 -->
|
||||
<span
|
||||
v-else-if="source.file_status === 'no_data'"
|
||||
class="inline-flex items-center gap-1 rounded-full bg-sky-50 px-2 py-0.5 text-[10px] font-bold text-sky-700"
|
||||
:data-testid="`transfer-source-status-${source.source_code}`"
|
||||
>
|
||||
{{ t('chat.transfer.fileNoData') }}
|
||||
</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"
|
||||
@@ -365,9 +434,42 @@ function confirm() {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-end border-t border-subtle pt-3">
|
||||
<!-- [知情部分确认] 混合状态点确认后按钮区原位替换为披露条(同槽位切换惯例):
|
||||
明确本次仅纳入就绪来源、逐状态分组展示未就绪项,用户显式确认后才提交。 -->
|
||||
<div
|
||||
v-if="showPartialConfirm"
|
||||
class="flex w-full flex-col gap-1.5 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2"
|
||||
data-testid="transfer-source-partial-confirm"
|
||||
>
|
||||
<p class="text-xs font-bold text-amber-700" data-testid="transfer-source-partial-summary">
|
||||
{{ $t('chat.transfer.partialConfirmSummary', { total: selectedCount, ready: selectedReadyCount, unready: selectedUnreadyCount }) }}
|
||||
<span v-if="unreadyBreakdownText" class="font-normal">{{ $t('chat.transfer.partialConfirmBreakdown', { items: unreadyBreakdownText }) }}</span>
|
||||
</p>
|
||||
<p class="text-xs text-amber-700">{{ $t('chat.transfer.partialConfirmHint') }}</p>
|
||||
<div class="flex items-center justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg border border-default px-3 py-1.5 text-xs font-bold text-secondary hover-surface-soft"
|
||||
data-testid="transfer-source-partial-cancel"
|
||||
@click="cancelPartialConfirm"
|
||||
>
|
||||
{{ $t('chat.transfer.partialConfirmCancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg bg-brand-600 px-4 py-1.5 text-xs font-bold text-white hover:bg-brand-700"
|
||||
data-testid="transfer-source-partial-proceed"
|
||||
@click="proceedPartialConfirm"
|
||||
>
|
||||
{{ $t('chat.transfer.partialConfirmProceed') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
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"
|
||||
:disabled="confirmDisabled"
|
||||
|
||||
+46
-5
@@ -5,6 +5,9 @@
|
||||
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
|
||||
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
|
||||
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
|
||||
阶段能力禁用态:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象
|
||||
(capabilityDisabledReason),命中时按钮渲染 disabled + 原因 tooltip(capabilityDisabled 命名空间),
|
||||
与 submitFormalGateAction 的点击拦截同源(展示=执行同源),禁止可点样式诱导用户点击后才被拦截;
|
||||
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
|
||||
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
|
||||
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
|
||||
@@ -45,12 +48,17 @@ const props = defineProps<{
|
||||
| null;
|
||||
retryable?: boolean;
|
||||
blockingReason?: ShippingProcessingBlockingReason | null;
|
||||
primaryAction?: ShippingProcessingPrimaryAction | null;
|
||||
primaryAction?: (ShippingProcessingPrimaryAction & {
|
||||
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
|
||||
capabilityDisabledReason?: string | null;
|
||||
}) | null;
|
||||
recoveryActions?: Array<{
|
||||
code: string;
|
||||
i18nKey?: string | null;
|
||||
label_key?: string | null;
|
||||
parameters?: Record<string, unknown>;
|
||||
/** 阶段能力禁用原因(视图层从 preparation.capabilities 并入);非空=按钮渲染禁用态。 */
|
||||
capabilityDisabledReason?: string | null;
|
||||
}>;
|
||||
/** 正式 Gate 原始状态仅用于区分未入队、运行中与外部回执等待;不参与按钮裁决。 */
|
||||
gateStatus?: string | null;
|
||||
@@ -296,6 +304,11 @@ const businessActionLabel = computed(() => {
|
||||
});
|
||||
|
||||
const businessActionTitle = computed(() => {
|
||||
// 能力禁用原因优先于重试中提示:禁用态按钮的 tooltip 必须解释"为什么不可点"。
|
||||
const capabilityText = capabilityDisabledText(
|
||||
props.primaryAction ? capabilityDisabledReasonOf(props.primaryAction) : null,
|
||||
);
|
||||
if (capabilityText) return capabilityText;
|
||||
const retryingFlag = Boolean(props.retrying);
|
||||
if (retryingFlag) {
|
||||
return t('chat.shippingOrderReview.currentTask.actionRetryRunningTooltip');
|
||||
@@ -305,6 +318,29 @@ const businessActionTitle = computed(() => {
|
||||
|
||||
const actionIsRetry = computed(() => String(props.primaryAction?.code || '').trim().startsWith('retry_'));
|
||||
const actionIsInventoryRpa = computed(() => String(props.primaryAction?.code || '').trim() === 'retry_inventory_preparation');
|
||||
|
||||
/**
|
||||
* 阶段能力禁用态裁决:与视图层 submitFormalGateAction 的点击拦截同源(展示=执行同源)。
|
||||
* 核心逻辑:视图层把 preparation.capabilities 的 disabled_reason 并进动作对象;本卡只负责
|
||||
* 渲染禁用态与原因 tooltip,不自行推断业务能力。原因文案复用 capabilityDisabled 命名空间,
|
||||
* 未登记的 reason fail-closed 禁用但不给 tooltip(禁止裸露内部原因码)。
|
||||
*/
|
||||
function capabilityDisabledReasonOf(action: { capabilityDisabledReason?: string | null }): string | null {
|
||||
const reason = String(action.capabilityDisabledReason || '').trim();
|
||||
return reason || null;
|
||||
}
|
||||
|
||||
function capabilityDisabledText(reason: string | null | undefined): string {
|
||||
const normalized = String(reason || '').trim();
|
||||
if (!normalized) return '';
|
||||
const key = `chat.shippingOrderReview.lifecycle.prepare.capabilityDisabled.${normalized}`;
|
||||
return te(key) ? t(key) : '';
|
||||
}
|
||||
|
||||
const businessActionCapabilityDisabled = computed(() => (
|
||||
Boolean(props.primaryAction && capabilityDisabledReasonOf(props.primaryAction))
|
||||
));
|
||||
|
||||
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
|
||||
const code = String(action.code || '').trim();
|
||||
if (!code || isNonTaskCapabilityAction(code) || isInternalInventoryAction(code)) return false;
|
||||
@@ -329,6 +365,8 @@ function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): st
|
||||
}
|
||||
|
||||
function handleBusinessActionClick() {
|
||||
// 能力禁用态兜底:disabled 按钮通常不派发 click,此处防御键盘等旁路触发。
|
||||
if (businessActionCapabilityDisabled.value) return;
|
||||
const primaryActionCode = String(props.primaryAction?.code || '').trim();
|
||||
if (!primaryActionCode || primaryActionCode === 'retry') return;
|
||||
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
|
||||
@@ -464,9 +502,10 @@ type ReviewCurrentUserStatus =
|
||||
<button
|
||||
v-if="showBusinessAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 dark:bg-sky-600 dark:hover:bg-sky-500"
|
||||
class="inline-flex items-center gap-1 rounded-md bg-sky-700 px-3 py-1.5 text-xs font-medium text-white shadow-sm transition hover:bg-sky-800 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-sky-600 dark:hover:bg-sky-500"
|
||||
:data-testid="actionIsRetry ? 'review-current-processing-retry' : 'review-current-task-primary-action'"
|
||||
:disabled="retrying || locating"
|
||||
:data-capability-disabled="businessActionCapabilityDisabled ? 'true' : undefined"
|
||||
:disabled="retrying || locating || businessActionCapabilityDisabled"
|
||||
:title="businessActionTitle"
|
||||
@click="handleBusinessActionClick"
|
||||
>
|
||||
@@ -482,9 +521,11 @@ type ReviewCurrentUserStatus =
|
||||
v-for="action in recoveryActions"
|
||||
:key="action.code"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-surface px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 disabled:cursor-not-allowed dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
|
||||
:data-testid="`review-current-task-recovery-${action.code}`"
|
||||
:disabled="retrying || locating"
|
||||
:data-capability-disabled="capabilityDisabledReasonOf(action) ? 'true' : undefined"
|
||||
:disabled="retrying || locating || Boolean(capabilityDisabledReasonOf(action))"
|
||||
:title="capabilityDisabledText(capabilityDisabledReasonOf(action))"
|
||||
@click="$emit('action', action.code, action.parameters || {})"
|
||||
>
|
||||
{{ recoveryActionLabel(action) }}
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
manualCloseTransferItem,
|
||||
retryTransferItem,
|
||||
retryTransferSourceRpa,
|
||||
retryTransferSourcesRpaBatch,
|
||||
} from '../api/transfer.api';
|
||||
import type {
|
||||
TransferBacklogItem,
|
||||
@@ -458,6 +459,15 @@ export function useChatTransfer() {
|
||||
return status;
|
||||
}
|
||||
|
||||
/** 批量来源重试:一次批量端点调用(多来源合并单 batch trigger,Worker 单次浏览器
|
||||
* 会话串行导出;逐来源循环会产生 N 个文件、开/关 N 次浏览器),随后刷新来源状态
|
||||
* (loadSources 观察到 fetching 自动开始轮询)。 */
|
||||
async function retrySourcesRpaBatch(sourceCodes: string[]) {
|
||||
const result = await retryTransferSourcesRpaBatch(sourceCodes);
|
||||
await loadSources();
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 加载待处理异常列表与汇总 */
|
||||
async function loadBacklog() {
|
||||
const [items, summary] = await Promise.all([listTransferBacklog(), getTransferBacklogSummary()]);
|
||||
@@ -559,6 +569,7 @@ export function useChatTransfer() {
|
||||
manualClose,
|
||||
loadSources,
|
||||
retrySourceRpa,
|
||||
retrySourcesRpaBatch,
|
||||
loadBacklog,
|
||||
loadBacklogSummary,
|
||||
loadExecutableItems,
|
||||
|
||||
@@ -1529,6 +1529,8 @@ export interface ShippingTaskUiState {
|
||||
part_number?: string | null;
|
||||
required_qty?: string | number | null;
|
||||
available_qty?: string | number | null;
|
||||
/** 料号维度总可用量(忽略预约号、行允许源内汇总);无快照/未就绪为 null。 */
|
||||
part_available_qty?: string | null;
|
||||
shortage_qty?: string | number | null;
|
||||
/** Match 正式匹配源;未匹配时为空,禁止用候选回填。 */
|
||||
source_code?: string | null;
|
||||
|
||||
@@ -67,6 +67,9 @@ export interface TransferMatchingItem {
|
||||
stale?: boolean;
|
||||
/** 行评估所用收料文件版本与来源最新可用文件是否一致;false = 文件已更新需重新匹配 */
|
||||
file_current?: boolean;
|
||||
/** [2026-10-12 单据数口径修正] 执行建单五元组首键(路由解析所得外部组织);
|
||||
* 匹配评估路径透出,历史回放缺省——预估 ERP 单据数按五元组去重的分组输入 */
|
||||
external_org?: string;
|
||||
}
|
||||
|
||||
/** 来源实例级进度(决策 18:来源隔离展示) */
|
||||
@@ -246,7 +249,7 @@ export interface TransferSourceOption {
|
||||
platform: string;
|
||||
enabled: boolean;
|
||||
/** 收料文件状态:ready / fetching / failed / parse_failed / expired / none(只读投影货代收料事实;parse_failed=当日可用收料文件解析失败) */
|
||||
file_status?: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
|
||||
file_status?: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
|
||||
/** 是否已有当前可用的收料文件(门禁:无 ready 文件禁止确认匹配) */
|
||||
has_ready_file?: boolean;
|
||||
file_no?: string | null;
|
||||
@@ -256,7 +259,7 @@ export interface TransferSourceOption {
|
||||
/** 来源收料文件状态(门禁 + 状态标识 + 重试返回) */
|
||||
export interface TransferSourceFileStatus {
|
||||
source_code: string;
|
||||
file_status: 'ready' | 'fetching' | 'failed' | 'parse_failed' | 'expired' | 'none';
|
||||
file_status: 'ready' | 'fetching' | 'failed' | 'no_data' | 'parse_failed' | 'expired' | 'none';
|
||||
has_ready_file: boolean;
|
||||
file_no?: string | null;
|
||||
file_sha256?: string | null;
|
||||
|
||||
@@ -701,8 +701,13 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
releaseShortageHint: '放行后本次发货按缺口处理。',
|
||||
releaseReasonPlaceholder: '可填写放行原因(选填)',
|
||||
releaseConfirm: '确认放行',
|
||||
reservedQty: '预约数量',
|
||||
partAvailableQty: '可用数量',
|
||||
shortage: '库存不足',
|
||||
pending: '库存匹配或通知文件尚未生成。',
|
||||
capabilityDisabled: {
|
||||
no_match_result: '暂无库存匹配结果,请先重新获取库存',
|
||||
},
|
||||
},
|
||||
uploadComplete: {
|
||||
title: '通知完成',
|
||||
@@ -759,6 +764,8 @@ async function mountView(query: Record<string, string> = {}) {
|
||||
actionCodes: {
|
||||
confirm_customer: '确认客户',
|
||||
resolve_field_conflicts: '处理字段冲突',
|
||||
retry_inventory_preparation: '重新获取库存',
|
||||
retry_inventory_matching: '重新匹配库存',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -1620,6 +1627,81 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('renders capability-disabled actions as disabled buttons with reason tooltip', async () => {
|
||||
// 回归(展示=执行同源):A 渲染的 retry_inventory_matching 命中阶段能力 disabled
|
||||
// (no_match_result)时,右卡必须直接渲染禁用态 + 原因 tooltip;
|
||||
// 禁止可点样式诱导用户点击后才被 submitFormalGateAction 弹提示拦截。
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
status: 'confirmed', has_formal_ot: true, task_missing: false,
|
||||
confirmed_task_id: 906, confirmed_task_no: 'SN-RPA-CAP-DISABLED',
|
||||
};
|
||||
shippingProcessingProjection.value = {
|
||||
workItemType: 'order_task', workItemNo: 'SN-RPA-CAP-DISABLED',
|
||||
status: 'failed', userStatus: 'retryable', stage: 'inventory_fetching',
|
||||
progressVersion: 5, currentGate: { status: 'blocked_retryable' },
|
||||
uiState: {
|
||||
status: 'retryable', stage: 'inventory_fetching', lifecycleStage: 'fulfillment_prep',
|
||||
primary_action: { code: 'retry_inventory_matching' },
|
||||
secondary_actions: [{ code: 'retry_inventory_preparation', enabled: true }],
|
||||
},
|
||||
} as any;
|
||||
const taskApi = await import('@/features/chat/api/shipping.api');
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-RPA-CAP-DISABLED', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
actions: { primary: null, secondary: [] },
|
||||
process_gate: {
|
||||
execution_no: 'EXEC-RPA-CAP-DISABLED',
|
||||
current_blocking_gate: {
|
||||
gate_code: 'inventory_preparation', evaluation_version: 2, status: 'blocked_retryable',
|
||||
},
|
||||
allowed_actions: ['retry_inventory_matching', 'retry_inventory_preparation'],
|
||||
},
|
||||
stage_context: {
|
||||
preparation: {
|
||||
status: 'blocked', source_locked: false,
|
||||
source_options: [{ source_code: 'DSV' }],
|
||||
failed_source_codes: ['DSV'],
|
||||
capabilities: [
|
||||
{
|
||||
code: 'retry_inventory_matching', scope: 'task',
|
||||
action_code: 'retry_inventory_matching', enabled: false,
|
||||
disabled_reason: 'no_match_result',
|
||||
},
|
||||
{
|
||||
code: 'retry_inventory_preparation', scope: 'task',
|
||||
action_code: 'retry_inventory_preparation', enabled: true,
|
||||
disabled_reason: null,
|
||||
},
|
||||
],
|
||||
frozen_order_lines: [], lines: [],
|
||||
},
|
||||
},
|
||||
summary: {}, steps: [],
|
||||
},
|
||||
} as any);
|
||||
|
||||
submitProcessGatePrimaryActionMock.mockClear();
|
||||
messageMocks.info.mockClear();
|
||||
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
|
||||
// 主按钮:能力禁用 → disabled + 原因 tooltip(复用 capabilityDisabled.no_match_result 文案)。
|
||||
const primary = wrapper.get('[data-testid="review-current-processing-retry"]');
|
||||
expect(primary.attributes('disabled')).toBeDefined();
|
||||
expect(primary.attributes('data-capability-disabled')).toBe('true');
|
||||
expect(primary.attributes('title')).toContain('暂无库存匹配结果');
|
||||
// 侧路按钮:能力 enabled → 保持可点,不受主按钮禁用影响。
|
||||
const recovery = wrapper.get('[data-testid="review-current-task-recovery-retry_inventory_preparation"]');
|
||||
expect(recovery.attributes('disabled')).toBeUndefined();
|
||||
// 点击禁用按钮不得触发提交,也不得弹任何 info 提示(此前会弹未翻译 key)。
|
||||
await primary.trigger('click');
|
||||
await flushPromises();
|
||||
expect(submitProcessGatePrimaryActionMock).not.toHaveBeenCalled();
|
||||
expect(messageMocks.info).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refreshes the processing projection after field-conflict adjudication refreshes the Case', async () => {
|
||||
activeCase.value = {
|
||||
...activeCase.value,
|
||||
@@ -2022,6 +2104,65 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('does not auto-advance when switching formal-downstream files without an activeCase identity', async () => {
|
||||
// 回归:正式下游(通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,
|
||||
// 切换前后 activeCase 身份(case_no/document_id)恒为空值;自动推进守卫若用
|
||||
// activeCase 做“同一文件”判据,会把目标文件更晚的阶段误判成当前文件被推进,
|
||||
// 弹出“已自动推进到货代上传”。文件身份必须用 requestedCaseNo(与阶段解析同源,
|
||||
// selectCase/beginCrossRunSwitch 同步块内更新):切换必变更 → 静默;真实推进
|
||||
// 不触碰 requestedCaseNo → 提示行为不变。
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
summary: { total: 2, needs_action: 2, processing: 0, completed: 0 },
|
||||
items: [
|
||||
{
|
||||
...reviewQueue.value.items[0],
|
||||
has_formal_ot: true,
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
},
|
||||
{
|
||||
case_no: 'CASE-2', source_run_no: 'RUN-1', document_id: 2, file_name: 'po-2.pdf',
|
||||
status: 'confirmed', has_formal_ot: true, issue_count: 0,
|
||||
lifecycle_stage: 'freight_upload',
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'freight_upload', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'upload_complete', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
// 选法 2 盲区:源文件无复核 Case 快照(懒加载失败/未完成时生产即如此),
|
||||
// 此刻文件身份只剩 requestedCaseNo。
|
||||
activeCase.value = null;
|
||||
requestedCaseNo.value = 'CASE-1';
|
||||
|
||||
const wrapper = await mountView({ case_no: 'CASE-1', lifecycle_stage: 'fulfillment_prep' });
|
||||
await flushPromises();
|
||||
messageMocks.success.mockClear();
|
||||
|
||||
// 模拟真实 selectCase 正式下游分支的同步块:更新 requestedCaseNo + activeCase 保持 null。
|
||||
requestedCaseNo.value = 'CASE-2';
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
|
||||
expect(messageMocks.success).not.toHaveBeenCalledWith('已自动推进到货代上传');
|
||||
// 守卫不得替用户改写深链:切文件是展示上下文切换,不是流程推进。
|
||||
expect((wrapper.vm as any).$route.query.lifecycle_stage).toBe('fulfillment_prep');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('does not open a lifecycle stage before the backend authorizes lifecycle entries', async () => {
|
||||
// 未收到正式 ui_state.lifecycle_entries 时,前端只能等待实时裁决,
|
||||
// 不能因页面默认值自行开放订单复核或其他生命周期阶段。
|
||||
@@ -2686,7 +2827,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
lines: [{
|
||||
snapshot_line_id: 1001, line_no: 1,
|
||||
reservation_id: 'RSV-FROZEN', part_number: 'PN-FROZEN',
|
||||
required_qty: '6', available_qty: null, shortage_qty: null, source_code: 'DBS',
|
||||
required_qty: '6', available_qty: null, part_available_qty: '9', shortage_qty: null, source_code: 'DBS',
|
||||
inventory_file_no: 'SIF-LINE-DBS', status: 'shortage',
|
||||
draft_line_id: 'line-frozen',
|
||||
inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'],
|
||||
@@ -2719,6 +2860,12 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
expect(workspace.text()).toContain('RSV-FROZEN');
|
||||
expect(workspace.text()).toContain('PN-FROZEN');
|
||||
expect(workspace.text()).toContain('DBS');
|
||||
// 断言意图:原可用数量列头改由 reservedQty 键渲染(预约数量),
|
||||
// 新增料号总库存列紧随其后,值来自 part_available_qty。
|
||||
const headers = workspace.findAll('thead th').map((th) => th.text());
|
||||
expect(headers).toContain('预约数量');
|
||||
expect(headers.indexOf('可用数量')).toBe(headers.indexOf('预约数量') + 1);
|
||||
expect(workspace.text()).toContain('9');
|
||||
expect(wrapper.find('[data-testid="review-fulfillment-frozen-order"]').exists()).toBe(false);
|
||||
// 展示态行级动作收纳进更多菜单(⋯):逐项断言授权动作入口存在,不再有常显按钮。
|
||||
await openLineOverflowMenu(wrapper, 1001);
|
||||
|
||||
@@ -817,6 +817,33 @@ const LINE_SCOPE_INVENTORY_ACTIONS = new Set([
|
||||
'override_line_inventory_source',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 阶段能力按执行动作码索引(preparation.capabilities)。
|
||||
* 核心逻辑:右卡按钮的禁用态渲染必须与 submitFormalGateAction 的点击拦截消费同一份
|
||||
* 能力投影,保证「展示=执行同源」——禁止按钮渲染成可点、点击才被能力门禁弹提示。
|
||||
*/
|
||||
const stageCapabilityByActionCode = computed(() => {
|
||||
const map = new Map<string, { enabled: boolean; disabled_reason?: string | null }>();
|
||||
for (const cap of formalPreparationContext.value?.capabilities || []) {
|
||||
const code = String(cap.action_code || '').trim();
|
||||
if (code) map.set(code, cap);
|
||||
}
|
||||
return map;
|
||||
});
|
||||
|
||||
/**
|
||||
* 给右卡动作附加阶段能力禁用原因。
|
||||
* @param action - 已统一到卡片域的动作对象(须含 code)
|
||||
* @returns 原对象浅拷贝;能力禁用时带 capabilityDisabledReason,否则该字段为 null
|
||||
*/
|
||||
function withStageCapabilityState<T extends { code: string }>(
|
||||
action: T,
|
||||
): T & { capabilityDisabledReason?: string | null } {
|
||||
const cap = stageCapabilityByActionCode.value.get(String(action.code || '').trim());
|
||||
if (!cap || cap.enabled) return { ...action, capabilityDisabledReason: null };
|
||||
return { ...action, capabilityDisabledReason: String(cap.disabled_reason || '').trim() || null };
|
||||
}
|
||||
|
||||
const currentTaskPrimaryAction = computed(() => {
|
||||
if (formalTaskProjectionPending.value) return null;
|
||||
if (hasFormalOt.value) {
|
||||
@@ -828,10 +855,10 @@ const currentTaskPrimaryAction = computed(() => {
|
||||
// 故必须统一映射到卡片域,否则按钮会因 businessActionLabel 为空而 fail-closed 消失。
|
||||
const action = currentTaskUiState.value?.primary_action ?? null;
|
||||
if (!action?.code || LINE_SCOPE_INVENTORY_ACTIONS.has(action.code)) return null;
|
||||
return {
|
||||
return withStageCapabilityState({
|
||||
code: String(action.code).trim(),
|
||||
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
|
||||
};
|
||||
});
|
||||
}
|
||||
const projection = shippingProcessingProjection.value;
|
||||
if (projection) {
|
||||
@@ -914,6 +941,8 @@ const currentTaskRecoveryActions = computed(() => {
|
||||
// [§2.4 单源] 任务级恢复按钮只读 A.secondary_actions;不再叠加 B.capabilities。
|
||||
// capabilities 仍可作点击执行的 stageCapabilityBypass 查找(见 handleCurrentTaskAction),
|
||||
// 但不得单独渲成右卡按钮——能力要展示须先并进 A。行级选源禁止出现在右卡。
|
||||
// [展示=执行同源] A 已渲染的按钮若命中阶段能力 disabled(capabilityDisabledReason
|
||||
// 非空),右卡必须渲染禁用态 + 原因 tooltip,禁止可点样式诱导用户点击后才被拦截。
|
||||
return (currentTaskUiState.value?.secondary_actions || [])
|
||||
.filter((action) => action.enabled
|
||||
&& String(action.code || '').trim() !== 'download_excel'
|
||||
@@ -923,7 +952,8 @@ const currentTaskRecoveryActions = computed(() => {
|
||||
// 统一右卡 domain:actionCodes.<code>(见 currentTaskPrimaryAction 注;A 的 i18nKey 可能是 chat 域)。
|
||||
i18nKey: `workspace.shippingNotice.processGate.actionCodes.${String(action.code || '').trim()}`,
|
||||
}))
|
||||
.filter((action): action is { code: string; i18nKey: string } => {
|
||||
.map((action) => withStageCapabilityState(action))
|
||||
.filter((action): action is { code: string; i18nKey: string; capabilityDisabledReason?: string | null } => {
|
||||
const code = String(action.code || '').trim();
|
||||
return Boolean(code) && !LINE_SCOPE_INVENTORY_ACTIONS.has(code);
|
||||
});
|
||||
@@ -2568,8 +2598,12 @@ const formalPreparationLines = computed(() => {
|
||||
...line,
|
||||
required_qty: displayDecimalQty(line.required_qty),
|
||||
available_qty: displayDecimalQty(line.available_qty),
|
||||
// available_qty 语义为「预约匹配量」(列头:预约数量);part_available_qty 为料号总库存
|
||||
// (列头:可用数量)。null 透传,由模板渲染待确认占位,避免把「无快照」误显示为 0。
|
||||
part_available_qty:
|
||||
line.part_available_qty == null ? null : displayDecimalQty(line.part_available_qty),
|
||||
shortage_qty: displayDecimalQty(line.shortage_qty),
|
||||
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string }>;
|
||||
})) as Array<typeof rows[number] & { snapshot_line_id?: number | null; required_qty: string; available_qty: string; shortage_qty: string; part_available_qty: string | null }>;
|
||||
});
|
||||
|
||||
/** 通知准备固定展示冻结订单明细;库存匹配结果只作为附加事实合并。 */
|
||||
@@ -4875,20 +4909,21 @@ watch(
|
||||
watch(
|
||||
() => [
|
||||
lifecycleCurrentStageCode.value,
|
||||
String(activeCase.value?.case_no || '').trim(),
|
||||
activeReviewDocumentId(),
|
||||
// 文件身份必须用 requestedCaseNo(与 lifecycleUiState 解析阶段同源):正式下游
|
||||
// (通知准备/货代上传/通知完成,选法 2)activeCase 刻意为 null,其 case_no/document_id
|
||||
// 在这些文件之间恒为空值,用 activeCase 做身份会让"切换文件"被误判成"同一文件的
|
||||
// 阶段推进"而弹出"已自动推进"。requestedCaseNo 在 selectCase/beginCrossRunSwitch/
|
||||
// load 里与阶段重算同一同步块内更新,切换文件时本 watcher 必然看到变化而静默;
|
||||
// 真正的自动推进只改队列投影、不触碰 requestedCaseNo,提示行为不变。
|
||||
String(requestedCaseNo.value || activeCase.value?.case_no || '').trim(),
|
||||
] as const,
|
||||
async (current, previous) => {
|
||||
const [currentStage, currentCaseNo, currentDocumentId] = current;
|
||||
const [previousStage, previousCaseNo, previousDocumentId] = previous || [];
|
||||
const [currentStage, currentFileKey] = current;
|
||||
const [previousStage, previousFileKey] = previous || [];
|
||||
if (await syncPendingReleaseAutoAdvance()) return;
|
||||
// 切换文件时生命周期阶段会随新 Case 一起变更;这不是当前文件的自动推进,
|
||||
// 切换文件时生命周期阶段会随新文件身份一起变更;这不是当前文件的自动推进,
|
||||
// 不能跳转或弹出“已自动推进”提示。
|
||||
if (
|
||||
!previous
|
||||
|| currentCaseNo !== previousCaseNo
|
||||
|| currentDocumentId !== previousDocumentId
|
||||
) return;
|
||||
if (!previous || currentFileKey !== previousFileKey) return;
|
||||
if (!currentStage || !previousStage || currentStage === previousStage) return;
|
||||
const pendingReparse = pendingReparseNavigation.value;
|
||||
if (
|
||||
@@ -5329,8 +5364,8 @@ watch(
|
||||
</div>
|
||||
<div class="overflow-x-auto overscroll-x-contain" data-testid="review-fulfillment-prep-table-scroll">
|
||||
<table class="review-fulfillment-prep-table min-w-[1060px] text-xs">
|
||||
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.availableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
|
||||
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
|
||||
<thead class="border-b border-default bg-surface-muted/50 text-left"><tr><th v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="allPreparationWaveSelected" :disabled="!preparationWaveSelectableLines.length || preparationWaveBusy" :aria-label="t('chat.shippingOrderReview.fulfillmentDecision.selectReady')" @change="toggleAllPreparationLineSelection(($event.target as HTMLInputElement).checked)"></th><th v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationCustomerPoLineLabel() }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.inventorySource') }}</th><th v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.odmConflict.column') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.reservedQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.partAvailableQty') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.fulfillmentDecision.shortage') }}</th><th class="whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.lineStatus') }}</th><th class="review-fulfillment-sticky-action-head whitespace-nowrap px-3 py-2">{{ t('chat.shippingOrderReview.lineOps.moreActions') }}</th></tr></thead>
|
||||
<tbody><template v-for="(line, lineIndex) in formalPreparationDisplayLines" :key="line.snapshot_line_id || `${line.reservation_id}-${line.part_number}`"><tr :class="Number(line.shortage_qty || 0) > 0 ? 'border-b border-amber-100 bg-amber-50/40 last:border-0 dark:border-amber-950 dark:bg-amber-950/10' : 'border-b border-default last:border-0'"><td v-if="preparationEditable" class="w-10 px-3 py-2"><input type="checkbox" class="rounded border-default" :checked="selectedPreparationSnapshotLineIds.includes(String(line.snapshot_line_id))" :disabled="preparationWaveBusy || !preparationWaveSelectableLines.some((item) => String(item.snapshot_line_id) === String(line.snapshot_line_id))" :aria-label="`${t('chat.shippingOrderReview.fulfillmentDecision.selectReady')}: ${preparationLineCustomerPoLine(line)}`" :data-testid="`review-fulfillment-line-select-${line.snapshot_line_id || lineIndex}`" @change="togglePreparationLineSelection(String(line.snapshot_line_id || lineIndex), ($event.target as HTMLInputElement).checked)"></td><td v-if="preparationCustomerPoLineVisible" class="whitespace-nowrap px-3 py-2">{{ preparationLineCustomerPoLine(line) }}</td><td class="whitespace-nowrap px-3 py-2 font-medium text-primary"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.reservation_id" type="text" class="w-28 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultReservation')" :data-testid="`review-fulfillment-line-edit-reservation-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.reservation_id || '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input v-model="editingLine.part_number" type="text" class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.workbench.resultPartNumber')" :data-testid="`review-fulfillment-line-edit-part-${line.snapshot_line_id}`" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else class="block max-w-[220px] truncate" :title="line.part_number || '—'">{{ line.part_number || '—' }}</span></td><td class="whitespace-nowrap px-3 py-2"><template v-if="editingLine && isInlineEditing(line)"><input :value="editingLine.required_qty" type="number" min="0" step="any" class="w-20 rounded border border-default bg-surface px-1.5 py-1 text-xs" :disabled="inlineEditSaving" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.requiredQty')" :data-testid="`review-fulfillment-line-edit-qty-${line.snapshot_line_id}`" @input="updateInlineEditQty(($event.target as HTMLInputElement).value)" @keyup.enter="saveInlineEdit(line)" @keyup.esc="cancelInlineEdit" /></template><span v-else>{{ line.required_qty ?? '—' }}</span></td><td class="max-w-[220px] px-3 py-2"><template v-if="isInlineEditing(line) && inlineSourceOptions(line).length"><select class="w-full min-w-0 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-fulfillment-line-edit-source-${line.snapshot_line_id}`" :aria-label="t('chat.shippingOrderReview.lifecycle.prepare.selectSource')" :value="editingLine?.source_code" :disabled="inlineEditSaving" @change="updateInlineEditSource(($event.target as HTMLSelectElement).value)"><option v-for="option in inlineSourceOptions(line)" :key="option.value" :value="option.value">{{ option.label }}</option></select></template><span v-else class="block max-w-[220px] truncate" :title="formalPreparationLineSource(line)">{{ formalPreparationLineSource(line) || '—' }}</span></td><td v-if="formalPreparationOdmColumnVisible" class="whitespace-nowrap px-3 py-2"><div v-if="(line.odm_values?.length || 0) > 1 && !formalPreparationSourceLocked" class="flex items-center gap-1" :data-testid="`review-line-odm-${line.snapshot_line_id || lineIndex}`"><select class="min-w-0 flex-1 rounded border border-default bg-surface px-1.5 py-1 text-xs" :data-testid="`review-line-odm-select-${line.snapshot_line_id || lineIndex}`" :aria-label="t('chat.shippingOrderReview.odmConflict.title')" :value="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || line.chosen_odm_id || ''" @change="lineOdmSelections[String(line.snapshot_line_id || lineIndex)] = ($event.target as HTMLSelectElement).value"><option value="" disabled>{{ t('chat.shippingOrderReview.odmConflict.placeholder') }}</option><option v-for="value in line.odm_values" :key="value" :value="value">{{ value }}</option></select><button type="button" class="rounded bg-brand-600 px-2 py-1 text-xs font-medium text-white disabled:opacity-50" :data-testid="`review-line-odm-confirm-${line.snapshot_line_id || lineIndex}`" :disabled="!lineOdmSelections[String(line.snapshot_line_id || lineIndex)] || lineOdmBusy" :aria-label="t('chat.shippingOrderReLine truncated
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2560,7 +2560,8 @@
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferNotifyUsers": "Notify users",
|
||||
"transferReceiptDateFrom": "Receipt date from (T-N)",
|
||||
"transferReceiptDateTo": "Receipt date to (T-N)",
|
||||
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
|
||||
"shippingInventoryJobHint": "Fetches inventory data from configured sources on schedule; exported asynchronously by the RPA worker.",
|
||||
"shippingInventoryJobParams": "Job parameters (optional)",
|
||||
@@ -2693,7 +2694,7 @@
|
||||
"voucherCheckNotifyMissingHint": "Master switch. Set missing-file recipients in Chat “Accounting voucher check → Notification config” by file type. The schedule people picker is only for failure alerts.",
|
||||
"voucherCheckNotifyFailure": "Failure alert",
|
||||
"voucherCheckNotifyFailureHint": "Technical failures go to the people selected below.",
|
||||
"dynamicParamsSearchPlaceholder": "Search options (name / ID / dept)…",
|
||||
"dynamicParamsSearchPlaceholder": "Search options…",
|
||||
"dynamicParamsSearchNoMatch": "No matching options"
|
||||
},
|
||||
"testRun": {
|
||||
|
||||
@@ -1696,6 +1696,8 @@
|
||||
"releaseReasonPlaceholder": "Enter release reason (required)",
|
||||
"releaseConfirm": "Confirm release",
|
||||
"requiredQty": "Required quantity",
|
||||
"reservedQty": "Reserved qty",
|
||||
"partAvailableQty": "Available qty",
|
||||
"matchWorkspace": "Inventory matching",
|
||||
"lineCount": "{count} inventory results",
|
||||
"lineStatus": "Match status",
|
||||
@@ -1724,7 +1726,8 @@
|
||||
"capabilityDisabled": {
|
||||
"excel_locked": "Notice Excel generated; inventory source is locked",
|
||||
"no_candidates": "No available inventory source candidates",
|
||||
"no_prior_result": "No prior inventory result"
|
||||
"no_prior_result": "No prior inventory result",
|
||||
"no_match_result": "No inventory match result yet; re-fetch inventory first"
|
||||
},
|
||||
"status": {
|
||||
"ready": "Match ready",
|
||||
@@ -3898,6 +3901,7 @@
|
||||
"fileReady": "File ready",
|
||||
"fileFetching": "Fetching",
|
||||
"fileFailed": "Fetch failed",
|
||||
"fileNoData": "No receipt data",
|
||||
"fileExpired": "File expired",
|
||||
"fileParseFailed": "Parse failed",
|
||||
"sourceErrorTitle": "Source processing failed",
|
||||
@@ -3909,6 +3913,11 @@
|
||||
"downloadFiles": "Download receipt files",
|
||||
"selectedRetryableCount": "{count} retryable",
|
||||
"noRetryable": "No selected source needs retry (fetching in progress)",
|
||||
"partialConfirmSummary": "{total} selected · {ready} ready to match · {unready} not ready",
|
||||
"partialConfirmBreakdown": " ({items})",
|
||||
"partialConfirmHint": "Only ready sources will be matched; the rest can be matched later once ready.",
|
||||
"partialConfirmProceed": "Match ready only",
|
||||
"partialConfirmCancel": "Cancel",
|
||||
"homeMatchLabel": "Stock matching",
|
||||
"homeBoardLabel": "To-do board",
|
||||
"homeExecutable": "Executable items",
|
||||
|
||||
@@ -2465,7 +2465,8 @@
|
||||
"platformJobFileAssetCleanup": "Temporary file asset cleanup",
|
||||
"transferSourceCodes": "Source instances",
|
||||
"transferRecoverHistory": "Recover retryable history",
|
||||
"transferNotifyUsers": "Notify users",
|
||||
"transferReceiptDateFrom": "Receipt date from (T-N)",
|
||||
"transferReceiptDateTo": "Receipt date to (T-N)",
|
||||
"platformJobFixedAssetsSnapshot": "Fixed assets snapshot",
|
||||
"shippingInventoryJobHint": "ดึงข้อมูลสต็อกจากแหล่งที่กำหนดตามกำหนดเวลา โดย RPA worker ส่งออกแบบอะซิงโครนัส",
|
||||
"shippingInventoryJobParams": "พารามิเตอร์ Job (ไม่บังคับ)",
|
||||
@@ -2606,7 +2607,7 @@
|
||||
"saving": "Saving...",
|
||||
"saveChanges": "Save changes",
|
||||
"createSchedule": "Create schedule",
|
||||
"dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก (ชื่อ/รหัส/แผนก)…",
|
||||
"dynamicParamsSearchPlaceholder": "ค้นหาตัวเลือก…",
|
||||
"dynamicParamsSearchNoMatch": "ไม่มีตัวเลือกที่ตรง"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -1696,6 +1696,8 @@
|
||||
"releaseReasonPlaceholder": "กรอกเหตุผลการอนุมัติ (จำเป็น)",
|
||||
"releaseConfirm": "ยืนยันการอนุมัติ",
|
||||
"requiredQty": "จำนวนที่ต้องการ",
|
||||
"reservedQty": "จำนวนตามใบจอง",
|
||||
"partAvailableQty": "จำนวนที่ใช้ได้",
|
||||
"matchWorkspace": "การจับคู่สต็อก",
|
||||
"lineCount": "ผลลัพธ์สต็อก {count} รายการ",
|
||||
"lineStatus": "สถานะการจับคู่",
|
||||
@@ -1724,7 +1726,8 @@
|
||||
"capabilityDisabled": {
|
||||
"excel_locked": "สร้าง Excel แจ้งเตือนแล้ว แหล่งสินค้าถูกล็อก",
|
||||
"no_candidates": "ยังไม่มีตัวเลือกแหล่งสต็อกที่พร้อมใช้",
|
||||
"no_prior_result": "ยังไม่มีผลลัพธ์สต็อกในประวัติ"
|
||||
"no_prior_result": "ยังไม่มีผลลัพธ์สต็อกในประวัติ",
|
||||
"no_match_result": "ยังไม่มีผลการจับคู่สต็อก โปรดดึงข้อมูลสต็อกอีกครั้งก่อน"
|
||||
},
|
||||
"status": {
|
||||
"ready": "จับคู่พร้อมแล้ว",
|
||||
@@ -3898,6 +3901,7 @@
|
||||
"fileReady": "ไฟล์พร้อมแล้ว",
|
||||
"fileFetching": "กำลังดึง",
|
||||
"fileFailed": "ดึงล้มเหลว",
|
||||
"fileNoData": "ไม่มีข้อมูลการรับสินค้า",
|
||||
"fileExpired": "ไฟล์หมดอายุ",
|
||||
"fileParseFailed": "แยกวิเคราะห์ไม่สำเร็จ",
|
||||
"sourceErrorTitle": "ประมวลผลแหล่งข้อมูลล้มเหลว",
|
||||
@@ -3909,6 +3913,11 @@
|
||||
"downloadFiles": "ดาวน์โหลดไฟล์การรับสินค้า",
|
||||
"selectedRetryableCount": "ลองใหม่ได้ {count} รายการ",
|
||||
"noRetryable": "ไม่มีแหล่งที่เลือกต้องลองใหม่ (กำลังดึงข้อมูล)",
|
||||
"partialConfirmSummary": "เลือก {total} แหล่ง · พร้อมจับคู่ {ready} แหล่ง · ยังไม่พร้อม {unready} แหล่ง",
|
||||
"partialConfirmBreakdown": " ({items})",
|
||||
"partialConfirmHint": "จับคู่เฉพาะแหล่งที่พร้อมเท่านั้น ส่วนที่เหลือสามารถจับคู่เพิ่มได้เมื่อพร้อม",
|
||||
"partialConfirmProceed": "จับคู่เฉพาะที่พร้อม",
|
||||
"partialConfirmCancel": "ยกเลิก",
|
||||
"homeMatchLabel": "จับคู่สต็อก",
|
||||
"homeBoardLabel": "บอร์ดงานที่ต้องดำเนินการ",
|
||||
"homeExecutable": "รายการที่โอนได้",
|
||||
|
||||
@@ -2688,7 +2688,8 @@
|
||||
"platformJobFileAssetCleanup": "临时文件资产清理",
|
||||
"transferSourceCodes": "来源实例",
|
||||
"transferRecoverHistory": "历史可恢复异常复核",
|
||||
"transferNotifyUsers": "通知人",
|
||||
"transferReceiptDateFrom": "收料日期起(T-N)",
|
||||
"transferReceiptDateTo": "收料日期止(T-N)",
|
||||
"platformJobFixedAssetsSnapshot": "固资快照",
|
||||
"shippingInventoryJobHint": "按计划从配置的库存源抓取库存数据,由 RPA Worker 异步导出。",
|
||||
"shippingInventoryJobParams": "Job 参数(可选)",
|
||||
@@ -2821,7 +2822,7 @@
|
||||
"voucherCheckNotifyMissingHint": "总开关。缺件接收人请到 Chat「立账凭证 → 通知配置」按文件类型设置;排程选人只用于技术失败告警。",
|
||||
"voucherCheckNotifyFailure": "失败告警",
|
||||
"voucherCheckNotifyFailureHint": "技术失败发给下方「选择通知人员」。",
|
||||
"dynamicParamsSearchPlaceholder": "搜索选项(姓名/工号/部门)…",
|
||||
"dynamicParamsSearchPlaceholder": "搜索选项…",
|
||||
"dynamicParamsSearchNoMatch": "没有匹配的选项"
|
||||
},
|
||||
"testRun": {
|
||||
|
||||
@@ -1730,6 +1730,8 @@
|
||||
"releaseReasonPlaceholder": "请输入放行原因(必填)",
|
||||
"releaseConfirm": "确认放行",
|
||||
"requiredQty": "需求数量",
|
||||
"reservedQty": "预约数量",
|
||||
"partAvailableQty": "可用数量",
|
||||
"matchWorkspace": "库存匹配",
|
||||
"lineCount": "{count} 行库存结果",
|
||||
"lineStatus": "匹配状态",
|
||||
@@ -1758,7 +1760,8 @@
|
||||
"capabilityDisabled": {
|
||||
"excel_locked": "通知 Excel 已生成,库存源已锁定",
|
||||
"no_candidates": "暂无可用库存源候选",
|
||||
"no_prior_result": "暂无历史库存结果"
|
||||
"no_prior_result": "暂无历史库存结果",
|
||||
"no_match_result": "暂无库存匹配结果,请先重新获取库存"
|
||||
},
|
||||
"status": {
|
||||
"ready": "匹配完成",
|
||||
@@ -3897,6 +3900,7 @@
|
||||
"fileReady": "文件已就绪",
|
||||
"fileFetching": "抓取中",
|
||||
"fileFailed": "抓取失败",
|
||||
"fileNoData": "无收料数据",
|
||||
"fileExpired": "文件已过期",
|
||||
"fileParseFailed": "解析失败",
|
||||
"sourceErrorTitle": "来源处理失败",
|
||||
@@ -3908,6 +3912,11 @@
|
||||
"downloadFiles": "下载收料文件",
|
||||
"selectedRetryableCount": "其中 {count} 个可重试",
|
||||
"noRetryable": "所选来源均无需重试(抓取中)",
|
||||
"partialConfirmSummary": "已选 {total} 个来源 · 可匹配 {ready} 个 · 暂不可匹配 {unready} 个",
|
||||
"partialConfirmBreakdown": "({items})",
|
||||
"partialConfirmHint": "本次仅匹配就绪来源;其余来源就绪后可重新匹配补入。",
|
||||
"partialConfirmProceed": "仅匹配就绪来源",
|
||||
"partialConfirmCancel": "取消",
|
||||
"homeMatchLabel": "库存匹配",
|
||||
"homeBoardLabel": "待办看板",
|
||||
"homeExecutable": "可调拨明细",
|
||||
|
||||
@@ -2465,7 +2465,8 @@
|
||||
"platformJobFileAssetCleanup": "暫存檔案資產清理",
|
||||
"transferSourceCodes": "來源實例",
|
||||
"transferRecoverHistory": "歷史可復原異常複核",
|
||||
"transferNotifyUsers": "通知人",
|
||||
"transferReceiptDateFrom": "收料日期起(T-N)",
|
||||
"transferReceiptDateTo": "收料日期止(T-N)",
|
||||
"platformJobFixedAssetsSnapshot": "固資快照",
|
||||
"shippingInventoryJobHint": "按計畫從配置的庫存來源抓取庫存資料,由 RPA Worker 非同步匯出。",
|
||||
"shippingInventoryJobParams": "Job 參數(可選)",
|
||||
@@ -2606,7 +2607,7 @@
|
||||
"saving": "Saving...",
|
||||
"saveChanges": "Save changes",
|
||||
"createSchedule": "Create schedule",
|
||||
"dynamicParamsSearchPlaceholder": "搜尋選項(姓名/工號/部門)…",
|
||||
"dynamicParamsSearchPlaceholder": "搜尋選項…",
|
||||
"dynamicParamsSearchNoMatch": "沒有符合的選項"
|
||||
},
|
||||
"status": {
|
||||
|
||||
@@ -1696,6 +1696,8 @@
|
||||
"releaseReasonPlaceholder": "請輸入放行原因(必填)",
|
||||
"releaseConfirm": "確認放行",
|
||||
"requiredQty": "需求數量",
|
||||
"reservedQty": "預約數量",
|
||||
"partAvailableQty": "可用數量",
|
||||
"matchWorkspace": "庫存匹配",
|
||||
"lineCount": "{count} 行庫存結果",
|
||||
"lineStatus": "匹配狀態",
|
||||
@@ -1724,7 +1726,8 @@
|
||||
"capabilityDisabled": {
|
||||
"excel_locked": "通知 Excel 已生成,庫存源已鎖定",
|
||||
"no_candidates": "暫無可用庫存來源候選",
|
||||
"no_prior_result": "暫無歷史庫存結果"
|
||||
"no_prior_result": "暫無歷史庫存結果",
|
||||
"no_match_result": "暫無庫存匹配結果,請先重新取得庫存"
|
||||
},
|
||||
"status": {
|
||||
"ready": "匹配完成",
|
||||
@@ -3898,6 +3901,7 @@
|
||||
"fileReady": "檔案已就緒",
|
||||
"fileFetching": "抓取中",
|
||||
"fileFailed": "抓取失敗",
|
||||
"fileNoData": "無收料數據",
|
||||
"fileExpired": "檔案已過期",
|
||||
"fileParseFailed": "解析失敗",
|
||||
"sourceErrorTitle": "來源處理失敗",
|
||||
@@ -3909,6 +3913,11 @@
|
||||
"downloadFiles": "下載收料文件",
|
||||
"selectedRetryableCount": "其中 {count} 個可重試",
|
||||
"noRetryable": "所選來源均無需重試(抓取中)",
|
||||
"partialConfirmSummary": "已選 {total} 個來源 · 可匹配 {ready} 個 · 暫不可匹配 {unready} 個",
|
||||
"partialConfirmBreakdown": "({items})",
|
||||
"partialConfirmHint": "本次僅匹配就緒來源;其餘來源就緒後可重新匹配補入。",
|
||||
"partialConfirmProceed": "僅匹配就緒來源",
|
||||
"partialConfirmCancel": "取消",
|
||||
"homeMatchLabel": "庫存匹配",
|
||||
"homeBoardLabel": "待辦看板",
|
||||
"homeExecutable": "可調撥明細",
|
||||
|
||||
@@ -209,6 +209,9 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
核心逻辑:先用 DOM 脚本按方法行点击(兼容 mfaForm / device-list / 泛化 listitem);
|
||||
失败再按 Playwright 行选择器与精确文案 `Password`/`密码` 点击;任一路经须
|
||||
`transition_confirmed`(密码框出现或离开方法页)才算成功。
|
||||
防误点约束:“忘记密码”链接锚点文本恰好是“密码”(“忘记”在 #forgotLinks 父级文本
|
||||
节点里),方法页判定、DOM 脚本与文案兜底三层都必须按容器/跳转目标将其排除,
|
||||
否则会跳到 password.dbschenker.com 找回密码页导致登录中断。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(可含 iframe)。
|
||||
@@ -255,7 +258,45 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
time.sleep(0.3)
|
||||
return False
|
||||
|
||||
def text_candidate_clickable(locator: Any) -> bool:
|
||||
"""
|
||||
文案兜底命中候选时,只放行真正的控件(button/a/li/input/role=button)。
|
||||
|
||||
[BUGFIX] text=密码 这类子串选择器会命中 body/表单包裹层,force 点击其几何中心,
|
||||
中心压在“忘记密码”链接上就会跳到 password.dbschenker.com;容器命中一律跳过。
|
||||
"""
|
||||
try:
|
||||
info = locator.evaluate(
|
||||
"(node) => ({"
|
||||
" tag: node.tagName,"
|
||||
" forgot: !!(node.closest && node.closest('#forgotLinks')),"
|
||||
" href: (node.getAttribute ? (node.getAttribute('href') || '') : ''),"
|
||||
" role: (node.getAttribute && node.getAttribute('role')) || ''"
|
||||
"})"
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
if not isinstance(info, dict):
|
||||
return False
|
||||
if info.get('forgot'):
|
||||
return False
|
||||
if 'password.dbschenker.com' in str(info.get('href') or '').lower():
|
||||
return False
|
||||
tag = str(info.get('tag') or '').upper()
|
||||
return tag in {'BUTTON', 'A', 'LI', 'INPUT'} or str(info.get('role') or '') == 'button'
|
||||
|
||||
def try_click_locator(locator: Any) -> bool:
|
||||
# [BUGFIX] “忘记密码”链接锚点文本就是“密码”,text="密码"/a:has-text("密码") 都会命中;
|
||||
# 点击前按所在容器与跳转目标统一拦截,防止误跳 password.dbschenker.com 找回密码页。
|
||||
try:
|
||||
if locator.evaluate(
|
||||
"(node) => (node.closest && !!node.closest('#forgotLinks'))"
|
||||
" || ((node.getAttribute ? (node.getAttribute('href') || '') : '')"
|
||||
".toLowerCase().includes('password.dbschenker.com'))"
|
||||
):
|
||||
return False
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
locator.scroll_into_view_if_needed(timeout=3_000)
|
||||
except Exception:
|
||||
@@ -288,7 +329,12 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
const style = window.getComputedStyle(node);
|
||||
return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0);
|
||||
};
|
||||
const isPasswordMethod = (text) => {
|
||||
const isPasswordMethod = (node, text) => {
|
||||
// [BUGFIX] “忘记密码”链接的锚点文本恰好是“密码”(“忘记”二字在父级 #forgotLinks 的
|
||||
// 文本节点里),仅按元素自身文案排除会漏掉它;必须按所在容器与跳转目标排除。
|
||||
if (node.closest && node.closest('#forgotLinks')) return false;
|
||||
const href = (node.getAttribute && node.getAttribute('href')) || '';
|
||||
if (node.tagName === 'A' && /password\\.dbschenker\\.com/i.test(href)) return false;
|
||||
const lowered = (text || '').toLowerCase();
|
||||
const excluded = (
|
||||
text.includes('忘记密码') || lowered.includes('forgot password')
|
||||
@@ -309,7 +355,7 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
const rows = Array.from(document.querySelectorAll(
|
||||
"form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2, li.mb-2, [role='listitem'], .device-type, button, a, [role='button']"
|
||||
)).filter((node) => isVisible(node));
|
||||
const row = rows.find((node) => isPasswordMethod(textOf(node)));
|
||||
const row = rows.find((node) => isPasswordMethod(node, textOf(node)));
|
||||
if (!row) return false;
|
||||
const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row;
|
||||
target.scrollIntoView({ block: 'center', inline: 'center' });
|
||||
@@ -378,6 +424,8 @@ def _click_dsv_password_method(page: Any) -> bool:
|
||||
locator.wait_for(state="visible", timeout=500)
|
||||
except Exception:
|
||||
continue
|
||||
if not text_candidate_clickable(locator):
|
||||
continue
|
||||
if try_click_locator(locator):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
@@ -556,14 +604,16 @@ def _is_dsv_password_upgrade_redirect(page: Any) -> bool:
|
||||
"""
|
||||
判断是否处在点击登录后的密码升级提示地址。
|
||||
|
||||
核心逻辑:只有 `auth.dbschenker.com/.../resume/as/authorization.ping` 才需要点击
|
||||
“也许以后”;如果登录直接进入 s360 portal,则不做升级提示处理。
|
||||
核心逻辑:只有认证域的 `/resume/as/authorization.ping` 才需要点击“也许以后”
|
||||
(2026-10-12 起 resume 链出现在 auth.dsv.com,判定须覆盖双认证域;
|
||||
域漏判会导致提示检测为 False,登录卡死在升级提示页);
|
||||
如果登录直接进入 s360 portal,则不做升级提示处理。
|
||||
"""
|
||||
try:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
return "auth.dbschenker.com" in current_url and "/resume/as/authorization.ping" in current_url
|
||||
return _on_dsv_auth_domain(current_url) and "/resume/as/authorization.ping" in current_url
|
||||
|
||||
|
||||
def _portal_home_nav_already_usable(page: Any) -> bool:
|
||||
@@ -574,7 +624,7 @@ def _portal_home_nav_already_usable(page: Any) -> bool:
|
||||
误判为“首页已稳定”。
|
||||
"""
|
||||
current_url = str(getattr(page, "url", "") or "").lower()
|
||||
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
|
||||
if "s360.dbschenker.com" not in current_url or _on_dsv_auth_domain(current_url):
|
||||
return False
|
||||
try:
|
||||
import dsv_session
|
||||
@@ -802,6 +852,11 @@ def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
# 宽泛 needle 造成误判(反复尝试点击“密码方式”而非关闭弹窗);命中升级提示时直接判非方法页。
|
||||
if _has_dsv_password_upgrade_prompt(page):
|
||||
return False
|
||||
# [BUGFIX] 密码输入页正文同样含“密码/Password”(label、placeholder、忘记密码链接),
|
||||
# 会被下方宽泛 needle 误判成方法页,导致 _click_dsv_password_method 在密码页上运行、
|
||||
# 其文案兜底点中“忘记密码”链接跳到 password.dbschenker.com。密码框可见即必非方法页。
|
||||
if _find_dsv_password_locator(page, timeout_ms=120) is not None:
|
||||
return False
|
||||
# 含英文新版 “Choose a sign in method”(无连字符);旧版为 sign-on。
|
||||
needles = (
|
||||
"选择登录方法",
|
||||
@@ -824,6 +879,29 @@ def _looks_like_dsv_login_method_page(page: Any) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _looks_like_dsv_identifier_chooser(page: Any) -> bool:
|
||||
"""
|
||||
判断是否为「已记住标识」的 PingID 选择登录方法页(无用户名输入框的变体)。
|
||||
|
||||
与 _looks_like_dsv_login_method_page 的区别:那个宽泛 needle 含“密码/Password”,
|
||||
用于密码阶段;本判定用于用户名步骤分叉,必须只认方法选择器标题强特征
|
||||
(选择登录方法 / Choose a sign in / sign-on method)且密码框不可见,
|
||||
防止普通用户名页恰含密码类文案时被误跳过用户名步骤。
|
||||
"""
|
||||
if _find_dsv_password_locator(page, timeout_ms=120) is not None:
|
||||
return False
|
||||
strong_markers = ("选择登录方法", "choose a sign in method", "choose a sign-on method")
|
||||
for frame in page.frames:
|
||||
try:
|
||||
text = str(frame.locator("body").inner_text(timeout=300) or "")
|
||||
except Exception:
|
||||
text = ""
|
||||
lowered = text.lower()
|
||||
if any(marker in text or marker in lowered for marker in strong_markers):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _has_dsv_human_check_prompt(page: Any) -> bool:
|
||||
"""快速判断当前页是否出现真人验证提示,避免在普通登录轮询里反复触发重等待。"""
|
||||
try:
|
||||
@@ -838,7 +916,7 @@ def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) ->
|
||||
wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("FREIGHT_RPA_WORKER_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000"))
|
||||
deadline = time.monotonic() + (wait_ms / 1000)
|
||||
while time.monotonic() < deadline:
|
||||
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
|
||||
if "s360.dbschenker.com" in page.url and not _on_dsv_auth_domain(str(page.url)):
|
||||
return True
|
||||
if _looks_like_dsv_login_method_page(page):
|
||||
return True
|
||||
@@ -923,16 +1001,28 @@ def _find_dsv_password_locator(page: Any, timeout_ms: int = 250):
|
||||
return None
|
||||
|
||||
|
||||
# DSV 认证域清单:2026-10-12 prod 事故确认 PingFederate resume 链迁移至 auth.dsv.com
|
||||
# (auth.dbschenker.com 并存)。所有认证态判定必须经 on_dsv_auth_domain,
|
||||
# 禁止回退到单一域名硬编码,否则会出现“升级提示不点也许以后/用户名页等超时”类卡死。
|
||||
_DSV_AUTH_HOST_TOKENS = ("auth.dbschenker.com", "auth.dsv.com")
|
||||
|
||||
|
||||
def _on_dsv_auth_domain(url: str) -> bool:
|
||||
"""判断 URL 是否处于 DSV 认证域(auth.dbschenker.com / auth.dsv.com 任一)。"""
|
||||
current = str(url or "").lower()
|
||||
return any(token in current for token in _DSV_AUTH_HOST_TOKENS)
|
||||
|
||||
|
||||
def _is_dsv_oauth_handshake_url(url: str) -> bool:
|
||||
"""PingFederate OAuth 握手页:常见为空白 body,需等待 JS 跳转或 reload。"""
|
||||
current = str(url or "").lower()
|
||||
return "auth.dbschenker.com" in current and "authorization.oauth2" in current
|
||||
return _on_dsv_auth_domain(current) and "authorization.oauth2" in current
|
||||
|
||||
|
||||
def _is_dsv_auth_ping_url(url: str) -> bool:
|
||||
"""PingFederate 密码阶段 authorization.ping:同样可能出现空白 body。"""
|
||||
"""PingFederate authorization.ping(含 /resume/as/ 链):可能出现空白 body 或方法选择页。"""
|
||||
current = str(url or "").lower()
|
||||
return "auth.dbschenker.com" in current and "authorization.ping" in current
|
||||
return _on_dsv_auth_domain(current) and "authorization.ping" in current
|
||||
|
||||
|
||||
def _is_dsv_blank_auth_transition(page: Any) -> bool:
|
||||
@@ -969,7 +1059,7 @@ def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -
|
||||
reload_attempted = False
|
||||
while time.monotonic() < deadline:
|
||||
current_url = str(page.url or "").lower()
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
if "s360.dbschenker.com" in current_url and not _on_dsv_auth_domain(current_url):
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
|
||||
return True
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
|
||||
@@ -985,7 +1075,7 @@ def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -
|
||||
return True
|
||||
if _wait_for_dsv_login_method_page(page, timeout_ms=200):
|
||||
return True
|
||||
if "auth.dbschenker.com" not in current_url:
|
||||
if not _on_dsv_auth_domain(current_url):
|
||||
return True
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").strip()
|
||||
@@ -1246,7 +1336,9 @@ is_dsv_oauth_handshake_url = _is_dsv_oauth_handshake_url
|
||||
is_dsv_password_method_label = _is_dsv_password_method_label
|
||||
is_dsv_username_page = _is_dsv_username_page
|
||||
looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page
|
||||
looks_like_dsv_identifier_chooser = _looks_like_dsv_identifier_chooser
|
||||
maybe_switch_dsv_locale_to_zh_cn = _maybe_switch_dsv_locale_to_zh_cn
|
||||
on_dsv_auth_domain = _on_dsv_auth_domain
|
||||
read_dsv_locale_nav_label = _read_dsv_locale_nav_label
|
||||
submit_dsv_password_form = _submit_dsv_password_form
|
||||
submit_dsv_username_form = _submit_dsv_username_form
|
||||
|
||||
@@ -5,6 +5,9 @@ scripts/freight_rpa/dsv_auth_login_flow.py
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(表单/探测辅助)、dsv_session(登录后首页 ready)。
|
||||
逻辑:由 dsv_auth 在模块末尾 re-export;dsv_report_export ensure 时触发;
|
||||
账号页/方法页若为英文,先尝试切「中文简体」再继续(失败不阻断)。
|
||||
2026-10-12 prod 事故(auth.dsv.com resume 链 + 记住标识)后补齐两个变体分支:
|
||||
①「选择登录方法」页无用户名框时跳过邮箱/继续直进密码阶段;
|
||||
② 以上走不通时清空 Cookie 从 portal 重新发起登录,仍失败才抛错。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -59,6 +62,7 @@ _is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
|
||||
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
|
||||
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
|
||||
_is_dsv_username_page = dsv_auth._is_dsv_username_page
|
||||
_looks_like_dsv_identifier_chooser = dsv_auth._looks_like_dsv_identifier_chooser
|
||||
_maybe_switch_dsv_locale_to_zh_cn = dsv_auth._maybe_switch_dsv_locale_to_zh_cn
|
||||
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
|
||||
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
|
||||
@@ -82,6 +86,53 @@ def _wait_for_dsv_home_ready_after_login(
|
||||
)
|
||||
|
||||
|
||||
_DSV_PORTAL_HOME_URL = "https://s360.dbschenker.com/"
|
||||
|
||||
|
||||
def _retry_dsv_login_with_purged_cookies(page: Any, username: str) -> bool:
|
||||
"""
|
||||
Cookie 清空兜底:回到「全新浏览器」状态重新发起一次完整登录。
|
||||
|
||||
用途与触发时机:登录页既没有用户名框、也不是「选择登录方法」页、空白握手 reload
|
||||
亦未救回时,持久 Profile 的残留 Cookie(记住标识/半完成会话)是最后嫌疑——
|
||||
清空后从 portal 首页重新发起 SSO,认证链会回到全新标识优先页。
|
||||
|
||||
核心逻辑:context.clear_cookies → goto s360 首页(未登录时 SSO 中止导航属预期信号)
|
||||
→ 等 auth 页渲染 → 填用户名。
|
||||
|
||||
Args:
|
||||
page: Playwright Page。
|
||||
username: DSV 登录账号。
|
||||
|
||||
Returns:
|
||||
用户名是否已成功填入;True 时调用方继续走「继续 → 方法 → 密码」常规链路。
|
||||
|
||||
约束:只能在登录已判定失败时调用;有效会话中调用等同主动登出。
|
||||
"""
|
||||
print("[dsv-login] login state unknown, purge cookies and retry clean login")
|
||||
try:
|
||||
page.context.clear_cookies()
|
||||
except Exception as exc:
|
||||
print(f"[dsv-login] cookie purge failed: {exc}", file=sys.stderr)
|
||||
return False
|
||||
try:
|
||||
page.goto(_DSV_PORTAL_HOME_URL, wait_until="domcontentloaded", timeout=45_000)
|
||||
except Exception as exc:
|
||||
# 未登录访问 portal 的 SSO 重定向会中止导航,属预期;真正的失败在后续认证页等待中暴露。
|
||||
print(f"[dsv-login] clean re-login goto note: {exc}", file=sys.stderr)
|
||||
if not _wait_for_dsv_auth_page_ready(page, timeout_ms=45_000):
|
||||
return False
|
||||
locator = _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_WORKER_DSV_USERNAME_SELECTOR",
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=15_000,
|
||||
)
|
||||
if locator is None:
|
||||
return False
|
||||
return _fill_dsv_username(page, username, preferred_locator=locator) is not None
|
||||
|
||||
|
||||
def _wait_for_dsv_app_after_login(
|
||||
page: Any,
|
||||
timeout_ms: int | None = None,
|
||||
@@ -109,7 +160,7 @@ def _has_existing_dsv_portal_session(page: Any) -> bool:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
|
||||
if "s360.dbschenker.com" not in current_url or dsv_auth.on_dsv_auth_domain(current_url):
|
||||
return False
|
||||
try:
|
||||
body = str(page.locator("body").inner_text(timeout=1_000) or "").lower()
|
||||
@@ -121,6 +172,11 @@ def _has_existing_dsv_portal_session(page: Any) -> bool:
|
||||
def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
"""
|
||||
DSV 登录使用 PingID 分步流程:邮箱 -> 继续 -> 密码方式 -> 密码 -> 登录。
|
||||
|
||||
两个已实测的变体分支(2026-10-12 prod 事故 auth.dsv.com resume 链后补齐):
|
||||
- 已记住标识:resume 链直接给出「选择登录方法」页(无用户名框),
|
||||
跳过邮箱/继续两步直接进密码阶段;
|
||||
- 清态兜底:以上都走不通时清空 Cookie 从 portal 重新发起登录,仍失败才抛错。
|
||||
"""
|
||||
username = _env("FREIGHT_RPA_WORKER_DSV_USERNAME")
|
||||
password = _env("FREIGHT_RPA_WORKER_DSV_PASSWORD")
|
||||
@@ -186,13 +242,36 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=login_ready_ms,
|
||||
)
|
||||
if username_locator is not None:
|
||||
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
|
||||
user_filled = username_locator is not None
|
||||
# [STEP 2] 用户名步分叉。已记住标识时 PingFederate resume 链直接给出「选择登录方法」页,
|
||||
# 无用户名框可填——先做强特征预检(looks_like_dsv_identifier_chooser),命中即跳过
|
||||
# 用户名等待与继续点击,直接进密码阶段(否则每源白等 login_ready 超时约 2 分钟);
|
||||
# 未命中再等用户名框,超时后二次复核(等待期间页面才切到方法选择页的情形)。
|
||||
# 普通用户名页恰含密码类文案不会误判(只认方法选择器标题)。三个状态变量必须
|
||||
# 先初始化:chooser/泛化填装分支不经过全部分支,后续统一读取。
|
||||
method_first = False
|
||||
user_filled = False
|
||||
username_locator = None
|
||||
if _looks_like_dsv_identifier_chooser(page):
|
||||
print("[dsv-login] remembered-identifier chooser detected, skip username/continue steps")
|
||||
method_first = True
|
||||
else:
|
||||
username_locator = None
|
||||
user_filled = _fill_first_visible_text_input(page, username)
|
||||
if not user_filled:
|
||||
login_ready_ms = _dsv_login_ready_timeout_ms()
|
||||
print("[dsv-login] waiting username field")
|
||||
username_locator = _wait_for_visible_selector(
|
||||
page,
|
||||
"FREIGHT_RPA_WORKER_DSV_USERNAME_SELECTOR",
|
||||
_DSV_USERNAME_SELECTORS,
|
||||
timeout_ms=login_ready_ms,
|
||||
)
|
||||
if username_locator is not None:
|
||||
username_locator = _fill_dsv_username(page, username, preferred_locator=username_locator)
|
||||
user_filled = username_locator is not None
|
||||
elif _looks_like_dsv_identifier_chooser(page):
|
||||
print("[dsv-login] remembered-identifier chooser detected after username wait, skip username/continue steps")
|
||||
method_first = True
|
||||
else:
|
||||
user_filled = _fill_first_visible_text_input(page, username)
|
||||
if not user_filled and not method_first:
|
||||
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=10_000) is not None:
|
||||
print("[dsv-login] existing session detected")
|
||||
# #region debug-point E:existing-session-late
|
||||
@@ -222,6 +301,16 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
if username_locator is not None:
|
||||
user_filled = True
|
||||
if not user_filled:
|
||||
# [FALLBACK] 持久 Profile 残留「记住标识/半完成会话」Cookie 可能把认证链带进
|
||||
# 未知页面变体;清空 Cookie 从 portal 重新发起登录是最后自愈手段,
|
||||
# 仍失败才判死本源交由上层批内重试。
|
||||
if _retry_dsv_login_with_purged_cookies(page, username):
|
||||
print("[dsv-login] username filled after clean re-login fallback")
|
||||
user_filled = True
|
||||
elif _looks_like_dsv_identifier_chooser(page):
|
||||
print("[dsv-login] chooser still shown after clean re-login, skip username/continue steps")
|
||||
method_first = True
|
||||
if not (user_filled or method_first):
|
||||
try:
|
||||
text = page.locator("body").inner_text(timeout=3_000)
|
||||
except Exception:
|
||||
@@ -229,31 +318,36 @@ def _maybe_auto_login_dsv(page: Any) -> None:
|
||||
raise RuntimeError(
|
||||
"DSV login state is unknown "
|
||||
f"url={page.url} body={text[:300]!r} "
|
||||
"(oauth handshake page stayed blank; check network/VPN or complete login manually in browser)"
|
||||
"(username field never rendered and clean re-login fallback failed; "
|
||||
"check network/VPN or complete login manually in browser)"
|
||||
)
|
||||
print("[dsv-login] username filled")
|
||||
_report_auto_login_substage("username_step", username_step_started_at)
|
||||
|
||||
continue_selector = _env("FREIGHT_RPA_WORKER_DSV_CONTINUE_BUTTON_SELECTOR")
|
||||
if continue_selector:
|
||||
page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
clicked_continue = True
|
||||
if method_first:
|
||||
# 已记住标识:无需填账号/点继续,直接进入密码阶段轮询。
|
||||
continue_to_method_started_at = time.monotonic()
|
||||
else:
|
||||
clicked_continue = _click_dsv_continue(page, username_locator)
|
||||
if not clicked_continue:
|
||||
identifier_value, button_state = _dsv_login_debug_value(page)
|
||||
print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}")
|
||||
raise RuntimeError("DSV login email step detected but continue button was not found")
|
||||
print("[dsv-login] continue clicked")
|
||||
continue_to_method_started_at = time.monotonic()
|
||||
# #region debug-point E:continue-clicked
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked",
|
||||
"[DEBUG] dsv username step submitted",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
print("[dsv-login] username filled")
|
||||
_report_auto_login_substage("username_step", username_step_started_at)
|
||||
|
||||
continue_selector = _env("FREIGHT_RPA_WORKER_DSV_CONTINUE_BUTTON_SELECTOR")
|
||||
if continue_selector:
|
||||
page.locator(continue_selector).first.click(timeout=_browser_timeout_ms(), force=True)
|
||||
clicked_continue = True
|
||||
else:
|
||||
clicked_continue = _click_dsv_continue(page, username_locator)
|
||||
if not clicked_continue:
|
||||
identifier_value, button_state = _dsv_login_debug_value(page)
|
||||
print(f"[dsv-login] continue missing identifier_value={identifier_value!r} button={button_state!r}")
|
||||
raise RuntimeError("DSV login email step detected but continue button was not found")
|
||||
print("[dsv-login] continue clicked")
|
||||
continue_to_method_started_at = time.monotonic()
|
||||
# #region debug-point E:continue-clicked
|
||||
_report_debug_event(
|
||||
"E",
|
||||
"freight_rpa_worker.py:_maybe_auto_login_dsv:continue_clicked",
|
||||
"[DEBUG] dsv username step submitted",
|
||||
_collect_dsv_reports_probe(page),
|
||||
)
|
||||
# #endregion
|
||||
|
||||
print("[dsv-login] waiting password field")
|
||||
password_locator = None
|
||||
|
||||
@@ -1175,13 +1175,16 @@ def _fill_dsv_filter_if_needed(
|
||||
value: 参数值。
|
||||
report_name: 报表名;透传给 dsv_report_parameters 按报表模板解析控件。
|
||||
program_label: 业务标签(如 AWSRTM);同名报表的站点控件覆盖。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 配置了值但全部填充路径失败(FILL-FAIL-FAST,中止本源触发批内重试)。
|
||||
"""
|
||||
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
module.fill_dsv_filter_if_needed(
|
||||
filled = module.fill_dsv_filter_if_needed(
|
||||
page,
|
||||
selector_env,
|
||||
label,
|
||||
@@ -1192,6 +1195,11 @@ def _fill_dsv_filter_if_needed(
|
||||
report_name=report_name,
|
||||
program_label=program_label,
|
||||
)
|
||||
if not filled:
|
||||
# [FILL-FAIL-FAST] 配置了值但全部填充路径失败时必须中止本源,禁止静默吞掉后在
|
||||
# 错误上下文继续执行(2026-10-09 AWSRTM 串报曾因此连环误报;2026-08-26 AWSRTM
|
||||
# 填参失败曾把空参数报表误报为 skipped)。抛错后由批内重试在干净上下文重来。
|
||||
raise RuntimeError(f"DSV report filter fill failed: {label}={str(value or '').strip()!r}")
|
||||
|
||||
|
||||
def _fill_dsv_multi_select(
|
||||
@@ -1370,7 +1378,11 @@ def _dsv_entry_url_host(entry_url: str) -> str:
|
||||
|
||||
|
||||
def _is_dsv_on_entry_site(page: Any, entry_url: str) -> bool:
|
||||
"""当前 tab 是否已在目标 entry_url 对应 portal 域(非 auth 跳转页)。"""
|
||||
"""当前 tab 是否已在目标 entry_url 对应 portal 域(非 auth 跳转页)。
|
||||
|
||||
认证域判定统一走 dsv_session.on_dsv_auth_domain(auth.dbschenker.com /
|
||||
auth.dsv.com 双域,2026-10-12 起 resume 链迁移至 auth.dsv.com)。
|
||||
"""
|
||||
host = _dsv_entry_url_host(entry_url)
|
||||
if not host:
|
||||
return False
|
||||
@@ -1378,7 +1390,7 @@ def _is_dsv_on_entry_site(page: Any, entry_url: str) -> bool:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
return False
|
||||
if "auth.dbschenker.com" in current_url:
|
||||
if dsv_session.on_dsv_auth_domain(current_url):
|
||||
return False
|
||||
return host in current_url
|
||||
|
||||
@@ -1553,8 +1565,58 @@ def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None:
|
||||
_wait_for_dsv_report_form_ready(page, report_name)
|
||||
|
||||
|
||||
def _assert_dsv_report_viewer_identity(page: Any, source: dict[str, Any], *, timeout_ms: int = 10_000) -> None:
|
||||
"""
|
||||
校验报表查看器载入的确实是目标报表,防止"菜单点对、报表开错"。
|
||||
|
||||
核心逻辑:2026-10-09 AWSRTM 生产事故——批内重试导航时菜单 fast-path 全部命中,
|
||||
但 viewer(myIframe) 实际载入了 Bison 的同名 3lv 报表;现有 report_title 子串检查
|
||||
("On Hand Inventory By Location 3lv" 包含 "on hand inventory by location")无法识破。
|
||||
program_label(如 AWSRTM)才是站点唯一标识:只扫描 URL 含 /s360reports/ssrs/ 的
|
||||
viewer frame 正文(portal 顶层 Recent Reports 文本同样含 program_label,禁止全 frame 扫描),
|
||||
超时未命中即抛错,由 _navigate_dsv_to_report_form 整页 reset 后重导一次。
|
||||
|
||||
Args:
|
||||
page: Playwright Page 对象。
|
||||
source: 库存源配置(取 query/navigation.program_label 作身份标识)。
|
||||
timeout_ms: 等待 viewer 标题刷新的上限;超时视为载入了错误报表。
|
||||
|
||||
Raises:
|
||||
RuntimeError: 超时仍未见 program_label(含观测到的 viewer 正文片段,便于定位串报来源)。
|
||||
"""
|
||||
program_label = _dsv_navigation_signature(source)[1]
|
||||
if not program_label:
|
||||
return
|
||||
expected = program_label.strip().lower()
|
||||
deadline = time.monotonic() + max(timeout_ms / 1000, 1)
|
||||
last_viewer_body = ""
|
||||
while True:
|
||||
for frame in page.frames:
|
||||
try:
|
||||
frame_url = str(frame.url or "").lower()
|
||||
except Exception:
|
||||
frame_url = ""
|
||||
if "/s360reports/ssrs/" not in frame_url:
|
||||
continue
|
||||
try:
|
||||
body = frame.locator("body").inner_text(timeout=500).lower()
|
||||
except Exception:
|
||||
body = ""
|
||||
last_viewer_body = body[:300]
|
||||
if expected in body:
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(
|
||||
"DSV report viewer identity mismatch: "
|
||||
f"expected program_label={program_label!r} in SSRS viewer title; "
|
||||
f"last_viewer_body={last_viewer_body!r}"
|
||||
)
|
||||
|
||||
|
||||
def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_name: str) -> None:
|
||||
"""单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪。"""
|
||||
"""单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪 → 校验 viewer 身份。"""
|
||||
query = source.get("query") if isinstance(source.get("query"), dict) else {}
|
||||
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
|
||||
reports_selector = _env("FREIGHT_RPA_WORKER_DSV_REPORTS_SELECTOR")
|
||||
@@ -1589,6 +1651,9 @@ def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_
|
||||
_click_dsv_menu_item(page, report_name)
|
||||
|
||||
_wait_for_dsv_report_form_ready(page, report_name)
|
||||
# [IDENTITY-GATE] 菜单点击成功≠目标报表已打开:viewer 载错报表时在此快速失败,
|
||||
# 由外层 _navigate_dsv_to_report_form 整页 reset 后重导一次(2026-10-09 AWSRTM 串报)。
|
||||
_assert_dsv_report_viewer_identity(page, source)
|
||||
|
||||
|
||||
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
|
||||
|
||||
@@ -45,13 +45,10 @@ def _normalize_report_name(report_name: str) -> str:
|
||||
# 报表名 → 参数控件模板。同名的 SSRS 参数在不同报表里的控件长相不同:
|
||||
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
|
||||
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
|
||||
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
|
||||
# - Receipt Detail(Bison/AWSBI 收料):Warehouse 亦为原生 select,但控件位是 ctl27(非库存 ctl17);
|
||||
# 父容器 data-parametername=p_dns_cd_wh(2026-09-28 实机 DOM 核对)。
|
||||
# - Receipt Detail@AWSRTM(Moerdijk 收料):Warehouse 与库存 JDA 同构为 multi_value,控件位 ctl29
|
||||
# (2026-09-28 实机:txtValue + glyphui-downarrow + divDropDown)。
|
||||
# 模板按"归一化报表名"精确匹配;可用 `报表名@program_label` 覆盖站点差异;
|
||||
# 未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
|
||||
# 组成的多选框下拉(multi_value)。
|
||||
# [2026-10-08] SSRS 参数控件 ctl 编号每次渲染都会漂移(实测:昨夜登记的 ctl29=Warehouse,
|
||||
# 今日同页 ctl29=Project ID),ctl 注册条目仅作结构性解析失败时的最后回退;
|
||||
# multi_select 一律优先 resolve_parameter_controls_structural(按 ParamLabelCell 标签现场派生)。
|
||||
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
|
||||
"on hand inventory by location 3lv": {
|
||||
"Warehouse": {
|
||||
@@ -117,6 +114,61 @@ def resolve_parameter_controls(
|
||||
return dict(template.get(label_key) or {})
|
||||
|
||||
|
||||
# 结构性解析脚本:在 SSRS 参数网格(ParametersGrid)中按 ParamLabelCell 标签定位参数行,
|
||||
# 从行内 _txtValue 的 id 基座派生 multi_value 三件套(_txtValue/_ctl01/_divDropDown)。
|
||||
# 控件位(ctlNN)是随报表实例变化的实现细节,禁止在代码/配置中写死——一律由此派生。
|
||||
_STRUCTURAL_CONTROLS_JS = """(label) => {
|
||||
const wanted = String(label || "").trim().toLowerCase();
|
||||
const rows = Array.from(document.querySelectorAll(
|
||||
"table[id*='ParametersGrid'] tr.isparameterrow, table[id*='ParametersGrid'] tr"));
|
||||
for (const row of rows) {
|
||||
const cell = row.querySelector(".ParamLabelCell");
|
||||
if (!cell) continue;
|
||||
const text = (cell.innerText || cell.textContent || "").trim().toLowerCase();
|
||||
if (text !== wanted) continue;
|
||||
const txt = row.querySelector("[id$='_txtValue']");
|
||||
if (!txt || !txt.id) continue;
|
||||
const base = txt.id.replace(/_txtValue$/, "");
|
||||
const toggle = document.getElementById(base + "_ctl01");
|
||||
const dropdown = document.getElementById(base + "_divDropDown");
|
||||
if (!toggle || !dropdown) return null;
|
||||
return { text: "#" + base + "_txtValue", toggle: "#" + base + "_ctl01", dropdown: "#" + base + "_divDropDown" };
|
||||
}
|
||||
return null;
|
||||
}"""
|
||||
|
||||
|
||||
def resolve_parameter_controls_structural(page: Any, label: str) -> dict[str, str] | None:
|
||||
"""按参数标签在 SSRS 参数网格中结构性解析 multi_value 控件三件套(免硬编码/免发版)。
|
||||
|
||||
【AI 触发时机】:报表/站点的控件位未登记注册表模板时调用(如 Owner@Receipt
|
||||
Detail@AWSRTM);SSRS 参数行自带 ParamLabelCell 标签与 _txtValue/_ctl01/_divDropDown
|
||||
控件族,按标签定位行即可派生控件位,适配任意站点/报表,无需为每个站点改代码。
|
||||
|
||||
核心逻辑:逐 frame 在 ParametersGrid 中找标签匹配的参数行 → 行内 _txtValue 的 id
|
||||
基座 → 校验 _ctl01/_divDropDown 存在 → 返回三件套;任一 frame 命中即返回,
|
||||
全部未命中(或命中但非 multi_value 形态)返回 None,由调用方回退默认/通用路径。
|
||||
|
||||
Args:
|
||||
page: Playwright Page(跨主文档与全部 frame 探测)。
|
||||
label: 参数名(与页面 ParamLabelCell 展示文本一致,如 Owner)。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: {text, toggle, dropdown} 三件套选择器;未命中为 None。
|
||||
"""
|
||||
wanted = str(label or "").strip()
|
||||
if not wanted or page is None:
|
||||
return None
|
||||
for frame in getattr(page, "frames", None) or []:
|
||||
try:
|
||||
found = frame.evaluate(_STRUCTURAL_CONTROLS_JS, wanted)
|
||||
except Exception:
|
||||
continue # 跨域/已销毁帧等探测失败:换下一 frame
|
||||
if isinstance(found, dict) and found.get("text"):
|
||||
return {key: str(found[key]) for key in ("text", "toggle", "dropdown")}
|
||||
return None
|
||||
|
||||
|
||||
def _iter_dsv_report_roots(page: Any) -> list[Any]:
|
||||
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
|
||||
matched: list[Any] = []
|
||||
@@ -278,6 +330,21 @@ def _fill_input_via_script(root: Any, selector: str, value: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _multi_value_already_set(current: str, wanted_values: list[str]) -> bool:
|
||||
"""判断 SSRS 多选框 txtValue 是否已"精确等于"目标集合(相等才允许跳过勾选)。
|
||||
|
||||
[2026-10-08 Owner@AWSRTM 事故根因] 旧实现用子串包含判断:多选框默认"全选",
|
||||
txtValue 恒为全量 CSV,任何 CRTM 目标值都是它的子串 → 恒误判"已设置"并跳过
|
||||
下拉勾选,Owner 恒为全部、报表恒为巨量。必须用集合相等判定。
|
||||
"""
|
||||
current = str(current or "").strip()
|
||||
wanted_items = {str(item).strip().casefold() for item in (wanted_values or []) if str(item).strip()}
|
||||
if not current or not wanted_items:
|
||||
return False
|
||||
current_items = {item.strip().casefold() for item in current.split(",") if item.strip()}
|
||||
return current_items == wanted_items
|
||||
|
||||
|
||||
def _fill_multi_value_parameter(
|
||||
page: Any,
|
||||
label: str,
|
||||
@@ -309,7 +376,7 @@ def _fill_multi_value_parameter(
|
||||
if text_locator is not None and not select_all:
|
||||
try:
|
||||
current = str(text_locator.input_value(timeout=2_000) or "").strip()
|
||||
if current and all(item.casefold() in current.casefold() for item in cleaned):
|
||||
if _multi_value_already_set(current, cleaned):
|
||||
print(f"[dsv-filter] {label} already set text={current!r}")
|
||||
return True
|
||||
except Exception:
|
||||
@@ -559,17 +626,23 @@ def fill_dsv_filter_if_needed(
|
||||
debug_stage: Callable[..., None] | None = None,
|
||||
report_name: str | None = None,
|
||||
program_label: str | None = None,
|
||||
) -> None:
|
||||
) -> bool:
|
||||
"""
|
||||
按 ReportViewer 控件类型填充 DSV 报表参数。
|
||||
|
||||
核心逻辑:报表模板(report_name + program_label)命中时整表替换默认控件;
|
||||
multi_value(如 Receipt Detail@AWSRTM Warehouse=ctl29)优先勾选 checkbox,
|
||||
失败时只回退同模板 txtValue,禁止残留默认 ctl17_ddValue 误走库存 select。
|
||||
|
||||
Returns:
|
||||
bool: True 表示已填充或合法跳过(值为空/未配置控件);False 表示配置了值
|
||||
但全部填充路径失败——调用方(导出包装层)必须据此中止本源,禁止静默吞掉
|
||||
后在错误上下文继续执行(2026-10-09 AWSRTM 串报事故链之一,2026-08-26
|
||||
AWSRTM 填参失败曾误报 skipped)。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return
|
||||
return True
|
||||
|
||||
def _debug(stage: str, target: str) -> None:
|
||||
if debug_stage is not None:
|
||||
@@ -582,7 +655,7 @@ def fill_dsv_filter_if_needed(
|
||||
if label not in {"Warehouse", "Owner", "PutawayZone"}:
|
||||
print(f"[dsv-filter] {label} already visible text={text!r}")
|
||||
_debug(f"filter-skip-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -607,7 +680,7 @@ def fill_dsv_filter_if_needed(
|
||||
if not selector and not defaults:
|
||||
print(f"[dsv] skip {label} filter; no selector configured")
|
||||
_debug(f"filter-no-selector-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
|
||||
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
|
||||
|
||||
@@ -617,7 +690,7 @@ def fill_dsv_filter_if_needed(
|
||||
page, label, values, timeout_ms=timeout_ms, config_override=defaults,
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
|
||||
# [STEP 2] 仅当控件类型确认为 select 时走 ddValue;禁止用 endswith(ddValue) 盖过 multi_value。
|
||||
if defaults.get("control") == "select":
|
||||
@@ -626,7 +699,7 @@ def fill_dsv_filter_if_needed(
|
||||
page, label, text, select_selector, timeout_ms=timeout_ms,
|
||||
):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
|
||||
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
|
||||
if not selector:
|
||||
@@ -637,12 +710,12 @@ def fill_dsv_filter_if_needed(
|
||||
)
|
||||
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
return
|
||||
return False
|
||||
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
|
||||
for root in _iter_dsv_report_roots(page):
|
||||
if _fill_input_via_script(root, selector, text):
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
|
||||
# 最后回退:Playwright fill(适用于普通文本参数)
|
||||
_, locator = _find_locator(page, selector)
|
||||
@@ -651,7 +724,7 @@ def fill_dsv_filter_if_needed(
|
||||
try:
|
||||
locator.fill(text, timeout=timeout_ms)
|
||||
_debug(f"filter-filled-{label.lower()}", text)
|
||||
return
|
||||
return True
|
||||
except Exception as exc:
|
||||
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
|
||||
|
||||
@@ -663,6 +736,7 @@ def fill_dsv_filter_if_needed(
|
||||
)
|
||||
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
|
||||
_debug(f"filter-failed-{label.lower()}", text)
|
||||
return False
|
||||
|
||||
|
||||
def fill_dsv_multi_select_parameter(
|
||||
@@ -680,11 +754,16 @@ def fill_dsv_multi_select_parameter(
|
||||
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
|
||||
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
|
||||
组合控件时调用;例如 AWSAMS / AWSRTM 的 Warehouse 下拉需要多选或全选。
|
||||
核心逻辑:selectors 缺省时按报表模板(report_name + program_label)解析控件;两者都没有则返回 False。
|
||||
核心逻辑:selectors 缺省时**优先按参数标签结构性解析控件位**——SSRS 参数控件的
|
||||
ctl 编号每次渲染都会漂移(2026-10-08 实测:昨夜登记的 ctl29 今日漂移为 Project ID,
|
||||
RTM 被写进错误栏位),任何 ctl 编号注册条目都不可靠;结构性解析失败才回退
|
||||
报表模板/默认表。两者都没有则返回 False。
|
||||
"""
|
||||
config_override = {"control": "multi_value"}
|
||||
effective_selectors = selectors or (
|
||||
resolve_parameter_controls(report_name, label, program_label=program_label) or None
|
||||
resolve_parameter_controls_structural(page, label)
|
||||
or resolve_parameter_controls(report_name, label, program_label=program_label)
|
||||
or None
|
||||
)
|
||||
if effective_selectors:
|
||||
for key in ("text", "toggle", "dropdown"):
|
||||
|
||||
@@ -4,6 +4,8 @@ scripts/freight_rpa/dsv_session.py
|
||||
用途:DSV 360 portal 壳层检测、首页 Reports 导航就绪与 entry_url 打开。
|
||||
依赖:rpa_common、dsv_debug、dsv_auth(升级提示与登录后回调)。
|
||||
逻辑:dsv_navigation / dsv_debug 探针;dsv_report_export 在 ensure 前检测 session。
|
||||
认证态判定统一走 on_dsv_auth_domain(auth.dbschenker.com / auth.dsv.com 双域,
|
||||
2026-10-12 起 resume 链迁移至 auth.dsv.com)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,6 +32,8 @@ from typing import Any, Callable
|
||||
from rpa_common import browser_timeout_ms as _browser_timeout_ms
|
||||
from rpa_common import env as _env
|
||||
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
|
||||
import dsv_auth
|
||||
from dsv_auth import on_dsv_auth_domain as _on_dsv_auth_domain
|
||||
import dsv_debug
|
||||
from dsv_debug import (
|
||||
collect_dsv_reports_probe as _collect_dsv_reports_probe,
|
||||
@@ -115,7 +119,7 @@ def _is_dsv_on_portal_home(page: Any) -> bool:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if "auth.dbschenker.com" in current_url:
|
||||
if _on_dsv_auth_domain(current_url):
|
||||
return False
|
||||
if "s360.dbschenker.com" not in current_url:
|
||||
return False
|
||||
@@ -185,7 +189,7 @@ def _wait_for_dsv_app_after_login(
|
||||
current_title = str(page.title() or "").lower()
|
||||
except Exception:
|
||||
current_title = ""
|
||||
auth_transition = "auth.dbschenker.com" in current_url or "verifying compliance" in current_title
|
||||
auth_transition = _on_dsv_auth_domain(current_url) or "verifying compliance" in current_title
|
||||
if now - last_debug_at >= 3:
|
||||
elapsed = int((time.monotonic() - started_at) * 1000)
|
||||
_debug_dsv_stage(page, f"wait-app-{elapsed // 1000}s", target_text="Reports")
|
||||
@@ -273,7 +277,7 @@ def _wait_for_dsv_app_after_login(
|
||||
elif _has_dsv_portal_shell(page) and on_portal_shell_seen is not None and not portal_shell_callback_fired:
|
||||
on_portal_shell_seen()
|
||||
portal_shell_callback_fired = True
|
||||
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
|
||||
if "s360.dbschenker.com" in current_url and not _on_dsv_auth_domain(current_url):
|
||||
if not _has_dsv_report_nav_usable(page) and dsv_auth.has_dsv_password_upgrade_prompt(page, timeout_ms=250):
|
||||
dsv_auth.dismiss_dsv_password_upgrade_prompt(page)
|
||||
continue
|
||||
@@ -320,7 +324,7 @@ def _is_dsv_home_ready(page: Any) -> bool:
|
||||
核心逻辑:必须离开认证域名与报表 iframe 上下文,且 Reports 导航已可用;
|
||||
停留在 `/main/portal/frame/reports/` 时即使顶栏可见,也不应视为 home-ready。
|
||||
"""
|
||||
if "auth.dbschenker.com" in page.url:
|
||||
if _on_dsv_auth_domain(str(page.url or "")):
|
||||
return False
|
||||
if _is_dsv_in_report_navigation_context(page):
|
||||
return False
|
||||
@@ -460,7 +464,7 @@ def _goto_dsv_entry_url(page: Any, entry_url: str) -> None:
|
||||
current_url = str(page.url or "").lower()
|
||||
except Exception:
|
||||
current_url = ""
|
||||
if any(token in current_url for token in ("auth.dbschenker.com", "s360.dbschenker.com")):
|
||||
if "s360.dbschenker.com" in current_url or _on_dsv_auth_domain(current_url):
|
||||
print(
|
||||
"[dsv] entry goto domcontentloaded timeout, continue auth redirect "
|
||||
f"url={page.url!r}"
|
||||
@@ -479,6 +483,7 @@ is_dsv_home_ready = _is_dsv_home_ready
|
||||
is_dsv_in_report_navigation_context = _is_dsv_in_report_navigation_context
|
||||
is_dsv_on_portal_home = _is_dsv_on_portal_home
|
||||
iter_dsv_report_nav_locators = _iter_dsv_report_nav_locators
|
||||
on_dsv_auth_domain = _on_dsv_auth_domain
|
||||
wait_for_dsv_app_after_login = _wait_for_dsv_app_after_login
|
||||
wait_for_dsv_home_ready = _wait_for_dsv_home_ready
|
||||
wait_for_dsv_report_nav_grace = _wait_for_dsv_report_nav_grace
|
||||
@@ -496,9 +501,11 @@ from dsv_auth import ( # noqa: E402
|
||||
has_dsv_password_upgrade_prompt,
|
||||
is_dsv_password_method_label,
|
||||
is_dsv_username_page,
|
||||
looks_like_dsv_identifier_chooser,
|
||||
looks_like_dsv_login_method_page,
|
||||
maybe_auto_login_dsv,
|
||||
maybe_switch_dsv_locale_to_zh_cn,
|
||||
on_dsv_auth_domain,
|
||||
submit_dsv_password_form,
|
||||
wait_for_dsv_human_check_if_present,
|
||||
wait_for_dsv_login_method_page,
|
||||
|
||||
@@ -114,6 +114,7 @@ _collect_dsv_reports_probe = dsv_debug.collect_dsv_reports_probe
|
||||
_debug_dsv_stage = dsv_debug.debug_dsv_stage
|
||||
_emit_debug_event = dsv_debug.emit_debug_event
|
||||
_looks_like_dsv_login_method_page = dsv_session.looks_like_dsv_login_method_page
|
||||
_looks_like_dsv_identifier_chooser = dsv_session.looks_like_dsv_identifier_chooser
|
||||
_has_dsv_human_check_prompt = dsv_session.has_dsv_human_check_prompt
|
||||
_wait_for_dsv_reports_nav_stable = dsv_navigation.wait_for_dsv_reports_nav_stable
|
||||
_ensure_dsv_session = dsv_report_export.ensure_dsv_session
|
||||
@@ -1308,10 +1309,32 @@ def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[s
|
||||
|
||||
|
||||
# 批内单源导出的暂态失败重试参数:DSV s360 服务端报表错误(rsProcessingAborted 等)
|
||||
# 属暂态故障(AWSRTM 2026-09-20 生产实测),失败源重新导航后重试一次,间隔 30s 覆盖
|
||||
# SSRS 端恢复窗口;不设 env 开关,保持行为确定。
|
||||
# 属暂态故障(AWSRTM 2026-09-20 生产实测),失败源重新导航后重试;不设 env 开关,保持行为确定。
|
||||
# 2026-10-09 补充:rsPutawayZone 每日首跑失败(09-29~10-09 共 6 个早晨)为数据集执行
|
||||
# 超时/后端早批窗口类暂态,恢复窗口是分钟级——此类错误定向放宽到 3 次尝试、每次间隔
|
||||
# 120s,最大化当日导出成功率;其余错误维持 2 次/30s,避免非暂态失败拖长批次。
|
||||
_EXPORT_SOURCE_MAX_ATTEMPTS = 2
|
||||
_EXPORT_SOURCE_RETRY_WAIT_SECONDS = 30
|
||||
_EXPORT_SOURCE_MAX_PROCESSING_ATTEMPTS = 3
|
||||
_EXPORT_SOURCE_RETRY_WAIT_PROCESSING_ERROR_SECONDS = 120
|
||||
|
||||
|
||||
def _export_source_retry_wait_seconds(exc: Exception) -> int:
|
||||
"""按异常类型选择批内重试等待时长:processing error(首跑数据集超时类)用更长窗口。"""
|
||||
return (
|
||||
_EXPORT_SOURCE_RETRY_WAIT_PROCESSING_ERROR_SECONDS
|
||||
if isinstance(exc, DsvReportProcessingError)
|
||||
else _EXPORT_SOURCE_RETRY_WAIT_SECONDS
|
||||
)
|
||||
|
||||
|
||||
def _export_source_max_attempts(exc: Exception) -> int:
|
||||
"""按异常类型选择批内重试次数上限:processing error 类 3 次,其余 2 次。"""
|
||||
return (
|
||||
_EXPORT_SOURCE_MAX_PROCESSING_ATTEMPTS
|
||||
if isinstance(exc, DsvReportProcessingError)
|
||||
else _EXPORT_SOURCE_MAX_ATTEMPTS
|
||||
)
|
||||
|
||||
|
||||
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
|
||||
@@ -1509,10 +1532,15 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
if site == "dsv360":
|
||||
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
|
||||
# 的登录态——同导航走 _return_to_dsv_report_parameters 复用参数页,
|
||||
# 导航不同走 _reset_dsv_export_entry(goto entry + 会话检测,不重复 OAuth)。
|
||||
# 导航不同直接从当前报表上下文展开菜单导航(不重复 OAuth)。
|
||||
# 曾因"每源新开空白页 + 写死 index=0"导致每源重复走 SSO 重定向链
|
||||
# (每源 2-2.5 分钟,且偶发 OAuth 空白页单源失败),现已移除。
|
||||
# 页面串站状态由整页/帧重载兜底,无需隔离页。
|
||||
# [RETRY-RESET] 2026-10-09 AWSRTM 生产事故:attempt 1 失败后页面残留
|
||||
# SSRS 错误页/旧菜单 DOM,在其上直接重开菜单曾把错误报表(Bison 3lv)
|
||||
# 载入 viewer。重试(attempt>1)先整页回 portal 首页清场再导航。
|
||||
if attempt > 1:
|
||||
dsv_report_export.reset_dsv_export_entry(page, entry_url)
|
||||
previous_source = site_sources[index - 1] if index > 0 else None
|
||||
try:
|
||||
# 返回 True 表示参数页已就绪:后续跳过菜单导航直接填参/导出。
|
||||
@@ -1563,14 +1591,15 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
if isinstance(exc, DsvReportProcessingError)
|
||||
else "rpa_export_failed"
|
||||
)
|
||||
if attempt < _EXPORT_SOURCE_MAX_ATTEMPTS:
|
||||
if attempt < _export_source_max_attempts(exc):
|
||||
retry_wait_seconds = _export_source_retry_wait_seconds(exc)
|
||||
print(
|
||||
f"[inventory-batch] {site} export failed {code}/{wh} "
|
||||
f"(attempt {attempt}/{_EXPORT_SOURCE_MAX_ATTEMPTS}), "
|
||||
f"retry in {_EXPORT_SOURCE_RETRY_WAIT_SECONDS}s: {exc}",
|
||||
f"(attempt {attempt}/{_export_source_max_attempts(exc)}), "
|
||||
f"retry in {retry_wait_seconds}s: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
time.sleep(_EXPORT_SOURCE_RETRY_WAIT_SECONDS)
|
||||
time.sleep(retry_wait_seconds)
|
||||
continue
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": error_code, "error_message": str(exc), "worker_attempt": attempt, "validation_run_no": source.get("validation_run_no")})
|
||||
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
|
||||
|
||||
Reference in new issue
Block a user