pl_plan_stop_service.py 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. """运输计划 · 装货/送货段读取与列表摘要。"""
  2. from __future__ import annotations
  3. from collections import defaultdict
  4. from datetime import date, datetime
  5. from decimal import Decimal
  6. from typing import Optional
  7. from fastapi import HTTPException
  8. from sqlalchemy.orm import Session
  9. from app.core.utils import generate_uuid
  10. from app.models.crm_models import CrmContractProduct
  11. from app.models.pl_models import (
  12. PlPlan,
  13. PlPlanContract,
  14. PlPlanDelivery,
  15. PlPlanDeliveryProduct,
  16. PlPlanLoad,
  17. PlPlanLoadProduct,
  18. PlTransportAddress,
  19. )
  20. from app.schemas.pl.plan import (
  21. PlanArchiveBrandQtyItem,
  22. PlanContractLink,
  23. PlanDeliveryBody,
  24. PlanDeliveryRead,
  25. PlanLoadBody,
  26. PlanLoadRead,
  27. PlanStopProductBody,
  28. PlanStopProductRead,
  29. )
  30. from app.services.pl_brand_archive import load_brand_qtys_by_stop_product_ids
  31. from app.services.pl_internal_customer import is_internal_customer_name
  32. from app.services.pl_plan_stop_rules import normalize_stop_dibang_fields, warn_qty_imbalance
  33. from app.services.pl_plan_service import (
  34. PLAN_CONTRACT_SIDE_DEMANDER,
  35. PLAN_CONTRACT_SIDE_SUPPLIER,
  36. assert_contract_selectable_for_plan,
  37. )
  38. from app.services.pl_product_display import load_crm_product_alias_maps, resolve_product_display_names
  39. PLAN_CONTRACT_SIDE_LOAD = "load"
  40. PLAN_CONTRACT_SIDE_DELIVERY = "delivery"
  41. def _contract_link(row: PlPlanContract) -> PlanContractLink:
  42. return PlanContractLink(
  43. contractId=row.contract_id,
  44. contractNo=row.contract_no,
  45. stopId=row.stop_id,
  46. )
  47. def _attach_stop_brand_qtys(
  48. product: PlanStopProductRead,
  49. brand_qtys_by_stop: dict[str, list[dict]],
  50. ) -> PlanStopProductRead:
  51. raw = brand_qtys_by_stop.get(product.id) or None
  52. if raw:
  53. product.brand_qtys = [PlanArchiveBrandQtyItem.model_validate(x) for x in raw]
  54. else:
  55. product.brand_qtys = None
  56. return product
  57. def _resolve_stop_list_product_name(
  58. *,
  59. saved_product_name: Optional[str],
  60. product_id: Optional[str],
  61. standard_by_id: dict[str, str],
  62. alias_options_by_id: dict[str, list[str]],
  63. ) -> str:
  64. """列表展示用:优先 CRM 标准名,不展示别名。"""
  65. display_name, _alias = resolve_product_display_names(
  66. saved_product_name=saved_product_name,
  67. product_id=product_id,
  68. standard_by_id=standard_by_id,
  69. alias_options_by_id=alias_options_by_id,
  70. )
  71. return display_name or (saved_product_name or "")
  72. def _apply_stop_list_product_name(
  73. product: PlanStopProductRead,
  74. *,
  75. standard_by_id: dict[str, str],
  76. alias_options_by_id: dict[str, list[str]],
  77. ) -> PlanStopProductRead:
  78. product.product_name = _resolve_stop_list_product_name(
  79. saved_product_name=product.product_name,
  80. product_id=product.product_id,
  81. standard_by_id=standard_by_id,
  82. alias_options_by_id=alias_options_by_id,
  83. )
  84. return product
  85. def _load_stop_product(
  86. row: PlPlanLoadProduct,
  87. brand_qtys_by_stop: dict[str, list[dict]] | None = None,
  88. *,
  89. standard_by_id: dict[str, str] | None = None,
  90. alias_options_by_id: dict[str, list[str]] | None = None,
  91. ) -> PlanStopProductRead:
  92. product = PlanStopProductRead.model_validate(row)
  93. if standard_by_id is not None and alias_options_by_id is not None:
  94. product = _apply_stop_list_product_name(
  95. product,
  96. standard_by_id=standard_by_id,
  97. alias_options_by_id=alias_options_by_id,
  98. )
  99. if brand_qtys_by_stop is not None:
  100. return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
  101. return product
  102. def _delivery_stop_product(
  103. row: PlPlanDeliveryProduct,
  104. brand_qtys_by_stop: dict[str, list[dict]] | None = None,
  105. *,
  106. standard_by_id: dict[str, str] | None = None,
  107. alias_options_by_id: dict[str, list[str]] | None = None,
  108. ) -> PlanStopProductRead:
  109. product = PlanStopProductRead.model_validate(row)
  110. if standard_by_id is not None and alias_options_by_id is not None:
  111. product = _apply_stop_list_product_name(
  112. product,
  113. standard_by_id=standard_by_id,
  114. alias_options_by_id=alias_options_by_id,
  115. )
  116. if brand_qtys_by_stop is not None:
  117. return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
  118. return product
  119. def load_stop_contract_rows_grouped(
  120. db: Session,
  121. tenant_no: str,
  122. plan_ids: list[str],
  123. ) -> dict[str, list[PlPlanContract]]:
  124. if not plan_ids:
  125. return {}
  126. rows = (
  127. db.query(PlPlanContract)
  128. .filter(
  129. PlPlanContract.tenant_no == tenant_no,
  130. PlPlanContract.plan_id.in_(plan_ids),
  131. PlPlanContract.del_flag == 0,
  132. )
  133. .order_by(PlPlanContract.order_num.asc(), PlPlanContract.create_time.asc())
  134. .all()
  135. )
  136. grouped: dict[str, list[PlPlanContract]] = defaultdict(list)
  137. for row in rows:
  138. grouped[row.plan_id].append(row)
  139. return grouped
  140. def _contracts_for_stop(
  141. contract_rows: list[PlPlanContract],
  142. stop_id: str,
  143. legacy_sides: tuple[str, ...],
  144. ) -> list[PlanContractLink]:
  145. by_stop = [_contract_link(r) for r in contract_rows if (r.stop_id or "") == stop_id]
  146. if by_stop:
  147. return by_stop
  148. return [
  149. _contract_link(r)
  150. for r in contract_rows
  151. if not (r.stop_id or "").strip() and r.side in legacy_sides
  152. ]
  153. def _to_decimal(value) -> Optional[Decimal]:
  154. if value is None or value == "":
  155. return None
  156. try:
  157. return Decimal(str(value))
  158. except Exception:
  159. return None
  160. def resolve_stop_address_from_library(
  161. db: Session,
  162. tenant_no: str,
  163. address: Optional[str],
  164. lng,
  165. lat,
  166. ) -> Optional[str]:
  167. """段 address 为空时,按经纬度从运输地址库补全 full_address。"""
  168. text = (address or "").strip()
  169. if text:
  170. return text
  171. lat_d = _to_decimal(lat)
  172. lng_d = _to_decimal(lng)
  173. if lat_d is None and lng_d is None:
  174. return text or None
  175. query = db.query(PlTransportAddress).filter(
  176. PlTransportAddress.tenant_no == tenant_no,
  177. PlTransportAddress.del_flag == 0,
  178. PlTransportAddress.status == "1",
  179. )
  180. if lat_d is not None:
  181. query = query.filter(PlTransportAddress.lat == lat_d)
  182. if lng_d is not None:
  183. query = query.filter(PlTransportAddress.lng == lng_d)
  184. rows = query.order_by(PlTransportAddress.create_time.desc()).all()
  185. if not rows:
  186. return text or None
  187. if len(rows) == 1:
  188. full = (rows[0].full_address or "").strip()
  189. return full or None
  190. if lng_d is not None:
  191. for row in rows:
  192. if row.lng == lng_d:
  193. full = (row.full_address or "").strip()
  194. if full:
  195. return full
  196. full = (rows[0].full_address or "").strip()
  197. return full or None
  198. def enrich_stop_addresses_from_library(
  199. db: Session,
  200. tenant_no: str,
  201. load: PlanLoadBody,
  202. deliveries: list[PlanDeliveryBody],
  203. ) -> None:
  204. resolved_load = resolve_stop_address_from_library(
  205. db, tenant_no, load.address, load.lng, load.lat
  206. )
  207. if resolved_load:
  208. load.address = resolved_load
  209. for delivery in deliveries:
  210. resolved = resolve_stop_address_from_library(
  211. db, tenant_no, delivery.address, delivery.lng, delivery.lat
  212. )
  213. if resolved:
  214. delivery.address = resolved
  215. def load_plan_stops_grouped(
  216. db: Session,
  217. tenant_no: str,
  218. plan_ids: list[str],
  219. ) -> dict[str, tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]]]:
  220. """批量读取装货段与送货段(列表/详情共用)。"""
  221. if not plan_ids:
  222. return {}
  223. loads = (
  224. db.query(PlPlanLoad)
  225. .filter(
  226. PlPlanLoad.tenant_no == tenant_no,
  227. PlPlanLoad.plan_id.in_(plan_ids),
  228. PlPlanLoad.del_flag == 0,
  229. )
  230. .all()
  231. )
  232. load_by_plan = {row.plan_id: row for row in loads}
  233. load_ids = [row.id for row in loads]
  234. load_products: dict[str, list[PlPlanLoadProduct]] = defaultdict(list)
  235. if load_ids:
  236. for row in (
  237. db.query(PlPlanLoadProduct)
  238. .filter(
  239. PlPlanLoadProduct.tenant_no == tenant_no,
  240. PlPlanLoadProduct.load_id.in_(load_ids),
  241. PlPlanLoadProduct.del_flag == 0,
  242. )
  243. .order_by(PlPlanLoadProduct.order_num.asc(), PlPlanLoadProduct.create_time.asc())
  244. .all()
  245. ):
  246. load_products[row.load_id].append(row)
  247. deliveries = (
  248. db.query(PlPlanDelivery)
  249. .filter(
  250. PlPlanDelivery.tenant_no == tenant_no,
  251. PlPlanDelivery.plan_id.in_(plan_ids),
  252. PlPlanDelivery.del_flag == 0,
  253. )
  254. .order_by(PlPlanDelivery.seq.asc(), PlPlanDelivery.create_time.asc())
  255. .all()
  256. )
  257. deliveries_by_plan: dict[str, list[PlPlanDelivery]] = defaultdict(list)
  258. delivery_ids: list[str] = []
  259. for row in deliveries:
  260. deliveries_by_plan[row.plan_id].append(row)
  261. delivery_ids.append(row.id)
  262. delivery_products: dict[str, list[PlPlanDeliveryProduct]] = defaultdict(list)
  263. if delivery_ids:
  264. for row in (
  265. db.query(PlPlanDeliveryProduct)
  266. .filter(
  267. PlPlanDeliveryProduct.tenant_no == tenant_no,
  268. PlPlanDeliveryProduct.delivery_id.in_(delivery_ids),
  269. PlPlanDeliveryProduct.del_flag == 0,
  270. )
  271. .order_by(PlPlanDeliveryProduct.order_num.asc(), PlPlanDeliveryProduct.create_time.asc())
  272. .all()
  273. ):
  274. delivery_products[row.delivery_id].append(row)
  275. stop_product_ids: list[str] = []
  276. crm_product_ids: set[str] = set()
  277. for rows in load_products.values():
  278. for p in rows:
  279. if p.id:
  280. stop_product_ids.append(p.id)
  281. if (p.product_id or "").strip():
  282. crm_product_ids.add(p.product_id.strip())
  283. for rows in delivery_products.values():
  284. for p in rows:
  285. if p.id:
  286. stop_product_ids.append(p.id)
  287. if (p.product_id or "").strip():
  288. crm_product_ids.add(p.product_id.strip())
  289. brand_qtys_by_stop = load_brand_qtys_by_stop_product_ids(
  290. db, tenant_no=tenant_no, stop_product_ids=stop_product_ids
  291. )
  292. standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
  293. db, tenant_no=tenant_no, product_ids=crm_product_ids
  294. )
  295. contracts_by_plan = load_stop_contract_rows_grouped(db, tenant_no, plan_ids)
  296. result: dict[str, tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]]] = {}
  297. for plan_id in plan_ids:
  298. contract_rows = contracts_by_plan.get(plan_id, [])
  299. load_row = load_by_plan.get(plan_id)
  300. load_read: Optional[PlanLoadRead] = None
  301. if load_row:
  302. load_read = PlanLoadRead.model_validate(load_row)
  303. resolved_load_address = resolve_stop_address_from_library(
  304. db,
  305. tenant_no,
  306. load_read.address,
  307. load_read.lng,
  308. load_read.lat,
  309. )
  310. if resolved_load_address:
  311. load_read.address = resolved_load_address
  312. load_read.products = [
  313. _load_stop_product(
  314. p,
  315. brand_qtys_by_stop,
  316. standard_by_id=standard_by_id,
  317. alias_options_by_id=alias_options_by_id,
  318. )
  319. for p in load_products.get(load_row.id, [])
  320. ]
  321. load_read.contracts = _contracts_for_stop(
  322. contract_rows,
  323. load_row.id,
  324. (PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_SUPPLIER),
  325. )
  326. delivery_reads: list[PlanDeliveryRead] = []
  327. plan_deliveries = deliveries_by_plan.get(plan_id, [])
  328. for idx, delivery_row in enumerate(plan_deliveries):
  329. delivery_read = PlanDeliveryRead.model_validate(delivery_row)
  330. resolved_delivery_address = resolve_stop_address_from_library(
  331. db,
  332. tenant_no,
  333. delivery_read.address,
  334. delivery_read.lng,
  335. delivery_read.lat,
  336. )
  337. if resolved_delivery_address:
  338. delivery_read.address = resolved_delivery_address
  339. delivery_read.products = [
  340. _delivery_stop_product(
  341. p,
  342. brand_qtys_by_stop,
  343. standard_by_id=standard_by_id,
  344. alias_options_by_id=alias_options_by_id,
  345. )
  346. for p in delivery_products.get(delivery_row.id, [])
  347. ]
  348. legacy_sides = (PLAN_CONTRACT_SIDE_DELIVERY, PLAN_CONTRACT_SIDE_DEMANDER)
  349. # 未迁移合同仅挂到第一个送货段
  350. if idx == 0:
  351. delivery_read.contracts = _contracts_for_stop(
  352. contract_rows,
  353. delivery_row.id,
  354. legacy_sides,
  355. )
  356. else:
  357. delivery_read.contracts = _contracts_for_stop(
  358. contract_rows,
  359. delivery_row.id,
  360. (PLAN_CONTRACT_SIDE_DELIVERY,),
  361. )
  362. delivery_reads.append(delivery_read)
  363. result[plan_id] = (load_read, delivery_reads)
  364. return result
  365. def resolve_load_customer_name(
  366. plan: PlPlan,
  367. load: Optional[PlanLoadRead],
  368. ) -> Optional[str]:
  369. if load and (load.customer_name or "").strip():
  370. return load.customer_name.strip()
  371. legacy = (plan.supplier_name or "").strip()
  372. return legacy or None
  373. def resolve_delivery_customer_summary(
  374. plan: PlPlan,
  375. deliveries: list[PlanDeliveryRead],
  376. ) -> Optional[str]:
  377. names: list[str] = []
  378. seen: set[str] = set()
  379. for delivery in deliveries:
  380. name = (delivery.customer_name or "").strip()
  381. if name and name not in seen:
  382. seen.add(name)
  383. names.append(name)
  384. if names:
  385. if len(names) <= 2:
  386. return "、".join(names)
  387. return f"{names[0]}、{names[1]}等{len(names)}家"
  388. legacy = (plan.customer_name or plan.destination_name or "").strip()
  389. return legacy or None
  390. def collect_unique_delivery_date_strings(deliveries) -> list[str]:
  391. """送货段 delivery_time → 去重升序 YYYY-MM-DD。"""
  392. days: set[date] = set()
  393. for row in deliveries or []:
  394. raw = getattr(row, "delivery_time", None)
  395. if raw is None or raw == "":
  396. continue
  397. if isinstance(raw, datetime):
  398. days.add(raw.date())
  399. elif isinstance(raw, date):
  400. days.add(raw)
  401. else:
  402. text = str(raw).strip()
  403. if not text:
  404. continue
  405. try:
  406. days.add(datetime.strptime(text[:10], "%Y-%m-%d").date())
  407. except ValueError:
  408. continue
  409. return [d.isoformat() for d in sorted(days)]
  410. def attach_plan_stops_to_item(
  411. plan_item,
  412. plan: PlPlan,
  413. stops: tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]],
  414. ) -> None:
  415. load_read, delivery_reads = stops
  416. plan_item.load = load_read
  417. plan_item.deliveries = delivery_reads
  418. plan_item.load_customer_name = resolve_load_customer_name(plan, load_read)
  419. plan_item.delivery_customer_summary = resolve_delivery_customer_summary(plan, delivery_reads)
  420. if load_read and (load_read.address or "").strip():
  421. plan_item.pickup_address = load_read.address
  422. if delivery_reads and (delivery_reads[0].address or "").strip():
  423. plan_item.destination_address = delivery_reads[0].address
  424. plan_item.delivery_times = collect_unique_delivery_date_strings(delivery_reads)
  425. def uses_multi_stop_payload(load: Optional[PlanLoadBody], deliveries: Optional[list[PlanDeliveryBody]]) -> bool:
  426. return load is not None or deliveries is not None
  427. def _normalize_contract_links(links: Optional[list[PlanContractLink]]) -> list[PlanContractLink]:
  428. if not links:
  429. return []
  430. seen: set[str] = set()
  431. out: list[PlanContractLink] = []
  432. for link in links:
  433. cid = (link.contract_id or "").strip()
  434. if not cid or cid in seen:
  435. continue
  436. seen.add(cid)
  437. out.append(link)
  438. return out
  439. def assert_at_most_one_contract(
  440. links: list[PlanContractLink],
  441. side_label: str,
  442. ) -> list[PlanContractLink]:
  443. if len(links) > 1:
  444. raise HTTPException(
  445. status_code=422,
  446. detail=f"{side_label}只能选择 1 份",
  447. )
  448. return links
  449. def _assert_product_rows_in_contract_allowed(
  450. products: Optional[list],
  451. allowed: set[str],
  452. *,
  453. row_label: str = "装货产品",
  454. ) -> None:
  455. for prod in products or []:
  456. pid = str(getattr(prod, "product_id", None) or "").strip()
  457. name = (getattr(prod, "product_name", None) or pid or "未命名").strip()
  458. if not pid or pid not in allowed:
  459. raise HTTPException(
  460. status_code=422,
  461. detail=f"{row_label}「{name}」不在所选合同明细中",
  462. )
  463. def _contract_product_rows(db: Session, tenant_no: str, contract_id: str) -> list:
  464. return (
  465. db.query(CrmContractProduct)
  466. .filter(
  467. CrmContractProduct.contract_id == contract_id,
  468. CrmContractProduct.tenant_no == tenant_no,
  469. CrmContractProduct.del_flag == 0,
  470. )
  471. .all()
  472. )
  473. def _contract_allowed_product_ids(db: Session, tenant_no: str, contract_id: str) -> set[str]:
  474. rows = _contract_product_rows(db, tenant_no, contract_id)
  475. return {
  476. str(r.product_id).strip()
  477. for r in rows
  478. if getattr(r, "product_id", None) and str(r.product_id).strip()
  479. }
  480. def _assert_stop_products_package_for_contract(
  481. db: Session,
  482. tenant_no: str,
  483. contract_id: str,
  484. stop_products: Optional[list],
  485. ) -> None:
  486. from app.services.pl_contract_plan_qty import (
  487. validate_stop_products_package_against_contract,
  488. )
  489. rows = _contract_product_rows(db, tenant_no, contract_id)
  490. ok, err = validate_stop_products_package_against_contract(
  491. contract_products=rows,
  492. stop_products=stop_products or [],
  493. )
  494. if not ok:
  495. raise HTTPException(status_code=422, detail=err or "包装规格不符合合同明细")
  496. def assert_load_products_in_selected_contract(
  497. db: Session,
  498. tenant_no: str,
  499. load: PlanLoadBody,
  500. plan_products: Optional[list] = None,
  501. ) -> None:
  502. if is_internal_customer_name(load.customer_name):
  503. return
  504. links = _normalize_contract_links(load.contracts)
  505. if not links:
  506. return
  507. contract_id = (links[0].contract_id or "").strip()
  508. if not contract_id:
  509. return
  510. allowed = _contract_allowed_product_ids(db, tenant_no, contract_id)
  511. _assert_product_rows_in_contract_allowed(load.products, allowed, row_label="装货产品")
  512. _assert_product_rows_in_contract_allowed(plan_products, allowed, row_label="装货产品")
  513. merged = list(load.products or []) + list(plan_products or [])
  514. _assert_stop_products_package_for_contract(db, tenant_no, contract_id, merged)
  515. def assert_delivery_products_in_selected_contract(
  516. db: Session,
  517. tenant_no: str,
  518. delivery: PlanDeliveryBody,
  519. seq: int,
  520. ) -> None:
  521. if is_internal_customer_name(delivery.customer_name):
  522. return
  523. links = _normalize_contract_links(delivery.contracts)
  524. if not links:
  525. return
  526. contract_id = (links[0].contract_id or "").strip()
  527. if not contract_id:
  528. return
  529. allowed = _contract_allowed_product_ids(db, tenant_no, contract_id)
  530. _assert_product_rows_in_contract_allowed(
  531. delivery.products,
  532. allowed,
  533. row_label=f"送货段#{seq}产品",
  534. )
  535. _assert_stop_products_package_for_contract(
  536. db, tenant_no, contract_id, delivery.products
  537. )
  538. def assert_stop_contract_required(
  539. customer_name: Optional[str],
  540. contracts: Optional[list[PlanContractLink]],
  541. side_label: str,
  542. ) -> None:
  543. """非内部客户装/送货段保存时必须至少选一份合同。"""
  544. if is_internal_customer_name(customer_name):
  545. return
  546. if not _normalize_contract_links(contracts):
  547. raise HTTPException(status_code=422, detail=f"请为{side_label}选择合同")
  548. def _resolve_stop_contracts(
  549. db: Session,
  550. tenant_no: str,
  551. customer_id: Optional[str],
  552. customer_name: Optional[str],
  553. contracts: Optional[list[PlanContractLink]],
  554. side_label: str,
  555. ) -> list[PlanContractLink]:
  556. if is_internal_customer_name(customer_name):
  557. return []
  558. links = _normalize_contract_links(contracts)
  559. links = assert_at_most_one_contract(links, side_label)
  560. if not links:
  561. return []
  562. resolved: list[PlanContractLink] = []
  563. for link in links:
  564. contract = assert_contract_selectable_for_plan(
  565. db,
  566. link.contract_id,
  567. tenant_no,
  568. expected_customer_id=customer_id,
  569. side_label=side_label,
  570. )
  571. resolved.append(
  572. PlanContractLink(
  573. contractId=contract.id,
  574. contractNo=contract.contract_no or link.contract_no,
  575. )
  576. )
  577. return resolved
  578. def validate_plan_stops_write(
  579. db: Session,
  580. tenant_no: str,
  581. load: Optional[PlanLoadBody],
  582. deliveries: Optional[list[PlanDeliveryBody]],
  583. products: Optional[list],
  584. ) -> tuple[PlanLoadBody, list[PlanDeliveryBody]]:
  585. if load is None:
  586. raise HTTPException(status_code=422, detail="请填写装货信息")
  587. if not (load.customer_id or "").strip() or not (load.customer_name or "").strip():
  588. raise HTTPException(status_code=422, detail="请选择装货客户")
  589. if not deliveries:
  590. raise HTTPException(status_code=422, detail="请至少添加一段送货信息")
  591. if products is not None and not products:
  592. raise HTTPException(status_code=422, detail="请至少保留一条产品明细")
  593. assert_stop_contract_required(load.customer_name, load.contracts, "装货客户")
  594. load.contracts = _resolve_stop_contracts(
  595. db,
  596. tenant_no,
  597. load.customer_id,
  598. load.customer_name,
  599. load.contracts,
  600. "装货合同",
  601. )
  602. resolved_deliveries: list[PlanDeliveryBody] = []
  603. for idx, delivery in enumerate(deliveries, start=1):
  604. if not (delivery.customer_id or "").strip() or not (delivery.customer_name or "").strip():
  605. raise HTTPException(status_code=422, detail=f"送货段#{idx}请选择客户")
  606. assert_stop_contract_required(delivery.customer_name, delivery.contracts, f"送货段#{idx}")
  607. delivery.contracts = _resolve_stop_contracts(
  608. db,
  609. tenant_no,
  610. delivery.customer_id,
  611. delivery.customer_name,
  612. delivery.contracts,
  613. f"送货段#{idx}合同",
  614. )
  615. resolved_deliveries.append(delivery)
  616. enrich_stop_addresses_from_library(db, tenant_no, load, resolved_deliveries)
  617. assert_load_products_in_selected_contract(db, tenant_no, load, plan_products=products)
  618. for idx, delivery in enumerate(resolved_deliveries, start=1):
  619. assert_delivery_products_in_selected_contract(db, tenant_no, delivery, idx)
  620. return load, resolved_deliveries
  621. def collect_stop_qty_warnings(
  622. products: Optional[list],
  623. load: PlanLoadBody,
  624. deliveries: list[PlanDeliveryBody],
  625. ) -> list[str]:
  626. plan_rows = products or []
  627. load_rows = load.products or []
  628. delivery_rows: list[PlanStopProductBody] = []
  629. for delivery in deliveries:
  630. delivery_rows.extend(delivery.products or [])
  631. return warn_qty_imbalance(plan_rows, load_rows, delivery_rows)
  632. def sync_plan_legacy_from_stops(
  633. plan: PlPlan,
  634. load: PlanLoadBody,
  635. deliveries: list[PlanDeliveryBody],
  636. ) -> None:
  637. plan.supplier_id = load.customer_id
  638. plan.supplier_name = load.customer_name
  639. plan.pickup_address = load.address
  640. plan.pickup_lng = load.lng
  641. plan.pickup_lat = load.lat
  642. plan.pickup_time = load.load_time
  643. plan.pickup_contact = load.contact
  644. plan.pickup_notes = load.notes
  645. first = deliveries[0]
  646. plan.customer_id = first.customer_id
  647. plan.customer_name = first.customer_name
  648. plan.destination_id = first.customer_id
  649. plan.destination_name = first.customer_name
  650. plan.destination_address = first.address
  651. plan.destination_lng = first.lng
  652. plan.destination_lat = first.lat
  653. plan.delivery_time = first.delivery_time
  654. plan.delivery_contact = first.contact
  655. plan.destination_notes = first.notes
  656. def _soft_delete_load_products_and_stop_contracts(
  657. db: Session,
  658. tenant_no: str,
  659. plan_id: str,
  660. user_id: Optional[str],
  661. ) -> None:
  662. """软删装货产品与装/送货段合同;送货段本体由 upsert 保留主键,不在此全量软删。"""
  663. now = datetime.now()
  664. load_ids = [
  665. row.id
  666. for row in db.query(PlPlanLoad)
  667. .filter(
  668. PlPlanLoad.plan_id == plan_id,
  669. PlPlanLoad.tenant_no == tenant_no,
  670. PlPlanLoad.del_flag == 0,
  671. )
  672. .all()
  673. ]
  674. if load_ids:
  675. db.query(PlPlanLoadProduct).filter(
  676. PlPlanLoadProduct.load_id.in_(load_ids),
  677. PlPlanLoadProduct.del_flag == 0,
  678. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  679. db.query(PlPlanContract).filter(
  680. PlPlanContract.plan_id == plan_id,
  681. PlPlanContract.tenant_no == tenant_no,
  682. PlPlanContract.del_flag == 0,
  683. PlPlanContract.side.in_(
  684. [PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_DELIVERY]
  685. ),
  686. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  687. def _soft_delete_delivery_products(
  688. db: Session,
  689. delivery_ids: list[str],
  690. user_id: Optional[str],
  691. now: datetime,
  692. ) -> None:
  693. if not delivery_ids:
  694. return
  695. db.query(PlPlanDeliveryProduct).filter(
  696. PlPlanDeliveryProduct.delivery_id.in_(delivery_ids),
  697. PlPlanDeliveryProduct.del_flag == 0,
  698. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  699. def resolve_delivery_id_for_upsert(
  700. *,
  701. plan_id: str,
  702. payload_id: Optional[str],
  703. existing_by_id: dict,
  704. ) -> tuple[str, Optional[object]]:
  705. pid = (payload_id or "").strip()
  706. if not pid:
  707. return generate_uuid(), None
  708. row = existing_by_id.get(pid)
  709. if row is None or getattr(row, "plan_id", None) != plan_id:
  710. raise HTTPException(status_code=422, detail=f"送货段 id 无效或不属于本计划:{pid}")
  711. return pid, row
  712. def _write_stop_contracts(
  713. db: Session,
  714. tenant_no: str,
  715. plan_id: str,
  716. stop_id: str,
  717. side: str,
  718. contracts: list[PlanContractLink],
  719. user_id: Optional[str],
  720. dept_id: Optional[str],
  721. order_num_start: int,
  722. ) -> int:
  723. now = datetime.now()
  724. order_num = order_num_start
  725. for link in contracts:
  726. order_num += 1
  727. db.add(
  728. PlPlanContract(
  729. id=generate_uuid(),
  730. plan_id=plan_id,
  731. side=side,
  732. stop_id=stop_id,
  733. contract_id=link.contract_id,
  734. contract_no=link.contract_no,
  735. tenant_no=tenant_no,
  736. order_num=order_num,
  737. create_by=user_id,
  738. create_dept_id=dept_id or "",
  739. create_time=now,
  740. update_by=user_id,
  741. update_time=now,
  742. del_flag=0,
  743. )
  744. )
  745. return order_num
  746. def _resolve_plan_product_id(
  747. prod: PlanStopProductBody,
  748. plan_products: list,
  749. ) -> str:
  750. explicit = (prod.plan_product_id or "").strip()
  751. if explicit:
  752. for row in plan_products:
  753. if row.id == explicit:
  754. return explicit
  755. product_id = (prod.product_id or "").strip()
  756. if product_id:
  757. for row in plan_products:
  758. if (row.product_id or "").strip() == product_id:
  759. return row.id
  760. product_no = (prod.product_no or "").strip()
  761. if product_no:
  762. for row in plan_products:
  763. if (row.product_no or "").strip() == product_no:
  764. return row.id
  765. raise HTTPException(
  766. status_code=422,
  767. detail=f"无法匹配计划产品行:{prod.product_name or explicit or product_id}",
  768. )
  769. def _resolve_or_create_plan_load(
  770. db: Session,
  771. tenant_no: str,
  772. plan_id: str,
  773. load: PlanLoadBody,
  774. user_id: Optional[str],
  775. dept_id: Optional[str],
  776. now: datetime,
  777. ) -> str:
  778. """装货段与 plan 1:1;uk_pl_plan_load_plan 仅按 plan_id 唯一,软删后不可再 INSERT,须原地更新。"""
  779. generate_dibang, dibang_direction = normalize_stop_dibang_fields(
  780. load.customer_name,
  781. "load",
  782. load.generate_dibang,
  783. load.dibang_direction,
  784. )
  785. existing = (
  786. db.query(PlPlanLoad)
  787. .filter(
  788. PlPlanLoad.plan_id == plan_id,
  789. PlPlanLoad.tenant_no == tenant_no,
  790. )
  791. .order_by(PlPlanLoad.del_flag.asc(), PlPlanLoad.update_time.desc())
  792. .first()
  793. )
  794. if existing:
  795. existing.customer_id = load.customer_id
  796. existing.customer_name = load.customer_name
  797. existing.address = load.address
  798. existing.lng = load.lng
  799. existing.lat = load.lat
  800. existing.load_time = load.load_time
  801. existing.contact = load.contact
  802. existing.notes = load.notes
  803. existing.generate_dibang = generate_dibang
  804. existing.dibang_direction = dibang_direction
  805. existing.remark = load.remark
  806. existing.del_flag = 0
  807. existing.update_by = user_id
  808. existing.update_time = now
  809. return existing.id
  810. load_id = generate_uuid()
  811. db.add(
  812. PlPlanLoad(
  813. id=load_id,
  814. plan_id=plan_id,
  815. customer_id=load.customer_id,
  816. customer_name=load.customer_name,
  817. address=load.address,
  818. lng=load.lng,
  819. lat=load.lat,
  820. load_time=load.load_time,
  821. contact=load.contact,
  822. notes=load.notes,
  823. generate_dibang=generate_dibang,
  824. dibang_direction=dibang_direction,
  825. tenant_no=tenant_no,
  826. remark=load.remark,
  827. create_by=user_id,
  828. create_dept_id=dept_id or "",
  829. create_time=now,
  830. update_by=user_id,
  831. update_time=now,
  832. del_flag=0,
  833. )
  834. )
  835. return load_id
  836. def replace_plan_stops(
  837. db: Session,
  838. tenant_no: str,
  839. plan_id: str,
  840. load: PlanLoadBody,
  841. deliveries: list[PlanDeliveryBody],
  842. user_id: Optional[str],
  843. dept_id: Optional[str],
  844. plan_products: Optional[list] = None,
  845. ) -> None:
  846. _soft_delete_load_products_and_stop_contracts(db, tenant_no, plan_id, user_id)
  847. now = datetime.now()
  848. load_id = _resolve_or_create_plan_load(
  849. db,
  850. tenant_no,
  851. plan_id,
  852. load,
  853. user_id,
  854. dept_id,
  855. now,
  856. )
  857. plan_product_rows = plan_products or []
  858. for idx, prod in enumerate(load.products or []):
  859. plan_product_id = _resolve_plan_product_id(prod, plan_product_rows)
  860. db.add(
  861. PlPlanLoadProduct(
  862. id=generate_uuid(),
  863. load_id=load_id,
  864. plan_id=plan_id,
  865. plan_product_id=plan_product_id,
  866. product_id=prod.product_id,
  867. product_no=prod.product_no,
  868. product_name=prod.product_name,
  869. model=prod.model,
  870. unit=prod.unit or "吨",
  871. package_spec=prod.package_spec,
  872. delivery_method=prod.delivery_method,
  873. plan_qty=prod.plan_qty,
  874. tenant_no=tenant_no,
  875. order_num=idx,
  876. remark=prod.remark,
  877. create_by=user_id,
  878. create_dept_id=dept_id or "",
  879. create_time=now,
  880. update_by=user_id,
  881. update_time=now,
  882. del_flag=0,
  883. )
  884. )
  885. contract_order = 0
  886. contract_order = _write_stop_contracts(
  887. db,
  888. tenant_no,
  889. plan_id,
  890. load_id,
  891. PLAN_CONTRACT_SIDE_LOAD,
  892. load.contracts or [],
  893. user_id,
  894. dept_id,
  895. contract_order,
  896. )
  897. existing_deliveries = (
  898. db.query(PlPlanDelivery)
  899. .filter(
  900. PlPlanDelivery.plan_id == plan_id,
  901. PlPlanDelivery.tenant_no == tenant_no,
  902. )
  903. .all()
  904. )
  905. existing_by_id = {row.id: row for row in existing_deliveries}
  906. kept_ids: set[str] = set()
  907. for delivery in deliveries:
  908. generate_dibang, dibang_direction = normalize_stop_dibang_fields(
  909. delivery.customer_name,
  910. "delivery",
  911. delivery.generate_dibang,
  912. delivery.dibang_direction,
  913. )
  914. delivery_id, existing = resolve_delivery_id_for_upsert(
  915. plan_id=plan_id,
  916. payload_id=delivery.id,
  917. existing_by_id=existing_by_id,
  918. )
  919. kept_ids.add(delivery_id)
  920. if existing is not None:
  921. existing.seq = delivery.seq or 1
  922. existing.customer_id = delivery.customer_id
  923. existing.customer_name = delivery.customer_name
  924. existing.address = delivery.address
  925. existing.lng = delivery.lng
  926. existing.lat = delivery.lat
  927. existing.delivery_time = delivery.delivery_time
  928. existing.contact = delivery.contact
  929. existing.notes = delivery.notes
  930. existing.generate_dibang = generate_dibang
  931. existing.dibang_direction = dibang_direction
  932. existing.remark = delivery.remark
  933. existing.del_flag = 0
  934. existing.update_by = user_id
  935. existing.update_time = now
  936. else:
  937. db.add(
  938. PlPlanDelivery(
  939. id=delivery_id,
  940. plan_id=plan_id,
  941. seq=delivery.seq or 1,
  942. customer_id=delivery.customer_id,
  943. customer_name=delivery.customer_name,
  944. address=delivery.address,
  945. lng=delivery.lng,
  946. lat=delivery.lat,
  947. delivery_time=delivery.delivery_time,
  948. contact=delivery.contact,
  949. notes=delivery.notes,
  950. generate_dibang=generate_dibang,
  951. dibang_direction=dibang_direction,
  952. tenant_no=tenant_no,
  953. remark=delivery.remark,
  954. create_by=user_id,
  955. create_dept_id=dept_id or "",
  956. create_time=now,
  957. update_by=user_id,
  958. update_time=now,
  959. del_flag=0,
  960. )
  961. )
  962. _soft_delete_delivery_products(db, [delivery_id], user_id, now)
  963. for idx, prod in enumerate(delivery.products or []):
  964. plan_product_id = _resolve_plan_product_id(prod, plan_product_rows)
  965. db.add(
  966. PlPlanDeliveryProduct(
  967. id=generate_uuid(),
  968. delivery_id=delivery_id,
  969. plan_id=plan_id,
  970. plan_product_id=plan_product_id,
  971. product_id=prod.product_id,
  972. product_no=prod.product_no,
  973. product_name=prod.product_name,
  974. model=prod.model,
  975. unit=prod.unit or "吨",
  976. package_spec=prod.package_spec,
  977. delivery_method=prod.delivery_method,
  978. plan_qty=prod.plan_qty,
  979. tenant_no=tenant_no,
  980. order_num=idx,
  981. remark=prod.remark,
  982. create_by=user_id,
  983. create_dept_id=dept_id or "",
  984. create_time=now,
  985. update_by=user_id,
  986. update_time=now,
  987. del_flag=0,
  988. )
  989. )
  990. contract_order = _write_stop_contracts(
  991. db,
  992. tenant_no,
  993. plan_id,
  994. delivery_id,
  995. PLAN_CONTRACT_SIDE_DELIVERY,
  996. delivery.contracts or [],
  997. user_id,
  998. dept_id,
  999. contract_order,
  1000. )
  1001. removed_ids = [row.id for row in existing_deliveries if row.id not in kept_ids and row.del_flag == 0]
  1002. if removed_ids:
  1003. _soft_delete_delivery_products(db, removed_ids, user_id, now)
  1004. db.query(PlPlanDelivery).filter(
  1005. PlPlanDelivery.id.in_(removed_ids),
  1006. PlPlanDelivery.tenant_no == tenant_no,
  1007. PlPlanDelivery.del_flag == 0,
  1008. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)