| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368 |
- """合同产品在运输计划上的安排数量汇总。"""
- from __future__ import annotations
- from collections import defaultdict
- from typing import Any, DefaultDict, Dict, Iterable, Optional, Set, Tuple
- from sqlalchemy.orm import Session
- from app.models.pl_models import (
- PlPlan,
- PlPlanContract,
- PlPlanDelivery,
- PlPlanDeliveryProduct,
- PlPlanLoad,
- PlPlanLoadProduct,
- )
- from app.services.pl_plan_service import (
- PLAN_CONTRACT_SIDE_DEMANDER,
- PLAN_CONTRACT_SIDE_SUPPLIER,
- )
- from app.services.pl_plan_stop_service import (
- PLAN_CONTRACT_SIDE_DELIVERY,
- PLAN_CONTRACT_SIDE_LOAD,
- )
- from app.utils.crm_package_spec import decode_package_specs
- # 待安排 / 等通知 / 作废:不计入「已安排」(见 _bucket_for_plan)
- ProductPackageKey = Tuple[str, str]
- def normalize_package_spec(value: Any) -> str:
- if value is None:
- return ""
- return str(value).strip()
- def product_package_key(product_id: Any, package_spec: Any = None) -> Optional[ProductPackageKey]:
- pid = str(product_id or "").strip()
- if not pid:
- return None
- return (pid, normalize_package_spec(package_spec))
- def _to_float(value: Any) -> float:
- if value is None:
- return 0.0
- try:
- return float(value)
- except (TypeError, ValueError):
- return 0.0
- def contract_line_package_specs(row: Any) -> list[str]:
- """从合同产品行(ORM / dict / SimpleNamespace)解析包装列表。"""
- if isinstance(row, dict):
- raw_list = row.get("packageSpecs") or row.get("package_specs")
- if isinstance(raw_list, (list, tuple)) and raw_list:
- return decode_package_specs(raw_list)
- return decode_package_specs(row.get("packageSpec") or row.get("package_spec"))
- raw_list = getattr(row, "package_specs", None)
- if isinstance(raw_list, (list, tuple)) and raw_list:
- return decode_package_specs(raw_list)
- return decode_package_specs(getattr(row, "package_spec", None))
- def pool_keys_for_contract_line(row: Any) -> list[ProductPackageKey]:
- pid = ""
- if isinstance(row, dict):
- pid = str(row.get("productId") or row.get("product_id") or "").strip()
- else:
- pid = str(getattr(row, "product_id", None) or "").strip()
- if not pid:
- return []
- keys: list[ProductPackageKey] = []
- for spec in contract_line_package_specs(row):
- key = product_package_key(pid, spec)
- if key:
- keys.append(key)
- return keys
- def sum_qty_stats_for_keys(
- qty_map: Dict[ProductPackageKey, Dict[str, float]],
- keys: Iterable[ProductPackageKey],
- ) -> Dict[str, float]:
- archived = 0.0
- unarchived = 0.0
- for key in keys or []:
- stats = qty_map.get(key) or {}
- archived += _to_float(stats.get("archivedQty"))
- unarchived += _to_float(stats.get("arrangedUnarchivedQty"))
- archived = round(archived, 3)
- unarchived = round(unarchived, 3)
- return {
- "archivedQty": archived,
- "arrangedUnarchivedQty": unarchived,
- "arrangedTotalQty": round(archived + unarchived, 3),
- }
- def match_contract_product_for_key(
- products: Iterable[Any],
- key: Optional[ProductPackageKey],
- ) -> Optional[Any]:
- """按 productId + 包装∈行内集合 匹配合同产品行;同包装脏数据多行时 quantity 相加。"""
- if not key:
- return None
- pid, pkg = key[0], key[1]
- matched = []
- for p in products or []:
- row_pid = ""
- if isinstance(p, dict):
- row_pid = str(p.get("productId") or p.get("product_id") or "").strip()
- else:
- row_pid = str(getattr(p, "product_id", None) or "").strip()
- if row_pid != pid:
- continue
- specs = contract_line_package_specs(p)
- if pkg in specs:
- matched.append(p)
- if not matched:
- return None
- if len(matched) == 1:
- return matched[0]
- from types import SimpleNamespace
- total_qty = 0.0
- for p in matched:
- if isinstance(p, dict):
- total_qty += _to_float(p.get("quantity"))
- else:
- total_qty += _to_float(getattr(p, "quantity", None))
- base = matched[0]
- if isinstance(base, dict):
- return SimpleNamespace(
- id=base.get("id"),
- product_id=base.get("productId") or base.get("product_id"),
- package_spec=encode_specs_for_attr(contract_line_package_specs(base)),
- product_name=base.get("productName") or base.get("product_name"),
- model=base.get("model"),
- unit=base.get("unit"),
- quantity=total_qty,
- quantity_mode=base.get("quantityMode") or base.get("quantity_mode"),
- )
- return SimpleNamespace(
- id=getattr(base, "id", None),
- product_id=getattr(base, "product_id", None),
- package_spec=getattr(base, "package_spec", None),
- product_name=getattr(base, "product_name", None),
- model=getattr(base, "model", None),
- unit=getattr(base, "unit", None),
- quantity=total_qty,
- quantity_mode=getattr(base, "quantity_mode", None),
- )
- def encode_specs_for_attr(specs: list[str]) -> str:
- from app.utils.crm_package_spec import encode_package_specs
- return encode_package_specs(specs)
- def _bucket_for_plan(*, archive_status: Optional[str], follow_status: Optional[str], transport_status: Optional[str]) -> Optional[str]:
- """返回 'archived' | 'arranged_unarchived' | None(不计入)。"""
- follow = (follow_status or "").strip()
- if follow == "cancelled" or follow in ("wait_notice", "pending_arrange"):
- return None
- archive = (archive_status or "").strip() or "unarchived"
- if archive == "archived":
- return "archived"
- # 已安排未归档(含 archive draft 暂存)
- transport = (transport_status or "").strip()
- if transport == "arranged" or follow in ("arranged", "completed"):
- return "arranged_unarchived"
- return None
- def merge_product_qty_maps(
- *,
- archived: Dict[ProductPackageKey, float],
- arranged_unarchived: Dict[ProductPackageKey, float],
- ) -> Dict[ProductPackageKey, Dict[str, float]]:
- """(product_id, package_spec) -> {archivedQty, arrangedUnarchivedQty, arrangedTotalQty}"""
- keys = set(archived) | set(arranged_unarchived)
- out: Dict[ProductPackageKey, Dict[str, float]] = {}
- for key in keys:
- a = round(float(archived.get(key, 0.0)), 3)
- u = round(float(arranged_unarchived.get(key, 0.0)), 3)
- out[key] = {
- "archivedQty": a,
- "arrangedUnarchivedQty": u,
- "arrangedTotalQty": round(a + u, 3),
- }
- return out
- # plan:计划数量;archive_actual:装货 inbound / 送货 outbound,null 回退 plan_qty
- QTY_MODE_PLAN = "plan"
- QTY_MODE_ARCHIVE_ACTUAL = "archive_actual"
- def _resolve_stop_product_qty(
- row: Any,
- *,
- stop_kind: str,
- qty_mode: str,
- ) -> float:
- """按模式解析段产品计入量。"""
- if qty_mode == QTY_MODE_ARCHIVE_ACTUAL:
- attr = "inbound_qty" if stop_kind == "load" else "outbound_qty"
- raw = getattr(row, attr, None)
- if raw is not None:
- return _to_float(raw)
- return _to_float(getattr(row, "plan_qty", None))
- return _to_float(getattr(row, "plan_qty", None))
- def accumulate_stop_products(
- target: DefaultDict[ProductPackageKey, float],
- products: Iterable[Any],
- *,
- stop_kind: str = "load",
- qty_mode: str = QTY_MODE_PLAN,
- ) -> None:
- for row in products or []:
- key = product_package_key(
- getattr(row, "product_id", None),
- getattr(row, "package_spec", None),
- )
- if not key:
- continue
- qty = _resolve_stop_product_qty(row, stop_kind=stop_kind, qty_mode=qty_mode)
- if qty:
- target[key] += qty
- def resolve_linked_plan_scopes(
- link_rows: Iterable[PlPlanContract],
- legacy_plan_ids: Iterable[str],
- ) -> Dict[str, Dict[str, Any]]:
- """
- plan_id -> {
- load_ids: set[str] | None, # None = 该侧全部装货段
- delivery_ids: set[str] | None,
- use_all_stops: bool, # 遗留主表合同:优先送货段,否则装货段,各产品只计一次
- }
- """
- scopes: Dict[str, Dict[str, Any]] = {}
- def _ensure(plan_id: str) -> Dict[str, Any]:
- if plan_id not in scopes:
- scopes[plan_id] = {
- "load_ids": set(),
- "delivery_ids": set(),
- "use_all_stops": False,
- "has_explicit": False,
- }
- return scopes[plan_id]
- for row in link_rows or []:
- plan_id = str(getattr(row, "plan_id", None) or "").strip()
- if not plan_id:
- continue
- scope = _ensure(plan_id)
- side = (getattr(row, "side", None) or "").strip()
- stop_id = str(getattr(row, "stop_id", None) or "").strip()
- scope["has_explicit"] = True
- if side in (PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_SUPPLIER):
- if stop_id:
- scope["load_ids"].add(stop_id)
- else:
- scope["load_ids"] = None # type: ignore[assignment]
- elif side in (PLAN_CONTRACT_SIDE_DELIVERY, PLAN_CONTRACT_SIDE_DEMANDER):
- if stop_id:
- scope["delivery_ids"].add(stop_id)
- else:
- scope["delivery_ids"] = None # type: ignore[assignment]
- elif stop_id:
- # 未知 side 但有 stop:两边都尝试匹配时由调用方按 id 过滤
- scope["load_ids"].add(stop_id)
- scope["delivery_ids"].add(stop_id)
- for plan_id in legacy_plan_ids or []:
- pid = str(plan_id or "").strip()
- if not pid:
- continue
- scope = _ensure(pid)
- if not scope["has_explicit"]:
- scope["use_all_stops"] = True
- return scopes
- def sum_qtys_for_scope(
- *,
- load_products_by_load: Dict[str, list],
- delivery_products_by_delivery: Dict[str, list],
- all_load_ids: Set[str],
- all_delivery_ids: Set[str],
- scope: Dict[str, Any],
- qty_mode: str = QTY_MODE_PLAN,
- ) -> Dict[ProductPackageKey, float]:
- acc: DefaultDict[ProductPackageKey, float] = defaultdict(float)
- if scope.get("use_all_stops"):
- # 遗留:优先送货段数量;无送货则用装货,避免装+送双计
- if all_delivery_ids:
- for did in all_delivery_ids:
- accumulate_stop_products(
- acc,
- delivery_products_by_delivery.get(did, []),
- stop_kind="delivery",
- qty_mode=qty_mode,
- )
- else:
- for lid in all_load_ids:
- accumulate_stop_products(
- acc,
- load_products_by_load.get(lid, []),
- stop_kind="load",
- qty_mode=qty_mode,
- )
- return dict(acc)
- load_ids = scope.get("load_ids")
- delivery_ids = scope.get("delivery_ids")
- if load_ids is None:
- for lid in all_load_ids:
- accumulate_stop_products(
- acc,
- load_products_by_load.get(lid, []),
- stop_kind="load",
- qty_mode=qty_mode,
- )
- elif load_ids:
- for lid in load_ids:
- accumulate_stop_products(
- acc,
- load_products_by_load.get(lid, []),
- stop_kind="load",
- qty_mode=qty_mode,
- )
- if delivery_ids is None:
- for did in all_delivery_ids:
- accumulate_stop_products(
- acc,
- delivery_products_by_delivery.get(did, []),
- stop_kind="delivery",
- qty_mode=qty_mode,
- )
- elif delivery_ids:
- for did in delivery_ids:
- accumulate_stop_products(
- acc,
- delivery_products_by_delivery.get(did, []),
- stop_kind="delivery",
- qty_mode=qty_mode,
- )
- return dict(acc)
- def aggregate_contract_product_plan_qtys(
- db: Session,
- *,
- tenant_no: str,
- contract_id: str,
- ) -> Dict[ProductPackageKey, Dict[str, float]]:
- """返回 (productId, packageSpec) -> 三数量字段。"""
- cid = (contract_id or "").strip()
- if not cid:
- return {}
- link_rows = (
- db.query(PlPlanContract)
- .filter(
- PlPlanContract.tenant_no == tenant_no,
- PlPlanContract.del_flag == 0,
- PlPlanContract.contract_id == cid,
- )
- .all()
- )
- link_plan_ids = {str(r.plan_id) for r in link_rows if r.plan_id}
- legacy_plans = (
- db.query(PlPlan)
- .filter(
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- PlPlan.contract_id == cid,
- )
- .all()
- )
- legacy_only_ids = {p.id for p in legacy_plans if p.id not in link_plan_ids}
- scopes = resolve_linked_plan_scopes(link_rows, legacy_only_ids)
- plan_ids = list(scopes.keys())
- if not plan_ids:
- return {}
- plans = (
- db.query(PlPlan)
- .filter(
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- PlPlan.id.in_(plan_ids),
- PlPlan.follow_status != "cancelled",
- )
- .all()
- )
- plan_by_id = {p.id: p for p in plans}
- loads = (
- db.query(PlPlanLoad)
- .filter(
- PlPlanLoad.tenant_no == tenant_no,
- PlPlanLoad.del_flag == 0,
- PlPlanLoad.plan_id.in_(plan_ids),
- )
- .all()
- )
- deliveries = (
- db.query(PlPlanDelivery)
- .filter(
- PlPlanDelivery.tenant_no == tenant_no,
- PlPlanDelivery.del_flag == 0,
- PlPlanDelivery.plan_id.in_(plan_ids),
- )
- .all()
- )
- load_ids_by_plan: DefaultDict[str, Set[str]] = defaultdict(set)
- delivery_ids_by_plan: DefaultDict[str, Set[str]] = defaultdict(set)
- for row in loads:
- load_ids_by_plan[row.plan_id].add(row.id)
- for row in deliveries:
- delivery_ids_by_plan[row.plan_id].add(row.id)
- all_load_ids = {row.id for row in loads}
- all_delivery_ids = {row.id for row in deliveries}
- load_products_by_load: DefaultDict[str, list] = defaultdict(list)
- if all_load_ids:
- for prod in (
- db.query(PlPlanLoadProduct)
- .filter(
- PlPlanLoadProduct.tenant_no == tenant_no,
- PlPlanLoadProduct.del_flag == 0,
- PlPlanLoadProduct.load_id.in_(all_load_ids),
- )
- .all()
- ):
- load_products_by_load[prod.load_id].append(prod)
- delivery_products_by_delivery: DefaultDict[str, list] = defaultdict(list)
- if all_delivery_ids:
- for prod in (
- db.query(PlPlanDeliveryProduct)
- .filter(
- PlPlanDeliveryProduct.tenant_no == tenant_no,
- PlPlanDeliveryProduct.del_flag == 0,
- PlPlanDeliveryProduct.delivery_id.in_(all_delivery_ids),
- )
- .all()
- ):
- delivery_products_by_delivery[prod.delivery_id].append(prod)
- archived: DefaultDict[ProductPackageKey, float] = defaultdict(float)
- arranged_unarchived: DefaultDict[ProductPackageKey, float] = defaultdict(float)
- for plan_id, scope in scopes.items():
- plan = plan_by_id.get(plan_id)
- if not plan:
- continue
- bucket = _bucket_for_plan(
- archive_status=plan.archive_status,
- follow_status=plan.follow_status,
- transport_status=plan.transport_status,
- )
- if not bucket:
- continue
- qty_mode = (
- QTY_MODE_ARCHIVE_ACTUAL if bucket == "archived" else QTY_MODE_PLAN
- )
- qtys = sum_qtys_for_scope(
- load_products_by_load=load_products_by_load,
- delivery_products_by_delivery=delivery_products_by_delivery,
- all_load_ids=load_ids_by_plan.get(plan_id, set()),
- all_delivery_ids=delivery_ids_by_plan.get(plan_id, set()),
- scope=scope,
- qty_mode=qty_mode,
- )
- target = archived if bucket == "archived" else arranged_unarchived
- for pid, qty in qtys.items():
- target[pid] += qty
- return merge_product_qty_maps(archived=dict(archived), arranged_unarchived=dict(arranged_unarchived))
- def attach_plan_qty_fields_to_products(
- products: list,
- qty_by_product_id: Dict[ProductPackageKey, Dict[str, float]],
- ) -> None:
- zeros = {
- "archivedQty": 0.0,
- "arrangedUnarchivedQty": 0.0,
- "arrangedTotalQty": 0.0,
- }
- for item in products or []:
- if not isinstance(item, dict):
- continue
- specs = contract_line_package_specs(item)
- item["packageSpecs"] = specs
- if specs:
- item["packageSpec"] = specs[0]
- elif not item.get("packageSpec"):
- item["packageSpec"] = ""
- keys = pool_keys_for_contract_line(item)
- breakdown: list[Dict[str, Any]] = []
- for key in keys:
- stats = (qty_by_product_id.get(key) if key else None) or zeros
- breakdown.append(
- {
- "packageSpec": key[1] if key else "",
- "archivedQty": stats["archivedQty"],
- "arrangedUnarchivedQty": stats["arrangedUnarchivedQty"],
- "arrangedTotalQty": stats["arrangedTotalQty"],
- }
- )
- line_stats = sum_qty_stats_for_keys(qty_by_product_id, keys) if keys else dict(zeros)
- item["archivedQty"] = line_stats["archivedQty"]
- item["arrangedUnarchivedQty"] = line_stats["arrangedUnarchivedQty"]
- item["arrangedTotalQty"] = line_stats["arrangedTotalQty"]
- item["packageQtyBreakdown"] = breakdown
- line_qty = _to_float(item.get("quantity"))
- if line_qty > 0:
- item["remainingQty"] = round(line_qty - line_stats["arrangedTotalQty"], 3)
- else:
- item["remainingQty"] = None
- def plan_ids_linked_to_contract(
- db: Session,
- *,
- tenant_no: str,
- contract_id: str,
- ) -> Set[str]:
- cid = (contract_id or "").strip()
- if not cid:
- return set()
- ids: Set[str] = set()
- for (plan_id,) in (
- db.query(PlPlanContract.plan_id)
- .filter(
- PlPlanContract.tenant_no == tenant_no,
- PlPlanContract.del_flag == 0,
- PlPlanContract.contract_id == cid,
- )
- .distinct()
- .all()
- ):
- if plan_id:
- ids.add(str(plan_id))
- for (plan_id,) in (
- db.query(PlPlan.id)
- .filter(
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- PlPlan.contract_id == cid,
- )
- .all()
- ):
- if plan_id:
- ids.add(str(plan_id))
- return ids
- def contract_ids_linked_to_plan(
- db: Session,
- *,
- tenant_no: str,
- plan: PlPlan,
- ) -> Set[str]:
- ids: Set[str] = set()
- if plan.contract_id:
- ids.add(str(plan.contract_id).strip())
- for (cid,) in (
- db.query(PlPlanContract.contract_id)
- .filter(
- PlPlanContract.tenant_no == tenant_no,
- PlPlanContract.del_flag == 0,
- PlPlanContract.plan_id == plan.id,
- )
- .distinct()
- .all()
- ):
- if cid:
- ids.add(str(cid).strip())
- return {x for x in ids if x}
- def auto_start_execute_approved_contracts(
- db: Session,
- *,
- tenant_no: str,
- plan: PlPlan,
- user_id: Optional[str] = None,
- ) -> list[str]:
- """将关联且状态为 approved 的合同置为 executing(不 commit)。返回已推进的合同 id。"""
- from datetime import datetime
- from app.models.crm_models import CrmContract
- started: list[str] = []
- for cid in contract_ids_linked_to_plan(db, tenant_no=tenant_no, plan=plan):
- row = (
- db.query(CrmContract)
- .filter(
- CrmContract.id == cid,
- CrmContract.tenant_no == tenant_no,
- CrmContract.del_flag == 0,
- )
- .first()
- )
- if not row or row.status != "approved":
- continue
- row.status = "executing"
- row.update_by = user_id
- row.update_time = datetime.now()
- started.append(cid)
- return started
- # =============================================================================
- # 安排运输:合同数量硬拦 / 成功后提醒
- # =============================================================================
- FRAMEWORK_CONTRACT_TYPES = frozenset({"framework", "framework_sale", "framework_purchase"})
- def effective_arranged_total(
- *,
- arranged_total: float,
- old_plan_qty: float,
- new_plan_qty: float,
- ) -> float:
- """已安排合计 − 本计划旧量 + 本计划新量。"""
- return round(
- _to_float(arranged_total) - _to_float(old_plan_qty) + _to_float(new_plan_qty),
- 3,
- )
- def contract_product_has_fixed_qty(
- *,
- contract_type: Optional[str],
- quantity: Any,
- quantity_mode: Optional[str],
- ) -> bool:
- """合同产品行是否按固定数量做超量硬拦。"""
- ctype = (contract_type or "").strip()
- mode = (quantity_mode or "").strip() or "fixed"
- if ctype in FRAMEWORK_CONTRACT_TYPES and mode == "customer_demand":
- return False
- qty = _to_float(quantity)
- return qty > 0
- def evaluate_product_qty_for_arrange(
- *,
- has_fixed_qty: bool,
- contract_qty: Optional[float],
- arranged_total: float,
- old_plan_qty: float,
- new_plan_qty: float,
- ) -> Optional[Dict[str, Any]]:
- """
- 返回:
- - None: 跳过(本次无量)
- - kind=violation | remaining | framework_cumulative
- """
- new_qty = _to_float(new_plan_qty)
- if new_qty <= 0:
- return None
- old_qty = _to_float(old_plan_qty)
- arranged = _to_float(arranged_total)
- effective = effective_arranged_total(
- arranged_total=arranged,
- old_plan_qty=old_qty,
- new_plan_qty=new_qty,
- )
- if not has_fixed_qty:
- return {
- "kind": "framework_cumulative",
- "arrangedTotalQty": effective,
- "thisPlanQty": round(new_qty, 3),
- "effectiveTotal": effective,
- }
- cq = _to_float(contract_qty)
- overflow = round(effective - cq, 3)
- base = {
- "contractQty": round(cq, 3),
- "arrangedTotalQty": effective,
- "thisPlanQty": round(new_qty, 3),
- "oldPlanQty": round(old_qty, 3),
- "newPlanQty": round(new_qty, 3),
- "effectiveTotal": effective,
- }
- if overflow > 0:
- return {**base, "kind": "violation", "overflowQty": overflow}
- return {
- **base,
- "kind": "remaining",
- "remainingQty": round(cq - effective, 3),
- }
- CONTRACT_QTY_VIOLATION_CODE = "CONTRACT_QTY_OVERFLOW"
- def _stop_kind_from_scope(scope: Dict[str, Any]) -> str:
- load_ids = scope.get("load_ids")
- delivery_ids = scope.get("delivery_ids")
- has_load = load_ids is None or bool(load_ids)
- has_delivery = delivery_ids is None or bool(delivery_ids)
- if scope.get("use_all_stops"):
- return "delivery"
- if has_load and not has_delivery:
- return "load"
- if has_delivery and not has_load:
- return "delivery"
- if has_load:
- return "load"
- return "delivery"
- def _plan_scope_for_contract(
- *,
- plan_id: str,
- contract_id: str,
- link_rows: list[PlPlanContract],
- legacy_contract_id: Optional[str],
- ) -> Dict[str, Any]:
- cid = (contract_id or "").strip()
- links = [r for r in link_rows if str(r.contract_id or "").strip() == cid]
- legacy_ids: list[str] = []
- if not links and legacy_contract_id and str(legacy_contract_id).strip() == cid:
- legacy_ids = [plan_id]
- scopes = resolve_linked_plan_scopes(links, legacy_ids)
- return scopes.get(plan_id) or {
- "load_ids": set(),
- "delivery_ids": set(),
- "use_all_stops": False,
- "has_explicit": False,
- }
- def _load_plan_stop_product_maps(
- db: Session,
- *,
- tenant_no: str,
- plan_id: str,
- ) -> tuple[Set[str], Set[str], Dict[str, list], Dict[str, list]]:
- loads = (
- db.query(PlPlanLoad)
- .filter(
- PlPlanLoad.tenant_no == tenant_no,
- PlPlanLoad.del_flag == 0,
- PlPlanLoad.plan_id == plan_id,
- )
- .all()
- )
- deliveries = (
- db.query(PlPlanDelivery)
- .filter(
- PlPlanDelivery.tenant_no == tenant_no,
- PlPlanDelivery.del_flag == 0,
- PlPlanDelivery.plan_id == plan_id,
- )
- .all()
- )
- load_ids = {row.id for row in loads}
- delivery_ids = {row.id for row in deliveries}
- load_products_by_load: DefaultDict[str, list] = defaultdict(list)
- if load_ids:
- for prod in (
- db.query(PlPlanLoadProduct)
- .filter(
- PlPlanLoadProduct.tenant_no == tenant_no,
- PlPlanLoadProduct.del_flag == 0,
- PlPlanLoadProduct.load_id.in_(load_ids),
- )
- .all()
- ):
- load_products_by_load[prod.load_id].append(prod)
- delivery_products_by_delivery: DefaultDict[str, list] = defaultdict(list)
- if delivery_ids:
- for prod in (
- db.query(PlPlanDeliveryProduct)
- .filter(
- PlPlanDeliveryProduct.tenant_no == tenant_no,
- PlPlanDeliveryProduct.del_flag == 0,
- PlPlanDeliveryProduct.delivery_id.in_(delivery_ids),
- )
- .all()
- ):
- delivery_products_by_delivery[prod.delivery_id].append(prod)
- return load_ids, delivery_ids, dict(load_products_by_load), dict(delivery_products_by_delivery)
- def collect_plan_contract_qty_checks(
- db: Session,
- *,
- tenant_no: str,
- plan_id: str,
- ) -> tuple[list[Dict[str, Any]], list[Dict[str, Any]]]:
- """
- 返回 (violations, reminders)。
- 在写运输前调用;reminders 可缓存到成功响应,勿在状态变更后再算。
- """
- from app.models.crm_models import CrmContract, CrmContractProduct
- plan = (
- db.query(PlPlan)
- .filter(
- PlPlan.id == plan_id,
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- )
- .first()
- )
- if not plan:
- return [], []
- link_rows = (
- db.query(PlPlanContract)
- .filter(
- PlPlanContract.tenant_no == tenant_no,
- PlPlanContract.del_flag == 0,
- PlPlanContract.plan_id == plan_id,
- )
- .all()
- )
- contract_ids: Set[str] = set()
- for row in link_rows:
- cid = str(row.contract_id or "").strip()
- if cid:
- contract_ids.add(cid)
- legacy_cid = str(plan.contract_id or "").strip()
- if legacy_cid:
- contract_ids.add(legacy_cid)
- if not contract_ids:
- return [], []
- load_ids, delivery_ids, load_products_by_load, delivery_products_by_delivery = (
- _load_plan_stop_product_maps(db, tenant_no=tenant_no, plan_id=plan_id)
- )
- in_bucket = (
- _bucket_for_plan(
- archive_status=plan.archive_status,
- follow_status=plan.follow_status,
- transport_status=plan.transport_status,
- )
- is not None
- )
- violations: list[Dict[str, Any]] = []
- reminders: list[Dict[str, Any]] = []
- for cid in sorted(contract_ids):
- contract = (
- db.query(CrmContract)
- .filter(
- CrmContract.id == cid,
- CrmContract.tenant_no == tenant_no,
- CrmContract.del_flag == 0,
- )
- .first()
- )
- if not contract:
- continue
- scope = _plan_scope_for_contract(
- plan_id=plan_id,
- contract_id=cid,
- link_rows=link_rows,
- legacy_contract_id=legacy_cid,
- )
- plan_qtys = sum_qtys_for_scope(
- load_products_by_load=load_products_by_load,
- delivery_products_by_delivery=delivery_products_by_delivery,
- all_load_ids=load_ids,
- all_delivery_ids=delivery_ids,
- scope=scope,
- )
- if not plan_qtys:
- continue
- qty_map = aggregate_contract_product_plan_qtys(
- db, tenant_no=tenant_no, contract_id=cid
- )
- products = (
- db.query(CrmContractProduct)
- .filter(
- CrmContractProduct.contract_id == cid,
- CrmContractProduct.tenant_no == tenant_no,
- CrmContractProduct.del_flag == 0,
- )
- .all()
- )
- stop_kind = _stop_kind_from_scope(scope)
- contract_type = (contract.contract_type or "").strip()
- contract_no = contract.contract_no or ""
- customer_name = (contract.customer_name or "").strip()
- line_groups: Dict[str, Dict[str, Any]] = {}
- for key, new_qty_raw in plan_qtys.items():
- new_qty = _to_float(new_qty_raw)
- if new_qty <= 0:
- continue
- if not isinstance(key, tuple) or len(key) != 2:
- continue
- pid, pkg = key[0], key[1]
- cp = match_contract_product_for_key(products, key)
- # 计划产品不在合同明细:不校验数量(归属另有规则)
- if not cp:
- continue
- line_id = str(getattr(cp, "id", None) or "").strip()
- if not line_id:
- specs = contract_line_package_specs(cp)
- line_id = f"{pid}\0{'|'.join(specs)}"
- group = line_groups.get(line_id)
- if not group:
- group = {
- "cp": cp,
- "pid": pid,
- "pool_keys": pool_keys_for_contract_line(cp),
- "this_plan_qty": 0.0,
- "packages": [],
- }
- line_groups[line_id] = group
- group["this_plan_qty"] += new_qty
- if pkg:
- group["packages"].append(pkg)
- for group in line_groups.values():
- cp = group["cp"]
- pid = group["pid"]
- new_qty = group["this_plan_qty"]
- pkg_label = "、".join(dict.fromkeys(group["packages"])) or None
- pool_stats = sum_qty_stats_for_keys(qty_map, group["pool_keys"])
- arranged_total = pool_stats["arrangedTotalQty"]
- if in_bucket:
- old_qty = new_qty
- # arranged 已含当前库内量;effective = arranged - old + new = arranged
- else:
- old_qty = 0.0
- has_fixed = contract_product_has_fixed_qty(
- contract_type=contract_type,
- quantity=cp.quantity,
- quantity_mode=cp.quantity_mode,
- )
- evaluated = evaluate_product_qty_for_arrange(
- has_fixed_qty=has_fixed,
- contract_qty=_to_float(cp.quantity) if has_fixed else None,
- arranged_total=arranged_total,
- old_plan_qty=old_qty,
- new_plan_qty=new_qty,
- )
- if not evaluated:
- continue
- item = {
- "contractId": cid,
- "contractNo": contract_no,
- "contractType": contract_type,
- "customerName": customer_name,
- "stopKind": stop_kind,
- "productId": pid,
- "packageSpec": pkg_label,
- "packageSpecs": contract_line_package_specs(cp),
- "productName": cp.product_name or "",
- "model": (cp.model or "").strip() or None,
- "unit": (cp.unit or "").strip() or None,
- "thisPlanQty": evaluated.get("thisPlanQty", round(new_qty, 3)),
- "arrangedTotalQty": evaluated["arrangedTotalQty"],
- }
- kind = evaluated["kind"]
- if kind == "violation":
- violations.append(
- {
- **item,
- "contractQty": evaluated["contractQty"],
- "oldPlanQty": evaluated["oldPlanQty"],
- "newPlanQty": evaluated["newPlanQty"],
- "effectiveTotal": evaluated["effectiveTotal"],
- "overflowQty": evaluated["overflowQty"],
- # 与提醒表同列:剩余可为负,表示超量
- "remainingQty": round(
- evaluated["contractQty"] - evaluated["effectiveTotal"], 3
- ),
- }
- )
- elif kind == "remaining":
- reminders.append(
- {
- **item,
- "mode": "remaining",
- "contractQty": evaluated["contractQty"],
- "remainingQty": evaluated["remainingQty"],
- }
- )
- elif kind == "framework_cumulative":
- reminders.append(
- {
- **item,
- "mode": "framework_cumulative",
- }
- )
- return violations, reminders
- def assert_contract_qty_for_arrange(
- db: Session,
- *,
- tenant_no: str,
- plan_id: str,
- ) -> list[Dict[str, Any]]:
- """超限则 422;通过则返回 reminders(供成功响应复用)。"""
- from fastapi import HTTPException
- violations, reminders = collect_plan_contract_qty_checks(
- db, tenant_no=tenant_no, plan_id=plan_id
- )
- if violations:
- raise HTTPException(
- status_code=422,
- detail={
- "code": CONTRACT_QTY_VIOLATION_CODE,
- "message": "合同产品安排数量超过合同数量",
- "items": violations,
- },
- )
- return reminders
- def build_contract_qty_reminder_payload(
- reminders: list[Dict[str, Any]],
- ) -> Optional[Dict[str, Any]]:
- if not reminders:
- return None
- return {"items": reminders}
- def validate_stop_products_package_against_contract(
- *,
- contract_products: Iterable[Any],
- stop_products: Iterable[Any],
- ) -> tuple[bool, Optional[str]]:
- """
- 绑合同时:计划段产品包装必填,且必须属于本合同该产品的包装集合。
- 返回 (ok, error_message)。
- """
- allowed_by_pid: DefaultDict[str, Set[str]] = defaultdict(set)
- contract_pids: Set[str] = set()
- for row in contract_products or []:
- pid = ""
- if isinstance(row, dict):
- pid = str(row.get("productId") or row.get("product_id") or "").strip()
- else:
- pid = str(getattr(row, "product_id", None) or "").strip()
- if not pid:
- continue
- contract_pids.add(pid)
- for pkg in contract_line_package_specs(row):
- if pkg:
- allowed_by_pid[pid].add(pkg)
- for row in stop_products or []:
- pid = str(getattr(row, "product_id", None) or "").strip()
- if not pid or pid not in contract_pids:
- continue
- allowed = allowed_by_pid.get(pid) or set()
- if not allowed:
- continue
- pkg = normalize_package_spec(getattr(row, "package_spec", None))
- name = (
- str(getattr(row, "product_name", None) or "").strip()
- or pid
- )
- if not pkg:
- return False, f"请选择包装规格:{name}"
- if pkg not in allowed:
- return False, f"包装规格不在合同明细中:{name}({pkg})"
- return True, None
- def get_contract_product_arrange_qty_detail(
- db: Session,
- *,
- tenant_no: str,
- contract_id: str,
- product_id: str,
- package_spec: Optional[str] = None,
- exclude_plan_id: Optional[str] = None,
- ) -> Dict[str, Any]:
- """
- 表单「可安排数量」与问号弹窗数据。
- arrangedQty / availableQty 均不含 exclude_plan_id(若该计划已在已安排桶中)。
- """
- from app.models.crm_models import CrmContract, CrmContractProduct
- cid = (contract_id or "").strip()
- pid = (product_id or "").strip()
- pkg = normalize_package_spec(package_spec)
- key = product_package_key(pid, pkg)
- exclude_id = (exclude_plan_id or "").strip() or None
- empty = {
- "contractId": cid,
- "contractNo": None,
- "customerName": None,
- "productId": pid,
- "packageSpec": pkg or None,
- "packageSpecs": [],
- "packageBreakdown": [],
- "productName": None,
- "hasFixedQty": False,
- "contractQty": None,
- "arrangedQty": 0.0,
- "availableQty": None,
- "plans": [],
- }
- if not cid or not pid or not key:
- return empty
- contract = (
- db.query(CrmContract)
- .filter(
- CrmContract.id == cid,
- CrmContract.tenant_no == tenant_no,
- CrmContract.del_flag == 0,
- )
- .first()
- )
- if not contract:
- return empty
- candidates = (
- db.query(CrmContractProduct)
- .filter(
- CrmContractProduct.contract_id == cid,
- CrmContractProduct.product_id == pid,
- CrmContractProduct.tenant_no == tenant_no,
- CrmContractProduct.del_flag == 0,
- )
- .all()
- )
- cp = match_contract_product_for_key(candidates, key)
- contract_type = (contract.contract_type or "").strip()
- has_fixed = False
- contract_qty: Optional[float] = None
- package_specs: list[str] = []
- pool_keys: list[ProductPackageKey] = [key] if key else []
- if cp:
- package_specs = contract_line_package_specs(cp)
- pool_keys = pool_keys_for_contract_line(cp) or pool_keys
- has_fixed = contract_product_has_fixed_qty(
- contract_type=contract_type,
- quantity=cp.quantity,
- quantity_mode=cp.quantity_mode,
- )
- if has_fixed:
- contract_qty = round(_to_float(cp.quantity), 3)
- qty_map = aggregate_contract_product_plan_qtys(
- db, tenant_no=tenant_no, contract_id=cid
- )
- arranged_including = sum_qty_stats_for_keys(qty_map, pool_keys)["arrangedTotalQty"]
- package_breakdown = []
- for pool_key in pool_keys:
- stats = qty_map.get(pool_key) or {
- "archivedQty": 0.0,
- "arrangedUnarchivedQty": 0.0,
- "arrangedTotalQty": 0.0,
- }
- package_breakdown.append(
- {
- "packageSpec": pool_key[1],
- "archivedQty": stats["archivedQty"],
- "arrangedUnarchivedQty": stats["arrangedUnarchivedQty"],
- "arrangedTotalQty": stats["arrangedTotalQty"],
- }
- )
- link_rows = (
- db.query(PlPlanContract)
- .filter(
- PlPlanContract.tenant_no == tenant_no,
- PlPlanContract.del_flag == 0,
- PlPlanContract.contract_id == cid,
- )
- .all()
- )
- link_plan_ids = {str(r.plan_id) for r in link_rows if r.plan_id}
- legacy_plans = (
- db.query(PlPlan)
- .filter(
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- PlPlan.contract_id == cid,
- )
- .all()
- )
- legacy_only_ids = {p.id for p in legacy_plans if p.id not in link_plan_ids}
- scopes = resolve_linked_plan_scopes(link_rows, legacy_only_ids)
- plan_ids = list(scopes.keys())
- exclude_qty = 0.0
- plans_out: list[Dict[str, Any]] = []
- if plan_ids:
- plans = (
- db.query(PlPlan)
- .filter(
- PlPlan.tenant_no == tenant_no,
- PlPlan.del_flag == 0,
- PlPlan.id.in_(plan_ids),
- PlPlan.follow_status != "cancelled",
- )
- .all()
- )
- plan_by_id = {p.id: p for p in plans}
- loads = (
- db.query(PlPlanLoad)
- .filter(
- PlPlanLoad.tenant_no == tenant_no,
- PlPlanLoad.del_flag == 0,
- PlPlanLoad.plan_id.in_(plan_ids),
- )
- .all()
- )
- deliveries = (
- db.query(PlPlanDelivery)
- .filter(
- PlPlanDelivery.tenant_no == tenant_no,
- PlPlanDelivery.del_flag == 0,
- PlPlanDelivery.plan_id.in_(plan_ids),
- )
- .all()
- )
- load_ids_by_plan: DefaultDict[str, Set[str]] = defaultdict(set)
- delivery_ids_by_plan: DefaultDict[str, Set[str]] = defaultdict(set)
- for row in loads:
- load_ids_by_plan[row.plan_id].add(row.id)
- for row in deliveries:
- delivery_ids_by_plan[row.plan_id].add(row.id)
- all_load_ids = {row.id for row in loads}
- all_delivery_ids = {row.id for row in deliveries}
- load_products_by_load: DefaultDict[str, list] = defaultdict(list)
- if all_load_ids:
- for prod in (
- db.query(PlPlanLoadProduct)
- .filter(
- PlPlanLoadProduct.tenant_no == tenant_no,
- PlPlanLoadProduct.del_flag == 0,
- PlPlanLoadProduct.load_id.in_(all_load_ids),
- )
- .all()
- ):
- load_products_by_load[prod.load_id].append(prod)
- delivery_products_by_delivery: DefaultDict[str, list] = defaultdict(list)
- if all_delivery_ids:
- for prod in (
- db.query(PlPlanDeliveryProduct)
- .filter(
- PlPlanDeliveryProduct.tenant_no == tenant_no,
- PlPlanDeliveryProduct.del_flag == 0,
- PlPlanDeliveryProduct.delivery_id.in_(all_delivery_ids),
- )
- .all()
- ):
- delivery_products_by_delivery[prod.delivery_id].append(prod)
- for plan_id, scope in scopes.items():
- plan = plan_by_id.get(plan_id)
- if not plan:
- continue
- bucket = _bucket_for_plan(
- archive_status=plan.archive_status,
- follow_status=plan.follow_status,
- transport_status=plan.transport_status,
- )
- if not bucket:
- continue
- qty_mode = (
- QTY_MODE_ARCHIVE_ACTUAL if bucket == "archived" else QTY_MODE_PLAN
- )
- qtys = sum_qtys_for_scope(
- load_products_by_load=load_products_by_load,
- delivery_products_by_delivery=delivery_products_by_delivery,
- all_load_ids=load_ids_by_plan.get(plan_id, set()),
- all_delivery_ids=delivery_ids_by_plan.get(plan_id, set()),
- scope=scope,
- qty_mode=qty_mode,
- )
- pq = 0.0
- for pool_key in pool_keys:
- pq += _to_float(qtys.get(pool_key))
- if pq <= 0:
- continue
- if exclude_id and str(plan_id) == exclude_id:
- exclude_qty = pq
- continue
- plan_date = getattr(plan, "plan_date", None)
- plans_out.append(
- {
- "planId": plan_id,
- "planNo": plan.plan_no or "",
- "planDate": plan_date.isoformat() if plan_date else None,
- "planQty": round(pq, 3),
- "planType": getattr(plan, "plan_type", None),
- "belongsCompany": getattr(plan, "belongs_company", None),
- "supplierName": getattr(plan, "supplier_name", None),
- "customerName": getattr(plan, "customer_name", None),
- "licensePlate": getattr(plan, "license_plate", None),
- "driverName": getattr(plan, "driver_name", None),
- "followUserName": getattr(plan, "follow_user_name", None),
- "followStatus": plan.follow_status,
- "transportStatus": plan.transport_status,
- "archiveStatus": plan.archive_status,
- "createTime": plan.create_time.isoformat(sep=" ", timespec="seconds")
- if getattr(plan, "create_time", None)
- else None,
- }
- )
- plans_out.sort(key=lambda x: (x.get("planDate") or "", x.get("planNo") or ""), reverse=True)
- arranged_qty = round(max(0.0, arranged_including - exclude_qty), 3)
- available_qty = None
- if has_fixed and contract_qty is not None:
- available_qty = round(contract_qty - arranged_qty, 3)
- return {
- "contractId": cid,
- "contractNo": contract.contract_no or "",
- "customerName": (contract.customer_name or "").strip() or None,
- "productId": pid,
- "packageSpec": pkg or None,
- "packageSpecs": package_specs or ([pkg] if pkg else []),
- "packageBreakdown": package_breakdown,
- "productName": (cp.product_name if cp else None) or None,
- "hasFixedQty": has_fixed,
- "contractQty": contract_qty,
- "arrangedQty": arranged_qty,
- "availableQty": available_qty,
- "plans": plans_out,
- }
|