pl_plan_stop_service.py 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. """运输计划 · 装货/送货段读取与列表摘要。"""
  2. from __future__ import annotations
  3. from collections import defaultdict
  4. from datetime import 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 attach_plan_stops_to_item(
  391. plan_item,
  392. plan: PlPlan,
  393. stops: tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]],
  394. ) -> None:
  395. load_read, delivery_reads = stops
  396. plan_item.load = load_read
  397. plan_item.deliveries = delivery_reads
  398. plan_item.load_customer_name = resolve_load_customer_name(plan, load_read)
  399. plan_item.delivery_customer_summary = resolve_delivery_customer_summary(plan, delivery_reads)
  400. if load_read and (load_read.address or "").strip():
  401. plan_item.pickup_address = load_read.address
  402. if delivery_reads and (delivery_reads[0].address or "").strip():
  403. plan_item.destination_address = delivery_reads[0].address
  404. def uses_multi_stop_payload(load: Optional[PlanLoadBody], deliveries: Optional[list[PlanDeliveryBody]]) -> bool:
  405. return load is not None or deliveries is not None
  406. def _normalize_contract_links(links: Optional[list[PlanContractLink]]) -> list[PlanContractLink]:
  407. if not links:
  408. return []
  409. seen: set[str] = set()
  410. out: list[PlanContractLink] = []
  411. for link in links:
  412. cid = (link.contract_id or "").strip()
  413. if not cid or cid in seen:
  414. continue
  415. seen.add(cid)
  416. out.append(link)
  417. return out
  418. def assert_at_most_one_contract(
  419. links: list[PlanContractLink],
  420. side_label: str,
  421. ) -> list[PlanContractLink]:
  422. if len(links) > 1:
  423. raise HTTPException(
  424. status_code=422,
  425. detail=f"{side_label}只能选择 1 份",
  426. )
  427. return links
  428. def _assert_product_rows_in_contract_allowed(
  429. products: Optional[list],
  430. allowed: set[str],
  431. *,
  432. row_label: str = "装货产品",
  433. ) -> None:
  434. for prod in products or []:
  435. pid = str(getattr(prod, "product_id", None) or "").strip()
  436. name = (getattr(prod, "product_name", None) or pid or "未命名").strip()
  437. if not pid or pid not in allowed:
  438. raise HTTPException(
  439. status_code=422,
  440. detail=f"{row_label}「{name}」不在所选合同明细中",
  441. )
  442. def _contract_allowed_product_ids(db: Session, tenant_no: str, contract_id: str) -> set[str]:
  443. rows = (
  444. db.query(CrmContractProduct)
  445. .filter(
  446. CrmContractProduct.contract_id == contract_id,
  447. CrmContractProduct.tenant_no == tenant_no,
  448. CrmContractProduct.del_flag == 0,
  449. )
  450. .all()
  451. )
  452. return {
  453. str(r.product_id).strip()
  454. for r in rows
  455. if getattr(r, "product_id", None) and str(r.product_id).strip()
  456. }
  457. def assert_load_products_in_selected_contract(
  458. db: Session,
  459. tenant_no: str,
  460. load: PlanLoadBody,
  461. plan_products: Optional[list] = None,
  462. ) -> None:
  463. if is_internal_customer_name(load.customer_name):
  464. return
  465. links = _normalize_contract_links(load.contracts)
  466. if not links:
  467. return
  468. contract_id = (links[0].contract_id or "").strip()
  469. if not contract_id:
  470. return
  471. allowed = _contract_allowed_product_ids(db, tenant_no, contract_id)
  472. _assert_product_rows_in_contract_allowed(load.products, allowed, row_label="装货产品")
  473. _assert_product_rows_in_contract_allowed(plan_products, allowed, row_label="装货产品")
  474. def assert_delivery_products_in_selected_contract(
  475. db: Session,
  476. tenant_no: str,
  477. delivery: PlanDeliveryBody,
  478. seq: int,
  479. ) -> None:
  480. if is_internal_customer_name(delivery.customer_name):
  481. return
  482. links = _normalize_contract_links(delivery.contracts)
  483. if not links:
  484. return
  485. contract_id = (links[0].contract_id or "").strip()
  486. if not contract_id:
  487. return
  488. allowed = _contract_allowed_product_ids(db, tenant_no, contract_id)
  489. _assert_product_rows_in_contract_allowed(
  490. delivery.products,
  491. allowed,
  492. row_label=f"送货段#{seq}产品",
  493. )
  494. def assert_stop_contract_required(
  495. customer_name: Optional[str],
  496. contracts: Optional[list[PlanContractLink]],
  497. side_label: str,
  498. ) -> None:
  499. """非内部客户装/送货段保存时必须至少选一份合同。"""
  500. if is_internal_customer_name(customer_name):
  501. return
  502. if not _normalize_contract_links(contracts):
  503. raise HTTPException(status_code=422, detail=f"请为{side_label}选择合同")
  504. def _resolve_stop_contracts(
  505. db: Session,
  506. tenant_no: str,
  507. customer_id: Optional[str],
  508. customer_name: Optional[str],
  509. contracts: Optional[list[PlanContractLink]],
  510. side_label: str,
  511. ) -> list[PlanContractLink]:
  512. if is_internal_customer_name(customer_name):
  513. return []
  514. links = _normalize_contract_links(contracts)
  515. links = assert_at_most_one_contract(links, side_label)
  516. if not links:
  517. return []
  518. resolved: list[PlanContractLink] = []
  519. for link in links:
  520. contract = assert_contract_selectable_for_plan(
  521. db,
  522. link.contract_id,
  523. tenant_no,
  524. expected_customer_id=customer_id,
  525. side_label=side_label,
  526. )
  527. resolved.append(
  528. PlanContractLink(
  529. contractId=contract.id,
  530. contractNo=contract.contract_no or link.contract_no,
  531. )
  532. )
  533. return resolved
  534. def validate_plan_stops_write(
  535. db: Session,
  536. tenant_no: str,
  537. load: Optional[PlanLoadBody],
  538. deliveries: Optional[list[PlanDeliveryBody]],
  539. products: Optional[list],
  540. ) -> tuple[PlanLoadBody, list[PlanDeliveryBody]]:
  541. if load is None:
  542. raise HTTPException(status_code=422, detail="请填写装货信息")
  543. if not (load.customer_id or "").strip() or not (load.customer_name or "").strip():
  544. raise HTTPException(status_code=422, detail="请选择装货客户")
  545. if not deliveries:
  546. raise HTTPException(status_code=422, detail="请至少添加一段送货信息")
  547. if products is not None and not products:
  548. raise HTTPException(status_code=422, detail="请至少保留一条产品明细")
  549. assert_stop_contract_required(load.customer_name, load.contracts, "装货客户")
  550. load.contracts = _resolve_stop_contracts(
  551. db,
  552. tenant_no,
  553. load.customer_id,
  554. load.customer_name,
  555. load.contracts,
  556. "装货合同",
  557. )
  558. resolved_deliveries: list[PlanDeliveryBody] = []
  559. for idx, delivery in enumerate(deliveries, start=1):
  560. if not (delivery.customer_id or "").strip() or not (delivery.customer_name or "").strip():
  561. raise HTTPException(status_code=422, detail=f"送货段#{idx}请选择客户")
  562. assert_stop_contract_required(delivery.customer_name, delivery.contracts, f"送货段#{idx}")
  563. delivery.contracts = _resolve_stop_contracts(
  564. db,
  565. tenant_no,
  566. delivery.customer_id,
  567. delivery.customer_name,
  568. delivery.contracts,
  569. f"送货段#{idx}合同",
  570. )
  571. resolved_deliveries.append(delivery)
  572. enrich_stop_addresses_from_library(db, tenant_no, load, resolved_deliveries)
  573. assert_load_products_in_selected_contract(db, tenant_no, load, plan_products=products)
  574. for idx, delivery in enumerate(resolved_deliveries, start=1):
  575. assert_delivery_products_in_selected_contract(db, tenant_no, delivery, idx)
  576. return load, resolved_deliveries
  577. def collect_stop_qty_warnings(
  578. products: Optional[list],
  579. load: PlanLoadBody,
  580. deliveries: list[PlanDeliveryBody],
  581. ) -> list[str]:
  582. plan_rows = products or []
  583. load_rows = load.products or []
  584. delivery_rows: list[PlanStopProductBody] = []
  585. for delivery in deliveries:
  586. delivery_rows.extend(delivery.products or [])
  587. return warn_qty_imbalance(plan_rows, load_rows, delivery_rows)
  588. def sync_plan_legacy_from_stops(
  589. plan: PlPlan,
  590. load: PlanLoadBody,
  591. deliveries: list[PlanDeliveryBody],
  592. ) -> None:
  593. plan.supplier_id = load.customer_id
  594. plan.supplier_name = load.customer_name
  595. plan.pickup_address = load.address
  596. plan.pickup_lng = load.lng
  597. plan.pickup_lat = load.lat
  598. plan.pickup_time = load.load_time
  599. plan.pickup_contact = load.contact
  600. plan.pickup_notes = load.notes
  601. first = deliveries[0]
  602. plan.customer_id = first.customer_id
  603. plan.customer_name = first.customer_name
  604. plan.destination_id = first.customer_id
  605. plan.destination_name = first.customer_name
  606. plan.destination_address = first.address
  607. plan.destination_lng = first.lng
  608. plan.destination_lat = first.lat
  609. plan.delivery_time = first.delivery_time
  610. plan.delivery_contact = first.contact
  611. plan.destination_notes = first.notes
  612. def _soft_delete_plan_stops(
  613. db: Session,
  614. tenant_no: str,
  615. plan_id: str,
  616. user_id: Optional[str],
  617. ) -> None:
  618. now = datetime.now()
  619. load_ids = [
  620. row.id
  621. for row in db.query(PlPlanLoad)
  622. .filter(
  623. PlPlanLoad.plan_id == plan_id,
  624. PlPlanLoad.tenant_no == tenant_no,
  625. PlPlanLoad.del_flag == 0,
  626. )
  627. .all()
  628. ]
  629. if load_ids:
  630. db.query(PlPlanLoadProduct).filter(
  631. PlPlanLoadProduct.load_id.in_(load_ids),
  632. PlPlanLoadProduct.del_flag == 0,
  633. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  634. delivery_ids = [
  635. row.id
  636. for row in db.query(PlPlanDelivery)
  637. .filter(
  638. PlPlanDelivery.plan_id == plan_id,
  639. PlPlanDelivery.tenant_no == tenant_no,
  640. PlPlanDelivery.del_flag == 0,
  641. )
  642. .all()
  643. ]
  644. if delivery_ids:
  645. db.query(PlPlanDeliveryProduct).filter(
  646. PlPlanDeliveryProduct.delivery_id.in_(delivery_ids),
  647. PlPlanDeliveryProduct.del_flag == 0,
  648. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  649. db.query(PlPlanDelivery).filter(
  650. PlPlanDelivery.plan_id == plan_id,
  651. PlPlanDelivery.tenant_no == tenant_no,
  652. PlPlanDelivery.del_flag == 0,
  653. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  654. db.query(PlPlanContract).filter(
  655. PlPlanContract.plan_id == plan_id,
  656. PlPlanContract.tenant_no == tenant_no,
  657. PlPlanContract.del_flag == 0,
  658. PlPlanContract.side.in_(
  659. [PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_DELIVERY]
  660. ),
  661. ).update({"del_flag": 1, "update_by": user_id, "update_time": now}, synchronize_session=False)
  662. def _write_stop_contracts(
  663. db: Session,
  664. tenant_no: str,
  665. plan_id: str,
  666. stop_id: str,
  667. side: str,
  668. contracts: list[PlanContractLink],
  669. user_id: Optional[str],
  670. dept_id: Optional[str],
  671. order_num_start: int,
  672. ) -> int:
  673. now = datetime.now()
  674. order_num = order_num_start
  675. for link in contracts:
  676. order_num += 1
  677. db.add(
  678. PlPlanContract(
  679. id=generate_uuid(),
  680. plan_id=plan_id,
  681. side=side,
  682. stop_id=stop_id,
  683. contract_id=link.contract_id,
  684. contract_no=link.contract_no,
  685. tenant_no=tenant_no,
  686. order_num=order_num,
  687. create_by=user_id,
  688. create_dept_id=dept_id or "",
  689. create_time=now,
  690. update_by=user_id,
  691. update_time=now,
  692. del_flag=0,
  693. )
  694. )
  695. return order_num
  696. def _resolve_plan_product_id(
  697. prod: PlanStopProductBody,
  698. plan_products: list,
  699. ) -> str:
  700. explicit = (prod.plan_product_id or "").strip()
  701. if explicit:
  702. for row in plan_products:
  703. if row.id == explicit:
  704. return explicit
  705. product_id = (prod.product_id or "").strip()
  706. if product_id:
  707. for row in plan_products:
  708. if (row.product_id or "").strip() == product_id:
  709. return row.id
  710. product_no = (prod.product_no or "").strip()
  711. if product_no:
  712. for row in plan_products:
  713. if (row.product_no or "").strip() == product_no:
  714. return row.id
  715. raise HTTPException(
  716. status_code=422,
  717. detail=f"无法匹配计划产品行:{prod.product_name or explicit or product_id}",
  718. )
  719. def _resolve_or_create_plan_load(
  720. db: Session,
  721. tenant_no: str,
  722. plan_id: str,
  723. load: PlanLoadBody,
  724. user_id: Optional[str],
  725. dept_id: Optional[str],
  726. now: datetime,
  727. ) -> str:
  728. """装货段与 plan 1:1;uk_pl_plan_load_plan 仅按 plan_id 唯一,软删后不可再 INSERT,须原地更新。"""
  729. generate_dibang, dibang_direction = normalize_stop_dibang_fields(
  730. load.customer_name,
  731. "load",
  732. load.generate_dibang,
  733. load.dibang_direction,
  734. )
  735. existing = (
  736. db.query(PlPlanLoad)
  737. .filter(
  738. PlPlanLoad.plan_id == plan_id,
  739. PlPlanLoad.tenant_no == tenant_no,
  740. )
  741. .order_by(PlPlanLoad.del_flag.asc(), PlPlanLoad.update_time.desc())
  742. .first()
  743. )
  744. if existing:
  745. existing.customer_id = load.customer_id
  746. existing.customer_name = load.customer_name
  747. existing.address = load.address
  748. existing.lng = load.lng
  749. existing.lat = load.lat
  750. existing.load_time = load.load_time
  751. existing.contact = load.contact
  752. existing.notes = load.notes
  753. existing.generate_dibang = generate_dibang
  754. existing.dibang_direction = dibang_direction
  755. existing.remark = load.remark
  756. existing.del_flag = 0
  757. existing.update_by = user_id
  758. existing.update_time = now
  759. return existing.id
  760. load_id = generate_uuid()
  761. db.add(
  762. PlPlanLoad(
  763. id=load_id,
  764. plan_id=plan_id,
  765. customer_id=load.customer_id,
  766. customer_name=load.customer_name,
  767. address=load.address,
  768. lng=load.lng,
  769. lat=load.lat,
  770. load_time=load.load_time,
  771. contact=load.contact,
  772. notes=load.notes,
  773. generate_dibang=generate_dibang,
  774. dibang_direction=dibang_direction,
  775. tenant_no=tenant_no,
  776. remark=load.remark,
  777. create_by=user_id,
  778. create_dept_id=dept_id or "",
  779. create_time=now,
  780. update_by=user_id,
  781. update_time=now,
  782. del_flag=0,
  783. )
  784. )
  785. return load_id
  786. def replace_plan_stops(
  787. db: Session,
  788. tenant_no: str,
  789. plan_id: str,
  790. load: PlanLoadBody,
  791. deliveries: list[PlanDeliveryBody],
  792. user_id: Optional[str],
  793. dept_id: Optional[str],
  794. plan_products: Optional[list] = None,
  795. ) -> None:
  796. _soft_delete_plan_stops(db, tenant_no, plan_id, user_id)
  797. now = datetime.now()
  798. load_id = _resolve_or_create_plan_load(
  799. db,
  800. tenant_no,
  801. plan_id,
  802. load,
  803. user_id,
  804. dept_id,
  805. now,
  806. )
  807. plan_product_rows = plan_products or []
  808. for idx, prod in enumerate(load.products or []):
  809. plan_product_id = _resolve_plan_product_id(prod, plan_product_rows)
  810. db.add(
  811. PlPlanLoadProduct(
  812. id=generate_uuid(),
  813. load_id=load_id,
  814. plan_id=plan_id,
  815. plan_product_id=plan_product_id,
  816. product_id=prod.product_id,
  817. product_no=prod.product_no,
  818. product_name=prod.product_name,
  819. model=prod.model,
  820. unit=prod.unit or "吨",
  821. package_spec=prod.package_spec,
  822. delivery_method=prod.delivery_method,
  823. plan_qty=prod.plan_qty,
  824. tenant_no=tenant_no,
  825. order_num=idx,
  826. remark=prod.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. contract_order = 0
  836. contract_order = _write_stop_contracts(
  837. db,
  838. tenant_no,
  839. plan_id,
  840. load_id,
  841. PLAN_CONTRACT_SIDE_LOAD,
  842. load.contracts or [],
  843. user_id,
  844. dept_id,
  845. contract_order,
  846. )
  847. for delivery in deliveries:
  848. generate_dibang, dibang_direction = normalize_stop_dibang_fields(
  849. delivery.customer_name,
  850. "delivery",
  851. delivery.generate_dibang,
  852. delivery.dibang_direction,
  853. )
  854. delivery_id = generate_uuid()
  855. db.add(
  856. PlPlanDelivery(
  857. id=delivery_id,
  858. plan_id=plan_id,
  859. seq=delivery.seq or 1,
  860. customer_id=delivery.customer_id,
  861. customer_name=delivery.customer_name,
  862. address=delivery.address,
  863. lng=delivery.lng,
  864. lat=delivery.lat,
  865. delivery_time=delivery.delivery_time,
  866. contact=delivery.contact,
  867. notes=delivery.notes,
  868. generate_dibang=generate_dibang,
  869. dibang_direction=dibang_direction,
  870. tenant_no=tenant_no,
  871. remark=delivery.remark,
  872. create_by=user_id,
  873. create_dept_id=dept_id or "",
  874. create_time=now,
  875. update_by=user_id,
  876. update_time=now,
  877. del_flag=0,
  878. )
  879. )
  880. for idx, prod in enumerate(delivery.products or []):
  881. plan_product_id = _resolve_plan_product_id(prod, plan_product_rows)
  882. db.add(
  883. PlPlanDeliveryProduct(
  884. id=generate_uuid(),
  885. delivery_id=delivery_id,
  886. plan_id=plan_id,
  887. plan_product_id=plan_product_id,
  888. product_id=prod.product_id,
  889. product_no=prod.product_no,
  890. product_name=prod.product_name,
  891. model=prod.model,
  892. unit=prod.unit or "吨",
  893. package_spec=prod.package_spec,
  894. delivery_method=prod.delivery_method,
  895. plan_qty=prod.plan_qty,
  896. tenant_no=tenant_no,
  897. order_num=idx,
  898. remark=prod.remark,
  899. create_by=user_id,
  900. create_dept_id=dept_id or "",
  901. create_time=now,
  902. update_by=user_id,
  903. update_time=now,
  904. del_flag=0,
  905. )
  906. )
  907. contract_order = _write_stop_contracts(
  908. db,
  909. tenant_no,
  910. plan_id,
  911. delivery_id,
  912. PLAN_CONTRACT_SIDE_DELIVERY,
  913. delivery.contracts or [],
  914. user_id,
  915. dept_id,
  916. contract_order,
  917. )