pl_plan_stop_service.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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.services.pl_mobile_product_identity import resolve_mobile_product_link, is_existing_pending_delivery
  11. from app.models.crm_models import CrmContract, CrmContractProduct
  12. from app.models.pl_models import (
  13. PlPlan,
  14. PlPlanContract,
  15. PlPlanDelivery,
  16. PlPlanDeliveryProduct,
  17. PlPlanLoad,
  18. PlPlanLoadProduct,
  19. PlTransportAddress,
  20. )
  21. from app.schemas.pl.plan import (
  22. PlanArchiveBrandQtyItem,
  23. PlanContractLink,
  24. PlanDeliveryBody,
  25. PlanDeliveryRead,
  26. PlanLoadBody,
  27. PlanLoadRead,
  28. PlanStopProductBody,
  29. PlanStopProductRead,
  30. )
  31. from app.services.pl_brand_archive import load_brand_qtys_by_stop_product_ids
  32. from app.services.pl_internal_customer import is_internal_customer_name
  33. from app.services.pl_plan_stop_rules import normalize_stop_dibang_fields, warn_qty_imbalance
  34. from app.services.pl_plan_service import (
  35. PLAN_CONTRACT_SIDE_DEMANDER,
  36. PLAN_CONTRACT_SIDE_SUPPLIER,
  37. assert_contract_selectable_for_plan,
  38. belongs_company_trading_entity,
  39. )
  40. from app.services.pl_product_display import load_crm_product_alias_maps, resolve_product_display_names
  41. PLAN_CONTRACT_SIDE_LOAD = "load"
  42. PLAN_CONTRACT_SIDE_DELIVERY = "delivery"
  43. def _contract_link(row: PlPlanContract) -> PlanContractLink:
  44. return PlanContractLink(
  45. contractId=row.contract_id,
  46. contractNo=row.contract_no,
  47. stopId=row.stop_id,
  48. )
  49. def _attach_contract_nos_to_stop_products(
  50. db: Session,
  51. tenant_no: str,
  52. products: list[PlanStopProductRead],
  53. contracts: list[PlanContractLink],
  54. ) -> None:
  55. """段产品行展示用合同编号:优先段合同关联,其次按 contract_id 查 CRM。"""
  56. if not products:
  57. return
  58. by_id = {
  59. str(c.contract_id).strip(): (c.contract_no or "").strip()
  60. for c in contracts or []
  61. if (c.contract_id or "").strip()
  62. }
  63. missing: list[str] = []
  64. for product in products:
  65. cid = (product.contract_id or "").strip()
  66. if not cid:
  67. continue
  68. no = by_id.get(cid) or (product.contract_no or "").strip()
  69. if no:
  70. product.contract_no = no
  71. by_id.setdefault(cid, no)
  72. else:
  73. missing.append(cid)
  74. need = [cid for cid in dict.fromkeys(missing) if cid not in by_id or not by_id.get(cid)]
  75. if not need:
  76. return
  77. rows = (
  78. db.query(CrmContract.id, CrmContract.contract_no)
  79. .filter(
  80. CrmContract.tenant_no == tenant_no,
  81. CrmContract.del_flag == 0,
  82. CrmContract.id.in_(need),
  83. )
  84. .all()
  85. )
  86. for cid, cno in rows:
  87. key = str(cid or "").strip()
  88. if key and (cno or "").strip():
  89. by_id[key] = str(cno).strip()
  90. for product in products:
  91. cid = (product.contract_id or "").strip()
  92. if not cid:
  93. continue
  94. no = by_id.get(cid)
  95. if no:
  96. product.contract_no = no
  97. def _attach_stop_brand_qtys(
  98. product: PlanStopProductRead,
  99. brand_qtys_by_stop: dict[str, list[dict]],
  100. ) -> PlanStopProductRead:
  101. raw = brand_qtys_by_stop.get(product.id) or None
  102. if raw:
  103. product.brand_qtys = [PlanArchiveBrandQtyItem.model_validate(x) for x in raw]
  104. else:
  105. product.brand_qtys = None
  106. return product
  107. def _resolve_stop_list_product_name(
  108. *,
  109. saved_product_name: Optional[str],
  110. product_id: Optional[str],
  111. standard_by_id: dict[str, str],
  112. alias_options_by_id: dict[str, list[str]],
  113. ) -> str:
  114. """列表展示用:优先 CRM 标准名,不展示别名。"""
  115. display_name, _alias = resolve_product_display_names(
  116. saved_product_name=saved_product_name,
  117. product_id=product_id,
  118. standard_by_id=standard_by_id,
  119. alias_options_by_id=alias_options_by_id,
  120. )
  121. return display_name or (saved_product_name or "")
  122. def _apply_stop_list_product_name(
  123. product: PlanStopProductRead,
  124. *,
  125. standard_by_id: dict[str, str],
  126. alias_options_by_id: dict[str, list[str]],
  127. ) -> PlanStopProductRead:
  128. product.product_name = _resolve_stop_list_product_name(
  129. saved_product_name=product.product_name,
  130. product_id=product.product_id,
  131. standard_by_id=standard_by_id,
  132. alias_options_by_id=alias_options_by_id,
  133. )
  134. return product
  135. def _load_stop_product(
  136. row: PlPlanLoadProduct,
  137. brand_qtys_by_stop: dict[str, list[dict]] | None = None,
  138. *,
  139. standard_by_id: dict[str, str] | None = None,
  140. alias_options_by_id: dict[str, list[str]] | None = None,
  141. ) -> PlanStopProductRead:
  142. product = PlanStopProductRead.model_validate(row)
  143. if standard_by_id is not None and alias_options_by_id is not None:
  144. product = _apply_stop_list_product_name(
  145. product,
  146. standard_by_id=standard_by_id,
  147. alias_options_by_id=alias_options_by_id,
  148. )
  149. if brand_qtys_by_stop is not None:
  150. return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
  151. return product
  152. def _delivery_stop_product(
  153. row: PlPlanDeliveryProduct,
  154. brand_qtys_by_stop: dict[str, list[dict]] | None = None,
  155. *,
  156. standard_by_id: dict[str, str] | None = None,
  157. alias_options_by_id: dict[str, list[str]] | None = None,
  158. ) -> PlanStopProductRead:
  159. product = PlanStopProductRead.model_validate(row)
  160. if standard_by_id is not None and alias_options_by_id is not None:
  161. product = _apply_stop_list_product_name(
  162. product,
  163. standard_by_id=standard_by_id,
  164. alias_options_by_id=alias_options_by_id,
  165. )
  166. if brand_qtys_by_stop is not None:
  167. return _attach_stop_brand_qtys(product, brand_qtys_by_stop)
  168. return product
  169. def load_stop_contract_rows_grouped(
  170. db: Session,
  171. tenant_no: str,
  172. plan_ids: list[str],
  173. ) -> dict[str, list[PlPlanContract]]:
  174. if not plan_ids:
  175. return {}
  176. rows = (
  177. db.query(PlPlanContract)
  178. .filter(
  179. PlPlanContract.tenant_no == tenant_no,
  180. PlPlanContract.plan_id.in_(plan_ids),
  181. PlPlanContract.del_flag == 0,
  182. )
  183. .order_by(PlPlanContract.order_num.asc(), PlPlanContract.create_time.asc())
  184. .all()
  185. )
  186. grouped: dict[str, list[PlPlanContract]] = defaultdict(list)
  187. for row in rows:
  188. grouped[row.plan_id].append(row)
  189. return grouped
  190. def _contracts_for_stop(
  191. contract_rows: list[PlPlanContract],
  192. stop_id: str,
  193. legacy_sides: tuple[str, ...],
  194. ) -> list[PlanContractLink]:
  195. by_stop = [_contract_link(r) for r in contract_rows if (r.stop_id or "") == stop_id]
  196. if by_stop:
  197. return by_stop
  198. return [
  199. _contract_link(r)
  200. for r in contract_rows
  201. if not (r.stop_id or "").strip() and r.side in legacy_sides
  202. ]
  203. def _to_decimal(value) -> Optional[Decimal]:
  204. if value is None or value == "":
  205. return None
  206. try:
  207. return Decimal(str(value))
  208. except Exception:
  209. return None
  210. def resolve_stop_address_from_library(
  211. db: Session,
  212. tenant_no: str,
  213. address: Optional[str],
  214. lng,
  215. lat,
  216. ) -> Optional[str]:
  217. """段 address 为空时,按经纬度从运输地址库补全 full_address。"""
  218. text = (address or "").strip()
  219. if text:
  220. return text
  221. lat_d = _to_decimal(lat)
  222. lng_d = _to_decimal(lng)
  223. if lat_d is None and lng_d is None:
  224. return text or None
  225. query = db.query(PlTransportAddress).filter(
  226. PlTransportAddress.tenant_no == tenant_no,
  227. PlTransportAddress.del_flag == 0,
  228. PlTransportAddress.status == "1",
  229. )
  230. if lat_d is not None:
  231. query = query.filter(PlTransportAddress.lat == lat_d)
  232. if lng_d is not None:
  233. query = query.filter(PlTransportAddress.lng == lng_d)
  234. rows = query.order_by(PlTransportAddress.create_time.desc()).all()
  235. if not rows:
  236. return text or None
  237. if len(rows) == 1:
  238. full = (rows[0].full_address or "").strip()
  239. return full or None
  240. if lng_d is not None:
  241. for row in rows:
  242. if row.lng == lng_d:
  243. full = (row.full_address or "").strip()
  244. if full:
  245. return full
  246. full = (rows[0].full_address or "").strip()
  247. return full or None
  248. def enrich_stop_addresses_from_library(
  249. db: Session,
  250. tenant_no: str,
  251. load: PlanLoadBody,
  252. deliveries: list[PlanDeliveryBody],
  253. ) -> None:
  254. resolved_load = resolve_stop_address_from_library(
  255. db, tenant_no, load.address, load.lng, load.lat
  256. )
  257. if resolved_load:
  258. load.address = resolved_load
  259. for delivery in deliveries:
  260. resolved = resolve_stop_address_from_library(
  261. db, tenant_no, delivery.address, delivery.lng, delivery.lat
  262. )
  263. if resolved:
  264. delivery.address = resolved
  265. def load_plan_stops_grouped(
  266. db: Session,
  267. tenant_no: str,
  268. plan_ids: list[str],
  269. ) -> dict[str, tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]]]:
  270. """批量读取装货段与送货段(列表/详情共用)。"""
  271. if not plan_ids:
  272. return {}
  273. loads = (
  274. db.query(PlPlanLoad)
  275. .filter(
  276. PlPlanLoad.tenant_no == tenant_no,
  277. PlPlanLoad.plan_id.in_(plan_ids),
  278. PlPlanLoad.del_flag == 0,
  279. )
  280. .all()
  281. )
  282. load_by_plan = {row.plan_id: row for row in loads}
  283. load_ids = [row.id for row in loads]
  284. load_products: dict[str, list[PlPlanLoadProduct]] = defaultdict(list)
  285. if load_ids:
  286. for row in (
  287. db.query(PlPlanLoadProduct)
  288. .filter(
  289. PlPlanLoadProduct.tenant_no == tenant_no,
  290. PlPlanLoadProduct.load_id.in_(load_ids),
  291. PlPlanLoadProduct.del_flag == 0,
  292. )
  293. .order_by(PlPlanLoadProduct.order_num.asc(), PlPlanLoadProduct.create_time.asc())
  294. .all()
  295. ):
  296. load_products[row.load_id].append(row)
  297. deliveries = (
  298. db.query(PlPlanDelivery)
  299. .filter(
  300. PlPlanDelivery.tenant_no == tenant_no,
  301. PlPlanDelivery.plan_id.in_(plan_ids),
  302. PlPlanDelivery.del_flag == 0,
  303. )
  304. .order_by(PlPlanDelivery.seq.asc(), PlPlanDelivery.create_time.asc())
  305. .all()
  306. )
  307. deliveries_by_plan: dict[str, list[PlPlanDelivery]] = defaultdict(list)
  308. delivery_ids: list[str] = []
  309. for row in deliveries:
  310. deliveries_by_plan[row.plan_id].append(row)
  311. delivery_ids.append(row.id)
  312. delivery_products: dict[str, list[PlPlanDeliveryProduct]] = defaultdict(list)
  313. if delivery_ids:
  314. for row in (
  315. db.query(PlPlanDeliveryProduct)
  316. .filter(
  317. PlPlanDeliveryProduct.tenant_no == tenant_no,
  318. PlPlanDeliveryProduct.delivery_id.in_(delivery_ids),
  319. PlPlanDeliveryProduct.del_flag == 0,
  320. )
  321. .order_by(PlPlanDeliveryProduct.order_num.asc(), PlPlanDeliveryProduct.create_time.asc())
  322. .all()
  323. ):
  324. delivery_products[row.delivery_id].append(row)
  325. stop_product_ids: list[str] = []
  326. crm_product_ids: set[str] = set()
  327. for rows in load_products.values():
  328. for p in rows:
  329. if p.id:
  330. stop_product_ids.append(p.id)
  331. if (p.product_id or "").strip():
  332. crm_product_ids.add(p.product_id.strip())
  333. for rows in delivery_products.values():
  334. for p in rows:
  335. if p.id:
  336. stop_product_ids.append(p.id)
  337. if (p.product_id or "").strip():
  338. crm_product_ids.add(p.product_id.strip())
  339. brand_qtys_by_stop = load_brand_qtys_by_stop_product_ids(
  340. db, tenant_no=tenant_no, stop_product_ids=stop_product_ids
  341. )
  342. standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
  343. db, tenant_no=tenant_no, product_ids=crm_product_ids
  344. )
  345. contracts_by_plan = load_stop_contract_rows_grouped(db, tenant_no, plan_ids)
  346. result: dict[str, tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]]] = {}
  347. for plan_id in plan_ids:
  348. contract_rows = contracts_by_plan.get(plan_id, [])
  349. load_row = load_by_plan.get(plan_id)
  350. load_read: Optional[PlanLoadRead] = None
  351. if load_row:
  352. load_read = PlanLoadRead.model_validate(load_row)
  353. resolved_load_address = resolve_stop_address_from_library(
  354. db,
  355. tenant_no,
  356. load_read.address,
  357. load_read.lng,
  358. load_read.lat,
  359. )
  360. if resolved_load_address:
  361. load_read.address = resolved_load_address
  362. load_read.products = [
  363. _load_stop_product(
  364. p,
  365. brand_qtys_by_stop,
  366. standard_by_id=standard_by_id,
  367. alias_options_by_id=alias_options_by_id,
  368. )
  369. for p in load_products.get(load_row.id, [])
  370. ]
  371. load_read.contracts = _contracts_for_stop(
  372. contract_rows,
  373. load_row.id,
  374. (PLAN_CONTRACT_SIDE_LOAD, PLAN_CONTRACT_SIDE_SUPPLIER),
  375. )
  376. _attach_contract_nos_to_stop_products(
  377. db, tenant_no, load_read.products, load_read.contracts
  378. )
  379. delivery_reads: list[PlanDeliveryRead] = []
  380. plan_deliveries = deliveries_by_plan.get(plan_id, [])
  381. for idx, delivery_row in enumerate(plan_deliveries):
  382. delivery_read = PlanDeliveryRead.model_validate(delivery_row)
  383. resolved_delivery_address = resolve_stop_address_from_library(
  384. db,
  385. tenant_no,
  386. delivery_read.address,
  387. delivery_read.lng,
  388. delivery_read.lat,
  389. )
  390. if resolved_delivery_address:
  391. delivery_read.address = resolved_delivery_address
  392. delivery_read.products = [
  393. _delivery_stop_product(
  394. p,
  395. brand_qtys_by_stop,
  396. standard_by_id=standard_by_id,
  397. alias_options_by_id=alias_options_by_id,
  398. )
  399. for p in delivery_products.get(delivery_row.id, [])
  400. ]
  401. legacy_sides = (PLAN_CONTRACT_SIDE_DELIVERY, PLAN_CONTRACT_SIDE_DEMANDER)
  402. # 未迁移合同仅挂到第一个送货段
  403. if idx == 0:
  404. delivery_read.contracts = _contracts_for_stop(
  405. contract_rows,
  406. delivery_row.id,
  407. legacy_sides,
  408. )
  409. else:
  410. delivery_read.contracts = _contracts_for_stop(
  411. contract_rows,
  412. delivery_row.id,
  413. (PLAN_CONTRACT_SIDE_DELIVERY,),
  414. )
  415. _attach_contract_nos_to_stop_products(
  416. db, tenant_no, delivery_read.products, delivery_read.contracts
  417. )
  418. delivery_reads.append(delivery_read)
  419. result[plan_id] = (load_read, delivery_reads)
  420. return result
  421. def resolve_load_customer_name(
  422. plan: PlPlan,
  423. load: Optional[PlanLoadRead],
  424. ) -> Optional[str]:
  425. if load and (load.customer_name or "").strip():
  426. return load.customer_name.strip()
  427. legacy = (plan.supplier_name or "").strip()
  428. return legacy or None
  429. def resolve_delivery_customer_summary(
  430. plan: PlPlan,
  431. deliveries: list[PlanDeliveryRead],
  432. ) -> Optional[str]:
  433. names: list[str] = []
  434. seen: set[str] = set()
  435. for delivery in deliveries:
  436. name = (delivery.customer_name or "").strip()
  437. if name and name not in seen:
  438. seen.add(name)
  439. names.append(name)
  440. if names:
  441. if len(names) <= 2:
  442. return "、".join(names)
  443. return f"{names[0]}、{names[1]}等{len(names)}家"
  444. legacy = (plan.customer_name or plan.destination_name or "").strip()
  445. return legacy or None
  446. def collect_unique_delivery_date_strings(deliveries) -> list[str]:
  447. """送货段 delivery_time → 去重升序 YYYY-MM-DD。"""
  448. days: set[date] = set()
  449. for row in deliveries or []:
  450. raw = getattr(row, "delivery_time", None)
  451. if raw is None or raw == "":
  452. continue
  453. if isinstance(raw, datetime):
  454. days.add(raw.date())
  455. elif isinstance(raw, date):
  456. days.add(raw)
  457. else:
  458. text = str(raw).strip()
  459. if not text:
  460. continue
  461. try:
  462. days.add(datetime.strptime(text[:10], "%Y-%m-%d").date())
  463. except ValueError:
  464. continue
  465. return [d.isoformat() for d in sorted(days)]
  466. def attach_plan_stops_to_item(
  467. plan_item,
  468. plan: PlPlan,
  469. stops: tuple[Optional[PlanLoadRead], list[PlanDeliveryRead]],
  470. ) -> None:
  471. load_read, delivery_reads = stops
  472. plan_item.load = load_read
  473. plan_item.deliveries = delivery_reads
  474. plan_item.load_customer_name = resolve_load_customer_name(plan, load_read)
  475. plan_item.delivery_customer_summary = resolve_delivery_customer_summary(plan, delivery_reads)
  476. if load_read and (load_read.address or "").strip():
  477. plan_item.pickup_address = load_read.address
  478. if delivery_reads and (delivery_reads[0].address or "").strip():
  479. plan_item.destination_address = delivery_reads[0].address
  480. plan_item.delivery_times = collect_unique_delivery_date_strings(delivery_reads)
  481. def uses_multi_stop_payload(load: Optional[PlanLoadBody], deliveries: Optional[list[PlanDeliveryBody]]) -> bool:
  482. return load is not None or deliveries is not None
  483. def _normalize_contract_links(links: Optional[list[PlanContractLink]]) -> list[PlanContractLink]:
  484. if not links:
  485. return []
  486. seen: set[str] = set()
  487. out: list[PlanContractLink] = []
  488. for link in links:
  489. cid = (link.contract_id or "").strip()
  490. if not cid or cid in seen:
  491. continue
  492. seen.add(cid)
  493. out.append(link)
  494. return out
  495. def assert_at_most_one_contract(
  496. links: list[PlanContractLink],
  497. side_label: str,
  498. ) -> list[PlanContractLink]:
  499. if len(links) > 1:
  500. raise HTTPException(
  501. status_code=422,
  502. detail=f"{side_label}只能选择 1 份",
  503. )
  504. return links
  505. def _assert_product_rows_in_contract_allowed(
  506. products: Optional[list],
  507. allowed: set[str],
  508. *,
  509. row_label: str = "装货产品",
  510. ) -> None:
  511. for prod in products or []:
  512. pid = str(getattr(prod, "product_id", None) or "").strip()
  513. name = (getattr(prod, "product_name", None) or pid or "未命名").strip()
  514. if not pid or pid not in allowed:
  515. raise HTTPException(
  516. status_code=422,
  517. detail=f"{row_label}「{name}」不在所选合同明细中",
  518. )
  519. def _contract_product_rows(db: Session, tenant_no: str, contract_id: str) -> list:
  520. return (
  521. db.query(CrmContractProduct)
  522. .filter(
  523. CrmContractProduct.contract_id == contract_id,
  524. CrmContractProduct.tenant_no == tenant_no,
  525. CrmContractProduct.del_flag == 0,
  526. )
  527. .all()
  528. )
  529. def _contract_allowed_product_ids(db: Session, tenant_no: str, contract_id: str) -> set[str]:
  530. rows = _contract_product_rows(db, tenant_no, contract_id)
  531. return {
  532. str(r.product_id).strip()
  533. for r in rows
  534. if getattr(r, "product_id", None) and str(r.product_id).strip()
  535. }
  536. def _assert_stop_products_package_for_contract(
  537. db: Session,
  538. tenant_no: str,
  539. contract_id: str,
  540. stop_products: Optional[list],
  541. ) -> None:
  542. from app.services.pl_contract_plan_qty import (
  543. validate_stop_products_package_against_contract,
  544. )
  545. rows = _contract_product_rows(db, tenant_no, contract_id)
  546. ok, err = validate_stop_products_package_against_contract(
  547. contract_products=rows,
  548. stop_products=stop_products or [],
  549. )
  550. if not ok:
  551. raise HTTPException(status_code=422, detail=err or "包装规格不符合合同明细")
  552. def _union_contract_product_rows(
  553. db: Session,
  554. tenant_no: str,
  555. links: list[PlanContractLink],
  556. ) -> list:
  557. rows: list = []
  558. seen: set[str] = set()
  559. for link in links:
  560. cid = (link.contract_id or "").strip()
  561. if not cid or cid in seen:
  562. continue
  563. seen.add(cid)
  564. rows.extend(_contract_product_rows(db, tenant_no, cid))
  565. return rows
  566. def _assert_stop_products_package_for_union(
  567. stop_products: Optional[list],
  568. contract_rows: list,
  569. ) -> None:
  570. from app.services.pl_contract_plan_qty import (
  571. validate_stop_products_package_against_contract,
  572. )
  573. ok, err = validate_stop_products_package_against_contract(
  574. contract_products=contract_rows,
  575. stop_products=stop_products or [],
  576. )
  577. if not ok:
  578. raise HTTPException(status_code=422, detail=err or "包装规格不符合合同明细")
  579. def _assert_stop_products_bound_to_lines(
  580. stop_products: Optional[list],
  581. contract_rows: list,
  582. selected_contract_ids: set[str],
  583. *,
  584. row_label: str,
  585. ) -> None:
  586. from app.services.pl_contract_plan_qty import (
  587. contract_line_package_specs,
  588. normalize_package_spec,
  589. )
  590. by_id = {
  591. str(getattr(row, "id", None) or "").strip(): row
  592. for row in contract_rows
  593. if str(getattr(row, "id", None) or "").strip()
  594. }
  595. if not by_id:
  596. return
  597. for prod in stop_products or []:
  598. cpid = str(getattr(prod, "contract_product_id", None) or "").strip()
  599. if not cpid:
  600. continue
  601. line = by_id.get(cpid)
  602. if not line:
  603. name = (getattr(prod, "product_name", None) or cpid).strip()
  604. raise HTTPException(
  605. status_code=422,
  606. detail=f"{row_label}「{name}」不在所选合同明细中",
  607. )
  608. line_cid = str(getattr(line, "contract_id", None) or "").strip()
  609. if line_cid and selected_contract_ids and line_cid not in selected_contract_ids:
  610. name = (getattr(prod, "product_name", None) or cpid).strip()
  611. raise HTTPException(
  612. status_code=422,
  613. detail=f"{row_label}「{name}」不在所选合同明细中",
  614. )
  615. line_pid = str(getattr(line, "product_id", None) or "").strip()
  616. prod_pid = str(getattr(prod, "product_id", None) or "").strip()
  617. if line_pid and prod_pid and line_pid != prod_pid:
  618. name = (getattr(prod, "product_name", None) or prod_pid).strip()
  619. raise HTTPException(
  620. status_code=422,
  621. detail=f"{row_label}「{name}」与绑定合同行产品不一致",
  622. )
  623. pkg = normalize_package_spec(getattr(prod, "package_spec", None))
  624. specs = contract_line_package_specs(line)
  625. if pkg and specs and pkg not in specs:
  626. name = (getattr(prod, "product_name", None) or prod_pid).strip()
  627. raise HTTPException(
  628. status_code=422,
  629. detail=f"{row_label}包装规格不在合同明细中:{name}({pkg})",
  630. )
  631. def assert_load_products_in_selected_contract(
  632. db: Session,
  633. tenant_no: str,
  634. load: PlanLoadBody,
  635. plan_products: Optional[list] = None,
  636. ) -> None:
  637. if is_internal_customer_name(load.customer_name):
  638. return
  639. links = _normalize_contract_links(load.contracts)
  640. if not links:
  641. return
  642. rows = _union_contract_product_rows(db, tenant_no, links)
  643. allowed = {
  644. str(r.product_id).strip()
  645. for r in rows
  646. if getattr(r, "product_id", None) and str(r.product_id).strip()
  647. }
  648. _assert_product_rows_in_contract_allowed(load.products, allowed, row_label="装货产品")
  649. _assert_product_rows_in_contract_allowed(plan_products, allowed, row_label="装货产品")
  650. merged = list(load.products or []) + list(plan_products or [])
  651. _assert_stop_products_package_for_union(merged, rows)
  652. selected_ids = {(link.contract_id or "").strip() for link in links if (link.contract_id or "").strip()}
  653. _assert_stop_products_bound_to_lines(
  654. load.products, rows, selected_ids, row_label="装货产品"
  655. )
  656. def assert_delivery_products_in_selected_contract(
  657. db: Session,
  658. tenant_no: str,
  659. delivery: PlanDeliveryBody,
  660. seq: int,
  661. ) -> None:
  662. if is_internal_customer_name(delivery.customer_name):
  663. return
  664. links = _normalize_contract_links(delivery.contracts)
  665. if not links:
  666. return
  667. rows = _union_contract_product_rows(db, tenant_no, links)
  668. allowed = {
  669. str(r.product_id).strip()
  670. for r in rows
  671. if getattr(r, "product_id", None) and str(r.product_id).strip()
  672. }
  673. _assert_product_rows_in_contract_allowed(
  674. delivery.products,
  675. allowed,
  676. row_label=f"送货段#{seq}产品",
  677. )
  678. _assert_stop_products_package_for_union(delivery.products, rows)
  679. selected_ids = {(link.contract_id or "").strip() for link in links if (link.contract_id or "").strip()}
  680. _assert_stop_products_bound_to_lines(
  681. delivery.products, rows, selected_ids, row_label=f"送货段#{seq}产品"
  682. )
  683. def assert_external_stop_products_have_contract_line(
  684. load: PlanLoadBody,
  685. deliveries: Optional[list[PlanDeliveryBody]],
  686. ) -> None:
  687. """正式保存:外部客户已选合同时,每行产品必须绑到当前合同明细。暂存不调用。"""
  688. _assert_stop_rows_have_contract_line(
  689. load.customer_name, load.contracts, load.products, "装货产品"
  690. )
  691. for idx, delivery in enumerate(deliveries or [], start=1):
  692. _assert_stop_rows_have_contract_line(
  693. delivery.customer_name,
  694. delivery.contracts,
  695. delivery.products,
  696. f"送货段#{idx}产品",
  697. )
  698. def _assert_stop_rows_have_contract_line(
  699. customer_name: Optional[str],
  700. contracts: Optional[list[PlanContractLink]],
  701. products: Optional[list],
  702. row_label: str,
  703. ) -> None:
  704. if is_internal_customer_name(customer_name):
  705. return
  706. selected = {
  707. (link.contract_id or "").strip()
  708. for link in _normalize_contract_links(contracts)
  709. if (link.contract_id or "").strip()
  710. }
  711. if not selected:
  712. return
  713. for prod in products or []:
  714. contract_id = str(getattr(prod, "contract_id", None) or "").strip()
  715. contract_product_id = str(getattr(prod, "contract_product_id", None) or "").strip()
  716. if contract_id in selected and contract_product_id:
  717. continue
  718. name = (
  719. getattr(prod, "product_name", None)
  720. or getattr(prod, "product_no", None)
  721. or "未命名产品"
  722. )
  723. raise HTTPException(
  724. status_code=422,
  725. detail=f"{row_label}「{str(name).strip()}」没有合同编号,请从当前合同补到原来的产品行后再保存",
  726. )
  727. def assert_stop_contract_required(
  728. customer_name: Optional[str],
  729. contracts: Optional[list[PlanContractLink]],
  730. side_label: str,
  731. ) -> None:
  732. """非内部客户装/送货段保存时必须至少选一份合同。"""
  733. if is_internal_customer_name(customer_name):
  734. return
  735. if not _normalize_contract_links(contracts):
  736. raise HTTPException(status_code=422, detail=f"请为{side_label}选择合同")
  737. def _resolve_stop_contracts(
  738. db: Session,
  739. tenant_no: str,
  740. customer_id: Optional[str],
  741. customer_name: Optional[str],
  742. contracts: Optional[list[PlanContractLink]],
  743. side_label: str,
  744. *,
  745. expected_supplier_name: Optional[str] = None,
  746. ) -> list[PlanContractLink]:
  747. if is_internal_customer_name(customer_name):
  748. return []
  749. links = _normalize_contract_links(contracts)
  750. if not links:
  751. return []
  752. if expected_supplier_name is not None and not expected_supplier_name:
  753. raise HTTPException(status_code=422, detail="请先选择归属公司")
  754. resolved: list[PlanContractLink] = []
  755. for link in links:
  756. contract = assert_contract_selectable_for_plan(
  757. db,
  758. link.contract_id,
  759. tenant_no,
  760. expected_customer_id=customer_id,
  761. expected_supplier_name=expected_supplier_name or None,
  762. side_label=side_label,
  763. )
  764. resolved.append(
  765. PlanContractLink(
  766. contractId=contract.id,
  767. contractNo=contract.contract_no or link.contract_no,
  768. )
  769. )
  770. return resolved
  771. def has_pending_stop_products(db: Session, tenant_no: str, plan_id: str) -> bool:
  772. # Uses only pre-existing tables, including when the mobile feature is disabled.
  773. for model in (PlPlanLoadProduct, PlPlanDeliveryProduct):
  774. if db.query(model.id).filter(model.tenant_no == tenant_no, model.plan_id == plan_id,
  775. model.del_flag == 0, model.plan_product_id == "").first():
  776. return True
  777. return False
  778. def assert_no_pending_stop_products(db: Session, tenant_no: str, plan_id: str) -> None:
  779. if has_pending_stop_products(db, tenant_no, plan_id):
  780. raise HTTPException(422, '计划存在待关联装货产品,请补齐关联并正式保存后再安排运输')
  781. def validate_mobile_stop_sources(db: Session, tenant_no: str, load: PlanLoadBody,
  782. deliveries: list[PlanDeliveryBody], products: Optional[list],
  783. belongs_company: Optional[str] = None) -> None:
  784. """Opt-in source validation also runs for incomplete drafts; never trusts client tenant/line ids."""
  785. from app.models.crm_models import CrmProduct
  786. if load is None:
  787. raise HTTPException(422, "请填写装货信息")
  788. entity = belongs_company_trading_entity(belongs_company) if belongs_company is not None else None
  789. product_ids = {str(p.product_id) for p in (products or []) if p.product_id}
  790. for stop in [load] + list(deliveries or []):
  791. product_ids.update(str(p.product_id) for p in stop.products or [] if p.product_id)
  792. links = _normalize_contract_links(stop.contracts)
  793. if (
  794. belongs_company is not None
  795. and links
  796. and not is_internal_customer_name(stop.customer_name)
  797. and not entity
  798. ):
  799. raise HTTPException(422, "请先选择归属公司")
  800. # Even internal customers cannot attach an unverified foreign contract.
  801. for link in links:
  802. assert_contract_selectable_for_plan(db, link.contract_id, tenant_no,
  803. expected_customer_id=stop.customer_id,
  804. expected_supplier_name=entity if belongs_company is not None and not is_internal_customer_name(stop.customer_name) else None,
  805. side_label="移动段合同")
  806. contract_rows = _union_contract_product_rows(db, tenant_no, links) if links else []
  807. by_id = {str(row.id): row for row in contract_rows}
  808. selected = {str(link.contract_id) for link in links}
  809. for product in stop.products or []:
  810. cid = (product.contract_id or '').strip()
  811. cpid = (product.contract_product_id or '').strip()
  812. if not cid and not cpid:
  813. continue
  814. line = by_id.get(cpid)
  815. if not cid or not cpid or cid not in selected or line is None or str(line.contract_id) != cid:
  816. raise HTTPException(422, '移动段产品与所选合同明细关联不一致')
  817. if str(line.product_id) != str(product.product_id):
  818. raise HTTPException(422, '移动段合同行产品不一致')
  819. _assert_stop_products_bound_to_lines(stop.products, contract_rows, selected, row_label="移动段产品")
  820. if product_ids:
  821. found = db.query(CrmProduct.id).filter(CrmProduct.tenant_no == tenant_no,
  822. CrmProduct.del_flag == 0, CrmProduct.id.in_(product_ids)).all()
  823. if {str(row[0]) for row in found} != product_ids:
  824. raise HTTPException(422, '移动段产品不存在或不属于当前租户')
  825. def validate_mobile_draft_stops(db: Session, tenant_no: str, load: PlanLoadBody,
  826. deliveries: Optional[list[PlanDeliveryBody]], products: Optional[list],
  827. belongs_company: Optional[str] = None):
  828. rows = list(load.products or []) + [p for stop in deliveries or [] for p in stop.products or []]
  829. quantities = [getattr(p, 'plan_qty', None) for p in rows] + [getattr(p, 'quantity', None) for p in products or []]
  830. for value in quantities:
  831. if value is None:
  832. continue
  833. qty = Decimal(str(value))
  834. if not qty.is_finite() or qty < 0:
  835. raise HTTPException(422, '暂存产品数量须为非负有限数')
  836. validate_mobile_stop_sources(
  837. db, tenant_no, load, list(deliveries or []), products, belongs_company
  838. )
  839. return load, list(deliveries or [])
  840. def validate_plan_stops_write(
  841. db: Session,
  842. tenant_no: str,
  843. load: Optional[PlanLoadBody],
  844. deliveries: Optional[list[PlanDeliveryBody]],
  845. products: Optional[list],
  846. belongs_company: Optional[str] = None,
  847. ) -> tuple[PlanLoadBody, list[PlanDeliveryBody]]:
  848. if load is None:
  849. raise HTTPException(status_code=422, detail="请填写装货信息")
  850. if not (load.customer_id or "").strip() or not (load.customer_name or "").strip():
  851. raise HTTPException(status_code=422, detail="请选择装货客户")
  852. if not deliveries:
  853. raise HTTPException(status_code=422, detail="请至少添加一段送货信息")
  854. if products is not None and not products:
  855. raise HTTPException(status_code=422, detail="请至少保留一条产品明细")
  856. assert_stop_contract_required(load.customer_name, load.contracts, "装货客户")
  857. entity_name = (
  858. belongs_company_trading_entity(belongs_company) if belongs_company is not None else None
  859. )
  860. load.contracts = _resolve_stop_contracts(
  861. db,
  862. tenant_no,
  863. load.customer_id,
  864. load.customer_name,
  865. load.contracts,
  866. "装货合同",
  867. expected_supplier_name=entity_name,
  868. )
  869. resolved_deliveries: list[PlanDeliveryBody] = []
  870. for idx, delivery in enumerate(deliveries, start=1):
  871. if not (delivery.customer_id or "").strip() or not (delivery.customer_name or "").strip():
  872. raise HTTPException(status_code=422, detail=f"送货段#{idx}请选择客户")
  873. assert_stop_contract_required(delivery.customer_name, delivery.contracts, f"送货段#{idx}")
  874. delivery.contracts = _resolve_stop_contracts(
  875. db,
  876. tenant_no,
  877. delivery.customer_id,
  878. delivery.customer_name,
  879. delivery.contracts,
  880. f"送货段#{idx}合同",
  881. expected_supplier_name=entity_name,
  882. )
  883. resolved_deliveries.append(delivery)
  884. enrich_stop_addresses_from_library(db, tenant_no, load, resolved_deliveries)
  885. assert_load_products_in_selected_contract(db, tenant_no, load, plan_products=products)
  886. for idx, delivery in enumerate(resolved_deliveries, start=1):
  887. assert_delivery_products_in_selected_contract(db, tenant_no, delivery, idx)
  888. return load, resolved_deliveries
  889. def collect_stop_qty_warnings(
  890. products: Optional[list],
  891. load: PlanLoadBody,
  892. deliveries: list[PlanDeliveryBody],
  893. ) -> list[str]:
  894. plan_rows = products or []
  895. load_rows = load.products or []
  896. delivery_rows: list[PlanStopProductBody] = []
  897. for delivery in deliveries:
  898. delivery_rows.extend(delivery.products or [])
  899. return warn_qty_imbalance(plan_rows, load_rows, delivery_rows)
  900. def sync_plan_legacy_from_stops(
  901. plan: PlPlan,
  902. load: PlanLoadBody,
  903. deliveries: list[PlanDeliveryBody],
  904. ) -> None:
  905. plan.supplier_id = load.customer_id
  906. plan.supplier_name = load.customer_name
  907. plan.pickup_address = load.address
  908. plan.pickup_lng = load.lng
  909. plan.pickup_lat = load.lat
  910. plan.pickup_time = load.load_time
  911. plan.pickup_contact = load.contact
  912. plan.pickup_notes = load.notes
  913. if not deliveries:
  914. # Incomplete mobile drafts keep the load while clearing stale legacy customer fields.
  915. plan.customer_id = None
  916. plan.customer_name = None
  917. plan.destination_id = None
  918. plan.destination_name = None
  919. plan.destination_address = None
  920. plan.destination_lng = None
  921. plan.destination_lat = None
  922. plan.delivery_time = None
  923. plan.delivery_contact = None
  924. plan.destination_notes = None
  925. return
  926. first = deliveries[0]
  927. plan.customer_id = first.customer_id
  928. plan.customer_name = first.customer_name
  929. plan.destination_id = first.customer_id
  930. plan.destination_name = first.customer_name
  931. plan.destination_address = first.address
  932. plan.destination_lng = first.lng
  933. plan.destination_lat = first.lat
  934. plan.delivery_time = first.delivery_time
  935. plan.delivery_contact = first.contact
  936. plan.destination_notes = first.notes
  937. def resolve_delivery_id_for_upsert(
  938. *,
  939. plan_id: str,
  940. payload_id: Optional[str],
  941. existing_by_id: dict,
  942. ) -> tuple[str, Optional[object]]:
  943. pid = (payload_id or "").strip()
  944. if not pid:
  945. return generate_uuid(), None
  946. row = existing_by_id.get(pid)
  947. if row is None or getattr(row, "plan_id", None) != plan_id:
  948. raise HTTPException(status_code=422, detail=f"送货段 id 无效或不属于本计划:{pid}")
  949. return pid, row
  950. def _write_stop_contracts(
  951. db: Session, tenant_no: str, plan_id: str, stop_id: str, side: str,
  952. contracts: Optional[list[PlanContractLink]], user_id: Optional[str],
  953. dept_id: Optional[str], order_num_start: int,
  954. ) -> int:
  955. from app.services.pl_plan_service import sync_plan_contract_scope
  956. sync_plan_contract_scope(db, tenant_no=tenant_no, plan_id=plan_id, side=side,
  957. stop_id=stop_id, contracts=contracts, user_id=user_id,
  958. dept_id=dept_id, order_start=order_num_start)
  959. return order_num_start + len(contracts or [])
  960. def _resolve_plan_product_id(
  961. prod: PlanStopProductBody,
  962. plan_products: list,
  963. allow_unlinked_draft: bool = False,
  964. ) -> str:
  965. if getattr(prod, 'unlinked_draft', False):
  966. if allow_unlinked_draft and not prod.plan_product_id and not getattr(prod, 'plan_product_client_key', None):
  967. return ""
  968. raise HTTPException(422, '装货产品尚未匹配完成,请核对装货信息后再正式保存')
  969. mobile_id = resolve_mobile_product_link(prod, plan_products)
  970. if mobile_id is not None:
  971. return mobile_id
  972. explicit = (prod.plan_product_id or "").strip()
  973. if explicit:
  974. for row in plan_products:
  975. if row.id == explicit:
  976. if row.product_id != prod.product_id:
  977. raise HTTPException(422, '段产品与指定计划产品不一致')
  978. return explicit
  979. raise HTTPException(422, f'计划产品 id 无效或不属于当前计划:{prod.product_name}')
  980. product_id = (prod.product_id or "").strip()
  981. matches = [row for row in plan_products if product_id and (row.product_id or '').strip() == product_id]
  982. product_no = (prod.product_no or "").strip()
  983. if not product_id and product_no:
  984. matches = [row for row in plan_products if (row.product_no or '').strip() == product_no]
  985. if len(matches) == 1:
  986. return matches[0].id
  987. if len(matches) > 1:
  988. raise HTTPException(422, '存在多条相同产品,请回传明确的计划产品 id')
  989. raise HTTPException(
  990. status_code=422,
  991. detail=f"无法匹配计划产品行:{prod.product_name or explicit or product_id}",
  992. )
  993. def _resolve_or_create_plan_load(
  994. db: Session,
  995. tenant_no: str,
  996. plan_id: str,
  997. load: PlanLoadBody,
  998. user_id: Optional[str],
  999. dept_id: Optional[str],
  1000. now: datetime,
  1001. ) -> str:
  1002. """装货段与 plan 1:1;uk_pl_plan_load_plan 仅按 plan_id 唯一,软删后不可再 INSERT,须原地更新。"""
  1003. generate_dibang, dibang_direction = normalize_stop_dibang_fields(
  1004. load.customer_name,
  1005. "load",
  1006. load.generate_dibang,
  1007. load.dibang_direction,
  1008. )
  1009. existing = (
  1010. db.query(PlPlanLoad)
  1011. .filter(
  1012. PlPlanLoad.plan_id == plan_id,
  1013. PlPlanLoad.tenant_no == tenant_no,
  1014. )
  1015. .order_by(PlPlanLoad.del_flag.asc(), PlPlanLoad.update_time.desc())
  1016. .first()
  1017. )
  1018. if existing:
  1019. existing.customer_id = load.customer_id
  1020. existing.customer_name = load.customer_name
  1021. existing.address = load.address
  1022. existing.lng = load.lng
  1023. existing.lat = load.lat
  1024. existing.load_time = load.load_time
  1025. existing.contact = load.contact
  1026. existing.notes = load.notes
  1027. existing.generate_dibang = generate_dibang
  1028. existing.dibang_direction = dibang_direction
  1029. existing.remark = load.remark
  1030. existing.del_flag = 0
  1031. existing.update_by = user_id
  1032. existing.update_time = now
  1033. return existing.id
  1034. load_id = generate_uuid()
  1035. db.add(
  1036. PlPlanLoad(
  1037. id=load_id,
  1038. plan_id=plan_id,
  1039. customer_id=load.customer_id,
  1040. customer_name=load.customer_name,
  1041. address=load.address,
  1042. lng=load.lng,
  1043. lat=load.lat,
  1044. load_time=load.load_time,
  1045. contact=load.contact,
  1046. notes=load.notes,
  1047. generate_dibang=generate_dibang,
  1048. dibang_direction=dibang_direction,
  1049. tenant_no=tenant_no,
  1050. remark=load.remark,
  1051. create_by=user_id,
  1052. create_dept_id=dept_id or "",
  1053. create_time=now,
  1054. update_by=user_id,
  1055. update_time=now,
  1056. del_flag=0,
  1057. )
  1058. )
  1059. return load_id
  1060. def assert_plan_create_child_ids(payload):
  1061. stops = ([payload.load] if payload.load else []) + list(payload.deliveries or [])
  1062. children = list(payload.products or []) + stops + [row for stop in stops for row in stop.products or []]
  1063. if any((getattr(row, 'id', None) or '').strip() for row in children):
  1064. raise HTTPException(422, '新建或复制计划不能携带已有主产品、停靠段或段产品 id')
  1065. if any((row.plan_product_id or '').strip() for stop in stops for row in stop.products or []):
  1066. raise HTTPException(422, '新建或复制计划不能携带已有计划产品关联 id')
  1067. def complete_plan_stops_for_validation(db, tenant_no, plan_id, load, deliveries):
  1068. """Validate partial edits against stored values without marking omitted fields as submitted."""
  1069. def stored_body(row, schema, product_model, fk):
  1070. data = {field: getattr(row, field) for field in schema.model_fields if hasattr(row, field)}
  1071. products = db.query(product_model).filter(product_model.tenant_no == tenant_no,
  1072. product_model.plan_id == plan_id, fk == row.id, product_model.del_flag == 0).all()
  1073. data['products'] = [PlanStopProductBody(**{
  1074. field: getattr(product, field) for field in PlanStopProductBody.model_fields
  1075. if hasattr(product, field)}) for product in products]
  1076. contracts = db.query(PlPlanContract).filter(PlPlanContract.tenant_no == tenant_no,
  1077. PlPlanContract.plan_id == plan_id, PlPlanContract.stop_id == row.id,
  1078. PlPlanContract.del_flag == 0).all()
  1079. data['contracts'] = [_contract_link(contract) for contract in contracts]
  1080. return schema(**data)
  1081. old_load = db.query(PlPlanLoad).filter(PlPlanLoad.tenant_no == tenant_no,
  1082. PlPlanLoad.plan_id == plan_id, PlPlanLoad.del_flag == 0).first()
  1083. full_load = stored_body(old_load, PlanLoadBody, PlPlanLoadProduct, PlPlanLoadProduct.load_id) if old_load else None
  1084. if load is not None:
  1085. data = full_load.model_dump() if full_load else {}
  1086. data.update(load.model_dump(exclude_unset=True))
  1087. full_load = PlanLoadBody(**data)
  1088. old_deliveries = db.query(PlPlanDelivery).filter(PlPlanDelivery.tenant_no == tenant_no,
  1089. PlPlanDelivery.plan_id == plan_id, PlPlanDelivery.del_flag == 0).all()
  1090. by_id = {row.id: row for row in old_deliveries}
  1091. full_deliveries = []
  1092. for body in deliveries if deliveries is not None else [PlanDeliveryBody(id=row.id) for row in old_deliveries]:
  1093. old = by_id.get(body.id)
  1094. data = stored_body(old, PlanDeliveryBody, PlPlanDeliveryProduct, PlPlanDeliveryProduct.delivery_id).model_dump() if old else {}
  1095. data.update(body.model_dump(exclude_unset=True))
  1096. full_deliveries.append(PlanDeliveryBody(**data))
  1097. return full_load, full_deliveries
  1098. def preflight_plan_child_update(db, tenant_no, plan_id, payload):
  1099. """Run security/reference checks before the API edits its header or children."""
  1100. from types import SimpleNamespace
  1101. from app.models.pl_models import PlPlanProduct
  1102. from app.services.pl_child_references import assert_plan_products_removable
  1103. from app.services.pl_plan_service import prepare_plan_contract_scope, prepare_plan_product_identities
  1104. existing = db.query(PlPlanProduct).filter(PlPlanProduct.tenant_no == tenant_no,
  1105. PlPlanProduct.plan_id == plan_id, PlPlanProduct.del_flag == 0).all()
  1106. projected, removed, identities = existing, [], []
  1107. if payload.products is not None:
  1108. identities, removed = prepare_plan_product_identities(payload.products, existing)
  1109. projected = []
  1110. for product, old, row_id in identities:
  1111. values = product.model_dump() if old is None else {
  1112. field: getattr(old, field, getattr(product, field)) for field in type(product).model_fields}
  1113. values.update(product.model_dump(exclude_unset=True))
  1114. values['id'] = row_id
  1115. values['_mobile_request_client_key'] = getattr(product, 'client_key', None)
  1116. projected.append(SimpleNamespace(**values))
  1117. if old is not None and old.product_id != product.product_id:
  1118. assert_plan_products_removable(db, tenant_no, plan_id, [old])
  1119. jobs, removed_stops = prepare_plan_stops_write(db, tenant_no, plan_id,
  1120. payload.load, payload.deliveries, projected,
  1121. allow_unlinked_draft=bool(payload.mobile_product_meta and payload.save_mode == 'draft'),
  1122. preserve_pending_draft=payload.save_mode == 'draft')
  1123. ignored = {row.id for job in jobs for row in job[5]}
  1124. ignored.update(row.id for _, rows, _ in removed_stops for row in rows)
  1125. assert_plan_products_removable(db, tenant_no, plan_id, removed, ignored)
  1126. for side in ('supplier', 'demander'):
  1127. prepare_plan_contract_scope(db, tenant_no=tenant_no, plan_id=plan_id, side=side,
  1128. contracts=getattr(payload, side + '_contracts'))
  1129. return ([row_id for _, _, row_id in identities],
  1130. {id(body): stop_id for _, body, _, stop_id, *_ in jobs})
  1131. def _resolve_delivery_identities(db, tenant_no, plan_id, deliveries, existing):
  1132. """A customer is usable only when unique; child IDs can identify repeated stops."""
  1133. from app.services.pl_child_sync import validate_child_ids
  1134. by_id, explicit_ids = validate_child_ids(deliveries, existing, '送货段')
  1135. kept, resolved = set(explicit_ids), []
  1136. children = db.query(PlPlanDeliveryProduct).filter(
  1137. PlPlanDeliveryProduct.tenant_no == tenant_no, PlPlanDeliveryProduct.plan_id == plan_id,
  1138. PlPlanDeliveryProduct.delivery_id.in_(list(by_id)), PlPlanDeliveryProduct.del_flag == 0,
  1139. ).all() if deliveries and by_id else []
  1140. parent_by_child = {row.id: row.delivery_id for row in children}
  1141. for body in deliveries or []:
  1142. row = by_id.get((body.id or '').strip())
  1143. if row is None:
  1144. child_ids = [(product.id or '').strip() for product in body.products if product.id]
  1145. if child_ids:
  1146. parents = {parent_by_child.get(child_id) for child_id in child_ids}
  1147. if None in parents or len(parents) != 1:
  1148. raise HTTPException(422, '送货段子产品 id 无效或属于不同送货段')
  1149. parent_id = next(iter(parents))
  1150. if parent_id in kept:
  1151. raise HTTPException(422, '送货段缺少 id 且重复引用同一旧段')
  1152. row = by_id[parent_id]
  1153. else:
  1154. candidates = [candidate for candidate in existing if candidate.id not in explicit_ids]
  1155. customer_id = (body.customer_id or '').strip()
  1156. if not customer_id and candidates:
  1157. raise HTTPException(422, '送货段缺少 id 和客户标识,无法确定旧段')
  1158. candidates = [candidate for candidate in candidates
  1159. if (candidate.customer_id or '').strip() == customer_id] if customer_id else []
  1160. if len(candidates) > 1 or (candidates and candidates[0].id in kept):
  1161. raise HTTPException(422, '送货段缺少 id 且客户对应多个段,请刷新后回传段 id')
  1162. if candidates:
  1163. row = candidates[0]
  1164. if row is not None:
  1165. kept.add(row.id)
  1166. resolved.append((body, row))
  1167. for body, row in resolved:
  1168. if row is not None:
  1169. body.id = row.id
  1170. return by_id, kept
  1171. def prepare_plan_stops_write(
  1172. db, tenant_no, plan_id, load, deliveries, plan_products,
  1173. allow_unlinked_draft=False, preserve_pending_draft=False, resolved_stop_ids=None,
  1174. ):
  1175. """Resolve all identities and deletion guards before changing any row."""
  1176. from app.services.pl_child_sync import validate_child_ids
  1177. from app.services.pl_child_references import assert_stop_products_removable, assert_stop_removable
  1178. from app.services.pl_plan_service import prepare_plan_contract_scope
  1179. existing_load = db.query(PlPlanLoad).filter(
  1180. PlPlanLoad.tenant_no == tenant_no, PlPlanLoad.plan_id == plan_id,
  1181. ).order_by(PlPlanLoad.del_flag.asc()).first()
  1182. existing_deliveries = db.query(PlPlanDelivery).filter(
  1183. PlPlanDelivery.tenant_no == tenant_no, PlPlanDelivery.plan_id == plan_id,
  1184. PlPlanDelivery.del_flag == 0).all()
  1185. delivery_map, kept = _resolve_delivery_identities(db, tenant_no, plan_id, deliveries, existing_deliveries)
  1186. if load is not None and load.id and (
  1187. existing_load is None or load.id != existing_load.id or existing_load.del_flag != 0
  1188. ):
  1189. raise HTTPException(422, '装货段 id 无效或不属于当前计划')
  1190. jobs, removed_stops = [], []
  1191. stops = []
  1192. resolved_stop_ids = resolved_stop_ids or {}
  1193. if load is not None:
  1194. stops.append(('load', load, existing_load, existing_load.id if existing_load else resolved_stop_ids.get(id(load)) or generate_uuid()))
  1195. for body in deliveries or []:
  1196. existing = delivery_map.get((body.id or '').strip())
  1197. stops.append(('delivery', body, existing, existing.id if existing else resolved_stop_ids.get(id(body)) or generate_uuid()))
  1198. for kind, body, existing, stop_id in stops:
  1199. model = PlPlanLoadProduct if kind == 'load' else PlPlanDeliveryProduct
  1200. fk = model.load_id if kind == 'load' else model.delivery_id
  1201. old = db.query(model).filter(model.tenant_no == tenant_no, model.plan_id == plan_id,
  1202. fk == stop_id, model.del_flag == 0).all() if existing else []
  1203. product_jobs, removed = None, []
  1204. if 'products' in body.model_fields_set:
  1205. by_id, ids = validate_child_ids(body.products, old, '段产品')
  1206. # Reserve every explicit identity before resolving legacy no-ID rows.
  1207. # Quantity/name/position are editable values, never identity keys.
  1208. explicit_ids = set(ids)
  1209. product_jobs = []
  1210. for product in body.products or []:
  1211. row = by_id.get((product.id or '').strip())
  1212. candidates = [candidate for candidate in old
  1213. if candidate.id not in explicit_ids
  1214. and candidate.product_id == product.product_id
  1215. and all((getattr(candidate, field) or '') == (getattr(product, field) or '')
  1216. for field in ('contract_id', 'contract_product_id')
  1217. if field in product.model_fields_set)] if row is None else []
  1218. if (row is None and not product.plan_product_id and not product.plan_product_client_key
  1219. and len(candidates) > 1):
  1220. raise HTTPException(422, '段产品缺少 id 且业务键不唯一,请刷新后回传明细 id')
  1221. pending_rows = [candidate for candidate in ([row] if row is not None else candidates)
  1222. if not candidate.plan_product_id]
  1223. pending = kind == 'delivery' and preserve_pending_draft and is_existing_pending_delivery(product, stop_id, pending_rows)
  1224. linked = '' if pending else _resolve_plan_product_id(product, plan_products, allow_unlinked_draft)
  1225. if row is None:
  1226. matches = [candidate for candidate in candidates
  1227. if (candidate.plan_product_id or '') == linked]
  1228. if len(matches) > 1 or (matches and matches[0].id in ids):
  1229. raise HTTPException(422, '段产品缺少 id 且业务键不唯一,请刷新后回传明细 id')
  1230. if matches:
  1231. row = matches[0]
  1232. ids.add(row.id)
  1233. if row and (row.plan_product_id != linked or row.product_id != product.product_id):
  1234. assert_stop_products_removable(db, tenant_no, plan_id, kind, stop_id, [row])
  1235. product_jobs.append((row, product, linked))
  1236. removed = [row for row in old if row.id not in ids]
  1237. assert_stop_products_removable(db, tenant_no, plan_id, kind, stop_id, removed)
  1238. contracts = prepare_plan_contract_scope(
  1239. db, tenant_no=tenant_no, plan_id=plan_id, side=kind, stop_id=stop_id,
  1240. contracts=body.contracts)
  1241. jobs.append((kind, body, existing, stop_id, product_jobs, removed, contracts))
  1242. if deliveries is not None:
  1243. for stop in existing_deliveries:
  1244. if stop.id in kept:
  1245. continue
  1246. rows = db.query(PlPlanDeliveryProduct).filter(
  1247. PlPlanDeliveryProduct.tenant_no == tenant_no, PlPlanDeliveryProduct.plan_id == plan_id,
  1248. PlPlanDeliveryProduct.delivery_id == stop.id, PlPlanDeliveryProduct.del_flag == 0).all()
  1249. assert_stop_removable(db, tenant_no, plan_id, 'delivery', stop.id, rows)
  1250. contracts = prepare_plan_contract_scope(db, tenant_no=tenant_no, plan_id=plan_id,
  1251. side='delivery', stop_id=stop.id, contracts=[])
  1252. removed_stops.append((stop, rows, contracts))
  1253. return jobs, removed_stops
  1254. def replace_plan_stops(
  1255. db: Session, tenant_no: str, plan_id: str, load: Optional[PlanLoadBody],
  1256. deliveries: Optional[list[PlanDeliveryBody]], user_id: Optional[str],
  1257. dept_id: Optional[str], plan_products: Optional[list] = None,
  1258. allow_unlinked_draft: bool = False, preserve_pending_draft: bool = False,
  1259. resolved_stop_ids: Optional[dict] = None,
  1260. ) -> None:
  1261. from app.models.pl_models import PlPlanProduct
  1262. from app.services.pl_child_sync import apply_keyed_rows
  1263. if plan_products is None:
  1264. plan_products = db.query(PlPlanProduct).filter(PlPlanProduct.tenant_no == tenant_no,
  1265. PlPlanProduct.plan_id == plan_id, PlPlanProduct.del_flag == 0).all()
  1266. jobs, removed_stops = prepare_plan_stops_write(
  1267. db, tenant_no, plan_id, load, deliveries, plan_products,
  1268. allow_unlinked_draft, preserve_pending_draft, resolved_stop_ids)
  1269. now = datetime.now()
  1270. common = ('customer_id', 'customer_name', 'address', 'lng', 'lat', 'contact', 'notes', 'remark')
  1271. product_fields = ('product_id', 'product_no', 'product_name', 'model', 'unit', 'package_spec',
  1272. 'delivery_method', 'contract_id', 'contract_product_id', 'plan_qty', 'remark')
  1273. for kind, body, stop, stop_id, product_jobs, removed, contracts in jobs:
  1274. stop_model = PlPlanLoad if kind == 'load' else PlPlanDelivery
  1275. if stop is None:
  1276. # Load has a unique plan_id constraint even for deleted rows.
  1277. if kind == 'load':
  1278. stop = db.query(PlPlanLoad).filter(PlPlanLoad.tenant_no == tenant_no,
  1279. PlPlanLoad.plan_id == plan_id).first()
  1280. if stop is not None:
  1281. stop_id = stop.id
  1282. if stop is None:
  1283. stop = stop_model(id=stop_id, tenant_no=tenant_no, plan_id=plan_id,
  1284. create_by=user_id, create_dept_id=dept_id or '', create_time=now)
  1285. db.add(stop)
  1286. fields = common + (('load_time',) if kind == 'load' else ('seq', 'delivery_time'))
  1287. # Submitted parents retain the original full-form scalar semantics.
  1288. # Child collections below independently distinguish omission from [].
  1289. for field in fields:
  1290. setattr(stop, field, getattr(body, field))
  1291. if kind == 'delivery':
  1292. stop.seq = body.seq or 1
  1293. stop.generate_dibang, stop.dibang_direction = normalize_stop_dibang_fields(
  1294. stop.customer_name, kind, body.generate_dibang, body.dibang_direction)
  1295. stop.del_flag, stop.update_by, stop.update_time = 0, user_id, now
  1296. model = PlPlanLoadProduct if kind == 'load' else PlPlanDeliveryProduct
  1297. for idx, (row, product, linked) in enumerate(product_jobs or []):
  1298. if row is None:
  1299. row = model(id=generate_uuid(), tenant_no=tenant_no, plan_id=plan_id,
  1300. **{('load_id' if kind == 'load' else 'delivery_id'): stop_id},
  1301. create_by=user_id, create_dept_id=dept_id or '', create_time=now, del_flag=0)
  1302. db.add(row)
  1303. for field in product_fields:
  1304. if field in product.model_fields_set or row.id is None:
  1305. setattr(row, field, getattr(product, field))
  1306. row.plan_product_id = linked
  1307. row.order_num, row.update_by, row.update_time = idx, user_id, now
  1308. for row in removed:
  1309. row.del_flag, row.update_by, row.update_time = 1, user_id, now
  1310. if contracts is not None:
  1311. apply_keyed_rows(db, PlPlanContract, contracts, user_id=user_id, dept_id=dept_id)
  1312. for stop, rows, contracts in removed_stops:
  1313. for row in [stop] + rows:
  1314. row.del_flag, row.update_by, row.update_time = 1, user_id, now
  1315. apply_keyed_rows(db, PlPlanContract, contracts, user_id=user_id, dept_id=dept_id)