feat(in-transit-transfer): 自动调拨支持收料日期范围并收归排程通用通知
- 自动调拨任务新增收料日期范围动态参数(receipt_date_from/to):缩小匹配面便于测试与排障,非法范围由匹配层校验拒绝 - 排程动态参数表单支持占位文案 key 与空值归 null,日期筛选直达任务配置 - 执行结果通知统一走排程「启用通知」通用企微通知,任务不再自建领域通知 - 门禁契约澄清 retry_inventory_matching 语义:复用已抓库存重匹配不重抓;STP 多候选无匹配时阶段能力禁用、不隐式触发 RPA - 同步匹配/自动调拨/排程测试、四语言文案与文档
This commit is contained in:
1 parent
34c3bfb254
commit
a8d721e793
35 files changed
+863
-138
No files matched your search
@@ -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
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -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": [
|
||||
|
||||
@@ -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 跳过,不记失败。
|
||||
|
||||
@@ -566,10 +566,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=(
|
||||
@@ -591,16 +589,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'
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"]
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user