feat(schedule): 增加库存源选项描述字段与站点ID支持

This commit is contained in:
hugo committed 2026-07-10 00:48:27 +08:00
1 parent f4e74f7b07
commit 8b1efbedb9
37 files changed
+8488 -4126

No files matched your search

+5 -1
View File
@@ -39,7 +39,11 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
{
"label": source.get("display_name") or source.get("source_code"),
"value": source.get("source_code"),
"description": f"{source.get('site')} · {source.get('warehouse_id')}",
"description": (
f"{source.get('source_type')} · "
f"{source.get('site_id') or '-'} · "
f"{source.get('warehouse_id')}"
),
}
for source in list_inventory_sources()
]
@@ -28,6 +28,7 @@ FinalizeScheduleRunResult = dict[str, Any]
_INVENTORY_RPA_HEADER_ORDER = [
"source_code",
"site_id",
"warehouse_id",
"display_name",
"inventory_file_no",
@@ -36,6 +37,7 @@ _INVENTORY_RPA_HEADER_ORDER = [
]
_INVENTORY_RPA_HEADER_LABELS = {
"source_code": "库存源",
"site_id": "站点",
"warehouse_id": "仓库",
"display_name": "名称",
"inventory_file_no": "库存快照号",
@@ -139,6 +141,7 @@ def _build_finalize_details(
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"site_id": item.get("site_id") or base.get("site_id"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": item.get("inventory_file_no"),
@@ -155,6 +158,7 @@ def _build_finalize_details(
base = pending_by_key.get(key, {})
details.append({
"source_code": code or item.get("source_code"),
"site_id": item.get("site_id") or base.get("site_id"),
"warehouse_id": wh or base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
@@ -166,6 +170,7 @@ def _build_finalize_details(
continue
details.append({
"source_code": base.get("source_code"),
"site_id": base.get("site_id"),
"warehouse_id": base.get("warehouse_id"),
"display_name": base.get("display_name"),
"inventory_file_no": "",
@@ -52,9 +52,9 @@ def _normalize_filter_tokens(raw: Any) -> set[str]:
def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
"""收集库存源可用于匹配的标识集合(source_code / warehouse_id / match_aliases)。"""
"""收集库存源可用于匹配的标识集合(source_code / site_id / warehouse_id / match_aliases)。"""
tokens: set[str] = set()
for key in ("source_code", "warehouse_id", "warehouse_code"):
for key in ("source_code", "site_id", "warehouse_id"):
value = str(source.get(key) or "").strip().upper()
if value:
tokens.add(value)
@@ -68,12 +68,14 @@ def _source_identity_tokens(source: dict[str, Any]) -> set[str]:
def _extract_wanted_tokens(body_template: dict[str, Any]) -> set[str]:
"""
从 api_body_template 提取筛选 token。
推荐键:source_codes;兼容:source_code / warehouse_ids / warehouse_id / match_aliases。
推荐键:source_codes;兼容:source_code / site_ids / site_id / warehouse_ids / warehouse_id / match_aliases。
"""
wanted: set[str] = set()
for key in (
"source_codes",
"source_code",
"site_ids",
"site_id",
"warehouse_ids",
"warehouse_id",
"match_aliases",
@@ -103,7 +105,7 @@ def _resolve_filter_payload(task: ScheduleTask) -> dict[str, Any] | None:
def _filter_sources(task: ScheduleTask) -> list[dict[str, Any]]:
"""
读取 enabled 库存源;job_params / api_body_template 可限定子集。
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / warehouse_id / match_aliases 命中。
核心逻辑:无筛选则导出全部启用源;有筛选时按 source_code / site_id / warehouse_id / match_aliases 命中。
"""
enabled = list_inventory_sources()
body_template = _resolve_filter_payload(task)
@@ -164,6 +166,7 @@ def run_shipping_inventory_rpa_schedule(task: ScheduleTask, run: ScheduleRun) ->
details = [
{
"source_code": item.get("source_code"),
"site_id": item.get("site_id"),
"warehouse_id": item.get("warehouse_id"),
"display_name": item.get("display_name"),
}
+19 -2
View File
@@ -122,6 +122,24 @@ def _resolve_odm_id(task: ShippingTask) -> str:
return ""
def _shipment_warehouse_id(task: ShippingTask) -> str:
"""
解析发货 Excel Header 的 Warehouse ID。
核心逻辑:库存快照入库时按「配置 site_id 优先,否则库存 Excel 的 warehouse id」写入 inv_file.warehouse_id。
"""
try:
from app.services.shipping_notice.inventory_snapshot_store import serialize_inventory_snapshot_link
snapshot = serialize_inventory_snapshot_link(task)
except Exception:
snapshot = None
if isinstance(snapshot, dict):
value = str(snapshot.get("warehouse_id") or "").strip()
if value:
return value
return "AWSDU"
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
@@ -158,8 +176,7 @@ def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
if header_ws.cell(DATA_START_ROW, 1).value in (None, ""):
header_ws.cell(DATA_START_ROW, 1).value = "AWSDU"
header_ws.cell(DATA_START_ROW, 1).value = _shipment_warehouse_id(task)
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
@@ -106,7 +106,7 @@ def _try_reuse_inventory_snapshot(
优先复用未过期库存快照,避免重复触发 RPA。
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
核心逻辑:按 source_code + warehouse_id 查找 ready 快照;命中则 link 并进入映射/匹配。
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入映射/匹配。
retry_rpa 必须跳过缓存强制重新导出。
"""
if mode == "retry_rpa":
@@ -120,7 +120,7 @@ def _try_reuse_inventory_snapshot(
snapshot = find_latest_ready_snapshot(
str(rpa_source.get("source_code") or ""),
str(rpa_source.get("warehouse_id") or rpa_source.get("warehouse_code") or ""),
str(rpa_source.get("site_id") or ""),
)
if not snapshot:
return None
@@ -687,6 +687,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
success = bool(item.get("success", False))
source = build_rpa_inventory_source(source_code) or {
"source_code": source_code,
"site_id": item.get("site_id"),
"warehouse_id": warehouse_id,
"source_type": item.get("source_type"),
}
@@ -14,6 +14,7 @@ from pathlib import Path
from typing import Any
from flask import current_app
from openpyxl import load_workbook
from app import db
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -28,6 +29,13 @@ from app.services.shipping_notice.inventory_snapshot import read_inventory_schem
_SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
_WAREHOUSE_ID_HEADER_ALIASES = {
"warehouseid",
"warehouse",
"warehousecode",
"warehousecodeid",
"whid",
}
def inventory_snapshot_ttl_hours() -> int:
@@ -112,6 +120,41 @@ def expire_snapshot(inv_file: ShippingInventoryFile, reason: str) -> None:
inv_file.updated_at = datetime.utcnow()
def _normalize_header_key(value: Any) -> str:
"""将 Excel 表头标准化为可比较 key。"""
return "".join(ch for ch in str(value or "").strip().lower() if ch.isalnum())
def _extract_warehouse_id_from_inventory_excel(path: Path) -> str:
"""
从库存 Excel 内容中提取 Warehouse ID。
核心逻辑:扫描前几行表头,命中 Warehouse ID/WH ID 等列后取其下方第一条非空值。
"""
if not path or not path.is_file():
return ""
try:
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
except Exception:
return ""
try:
ws = wb.active
rows = list(ws.iter_rows(min_row=1, max_row=min(ws.max_row or 1, 40), values_only=True))
finally:
wb.close()
for row_idx, row in enumerate(rows):
for col_idx, cell in enumerate(row):
if _normalize_header_key(cell) not in _WAREHOUSE_ID_HEADER_ALIASES:
continue
for data_row in rows[row_idx + 1:]:
if col_idx >= len(data_row):
continue
value = str(data_row[col_idx] or "").strip().upper()
if value:
return value
return ""
def create_inventory_snapshot_from_rpa(
*,
source: dict[str, Any],
@@ -142,13 +185,19 @@ def create_inventory_snapshot_from_rpa(
exported_at = datetime.utcnow()
inventory_file_no = generate_inventory_file_no()
source_code = str(source.get("source_code") or "").strip().upper()
warehouse_id = str(source.get("warehouse_id") or source.get("warehouse_code") or "").strip()
warehouse_code = str(source.get("warehouse_code") or warehouse_id).strip()
configured_site_id = str(source.get("site_id") or "").strip().upper()
export_warehouse_id = str(source.get("warehouse_id") or "").strip().upper()
excel_warehouse_id = ""
warehouse_id = configured_site_id
warehouse_code = warehouse_id
if success:
path = inventory_file_upload_path(inventory_file_no)
path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(local_path, path)
excel_warehouse_id = _extract_warehouse_id_from_inventory_excel(path)
warehouse_id = configured_site_id or excel_warehouse_id
warehouse_code = warehouse_id
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = str(source_file_name or Path(local_path).name).strip() or path.name
snapshot_status = _SNAPSHOT_STATUS_READY
@@ -181,6 +230,10 @@ def create_inventory_snapshot_from_rpa(
"query": source.get("query"),
"navigation": source.get("navigation"),
"parameters": source.get("parameters"),
"site_id": configured_site_id or None,
"export_warehouse_id": export_warehouse_id,
"excel_warehouse_id": excel_warehouse_id or None,
"warehouse_id_source": "site_id" if configured_site_id else ("inventory_excel" if excel_warehouse_id else None),
"trigger_type": trigger_type,
},
)
@@ -16,7 +16,7 @@ from typing import Any
import yaml
from flask import current_app
_SITE_TO_SOURCE_TYPE = {
_VALID_SOURCE_TYPES = {
"dsv360": "dsv360",
"crane_footprint": "crane_footprint",
}
@@ -84,20 +84,20 @@ def _build_legacy_query(source: dict[str, Any]) -> dict[str, Any]:
"""
navigation = dict(source.get("navigation") or {})
query: dict[str, Any] = {}
site = str(source.get("site") or "").strip().lower()
source_type = str(source.get("source_type") or "").strip().lower()
if site == "dsv360":
if source_type == "dsv360":
for key in ("program_group", "program_label", "report_group", "report_name"):
if navigation.get(key):
query[key] = navigation[key]
elif site == "crane_footprint":
elif source_type == "crane_footprint":
if navigation.get("report_name"):
query["report_name"] = navigation["report_name"]
query["project_code"] = navigation.get("project_code")
warehouse_code = str(source.get("warehouse_code") or source.get("warehouse_id") or "").strip()
if warehouse_code:
query["warehouse_code"] = warehouse_code
warehouse_id = str(source.get("warehouse_id") or "").strip()
if warehouse_id:
query["warehouse_code"] = warehouse_id
for parameter in source.get("parameters") or []:
if not isinstance(parameter, dict):
@@ -140,14 +140,14 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
raise InventorySourceConfigError(f"duplicate source_code: {source_code}")
seen_codes.add(source_code)
site = str(raw.get("site") or "").strip().lower()
if site not in _SITE_TO_SOURCE_TYPE:
raise InventorySourceConfigError(f"{source_code}: site must be dsv360 or crane_footprint")
warehouse_id = str(raw.get("warehouse_id") or "").strip()
if not warehouse_id:
raise InventorySourceConfigError(f"{source_code}: warehouse_id is required")
source_type = str(raw.get("source_type") or "").strip().lower()
if source_type not in _VALID_SOURCE_TYPES:
raise InventorySourceConfigError(f"{source_code}: source_type must be dsv360 or crane_footprint")
warehouse_id = str(raw.get("warehouse_id") or "").strip().upper()
site_id = str(raw.get("site_id") or "").strip().upper()
if source_type == "dsv360" and not site_id:
raise InventorySourceConfigError(f"{source_code}: site_id is required for dsv360")
parameters: list[dict[str, Any]] = []
for item in raw.get("parameters") or []:
if not isinstance(item, dict):
@@ -163,13 +163,12 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
normalized = {
"source_code": source_code,
"source_type": _SITE_TO_SOURCE_TYPE[site],
"site": site,
"source_type": _VALID_SOURCE_TYPES[source_type],
"site_id": site_id,
"display_name": str(raw.get("display_name") or source_code).strip(),
"enabled": bool(raw.get("enabled", True)),
"entry_url": str(raw.get("entry_url") or "").strip(),
"warehouse_id": warehouse_id,
"warehouse_code": str(raw.get("warehouse_code") or warehouse_id).strip(),
"navigation": dict(raw.get("navigation") or {}),
"parameters": parameters,
"match_aliases": [
@@ -178,7 +177,7 @@ def _validate_source(raw: dict[str, Any], *, seen_codes: set[str]) -> dict[str,
if str(alias).strip()
],
}
if site == "crane_footprint" and raw.get("export"):
if source_type == "crane_footprint" and raw.get("export"):
normalized["export"] = dict(raw.get("export") or {})
normalized["query"] = _build_legacy_query(normalized)
return normalized
+1 -1
View File
@@ -125,8 +125,8 @@ def write_inventory_export_batch_trigger(
inventory_sources.append({
"source_code": source.get("source_code"),
"source_type": source.get("source_type"),
"site_id": source.get("site_id"),
"warehouse_id": source.get("warehouse_id"),
"warehouse_code": source.get("warehouse_code"),
"entry_url": source.get("entry_url"),
"navigation": source.get("navigation") or {},
"parameters": source.get("parameters") or [],
+81 -118
View File
@@ -5,11 +5,11 @@
version: 1
sources:
- source_code: DSV360_AWSBI_BYAWSATL01
enabled: true
site: dsv360
display_name: DSV 360 / Bison / AWSBI / BYAWSATL01
enabled: true
source_type: dsv360
site_id: AWSBI
warehouse_id: BYAWSATL01
warehouse_code: BYAWSATL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -28,10 +28,10 @@ sources:
- ATL01
- source_code: DSV360_AWSBI_BYAWSAVP01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSAVP01
warehouse_id: BYAWSAVP01
warehouse_code: BYAWSAVP01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -49,10 +49,10 @@ sources:
- BYAWSAVP01
- source_code: DSV360_AWSBI_BYAWSAZA01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSAZA01
warehouse_id: BYAWSAZA01
warehouse_code: BYAWSAZA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -70,10 +70,10 @@ sources:
- BYAWSAZA01
- source_code: DSV360_AWSBI_BYAWSCMH01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSCMH01
warehouse_id: BYAWSCMH01
warehouse_code: BYAWSCMH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -89,12 +89,13 @@ sources:
required: true
match_aliases:
- BYAWSCMH01
- CMH
- source_code: DSV360_AWSBI_BYAWSCMN01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSCMN01
warehouse_id: BYAWSCMN01
warehouse_code: BYAWSCMN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -110,12 +111,13 @@ sources:
required: true
match_aliases:
- BYAWSCMN01
- CMN
- source_code: DSV360_AWSBI_BYAWSEZE01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSEZE01
warehouse_id: BYAWSEZE01
warehouse_code: BYAWSEZE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -131,12 +133,13 @@ sources:
required: true
match_aliases:
- BYAWSEZE01
- EZE
- source_code: DSV360_AWSBI_BYAWSFRA01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSFRA01
warehouse_id: BYAWSFRA01
warehouse_code: BYAWSFRA01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -154,10 +157,10 @@ sources:
- BYAWSFRA01
- source_code: DSV360_AWSBI_BYAWSGRU01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSGRU01
warehouse_id: BYAWSGRU01
warehouse_code: BYAWSGRU01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -175,10 +178,10 @@ sources:
- BYAWSGRU01
- source_code: DSV360_AWSBI_BYAWSIAD01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSIAD01
warehouse_id: BYAWSIAD01
warehouse_code: BYAWSIAD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -196,10 +199,10 @@ sources:
- BYAWSIAD01
- source_code: DSV360_AWSBI_BYAWSJAN01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSJAN01
warehouse_id: BYAWSJAN01
warehouse_code: BYAWSJAN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -217,10 +220,10 @@ sources:
- BYAWSJAN01
- source_code: DSV360_AWSBI_BYAWSLTN01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSLTN01
warehouse_id: BYAWSLTN01
warehouse_code: BYAWSLTN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -238,10 +241,10 @@ sources:
- BYAWSLTN01
- source_code: DSV360_AWSBI_BYAWSMEL01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSMEL01
warehouse_id: BYAWSMEL01
warehouse_code: BYAWSMEL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -259,10 +262,10 @@ sources:
- BYAWSMEL01
- source_code: DSV360_AWSBI_BYAWSNRT01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSNRT01
warehouse_id: BYAWSNRT01
warehouse_code: BYAWSNRT01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -280,10 +283,10 @@ sources:
- BYAWSNRT01
- source_code: DSV360_AWSBI_BYAWSPHX01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPHX01
warehouse_id: BYAWSPHX01
warehouse_code: BYAWSPHX01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -301,10 +304,10 @@ sources:
- BYAWSPHX01
- source_code: DSV360_AWSBI_BYAWSPNE01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPNE01
warehouse_id: BYAWSPNE01
warehouse_code: BYAWSPNE01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -322,10 +325,10 @@ sources:
- BYAWSPNE01
- source_code: DSV360_AWSBI_BYAWSPRD01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPRD01
warehouse_id: BYAWSPRD01
warehouse_code: BYAWSPRD01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -343,10 +346,10 @@ sources:
- BYAWSPRD01
- source_code: DSV360_AWSBI_BYAWSPSC01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSPSC01
warehouse_id: BYAWSPSC01
warehouse_code: BYAWSPSC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -364,10 +367,10 @@ sources:
- BYAWSPSC01
- source_code: DSV360_AWSBI_BYAWSQRO01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSQRO01
warehouse_id: BYAWSQRO01
warehouse_code: BYAWSQRO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -385,10 +388,10 @@ sources:
- BYAWSQRO01
- source_code: DSV360_AWSBI_BYAWSRIC01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRIC01
warehouse_id: BYAWSRIC01
warehouse_code: BYAWSRIC01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -406,10 +409,10 @@ sources:
- BYAWSRIC01
- source_code: DSV360_AWSBI_BYAWSRNO01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRNO01
warehouse_id: BYAWSRNO01
warehouse_code: BYAWSRNO01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -427,10 +430,10 @@ sources:
- BYAWSRNO01
- source_code: DSV360_AWSBI_BYAWSRUH01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSRUH01
warehouse_id: BYAWSRUH01
warehouse_code: BYAWSRUH01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -448,10 +451,10 @@ sources:
- BYAWSRUH01
- source_code: DSV360_AWSBI_BYAWSSBN01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSSBN01
warehouse_id: BYAWSSBN01
warehouse_code: BYAWSSBN01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -469,10 +472,10 @@ sources:
- BYAWSSBN01
- source_code: DSV360_AWSBI_BYAWSSCL01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSSCL01
warehouse_id: BYAWSSCL01
warehouse_code: BYAWSSCL01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -490,10 +493,10 @@ sources:
- BYAWSSCL01
- source_code: DSV360_AWSBI_BYAWSYYZ01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSYYZ01
warehouse_id: BYAWSYYZ01
warehouse_code: BYAWSYYZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -511,10 +514,10 @@ sources:
- BYAWSYYZ01
- source_code: DSV360_AWSBI_BYAWSZAZ01
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSBI
display_name: DSV 360 / Bison / AWSBI / BYAWSZAZ01
warehouse_id: BYAWSZAZ01
warehouse_code: BYAWSZAZ01
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Bison
@@ -532,56 +535,39 @@ sources:
- BYAWSZAZ01
- source_code: DSV360_AWSCV
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSCV
display_name: DSV 360 / Cincinnati / AWSCV
warehouse_id: AWSCV
warehouse_code: AWSCV
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Cincinnati
program_label: AWSCV
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- CINCINNATI
- CVG
- AWSCV
- source_code: DSV360_AWSDU
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSDU
display_name: DSV 360 / Dublin / AWSDU - Prod (JDA)
warehouse_id: AWSDU
warehouse_code: AWSDU
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Dublin
program_label: AWSDU - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CADU-0000000100
required: true
match_aliases:
- DBS DUB
- DUB
- DUBLIN
- source_code: DSV360_AWSAMS
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSAMS
display_name: DSV 360 / Moerdijk / AWSAMS
warehouse_id: AWSAMS
warehouse_code: AWSAMS
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Moerdijk
@@ -589,11 +575,16 @@ sources:
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
- name: Warehouse
selector_env: FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR
mode: multi_select
select_all: true
selectors:
text: '#ReportViewerMain_ctl08_ctl17_txtValue'
toggle: '#ReportViewerMain_ctl08_ctl17_ctl01'
dropdown: '#ReportViewerMain_ctl08_ctl17_divDropDown'
values:
- CADU-0000000100
- RTM
required: true
match_aliases:
- MOERDIJK
@@ -601,73 +592,45 @@ sources:
- AWSAMS
- source_code: DSV360_AWSSL
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSSL
display_name: DSV 360 / Salt Lake City / AWSSL
warehouse_id: AWSSL
warehouse_code: AWSSL
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Salt Lake City
program_label: AWSSL
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- USLCK
- SALT LAKE CITY
- SALTLAKECITY
- source_code: DSV360_AWSSG
enabled: true
site: dsv360
source_type: dsv360
site_id: AWSSG
display_name: DSV 360 / Singapore / AWSSG - Prod (JDA)
warehouse_id: AWSSG
warehouse_code: AWSSG
entry_url: https://s360.dbschenker.com/
navigation:
program_group: Singapore
program_label: AWSSG - Prod (JDA)
report_group: Inventory
report_name: On Hand Inventory by Location
parameters:
- name: Owner
selector_env: FREIGHT_RPA_DSV_OWNER_SELECTOR
mode: single
values:
- CACV-0000000100
required: true
match_aliases:
- SINGAPORE HUB
- SINGAPORE
- SG
- source_code: CRANE_TZR2
- source_code: CRANE
enabled: true
site: crane_footprint
display_name: Crane FootPrint / Warehouse TZR2
warehouse_id: TZR2
warehouse_code: TZR2
source_type: crane_footprint
display_name: Crane FootPrint
entry_url: https://wms-portal.craneww.com/#/on-hand-details-query
navigation:
report_name: On Hand Details Query
download_mode: file_download
parameters:
- name: Owner
selector_env: FREIGHT_RPA_CRANE_OWNER_SELECTOR
mode: single
values:
- '0000000100'
required: true
- name: Warehouse
selector_env: FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR
mode: single
values:
- TZR2
required: true
download_mode: scheduled_report
parameters: []
match_aliases:
- TZR
- TZR2
- THAILAND
- TZR3
+159
View File
@@ -0,0 +1,159 @@
"""crane_navigation 报表页导航测试。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest.mock import MagicMock
import pytest
def _load_navigation():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py"
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class _FakeLocator:
def __init__(self, *, visible: bool = True) -> None:
self.visible = visible
self.clicked = False
self.hovered = False
@property
def first(self) -> "_FakeLocator":
return self
def is_visible(self, timeout: int = 0) -> bool:
return self.visible
def click(self, timeout: int = 0, force: bool = False) -> None:
self.clicked = True
def hover(self, timeout: int = 0) -> None:
self.hovered = True
class _FakePage:
def __init__(self, *, url: str = "https://wms-portal.craneww.com/#/") -> None:
self.url = url
self.frames: list[_FakePage] = []
self.goto_calls: list[str] = []
def locator(self, selector: str) -> _FakeLocator:
if "on-hand-details-query" in selector or "On Hand Details" in selector:
return _FakeLocator(visible=True)
if "Queries" in selector or "navbar" in selector:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
if role == "link" and name in {"On Hand Details", "Queries"}:
return _FakeLocator(visible=True)
return _FakeLocator(visible=False)
def goto(self, url: str, wait_until: str = "", timeout: int = 0) -> None:
self.goto_calls.append(url)
self.url = url
def test_navigate_prefers_dashboard_tile(monkeypatch):
"""应优先尝试首页 On Hand Details 卡片。"""
module = _load_navigation()
page = _FakePage()
calls: list[str] = []
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(
module,
"_click_dashboard_on_hand_details",
lambda *args, **kwargs: calls.append("dashboard") or True,
)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: calls.append("navbar") or True)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: True)
mode = module.navigate_to_crane_report(
page,
"https://wms-portal.craneww.com/#/on-hand-details-query",
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "dashboard_tile"
assert calls == ["dashboard"]
assert page.goto_calls == []
def test_navigate_falls_back_to_navbar_when_dashboard_misses(monkeypatch):
"""首页卡片未进入报表时应回退顶部 Queries 菜单。"""
module = _load_navigation()
page = _FakePage()
wait_calls = {"n": 0}
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
def _wait(page_arg, entry_url, *, browser_timeout_ms):
wait_calls["n"] += 1
return wait_calls["n"] >= 2
monkeypatch.setattr(module, "_wait_for_report_navigation", _wait)
mode = module.navigate_to_crane_report(
page,
"https://wms-portal.craneww.com/#/on-hand-details-query",
env=lambda name, default="": default,
browser_timeout_ms=5_000,
)
assert mode == "navbar_menu"
assert wait_calls["n"] == 2
def test_navigate_uses_direct_goto_as_last_resort(monkeypatch):
"""卡片与菜单均失败时应 goto entry_url。"""
module = _load_navigation()
page = _FakePage()
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
monkeypatch.setattr(module, "is_crane_report_form_ready", lambda page_arg, entry_url: False)
monkeypatch.setattr(module, "_click_dashboard_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_click_navbar_on_hand_details", lambda *args, **kwargs: True)
monkeypatch.setattr(module, "_wait_for_report_navigation", lambda *args, **kwargs: False)
with pytest.raises(RuntimeError, match="navigation failed"):
module.navigate_to_crane_report(page, entry, env=lambda n, d="": d, browser_timeout_ms=5_000)
assert page.goto_calls[0] == entry
assert any(call.rstrip("/") == "https://wms-portal.craneww.com" for call in page.goto_calls)
def test_is_crane_on_report_route_reads_entry_hash():
"""应从 entry_url hash 判断当前是否已在目标报表路由。"""
module = _load_navigation()
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
assert module.is_crane_on_report_route(page, entry) is True
def test_homepage_is_not_report_form_ready():
"""登录后首页 /#/ 不应被误判为报表表单已就绪。"""
module = _load_navigation()
page = _FakePage(url="https://wms-portal.craneww.com/#/")
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
assert module.is_crane_on_homepage(page) is True
assert module.is_crane_report_form_ready(page, entry) is False
def test_report_route_without_controls_is_not_ready(monkeypatch):
"""仅有 hash 路由但无 Run Report 控件时仍不算 ready。"""
module = _load_navigation()
page = _FakePage(url="https://wms-portal.craneww.com/#/on-hand-details-query")
entry = "https://wms-portal.craneww.com/#/on-hand-details-query"
monkeypatch.setattr(module, "_has_report_form_controls", lambda page_arg: False)
assert module.is_crane_report_form_ready(page, entry) is False
+446
View File
@@ -0,0 +1,446 @@
"""crane_report_export 异步报表导出流程测试。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest.mock import MagicMock
import pytest
def _load_export():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py"
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def test_fill_parameters_skips_warehouse(monkeypatch):
"""Warehouse 参数应被跳过,不再填写。"""
module = _load_export()
calls: list[tuple[str, str, str]] = []
def _fake_select(page, selector_env, label, value):
calls.append((selector_env, label, value))
module._fill_crane_report_parameters(
MagicMock(),
{
"parameters": [
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_CRANE_WAREHOUSE_SELECTOR",
"mode": "single",
"values": ["TZR2"],
},
{
"name": "Owner",
"selector_env": "FREIGHT_RPA_CRANE_OWNER_SELECTOR",
"mode": "single",
"values": ["OWNER1"],
},
]
},
env=lambda name, default="": default,
browser_timeout_ms=5_000,
select_or_fill=_fake_select,
)
assert calls == [("FREIGHT_RPA_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
"""Description 默认取 UUID4 前 12 位 hex,兼顾唯一性与列表可读性。"""
module = _load_export()
monkeypatch.setattr(
module.uuid,
"uuid4",
lambda: module.uuid.UUID("11111111-2222-4333-8444-555555555555"),
)
text = module._build_schedule_description(
{"source_code": "CRANE_TZR2"},
{"task_no": "SN-1001"},
env=lambda name, default="": default,
)
assert text == "111111112222"
assert len(text) == 12
def test_build_schedule_description_hex_len_env():
"""可通过环境变量调整 Description 长度(8~32)。"""
module = _load_export()
text = module._build_schedule_description(
{"source_code": "CRANE_TZR2"},
None,
env=lambda name, default="": "16" if name == "FREIGHT_RPA_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
)
assert len(text) == 16
def test_export_scheduled_report_flow(monkeypatch):
"""scheduled_report 模式应按 Run → Schedule → Scheduled Reports 顺序执行。"""
module = _load_export()
page = MagicMock()
page.url = "https://wms-portal.craneww.com/#/on-hand-details-query"
calls: list[str] = []
captured: dict[str, str] = {}
monkeypatch.setattr(module, "_fill_crane_report_parameters", lambda *args, **kwargs: None)
monkeypatch.setattr(module, "_build_schedule_description", lambda *args, **kwargs: "HXOPS-CRANE_TZR2-TEST")
monkeypatch.setattr(module, "_click_run_report", lambda *args, **kwargs: calls.append("run"))
monkeypatch.setattr(module, "_wait_for_run_report_results", lambda *args, **kwargs: calls.append("wait_run"))
def _schedule(*args, **kwargs):
calls.append("schedule")
def _confirm(page_arg, description, **kwargs):
calls.append("confirm")
captured["description"] = description
monkeypatch.setattr(module, "_click_schedule_report", _schedule)
monkeypatch.setattr(module, "_confirm_schedule_report_modal", _confirm)
monkeypatch.setattr(module, "_wait_for_report_submission_complete", lambda *args, **kwargs: calls.append("wait_submitted"))
monkeypatch.setattr(module, "_open_scheduled_reports", lambda *args, **kwargs: calls.append("open_scheduled"))
def _download(*args, **kwargs):
calls.append("download")
captured["download_description"] = kwargs.get("description", "")
return "download-object"
monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download)
result = module.export_crane_inventory_report(
page,
{"navigation": {"download_mode": "scheduled_report"}, "parameters": [], "source_code": "CRANE_TZR2"},
trigger={"task_no": "SN-1001"},
env=lambda name, default="": default,
browser_timeout_ms=5_000,
select_or_fill=lambda *args, **kwargs: None,
click_text=lambda *args, **kwargs: None,
)
assert result == "download-object"
assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"]
assert captured["description"] == "HXOPS-CRANE_TZR2-TEST"
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
def test_should_run_report_before_schedule_defaults_true():
"""默认必须先 Run Report;仅显式 run_before_schedule=false 可关闭。"""
module = _load_export()
assert (
module._should_run_report_before_schedule(
{"navigation": {}},
env=lambda name, default="": default,
)
is True
)
assert (
module._should_run_report_before_schedule(
{"navigation": {"run_before_schedule": False}},
env=lambda name, default="": default,
)
is False
)
assert (
module._should_run_report_before_schedule(
{"navigation": {}},
env=lambda name, default="": "false" if name == "FREIGHT_RPA_CRANE_RUN_BEFORE_SCHEDULE" else default,
)
is False
)
def test_is_on_scheduled_reports_page_detects_hash_route():
"""仅 on-hand-details-query 不算 Scheduled Reports 页。"""
module = _load_export()
class _Page:
def __init__(self, url: str) -> None:
self.url = url
assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/scheduled-reports")) is True
assert module._is_on_scheduled_reports_page(_Page("https://wms-portal.craneww.com/#/on-hand-details-query")) is False
def test_find_scheduled_download_waits_until_status_is_download():
"""Description 行末列为 Submitted 时不应返回下载链接。"""
module = _load_export()
class _Cells:
def __init__(self, texts: list[str]) -> None:
self._texts = texts
def count(self) -> int:
return len(self._texts)
def nth(self, index: int) -> _Cell:
return _Cell(self._texts[index])
class _Cell:
def __init__(self, text: str, *, visible: bool = False) -> None:
self._text = text
self._visible = visible
def inner_text(self, timeout: int = 0) -> str:
return self._text
def is_visible(self, timeout: int = 0) -> bool:
return self._visible
@property
def first(self):
return self
class _Row:
def __init__(self, name: str, description: str, status: str, *, submitted: str = "2026/7/9 04:45:45") -> None:
self._description = description
self._status = status
self._cells = _Cells([name, submitted, description, status])
def is_visible(self, timeout: int = 0) -> bool:
return True
def locator(self, selector: str) -> Any:
if selector == "td":
return self._cells
return _Cell("Download", visible=selector.startswith("a"))
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
return _Cell("Download", visible=True)
class _Rows:
def __init__(self, rows: list[_Row]) -> None:
self._rows = rows
def count(self) -> int:
return len(self._rows)
def nth(self, index: int) -> _Row:
return self._rows[index]
class _Page:
def __init__(self, rows: list[_Row]) -> None:
self.frames: list = []
self._rows = rows
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
def locator(self, selector: str) -> _Rows:
return _Rows(self._rows)
submitted = module._find_scheduled_download_by_description(
_Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")]),
"uuid-1",
env=lambda name, default="": default,
)
assert submitted is None
download = module._find_scheduled_download_by_description(
_Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")]),
"uuid-2",
env=lambda name, default="": default,
)
assert download is not None
def test_find_scheduled_download_skips_wrong_name_and_picks_first_match():
"""应跳过 Name 不符的行,自上而下取首条 OnHandDetails.xlsx + Description 匹配项。"""
module = _load_export()
class _Cells:
def __init__(self, texts: list[str]) -> None:
self._texts = texts
def count(self) -> int:
return len(self._texts)
def nth(self, index: int) -> _Cell:
return _Cell(self._texts[index])
class _Cell:
def __init__(self, text: str, *, visible: bool = False) -> None:
self._text = text
self._visible = visible
def inner_text(self, timeout: int = 0) -> str:
return self._text
def is_visible(self, timeout: int = 0) -> bool:
return self._visible
@property
def first(self):
return self
class _Row:
def __init__(self, name: str, submitted: str, description: str, status: str) -> None:
self._cells = _Cells([name, submitted, description, status])
def is_visible(self, timeout: int = 0) -> bool:
return True
def locator(self, selector: str) -> Any:
if selector == "td":
return self._cells
return _Cell("Download", visible=selector.startswith("a"))
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
return _Cell("Download", visible=True)
class _Rows:
def __init__(self, rows: list[_Row]) -> None:
self._rows = rows
def count(self) -> int:
return len(self._rows)
def nth(self, index: int) -> _Row:
return self._rows[index]
class _Page:
def __init__(self, rows: list[_Row]) -> None:
self.frames: list = []
self._rows = rows
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
def locator(self, selector: str) -> _Rows:
return _Rows(self._rows)
rows = [
_Row("OutboundDetails.xlsx", "2026/7/9 04:50:00", "target-uuid", "Download"),
_Row("OnHandDetails.xlsx", "2026/7/9 04:45:45", "other-uuid", "Download"),
_Row("OnHandDetails.xlsx", "2026/7/9 04:40:00", "target-uuid", "Download"),
]
locator = module._find_scheduled_download_by_description(
_Page(rows),
"target-uuid",
env=lambda name, default="": default,
)
assert locator is not None
def test_probe_scheduled_download_status_returns_submitted_before_download():
"""每轮 poll 应能读到 Submitted;仅 Download 时返回 locator。"""
module = _load_export()
class _Cells:
def __init__(self, texts: list[str]) -> None:
self._texts = texts
def count(self) -> int:
return len(self._texts)
def nth(self, index: int) -> _Cell:
return _Cell(self._texts[index])
class _Cell:
def __init__(self, text: str, *, visible: bool = False) -> None:
self._text = text
self._visible = visible
def inner_text(self, timeout: int = 0) -> str:
return self._text
def is_visible(self, timeout: int = 0) -> bool:
return self._visible
@property
def first(self):
return self
class _Row:
def __init__(self, name: str, description: str, status: str) -> None:
self._cells = _Cells([name, "2026/7/9 04:45:45", description, status])
def is_visible(self, timeout: int = 0) -> bool:
return True
def locator(self, selector: str) -> Any:
if selector == "td":
return self._cells
return _Cell("Download", visible=selector.startswith("a"))
def get_by_role(self, role: str, name: str, exact: bool = False) -> _Cell:
return _Cell("Download", visible=True)
class _Rows:
def __init__(self, rows: list[_Row]) -> None:
self._rows = rows
def count(self) -> int:
return len(self._rows)
def nth(self, index: int) -> _Row:
return self._rows[index]
class _Page:
def __init__(self, rows: list[_Row]) -> None:
self.frames: list = []
self._rows = rows
self.url = "https://wms-portal.craneww.com/#/scheduled-reports"
def locator(self, selector: str) -> _Rows:
return _Rows(self._rows)
page = _Page([_Row("OnHandDetails.xlsx", "uuid-1", "Submitted")])
status, locator = module._probe_scheduled_download_status(
page,
"uuid-1",
env=lambda name, default="": default,
)
assert status == "Submitted"
assert locator is None
page_ready = _Page([_Row("OnHandDetails.xlsx", "uuid-2", "Download")])
status2, locator2 = module._probe_scheduled_download_status(
page_ready,
"uuid-2",
env=lambda name, default="": default,
)
assert status2 == "Download"
assert locator2 is not None
def test_is_crane_login_blocking_ignores_login_flash_when_table_visible():
"""reload 过渡态:登录框闪现但表格仍在时,不应判定为需要重登。"""
module = _load_export()
class _Rows:
def count(self) -> int:
return 1
class _Page:
frames: list = []
url = "https://wms-portal.craneww.com/#/scheduled-reports"
def locator(self, selector: str) -> _Rows:
return _Rows()
page = _Page()
session = module._load_crane_session_module()
original = session.is_crane_login_page
session.is_crane_login_page = lambda _page: True
try:
assert module._is_crane_login_blocking(page) is False
assert module._is_on_scheduled_reports_page(page) is True
finally:
session.is_crane_login_page = original
def test_resolve_scheduled_report_file_name_prefers_navigation_config():
"""scheduled_report_file_name 应优先于环境变量默认值。"""
module = _load_export()
name = module._resolve_scheduled_report_file_name(
{"navigation": {"scheduled_report_file_name": "Custom.xlsx"}},
env=lambda name, default="": default,
)
assert name == "Custom.xlsx"
def test_resolve_download_mode_defaults_to_scheduled_report():
"""未配置 download_mode 时默认走 scheduled_report。"""
module = _load_export()
assert module._resolve_download_mode({"navigation": {}}) == "scheduled_report"
+166
View File
@@ -0,0 +1,166 @@
"""crane_session 登录页识别与自动填写测试。"""
from __future__ import annotations
import importlib.util
from pathlib import Path
from unittest.mock import MagicMock
def _load_crane_session():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py"
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class _FakeLocator:
def __init__(self, *, visible: bool = True, enabled: bool = True) -> None:
self.visible = visible
self.enabled = enabled
self.filled: list[str] = []
self.clicked = False
@property
def first(self) -> "_FakeLocator":
return self
def is_visible(self, timeout: int = 0) -> bool:
return self.visible
def is_enabled(self, timeout: int = 0) -> bool:
return self.enabled
def fill(self, value: str, timeout: int = 0) -> None:
self.filled.append(value)
def click(self, timeout: int = 0, force: bool = False) -> None:
self.clicked = True
def evaluate(self, script: str) -> bool:
return self.enabled
class _FakePage:
def __init__(self) -> None:
self.frames: list[_FakePage] = []
self.url = "https://wms-portal.craneww.com/"
def locator(self, selector: str) -> _FakeLocator:
lowered = selector.lower()
if "user name" in lowered or "password" in lowered:
return _FakeLocator(visible=True)
if "is-primary" in lowered or "sign in" in lowered:
return _FakeLocator(visible=True, enabled=True)
return _FakeLocator(visible=False)
def get_by_label(self, label: str, exact: bool = False) -> _FakeLocator:
return _FakeLocator(visible=label in {"User Name", "Password"})
def get_by_placeholder(self, placeholder: str, exact: bool = False) -> _FakeLocator:
return _FakeLocator(visible=placeholder.startswith("Enter "))
def get_by_role(self, role: str, name: str, exact: bool = False) -> _FakeLocator:
return _FakeLocator(visible=role == "button" and name == "Sign in", enabled=True)
def wait_for_load_state(self, state: str, timeout: int = 0) -> None:
return None
def test_is_crane_login_page_detects_username_placeholder():
"""登录页应通过 Enter user name... / Enter password... placeholder 识别。"""
module = _load_crane_session()
page = _FakePage()
assert module.is_crane_login_page(page) is True
def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monkeypatch):
"""自动登录应依次填写用户名、密码并点击 Sign in。"""
module = _load_crane_session()
page = _FakePage()
calls: list[tuple[str, str]] = []
def _fake_fill(
page_arg,
*,
selector_env,
value,
env,
browser_timeout_ms,
fallback_selectors,
label=None,
placeholder=None,
):
calls.append((selector_env, value))
return True
monkeypatch.setattr(module, "_fill_crane_field", _fake_fill)
login_page_states = iter([True, False])
monkeypatch.setattr(
module,
"is_crane_login_page",
lambda page_arg: next(login_page_states, False),
)
monkeypatch.setattr(module, "_click_crane_login_submit", lambda *args, **kwargs: True)
module.maybe_auto_login_crane(
page,
env=lambda name, default="": {
"FREIGHT_RPA_CRANE_USERNAME": "crane-user",
"FREIGHT_RPA_CRANE_PASSWORD": "crane-pass",
}.get(name, default),
browser_timeout_ms=5_000,
)
assert calls == [
("FREIGHT_RPA_CRANE_USERNAME_SELECTOR", "crane-user"),
("FREIGHT_RPA_CRANE_PASSWORD_SELECTOR", "crane-pass"),
]
def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
"""Sign in 初始 disabled,填写凭据后应能定位到可点击按钮。"""
module = _load_crane_session()
page = _FakePage()
states = iter([False, False, True])
def _fake_enabled(locator):
return next(states, True)
monkeypatch.setattr(module, "_is_crane_button_enabled", _fake_enabled)
locator = module._find_crane_sign_in_button(
page,
selector_env="FREIGHT_RPA_CRANE_LOGIN_BUTTON_SELECTOR",
env=lambda name, default="": default,
browser_timeout_ms=3_000,
)
assert locator is not None
assert locator.enabled is True
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
"""batch 内 session 有效时不应重复 goto + login。"""
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
assert spec and spec.loader
worker = importlib.util.module_from_spec(spec)
spec.loader.exec_module(worker)
page = MagicMock()
login = MagicMock()
ready = MagicMock()
goto = MagicMock()
monkeypatch.setattr(worker, "_is_crane_session_active", MagicMock(return_value=True))
monkeypatch.setattr(worker, "_goto_crane_entry_url", goto)
monkeypatch.setattr(worker, "_maybe_auto_login_crane", login)
monkeypatch.setattr(worker, "_wait_for_crane_app_ready", ready)
worker._ensure_crane_session(page, "https://wms-portal.craneww.com/#/on-hand-details-query")
goto.assert_not_called()
login.assert_not_called()
ready.assert_called_once()
@@ -112,3 +112,58 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
)
assert selected.get("value") == "BYAWSATL01" or selected.get("label") == "BYAWSATL01"
def test_fill_dsv_multi_select_parameter_supports_select_all_checkbox_dropdown():
"""AWSAMS Warehouse 这类 checkbox 下拉应支持 select_all 和显式 selector。"""
module = _load_module()
payloads: list[dict[str, object]] = []
class _FakeLocator:
first = None
def __init__(self) -> None:
self.first = self
def wait_for(self, *args, **kwargs) -> None:
return None
def input_value(self, timeout: int | None = None) -> str:
return ""
def click(self, timeout: int | None = None, force: bool = False) -> None:
return None
class _FakeReportRootLocator:
def count(self) -> int:
return 1
class _FakeFrame:
def locator(self, selector: str):
if selector == "#ReportViewerMain":
return _FakeReportRootLocator()
return _FakeLocator()
def evaluate(self, script: str, payload: dict[str, object]) -> bool:
payloads.append(payload)
return True
class _FakePage:
frames = [_FakeFrame()]
ok = module.fill_dsv_multi_select_parameter(
_FakePage(),
"Warehouse",
["RTM"],
selectors={
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
},
select_all=True,
browser_timeout_ms=lambda: 3_000,
)
assert ok is True
assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
assert payloads[-1]["selectAll"] is True
+32 -3
View File
@@ -1164,8 +1164,8 @@ def test_has_dsv_password_upgrade_prompt_does_not_match_generic_not_now_text():
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False
def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan():
"""已经进入 s360 portal 时,应直接判定没有升级提示,避免在首页做长时间空扫描。"""
def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
"""portal 首页导航已可用时,应直接判定没有升级提示,避免在稳定首页做无效扫描。"""
worker = _load_freight_rpa_worker()
locator_calls = {"value": 0}
@@ -1175,12 +1175,41 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan():
def locator(self, selector: str):
locator_calls["value"] += 1
raise AssertionError("portal page should short-circuit before scanning locators")
raise AssertionError("stable portal home should short-circuit before scanning locators")
monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: True)
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is False
assert locator_calls["value"] == 0
def test_has_dsv_password_upgrade_prompt_detects_maybe_later_on_portal(monkeypatch):
"""portal 上若升级弹窗挡住首页,仍应识别“也许以后”按钮。"""
worker = _load_freight_rpa_worker()
class _FakeLocator:
def __init__(self, selector: str) -> None:
self.selector = selector
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return self.selector == 'button.dbs-sims-button-secondary:has-text("也许以后")'
def inner_text(self, timeout: int | None = None) -> str:
return ""
class _FakePage:
url = "https://s360.dbschenker.com/main/portal"
frames: list[object] = []
def locator(self, selector: str) -> _FakeLocator:
return _FakeLocator(selector)
monkeypatch.setattr(worker.dsv_session, "has_dsv_report_nav_usable", lambda page: False)
assert worker._has_dsv_password_upgrade_prompt(_FakePage()) is True
def test_wait_for_dsv_home_ready_skips_duplicate_upgrade_prompt_check(monkeypatch):
"""首页已可探测或 app wait 返回后,若无升级提示强特征,不应再次进入升级提示处理。"""
worker = _load_freight_rpa_worker()
@@ -3,13 +3,25 @@
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
from unittest.mock import MagicMock
def _load_worker():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
spec = importlib.util.spec_from_file_location("freight_rpa_worker_param_test", module_path)
return _load_rpa_module("freight_rpa_worker")
def _load_dsv_report_export():
return _load_rpa_module("dsv_report_export")
def _load_rpa_module(module_name: str):
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
scripts_dir = str(module_path.parent)
if scripts_dir not in sys.path:
sys.path.insert(0, scripts_dir)
spec = importlib.util.spec_from_file_location(f"{module_name}_param_test", module_path)
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
@@ -18,11 +30,11 @@ def _load_worker():
def test_fill_report_parameter_multi_select(monkeypatch):
"""multi_select 应对每个值尝试多选填充,而非只取第一个。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
calls: list[tuple[str, str, list[str]]] = []
def _fake_multi(page_arg, selector_env, label, values):
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
calls.append((selector_env, label, list(values)))
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
@@ -38,6 +50,51 @@ def test_fill_report_parameter_multi_select(monkeypatch):
assert calls == [("FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
"""select_all 应传入 DSV checkbox 下拉处理,供 AWSAMS Warehouse 全选。"""
worker = _load_dsv_report_export()
page = MagicMock()
calls: list[dict[str, object]] = []
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
calls.append(
{
"selector_env": selector_env,
"label": label,
"values": list(values),
"selectors": selectors,
"select_all": select_all,
}
)
selectors = {
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
}
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
worker._fill_report_parameter(
page,
{
"name": "Warehouse",
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"mode": "multi_select",
"select_all": True,
"selectors": selectors,
"values": ["RTM"],
},
)
assert calls == [
{
"selector_env": "FREIGHT_RPA_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse",
"values": ["RTM"],
"selectors": selectors,
"select_all": True,
}
]
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
worker = _load_worker()
@@ -47,20 +104,40 @@ def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"source_code": "DSV360_AWSDU",
"parameters": [{"name": "Warehouse", "mode": "single", "values": ["AWSDU"], "selector_env": "X"}],
}
monkeypatch.setattr(worker, "_ensure_dsv_session", MagicMock())
export_mock = MagicMock(return_value="download")
monkeypatch.setattr(worker, "_export_dsv_inventory_source", export_mock)
monkeypatch.setattr(worker.dsv_driver, "download_dsv360_inventory", export_mock)
result = worker._download_dsv360_inventory(page, {"task_no": "SN-1"}, source)
worker._ensure_dsv_session.assert_called_once_with(page, "https://s360.dbschenker.com/")
export_mock.assert_called_once_with(page, {"task_no": "SN-1"}, source)
assert result == "download"
def test_dsv_report_has_inventory_data_rows_false_when_table_has_only_three_rows(monkeypatch):
"""DSV 报表明细表只有 3 行时应视为无库存数据,不进入导出。"""
worker = _load_dsv_report_export()
frame = MagicMock()
frame.evaluate.return_value = False
monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {}))
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is False
frame.evaluate.assert_called_once()
def test_dsv_report_has_inventory_data_rows_true_when_table_has_detail_rows(monkeypatch):
"""DSV 报表明细表第 4 行后存在非空行时应允许继续导出。"""
worker = _load_dsv_report_export()
frame = MagicMock()
frame.evaluate.return_value = True
monkeypatch.setattr(worker, "_find_dsv_report_result_frame", lambda page: (0, frame, {}))
assert worker._dsv_report_has_inventory_data_rows(MagicMock()) is True
frame.evaluate.assert_called_once()
def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
"""批量 navigation 变化时应 goto entry 并检测 session。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
login = MagicMock()
home = MagicMock()
@@ -79,7 +156,7 @@ def test_reset_dsv_export_entry_goes_home_without_forcing_login(monkeypatch):
def test_dsv_sources_share_navigation_when_program_report_match():
"""同 program/report 导航的 AWSBI 子仓应判定为可复用参数页。"""
worker = _load_worker()
worker = _load_dsv_report_export()
nav = {
"program_group": "Bison",
"program_label": "AWSBI",
@@ -93,7 +170,7 @@ def test_dsv_sources_share_navigation_when_program_report_match():
def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(monkeypatch):
"""同 navigation 的第二步应 reload 参数页而非 reset 首页。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
ensure = MagicMock()
reset = MagicMock()
@@ -120,7 +197,7 @@ def test_prepare_dsv_batch_export_reuses_parameter_form_when_navigation_matches(
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
"""program/report 变化时仍应回 portal 首页。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
reset = MagicMock()
reuse = MagicMock()
@@ -150,7 +227,7 @@ def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatc
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
login = MagicMock()
home = MagicMock()
@@ -171,7 +248,7 @@ def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
"""batch 首条前若 session 已有效,ensure 不应 goto + login。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
login = MagicMock()
home = MagicMock()
@@ -191,7 +268,7 @@ def test_ensure_dsv_session_skips_login_when_session_active(monkeypatch):
def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monkeypatch):
"""source_code 不同但 navigation/entry_url 一致时,第二步应复用参数页且不 reset 登录。"""
worker = _load_worker()
worker = _load_dsv_report_export()
page = MagicMock()
ensure = MagicMock()
reset = MagicMock()
@@ -228,7 +305,7 @@ def test_prepare_dsv_batch_reuses_form_for_different_source_code_same_entry(monk
def test_is_dsv_oauth_handshake_url_detects_pingfederate_page():
"""authorization.oauth2 应识别为 OAuth 握手中间页。"""
worker = _load_worker()
worker = _load_rpa_module("dsv_auth")
url = (
"https://auth.dbschenker.com/as/authorization.oauth2?"
"response_type=code&client_id=contract-logistics-360"
@@ -240,7 +317,7 @@ def test_is_dsv_oauth_handshake_url_detects_pingfederate_page():
def test_goto_dsv_entry_url_tolerates_domcontentloaded_timeout_on_auth_redirect(monkeypatch):
"""goto 超时但已跳转到 auth 域时不应抛错。"""
worker = _load_worker()
worker = _load_rpa_module("dsv_session")
page = MagicMock()
page.url = "https://auth.dbschenker.com/as/authorization.oauth2?response_type=code"
@@ -46,6 +46,76 @@ def test_fresh_snapshot_is_reused(app, tmp_path):
assert is_snapshot_fresh(found)
def test_snapshot_uses_site_id_as_matching_warehouse(app, tmp_path):
"""DSV 子仓导出入库后,应用 site_id 作为库存匹配与发货 Excel 的 warehouse id。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
xlsx = tmp_path / "stock.xlsx"
wb = Workbook()
wb.active.append(["sku", "qty"])
wb.active.append(["A001", 10])
wb.save(xlsx)
wb.close()
source = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert source is not None
assert source["site_id"] == "AWSBI"
assert source["warehouse_id"] == "BYAWSATL01"
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = ShippingTask(task_no="SN-SNAPSHOT-SITE", source_type="manual", process_status="waiting_inventory")
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="reuse_latest")
db.session.commit()
assert inv.warehouse_id == "AWSBI"
assert (inv.source_query_json or {}).get("export_warehouse_id") == "BYAWSATL01"
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "AWSBI") is not None
assert find_latest_ready_snapshot("DSV360_AWSBI_BYAWSATL01", "BYAWSATL01") is None
assert link is not None
assert link.matched_warehouse_id == "AWSBI"
def test_snapshot_without_site_id_uses_inventory_excel_warehouse_id(app, tmp_path):
"""无配置 site_id 时,快照 warehouse_id 应取库存 Excel 内的 Warehouse ID。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
from openpyxl import Workbook
xlsx = tmp_path / "crane_stock.xlsx"
wb = Workbook()
wb.active.append(["Warehouse ID", "sku", "qty"])
wb.active.append(["TZR2", "A001", 10])
wb.save(xlsx)
wb.close()
source = {
"source_code": "CRANE",
"source_type": "crane_footprint",
"site_id": "",
"warehouse_id": "",
}
with app.app_context():
inv = create_inventory_snapshot_from_rpa(source=source, local_path=xlsx, trigger_type="scheduled", success=True)
task = ShippingTask(task_no="SN-SNAPSHOT-EXCEL-WH", source_type="manual", process_status="waiting_inventory")
db.session.add(task)
db.session.flush()
link = link_snapshot_to_task(task, inv, reason="rpa_callback")
db.session.commit()
assert inv.warehouse_id == "TZR2"
assert (inv.source_query_json or {}).get("site_id") is None
assert (inv.source_query_json or {}).get("excel_warehouse_id") == "TZR2"
assert (inv.source_query_json or {}).get("warehouse_id_source") == "inventory_excel"
assert link is not None
assert link.matched_warehouse_id == "TZR2"
def test_expired_snapshot_not_reused(app, tmp_path):
"""过期快照不应被 find_latest_ready_snapshot 返回。"""
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
@@ -19,8 +19,9 @@ def test_inventory_sources_yaml_loads(app):
reload_inventory_sources_config()
source = get_inventory_source("DSV360_AWSDU")
assert source is not None
assert source["warehouse_id"] == "AWSDU"
assert source["source_type"] == "dsv360"
assert source["site_id"] == "AWSDU"
assert source["warehouse_id"] == ""
assert source["query"]["program_label"]
@@ -29,6 +30,7 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app):
with app.app_context():
payload = build_rpa_inventory_source("DSV360_AWSBI_BYAWSATL01")
assert payload is not None
assert payload["site_id"] == "AWSBI"
assert payload["warehouse_id"] == "BYAWSATL01"
assert payload["query"]["warehouse_code"] == "BYAWSATL01"
assert payload["query"]["program_label"] == "AWSBI"
@@ -37,6 +39,23 @@ def test_build_rpa_inventory_source_keeps_legacy_query(app):
assert payload["parameters"][0]["name"] == "Warehouse"
def test_awsams_warehouse_uses_multi_select_all(app):
"""AWSAMS Warehouse 是 SSRS checkbox 下拉,配置应显式走 multi_select + select_all。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("DSV360_AWSAMS")
assert payload is not None
warehouse_param = next(item for item in payload["parameters"] if item["name"] == "Warehouse")
assert warehouse_param["mode"] == "multi_select"
assert warehouse_param["select_all"] is True
assert warehouse_param["values"] == ["RTM"]
assert warehouse_param["selectors"] == {
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
}
def test_duplicate_source_code_raises(app, tmp_path):
"""source_code 重复时加载应报错。"""
bad = tmp_path / "bad_sources.json"
@@ -45,8 +64,8 @@ def test_duplicate_source_code_raises(app, tmp_path):
{
"version": 1,
"sources": [
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
{"source_code": "X1", "enabled": true, "site": "dsv360", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W1", "entry_url": "http://x", "navigation": {}, "parameters": []},
{"source_code": "X1", "enabled": true, "source_type": "dsv360", "site_id": "S1", "warehouse_id": "W2", "entry_url": "http://x", "navigation": {}, "parameters": []}
]
}
""",
@@ -58,6 +77,42 @@ def test_duplicate_source_code_raises(app, tmp_path):
reload_inventory_sources_config()
def test_dsv_source_requires_site_id(app, tmp_path):
"""DSV 源必须显式配置 site_id,避免把站点和仓库混用。"""
bad = tmp_path / "bad_sources.yaml"
bad.write_text(
"""
version: 1
sources:
- source_code: DSV360_BAD
enabled: true
source_type: dsv360
warehouse_id: AWSBI
entry_url: http://x
navigation: {}
parameters: []
""",
encoding="utf-8",
)
app.config["SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG"] = str(bad)
with app.app_context():
with pytest.raises(InventorySourceConfigError, match="site_id is required"):
reload_inventory_sources_config()
def test_build_rpa_inventory_source_crane_has_no_site_or_warehouse_requirement(app):
"""Crane 源不要求配置 site_id/warehouse_id,导出走 Schedule Report 异步下载。"""
with app.app_context():
reload_inventory_sources_config()
payload = build_rpa_inventory_source("CRANE")
assert payload is not None
assert payload["source_type"] == "crane_footprint"
assert payload["site_id"] == ""
assert payload["warehouse_id"] == ""
assert payload["parameters"] == []
assert payload["navigation"]["download_mode"] == "scheduled_report"
def test_match_aliases_available_via_list(app):
"""list_inventory_sources 应包含 match_aliases 供规则匹配。"""
with app.app_context():
@@ -65,6 +120,6 @@ def test_match_aliases_available_via_list(app):
codes = {item["source_code"] for item in list_inventory_sources()}
assert "DSV360_AWSDU" in codes
assert "DSV360_AWSBI_BYAWSATL01" in codes
assert "CRANE_TZR2" in codes
assert "CRANE" in codes
awsbi_count = sum(1 for item in list_inventory_sources() if str(item.get("source_code", "")).startswith("DSV360_AWSBI_"))
assert awsbi_count == 25