把 shipping 侧 inventory/receipt 词根迁到 onhand/inbound,29 张表与 枚举/权限/前端/i18n 同步改名;在手与入站报表配置及文件改由 freight_rpa 持有,发货与调拨仅按 source_code 消费;ORM 类加 FreightRpa 前缀, 上传动作改为 freight_rpa_upload。含类名与上传动作改名规格文档。 Co-authored-by: Cursor <cursoragent@cursor.com>
176 lines
8.2 KiB
Python
176 lines
8.2 KiB
Python
"""
|
||
scripts/import_freight_rpa_sources.py
|
||
|
||
用途:把期初 YAML 库存源导入 freight_rpa_sources / freight_rpa_profiles 主数据。
|
||
依赖:Flask app、SQLAlchemy、PyYAML、models.FreightRpaSource、models.FreightRpaProfile、
|
||
models.FreightRpaOnhandReportConfig(s18 起报表路径/查询条件归配置行)。
|
||
逻辑:由运维手工执行;读取 config/freight_rpa_sources.yaml,按平台与登录地址复用连接,
|
||
导入行一律保持停用,不导入 selector 与凭据;YAML 的报表路径与查询条件写入
|
||
FreightRpaOnhandReportConfig 配置行,解析方案绑定留空。运行时不再读这份 YAML。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import yaml
|
||
|
||
from app import create_app
|
||
from app.extensions import db
|
||
from app.models import FreightRpaOnhandReportConfig, FreightRpaSource, FreightRpaProfile
|
||
|
||
|
||
CONNECTOR_TYPES = {"dsv360": "dbs", "crane_footprint": "crane"}
|
||
|
||
|
||
def _source_payload(raw: dict[str, Any]) -> dict[str, Any]:
|
||
"""Convert one legacy source while excluding worker-only selector configuration.
|
||
|
||
Args:
|
||
raw: A source item from the legacy YAML document.
|
||
|
||
Returns:
|
||
Normalized source fields for ``FreightRpaSource`` plus the
|
||
``report_path_json`` / ``query_parameters_json`` carried by
|
||
``FreightRpaOnhandReportConfig`` since s18.
|
||
"""
|
||
connector_type = CONNECTOR_TYPES.get(str(raw.get("connector_type") or "").strip().lower())
|
||
if connector_type is None:
|
||
raise ValueError(f"Unsupported connector_type: {raw.get('connector_type')!r}")
|
||
navigation = raw.get("navigation") if isinstance(raw.get("navigation"), dict) else {}
|
||
parameters: list[dict[str, Any]] = []
|
||
for parameter in raw.get("parameters") or []:
|
||
if not isinstance(parameter, dict):
|
||
continue
|
||
parameters.append({
|
||
"name": str(parameter.get("name") or "").strip(),
|
||
"mode": str(parameter.get("mode") or "single").strip(),
|
||
"values": [str(value).strip() for value in parameter.get("values") or [] if str(value).strip()],
|
||
"required": bool(parameter.get("required", False)),
|
||
"select_all": bool(parameter.get("select_all", False)),
|
||
**({"joiner": str(parameter.get("joiner") or ",")} if str(parameter.get("mode") or "") == "multi_text" else {}),
|
||
})
|
||
dynamic = str(raw.get("warehouse_resolution") or "").strip() == "alias_match"
|
||
return {
|
||
"source_code": str(raw["source_code"]).strip().upper(),
|
||
"display_name": str(raw.get("display_name") or raw["source_code"]).strip(),
|
||
"connector_type": connector_type,
|
||
"login_url": str(raw.get("entry_url") or "").strip(),
|
||
"warehouse_resolution_mode": "inventory_match" if dynamic else "fixed",
|
||
"fixed_warehouse_id": None if dynamic else str(raw.get("warehouse_id") or "").strip() or None,
|
||
"report_path_json": ({
|
||
key: str(navigation.get(key) or "").strip()
|
||
for key in ("program_group", "program_label", "report_group", "report_name")
|
||
} if connector_type == "dbs" else {}),
|
||
"query_parameters_json": parameters,
|
||
}
|
||
|
||
|
||
def _connection_for(source: dict[str, Any]) -> FreightRpaProfile:
|
||
"""Return a compatible connection, reusing configured credentials whenever possible."""
|
||
profile = FreightRpaProfile.query.filter_by(
|
||
connector_type=source["connector_type"], login_url=source["login_url"],
|
||
).order_by(FreightRpaProfile.id).first()
|
||
if profile is not None and (profile.username_ciphertext or profile.password_ciphertext):
|
||
return profile
|
||
# Legacy YAML stores the portal root while a configured DBS connection can use a portal path.
|
||
# Prefer an existing credential-bearing platform connection instead of creating an unusable duplicate.
|
||
if source["connector_type"] == "dbs":
|
||
profile = FreightRpaProfile.query.filter_by(connector_type="dbs").filter(
|
||
(FreightRpaProfile.username_ciphertext.is_not(None)) | (FreightRpaProfile.password_ciphertext.is_not(None))
|
||
).order_by(FreightRpaProfile.credential_updated_at.desc(), FreightRpaProfile.id).first()
|
||
if profile is not None:
|
||
return profile
|
||
if profile is not None:
|
||
return profile
|
||
# The historical Crane connection was initially stored as DBS before source master data existed.
|
||
if source["connector_type"] == "crane":
|
||
profile = FreightRpaProfile.query.filter_by(profile_code="CRANE").first()
|
||
if profile is not None:
|
||
profile.connector_type = "crane"
|
||
profile.login_url = source["login_url"]
|
||
return profile
|
||
code = "DBS_S360" if source["connector_type"] == "dbs" else "CRANE"
|
||
profile = FreightRpaProfile(
|
||
profile_code=code,
|
||
display_name="DBS 平台" if source["connector_type"] == "dbs" else "Crane 平台",
|
||
connector_type=source["connector_type"],
|
||
login_url=source["login_url"],
|
||
login_config_json={"auth_mode": "password"},
|
||
enabled=True,
|
||
)
|
||
db.session.add(profile)
|
||
db.session.flush()
|
||
return profile
|
||
|
||
|
||
def import_sources(path: Path) -> tuple[int, int]:
|
||
"""Idempotently insert/update YAML source master data with imported rows disabled.
|
||
|
||
Returns:
|
||
A pair of ``(created, updated)`` counts.
|
||
"""
|
||
document = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
||
rows = document.get("sources") if isinstance(document, dict) else None
|
||
if not isinstance(rows, list):
|
||
raise ValueError("YAML must contain a sources list")
|
||
created = updated = 0
|
||
for raw in rows:
|
||
if not isinstance(raw, dict):
|
||
continue
|
||
data = _source_payload(raw)
|
||
profile = _connection_for(data)
|
||
source = FreightRpaSource.query.filter_by(source_code=data["source_code"]).first()
|
||
if source is None:
|
||
source = FreightRpaSource(
|
||
source_code=data["source_code"], display_name=data["display_name"],
|
||
connector_type=data["connector_type"], rpa_profile=profile,
|
||
warehouse_resolution_mode=data["warehouse_resolution_mode"], enabled=False,
|
||
)
|
||
db.session.add(source)
|
||
created += 1
|
||
else:
|
||
updated += 1
|
||
source.display_name = data["display_name"]
|
||
source.connector_type = data["connector_type"]
|
||
source.rpa_profile = profile
|
||
source.excel_template_id = None
|
||
source.warehouse_resolution_mode = data["warehouse_resolution_mode"]
|
||
source.fixed_warehouse_id = data["fixed_warehouse_id"]
|
||
# s18 起报表路径/查询条件归 FreightRpaOnhandReportConfig 配置行(无则插入);
|
||
# 解析方案绑定保持 None,与今日导入语义一致(启用前由管理员绑定)。
|
||
config = source.onhand_report_config
|
||
if config is None:
|
||
config = FreightRpaOnhandReportConfig(source=source)
|
||
db.session.add(config)
|
||
config.parsing_profile_id = None
|
||
config.report_path_json = data["report_path_json"]
|
||
config.query_parameters_json = data["query_parameters_json"]
|
||
source.snapshot_ttl_seconds = 86400
|
||
# Templates are not present in legacy YAML; activation requires published bindings.
|
||
source.enabled = False
|
||
db.session.commit()
|
||
# A previous run may have created this deterministic placeholder before a configured DBS connection was found.
|
||
placeholder = FreightRpaProfile.query.filter_by(profile_code="DBS_S360").first()
|
||
if placeholder and not placeholder.sources and not placeholder.username_ciphertext and not placeholder.password_ciphertext:
|
||
db.session.delete(placeholder)
|
||
db.session.commit()
|
||
return created, updated
|
||
|
||
|
||
def main() -> None:
|
||
"""Run the controlled YAML import and print counts without exposing credentials."""
|
||
parser = argparse.ArgumentParser(description="Import legacy freight RPA sources")
|
||
parser.add_argument("--file", type=Path, default=Path("config/freight_rpa_sources.yaml"))
|
||
args = parser.parse_args()
|
||
app = create_app()
|
||
with app.app_context():
|
||
created, updated = import_sources(args.file)
|
||
print(f"Imported freight RPA sources: created={created}, updated={updated}")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|