57 lines
2.7 KiB
Python
57 lines
2.7 KiB
Python
"""已授权运输计划的日历路线:客户简称优先,缺失时保留全称/地址。"""
|
|
from typing import Sequence
|
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.models.crm_models import CrmCustomer
|
|
|
|
|
|
def _text(obj, field: str) -> str:
|
|
return str(getattr(obj, field, None) or "").strip()
|
|
|
|
|
|
def attach_calendar_routes(db: Session, *, tenant_no: str, plans: Sequence) -> None:
|
|
# 调用方已对 plans 应用运输数据权限;只补充这些计划引用的客户名称。
|
|
customer_ids = set()
|
|
for plan in plans:
|
|
for field in ("supplier_id", "customer_id", "destination_id"):
|
|
if _text(plan, field):
|
|
customer_ids.add(_text(plan, field))
|
|
for stop in [getattr(plan, "load", None)] + list(getattr(plan, "deliveries", None) or []):
|
|
if _text(stop, "customer_id"):
|
|
customer_ids.add(_text(stop, "customer_id"))
|
|
names = {}
|
|
if customer_ids:
|
|
rows = db.query(CrmCustomer.id, CrmCustomer.short_name, CrmCustomer.customer_name).filter(
|
|
CrmCustomer.id.in_(customer_ids),
|
|
CrmCustomer.tenant_no == tenant_no,
|
|
CrmCustomer.del_flag == 0,
|
|
).all()
|
|
names = {row.id: (row.short_name or "").strip() or (row.customer_name or "").strip() for row in rows}
|
|
for plan in plans:
|
|
load = getattr(plan, "load", None)
|
|
origin = (
|
|
names.get(_text(load, "customer_id"))
|
|
or _text(load, "customer_name") or _text(plan, "load_customer_name")
|
|
or names.get(_text(plan, "supplier_id")) or _text(plan, "supplier_name") or _text(load, "address") or _text(plan, "pickup_address")
|
|
)
|
|
if load is not None:
|
|
load.calendar_customer_name = origin
|
|
stops = sorted(getattr(plan, "deliveries", None) or [], key=lambda stop: getattr(stop, "seq", 0) or 0)
|
|
destinations = []
|
|
for stop in stops:
|
|
stop.calendar_customer_name = (
|
|
names.get(_text(stop, "customer_id")) or _text(stop, "customer_name") or _text(stop, "address")
|
|
)
|
|
destinations.append(stop.calendar_customer_name)
|
|
destinations = [name for name in destinations if name]
|
|
if not destinations:
|
|
destination = (
|
|
names.get(_text(plan, "customer_id") or _text(plan, "destination_id"))
|
|
or _text(plan, "delivery_customer_summary") or _text(plan, "customer_name")
|
|
or _text(plan, "destination_name") or _text(plan, "destination_address")
|
|
)
|
|
if destination:
|
|
destinations.append(destination)
|
|
plan.calendar_route = " → ".join(name for name in [origin, *destinations] if name) or "去向待定"
|