Merge branch 'dev' into departmental-structure

This commit is contained in:
HTEWJ\26070045 committed 2026-10-29 17:11:21 +08:00
commit be49b44004
959 files changed
+89908 -34315

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
"""[DEBUG-perf1] 首页 /summary 计时基线(临时,诊断后删除)。"""
from time import perf_counter
from app import create_app
from app.services.in_transit_transfer.backlog_service import (
_pending_match_counts,
backlog_summary,
list_backlog,
)
app = create_app()
with app.app_context():
t0 = perf_counter()
items = list_backlog()
t1 = perf_counter()
pm, m = _pending_match_counts()
t2 = perf_counter()
s = backlog_summary()
t3 = perf_counter()
print(f"[DEBUG-perf1] list_backlog rows={len(items)}: {t1 - t0:.2f}s")
print(f"[DEBUG-perf1] _pending_match_counts pending={pm} matchable={m}: {t2 - t1:.2f}s")
print(f"[DEBUG-perf1] backlog_summary total: {t3 - t2:.2f}s (pending={s.pending_match_count}, matchable={s.matchable_count})")
@@ -1,165 +0,0 @@
"""Import legacy YAML inventory sources into the shipping configuration database.
Purpose: migrate business report paths, query inputs, aliases, and warehouse policies from
``config/shipping_inventory_sources.yaml`` into the new source master data.
Dependencies: Flask app context, SQLAlchemy models, PyYAML.
Flow: reuses connections by platform and login URL, keeps all imported sources disabled, and
never imports YAML selectors or credentials because those are worker implementation/secrets.
"""
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 ShippingInventorySource, ShippingRpaProfile
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 suitable for ``ShippingInventorySource``.
"""
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]) -> ShippingRpaProfile:
"""Return a compatible connection, reusing configured credentials whenever possible."""
profile = ShippingRpaProfile.query.filter_by(
connector_type=source["connector_type"], login_url=source["login_url"],
).order_by(ShippingRpaProfile.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 = ShippingRpaProfile.query.filter_by(connector_type="dbs").filter(
(ShippingRpaProfile.username_ciphertext.is_not(None)) | (ShippingRpaProfile.password_ciphertext.is_not(None))
).order_by(ShippingRpaProfile.credential_updated_at.desc(), ShippingRpaProfile.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 = ShippingRpaProfile.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 = ShippingRpaProfile(
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 = ShippingInventorySource.query.filter_by(source_code=data["source_code"]).first()
if source is None:
source = ShippingInventorySource(
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.parsing_profile_id = None
source.excel_template_id = None
source.warehouse_resolution_mode = data["warehouse_resolution_mode"]
source.fixed_warehouse_id = data["fixed_warehouse_id"]
source.report_path_json = data["report_path_json"]
source.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 = ShippingRpaProfile.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 shipping inventory sources")
parser.add_argument("--file", type=Path, default=Path("config/shipping_inventory_sources.yaml"))
args = parser.parse_args()
app = create_app()
with app.app_context():
created, updated = import_sources(args.file)
print(f"Imported inventory sources: created={created}, updated={updated}")
if __name__ == "__main__":
main()