pl_plan_stop_service.py 31 KB

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