pl_transport_stop_feedback_service.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. """运输计划 · 司机/现场按段回传"""
  2. from __future__ import annotations
  3. import json
  4. from dataclasses import dataclass, field
  5. from datetime import datetime
  6. from decimal import Decimal
  7. from typing import Any, Literal, Optional
  8. from sqlalchemy.orm import Session
  9. from app.core.config import settings
  10. from app.core.utils import generate_uuid
  11. from app.models.pl_models import (
  12. PlPlanDelivery,
  13. PlPlanDeliveryProduct,
  14. PlPlanLoad,
  15. PlPlanLoadProduct,
  16. PlTransport,
  17. PlTransportDriverStopFeedback,
  18. PlTransportSiteStopFeedback,
  19. )
  20. from app.services.pl_internal_customer import is_internal_customer_name
  21. StopType = Literal["load", "delivery"]
  22. @dataclass
  23. class PublicStopProductRow:
  24. stop_product_id: str
  25. plan_product_id: str
  26. product_id: str
  27. product_name: str
  28. model: Optional[str]
  29. unit: str
  30. package_spec: Optional[str]
  31. delivery_method: Optional[str]
  32. plan_qty: Optional[Decimal]
  33. remark: Optional[str]
  34. actual_qty: Optional[Decimal] = None
  35. brand_qtys: Optional[list[dict[str, Any]]] = None
  36. @dataclass
  37. class PublicStopSegment:
  38. stop_type: StopType
  39. stop_id: str
  40. seq: int
  41. label: str
  42. customer_name: str
  43. address: Optional[str]
  44. contact: Optional[str]
  45. notes: Optional[str]
  46. business_type: Optional[str]
  47. plan_qty: Optional[Decimal]
  48. attachment_urls: list[str]
  49. remark: Optional[str]
  50. feedback_time: Optional[datetime]
  51. lng: Optional[Decimal] = None
  52. lat: Optional[Decimal] = None
  53. quantity: Optional[Decimal] = None
  54. products: list[PublicStopProductRow] = field(default_factory=list)
  55. def build_transport_site_url(token: str) -> str:
  56. origin = (settings.PUBLIC_WEB_ORIGIN or "").rstrip("/")
  57. return f"{origin}/#/public/pl/transport-site/{token}"
  58. def ensure_transport_site_token(transport: PlTransport) -> str:
  59. token = (transport.site_access_token or "").strip()
  60. if not token:
  61. token = generate_uuid().replace("-", "")[:32]
  62. transport.site_access_token = token
  63. return token
  64. def rotate_transport_site_token(transport: PlTransport) -> str:
  65. token = generate_uuid().replace("-", "")[:32]
  66. transport.site_access_token = token
  67. return token
  68. def _parse_urls(raw: Optional[str]) -> list[str]:
  69. if not raw:
  70. return []
  71. try:
  72. parsed = json.loads(raw)
  73. if isinstance(parsed, list):
  74. return [str(item).strip() for item in parsed if str(item).strip()]
  75. except (TypeError, json.JSONDecodeError):
  76. pass
  77. return [part.strip() for part in raw.split(",") if part.strip()]
  78. def _dump_urls(urls: Optional[list[str]]) -> Optional[str]:
  79. if urls is None:
  80. return None
  81. cleaned = [str(item).strip() for item in urls if str(item).strip()]
  82. return json.dumps(cleaned, ensure_ascii=False)
  83. def _direction_label(direction: Optional[str]) -> Optional[str]:
  84. normalized = (direction or "").strip()
  85. if normalized == "outbound":
  86. return "出库"
  87. if normalized == "inbound":
  88. return "入库"
  89. return None
  90. def _sum_stop_qty(products: list[Any]) -> Optional[Decimal]:
  91. total = Decimal("0")
  92. has_qty = False
  93. for row in products:
  94. qty = getattr(row, "plan_qty", None)
  95. if qty is not None:
  96. total += Decimal(str(qty))
  97. has_qty = True
  98. return total if has_qty else None
  99. def _stop_product_row_from_load(row: PlPlanLoadProduct) -> PublicStopProductRow:
  100. return PublicStopProductRow(
  101. stop_product_id=row.id,
  102. plan_product_id=row.plan_product_id,
  103. product_id=row.product_id,
  104. product_name=row.product_name or "",
  105. model=row.model,
  106. unit=(row.unit or "吨").strip() or "吨",
  107. package_spec=row.package_spec,
  108. delivery_method=row.delivery_method,
  109. plan_qty=row.plan_qty,
  110. remark=(row.remark or "").strip() or None,
  111. )
  112. def _stop_product_row_from_delivery(row: PlPlanDeliveryProduct) -> PublicStopProductRow:
  113. return PublicStopProductRow(
  114. stop_product_id=row.id,
  115. plan_product_id=row.plan_product_id,
  116. product_id=row.product_id,
  117. product_name=row.product_name or "",
  118. model=row.model,
  119. unit=(row.unit or "吨").strip() or "吨",
  120. package_spec=row.package_spec,
  121. delivery_method=row.delivery_method,
  122. plan_qty=row.plan_qty,
  123. remark=(row.remark or "").strip() or None,
  124. )
  125. def _parse_product_feedbacks(raw: Optional[str]) -> dict[str, dict[str, Any]]:
  126. if not raw:
  127. return {}
  128. try:
  129. parsed = json.loads(raw)
  130. except (TypeError, json.JSONDecodeError):
  131. return {}
  132. if not isinstance(parsed, list):
  133. return {}
  134. result: dict[str, dict[str, Any]] = {}
  135. for item in parsed:
  136. if not isinstance(item, dict):
  137. continue
  138. stop_product_id = str(
  139. item.get("stopProductId") or item.get("stop_product_id") or ""
  140. ).strip()
  141. if not stop_product_id:
  142. continue
  143. result[stop_product_id] = item
  144. return result
  145. def _dump_product_feedbacks(products: Optional[list[dict[str, Any]]]) -> Optional[str]:
  146. if products is None:
  147. return None
  148. cleaned: list[dict[str, Any]] = []
  149. for item in products:
  150. stop_product_id = str(
  151. item.get("stopProductId") or item.get("stop_product_id") or ""
  152. ).strip()
  153. if not stop_product_id:
  154. continue
  155. actual_qty = item.get("actualQty", item.get("actual_qty"))
  156. row: dict[str, Any] = {
  157. "stopProductId": stop_product_id,
  158. "actualQty": float(Decimal(str(actual_qty or 0))),
  159. }
  160. brand_qtys = item.get("brandQtys") or item.get("brand_qtys")
  161. if brand_qtys:
  162. row["brandQtys"] = brand_qtys
  163. cleaned.append(row)
  164. return json.dumps(cleaned, ensure_ascii=False)
  165. def _merge_product_feedbacks_into_segment(
  166. segment: PublicStopSegment,
  167. feedback_map: dict[str, dict[str, Any]],
  168. ) -> None:
  169. if not feedback_map or not segment.products:
  170. return
  171. for product in segment.products:
  172. item = feedback_map.get(product.stop_product_id)
  173. if not item:
  174. continue
  175. actual = item.get("actualQty", item.get("actual_qty"))
  176. if actual is not None:
  177. product.actual_qty = Decimal(str(actual))
  178. brand_qtys = item.get("brandQtys") or item.get("brand_qtys")
  179. if brand_qtys:
  180. product.brand_qtys = brand_qtys if isinstance(brand_qtys, list) else None
  181. def _is_site_visible_stop(customer_name: Optional[str], generate_dibang: int) -> bool:
  182. return is_internal_customer_name(customer_name) and int(generate_dibang or 0) == 1
  183. def list_plan_stop_segments(
  184. db: Session,
  185. *,
  186. tenant_no: str,
  187. plan_id: str,
  188. include_all_for_driver: bool = True,
  189. site_internal_only: bool = False,
  190. ) -> list[PublicStopSegment]:
  191. segments: list[PublicStopSegment] = []
  192. load = (
  193. db.query(PlPlanLoad)
  194. .filter(
  195. PlPlanLoad.plan_id == plan_id,
  196. PlPlanLoad.tenant_no == tenant_no,
  197. PlPlanLoad.del_flag == 0,
  198. )
  199. .first()
  200. )
  201. if load:
  202. products = (
  203. db.query(PlPlanLoadProduct)
  204. .filter(
  205. PlPlanLoadProduct.load_id == load.id,
  206. PlPlanLoadProduct.tenant_no == tenant_no,
  207. PlPlanLoadProduct.del_flag == 0,
  208. )
  209. .all()
  210. )
  211. if include_all_for_driver or (
  212. site_internal_only and _is_site_visible_stop(load.customer_name, load.generate_dibang)
  213. ):
  214. stop_products = [
  215. _stop_product_row_from_load(row)
  216. for row in sorted(
  217. products,
  218. key=lambda item: (item.order_num or 0, item.create_time or datetime.min),
  219. )
  220. ]
  221. segments.append(
  222. PublicStopSegment(
  223. stop_type="load",
  224. stop_id=load.id,
  225. seq=0,
  226. label="装货",
  227. customer_name=(load.customer_name or "").strip(),
  228. address=load.address,
  229. contact=load.contact,
  230. notes=load.notes,
  231. lng=load.lng,
  232. lat=load.lat,
  233. business_type=_direction_label(load.dibang_direction),
  234. plan_qty=_sum_stop_qty(products),
  235. attachment_urls=[],
  236. remark=None,
  237. feedback_time=None,
  238. products=stop_products,
  239. )
  240. )
  241. deliveries = (
  242. db.query(PlPlanDelivery)
  243. .filter(
  244. PlPlanDelivery.plan_id == plan_id,
  245. PlPlanDelivery.tenant_no == tenant_no,
  246. PlPlanDelivery.del_flag == 0,
  247. )
  248. .order_by(PlPlanDelivery.seq.asc(), PlPlanDelivery.create_time.asc())
  249. .all()
  250. )
  251. for delivery in deliveries:
  252. products = (
  253. db.query(PlPlanDeliveryProduct)
  254. .filter(
  255. PlPlanDeliveryProduct.delivery_id == delivery.id,
  256. PlPlanDeliveryProduct.tenant_no == tenant_no,
  257. PlPlanDeliveryProduct.del_flag == 0,
  258. )
  259. .all()
  260. )
  261. if include_all_for_driver or (
  262. site_internal_only
  263. and _is_site_visible_stop(delivery.customer_name, delivery.generate_dibang)
  264. ):
  265. stop_products = [
  266. _stop_product_row_from_delivery(row)
  267. for row in sorted(
  268. products,
  269. key=lambda item: (item.order_num or 0, item.create_time or datetime.min),
  270. )
  271. ]
  272. segments.append(
  273. PublicStopSegment(
  274. stop_type="delivery",
  275. stop_id=delivery.id,
  276. seq=int(delivery.seq or 0),
  277. label=f"送货 #{delivery.seq or len(segments)}",
  278. customer_name=(delivery.customer_name or "").strip(),
  279. address=delivery.address,
  280. contact=delivery.contact,
  281. notes=delivery.notes,
  282. lng=delivery.lng,
  283. lat=delivery.lat,
  284. business_type=_direction_label(delivery.dibang_direction),
  285. plan_qty=_sum_stop_qty(products),
  286. attachment_urls=[],
  287. remark=None,
  288. feedback_time=None,
  289. products=stop_products,
  290. )
  291. )
  292. return segments
  293. def _merge_driver_feedback(
  294. segments: list[PublicStopSegment],
  295. feedback_rows: list[PlTransportDriverStopFeedback],
  296. ) -> None:
  297. feedback_map = {(row.stop_type, row.stop_id): row for row in feedback_rows}
  298. for segment in segments:
  299. row = feedback_map.get((segment.stop_type, segment.stop_id))
  300. if not row:
  301. continue
  302. segment.attachment_urls = _parse_urls(row.attachment_urls)
  303. segment.remark = row.remark
  304. segment.feedback_time = row.feedback_time
  305. _merge_product_feedbacks_into_segment(
  306. segment,
  307. _parse_product_feedbacks(row.product_feedbacks),
  308. )
  309. def _merge_site_feedback(
  310. segments: list[PublicStopSegment],
  311. feedback_rows: list[PlTransportSiteStopFeedback],
  312. ) -> None:
  313. feedback_map = {(row.stop_type, row.stop_id): row for row in feedback_rows}
  314. for segment in segments:
  315. row = feedback_map.get((segment.stop_type, segment.stop_id))
  316. if not row:
  317. continue
  318. segment.quantity = row.quantity
  319. segment.attachment_urls = _parse_urls(row.attachment_urls)
  320. segment.remark = row.remark
  321. segment.feedback_time = row.feedback_time
  322. if row.business_type:
  323. segment.business_type = row.business_type
  324. _merge_product_feedbacks_into_segment(
  325. segment,
  326. _parse_product_feedbacks(row.product_feedbacks),
  327. )
  328. def load_driver_stop_segments(
  329. db: Session,
  330. *,
  331. tenant_no: str,
  332. plan_id: str,
  333. transport_id: str,
  334. ) -> list[PublicStopSegment]:
  335. segments = list_plan_stop_segments(
  336. db,
  337. tenant_no=tenant_no,
  338. plan_id=plan_id,
  339. include_all_for_driver=True,
  340. site_internal_only=False,
  341. )
  342. rows = (
  343. db.query(PlTransportDriverStopFeedback)
  344. .filter(
  345. PlTransportDriverStopFeedback.transport_id == transport_id,
  346. PlTransportDriverStopFeedback.tenant_no == tenant_no,
  347. PlTransportDriverStopFeedback.del_flag == 0,
  348. )
  349. .all()
  350. )
  351. _merge_driver_feedback(segments, rows)
  352. return segments
  353. def _load_site_stop_feedback_rows(
  354. db: Session,
  355. *,
  356. tenant_no: str,
  357. transport_id: str,
  358. ) -> list[PlTransportSiteStopFeedback]:
  359. return (
  360. db.query(PlTransportSiteStopFeedback)
  361. .filter(
  362. PlTransportSiteStopFeedback.transport_id == transport_id,
  363. PlTransportSiteStopFeedback.tenant_no == tenant_no,
  364. PlTransportSiteStopFeedback.del_flag == 0,
  365. )
  366. .all()
  367. )
  368. def load_site_stop_segments(
  369. db: Session,
  370. *,
  371. tenant_no: str,
  372. plan_id: str,
  373. transport_id: str,
  374. ) -> list[PublicStopSegment]:
  375. segments = list_plan_stop_segments(
  376. db,
  377. tenant_no=tenant_no,
  378. plan_id=plan_id,
  379. include_all_for_driver=False,
  380. site_internal_only=True,
  381. )
  382. _merge_site_feedback(segments, _load_site_stop_feedback_rows(db, tenant_no=tenant_no, transport_id=transport_id))
  383. return segments
  384. def load_io_order_site_stop_segments(
  385. db: Session,
  386. *,
  387. tenant_no: str,
  388. plan_id: str,
  389. transport_id: str,
  390. ) -> list[PublicStopSegment]:
  391. """入库/出库单现场页:展示全部装货/送货段及段内产品。"""
  392. segments = list_plan_stop_segments(
  393. db,
  394. tenant_no=tenant_no,
  395. plan_id=plan_id,
  396. include_all_for_driver=True,
  397. site_internal_only=False,
  398. )
  399. _merge_site_feedback(segments, _load_site_stop_feedback_rows(db, tenant_no=tenant_no, transport_id=transport_id))
  400. return segments
  401. def _get_driver_feedback_row(
  402. db: Session,
  403. *,
  404. tenant_no: str,
  405. transport_id: str,
  406. stop_type: str,
  407. stop_id: str,
  408. ) -> Optional[PlTransportDriverStopFeedback]:
  409. return (
  410. db.query(PlTransportDriverStopFeedback)
  411. .filter(
  412. PlTransportDriverStopFeedback.transport_id == transport_id,
  413. PlTransportDriverStopFeedback.tenant_no == tenant_no,
  414. PlTransportDriverStopFeedback.stop_type == stop_type,
  415. PlTransportDriverStopFeedback.stop_id == stop_id,
  416. PlTransportDriverStopFeedback.del_flag == 0,
  417. )
  418. .first()
  419. )
  420. def save_driver_stop_feedback(
  421. db: Session,
  422. *,
  423. tenant_no: str,
  424. transport_id: str,
  425. plan_id: str,
  426. stop_type: str,
  427. stop_id: str,
  428. attachment_urls: list[str],
  429. products: Optional[list[dict[str, Any]]] = None,
  430. remark: Optional[str] = None,
  431. user_id: Optional[str] = None,
  432. dept_id: str = "",
  433. ) -> PlTransportDriverStopFeedback:
  434. row = _get_driver_feedback_row(
  435. db,
  436. tenant_no=tenant_no,
  437. transport_id=transport_id,
  438. stop_type=stop_type,
  439. stop_id=stop_id,
  440. )
  441. now = datetime.now()
  442. product_feedbacks_dump = _dump_product_feedbacks(products)
  443. if row:
  444. row.attachment_urls = _dump_urls(attachment_urls)
  445. if product_feedbacks_dump is not None:
  446. row.product_feedbacks = product_feedbacks_dump
  447. if remark is not None:
  448. row.remark = remark
  449. row.feedback_time = now
  450. row.update_by = user_id
  451. else:
  452. row = PlTransportDriverStopFeedback(
  453. id=generate_uuid(),
  454. tenant_no=tenant_no,
  455. transport_id=transport_id,
  456. plan_id=plan_id,
  457. stop_type=stop_type,
  458. stop_id=stop_id,
  459. attachment_urls=_dump_urls(attachment_urls),
  460. product_feedbacks=product_feedbacks_dump,
  461. remark=remark,
  462. feedback_time=now,
  463. create_by=user_id,
  464. create_dept_id=dept_id,
  465. )
  466. db.add(row)
  467. db.flush()
  468. return row
  469. def _get_site_feedback_row(
  470. db: Session,
  471. *,
  472. tenant_no: str,
  473. transport_id: str,
  474. stop_type: str,
  475. stop_id: str,
  476. ) -> Optional[PlTransportSiteStopFeedback]:
  477. return (
  478. db.query(PlTransportSiteStopFeedback)
  479. .filter(
  480. PlTransportSiteStopFeedback.transport_id == transport_id,
  481. PlTransportSiteStopFeedback.tenant_no == tenant_no,
  482. PlTransportSiteStopFeedback.stop_type == stop_type,
  483. PlTransportSiteStopFeedback.stop_id == stop_id,
  484. PlTransportSiteStopFeedback.del_flag == 0,
  485. )
  486. .first()
  487. )
  488. def _sum_product_actual_qty(products: Optional[list[dict[str, Any]]]) -> Optional[Decimal]:
  489. if not products:
  490. return None
  491. total = Decimal("0")
  492. has_qty = False
  493. for item in products:
  494. actual = item.get("actualQty", item.get("actual_qty"))
  495. if actual is None:
  496. continue
  497. qty = Decimal(str(actual))
  498. if qty > 0:
  499. total += qty
  500. has_qty = True
  501. return total if has_qty else None
  502. def _has_positive_feedback_qty(
  503. quantity: Optional[Decimal],
  504. products: Optional[list[dict[str, Any]]],
  505. ) -> bool:
  506. product_total = _sum_product_actual_qty(products)
  507. if product_total is not None:
  508. return product_total > 0
  509. return quantity is not None and quantity > 0
  510. def save_site_stop_feedback(
  511. db: Session,
  512. *,
  513. tenant_no: str,
  514. transport_id: str,
  515. plan_id: str,
  516. stop_type: str,
  517. stop_id: str,
  518. business_type: str,
  519. quantity: Optional[Decimal] = None,
  520. attachment_urls: Optional[list[str]] = None,
  521. products: Optional[list[dict[str, Any]]] = None,
  522. remark: Optional[str] = None,
  523. user_id: Optional[str] = None,
  524. dept_id: str = "",
  525. require_qty_before_attachments: bool = True,
  526. ) -> PlTransportSiteStopFeedback:
  527. product_feedbacks_dump = _dump_product_feedbacks(products)
  528. effective_qty = quantity
  529. if products is not None:
  530. effective_qty = _sum_product_actual_qty(products)
  531. if require_qty_before_attachments and attachment_urls and not _has_positive_feedback_qty(
  532. effective_qty, products
  533. ):
  534. raise ValueError("请先填写数量,再上传附件")
  535. row = _get_site_feedback_row(
  536. db,
  537. tenant_no=tenant_no,
  538. transport_id=transport_id,
  539. stop_type=stop_type,
  540. stop_id=stop_id,
  541. )
  542. now = datetime.now()
  543. if row:
  544. if effective_qty is not None:
  545. row.quantity = effective_qty
  546. if attachment_urls is not None:
  547. row.attachment_urls = _dump_urls(attachment_urls)
  548. if product_feedbacks_dump is not None:
  549. row.product_feedbacks = product_feedbacks_dump
  550. if remark is not None:
  551. row.remark = remark
  552. row.feedback_time = now
  553. row.update_by = user_id
  554. else:
  555. row = PlTransportSiteStopFeedback(
  556. id=generate_uuid(),
  557. tenant_no=tenant_no,
  558. transport_id=transport_id,
  559. plan_id=plan_id,
  560. stop_type=stop_type,
  561. stop_id=stop_id,
  562. business_type=business_type,
  563. quantity=effective_qty,
  564. attachment_urls=_dump_urls(attachment_urls or []),
  565. product_feedbacks=product_feedbacks_dump,
  566. remark=remark,
  567. feedback_time=now,
  568. create_by=user_id,
  569. create_dept_id=dept_id,
  570. )
  571. db.add(row)
  572. db.flush()
  573. return row
  574. def list_driver_stop_feedback_reads(
  575. db: Session,
  576. *,
  577. tenant_no: str,
  578. transport_id: str,
  579. plan_id: str,
  580. ) -> list[dict[str, Any]]:
  581. segments = load_driver_stop_segments(
  582. db,
  583. tenant_no=tenant_no,
  584. plan_id=plan_id,
  585. transport_id=transport_id,
  586. )
  587. return [
  588. {
  589. "stopType": segment.stop_type,
  590. "stopId": segment.stop_id,
  591. "label": segment.label,
  592. "customerName": segment.customer_name,
  593. "attachmentUrls": segment.attachment_urls,
  594. "products": [
  595. {
  596. "stopProductId": product.stop_product_id,
  597. "planProductId": product.plan_product_id,
  598. "productName": product.product_name,
  599. "model": product.model,
  600. "unit": product.unit,
  601. "packageSpec": product.package_spec,
  602. "quantity": float(product.plan_qty) if product.plan_qty is not None else None,
  603. "actualQty": float(product.actual_qty)
  604. if product.actual_qty is not None
  605. else None,
  606. "brandQtys": product.brand_qtys,
  607. }
  608. for product in segment.products
  609. if product.actual_qty is not None
  610. or (product.brand_qtys and len(product.brand_qtys) > 0)
  611. ],
  612. "remark": segment.remark,
  613. "feedbackTime": segment.feedback_time,
  614. }
  615. for segment in segments
  616. if segment.attachment_urls
  617. or segment.remark
  618. or segment.feedback_time
  619. or any(
  620. product.actual_qty is not None
  621. or (product.brand_qtys and len(product.brand_qtys) > 0)
  622. for product in segment.products
  623. )
  624. ]
  625. def list_site_stop_feedback_reads(
  626. db: Session,
  627. *,
  628. tenant_no: str,
  629. transport_id: str,
  630. plan_id: str,
  631. ) -> list[dict[str, Any]]:
  632. segments = load_site_stop_segments(
  633. db,
  634. tenant_no=tenant_no,
  635. plan_id=plan_id,
  636. transport_id=transport_id,
  637. )
  638. return [
  639. {
  640. "stopType": segment.stop_type,
  641. "stopId": segment.stop_id,
  642. "label": segment.label,
  643. "customerName": segment.customer_name,
  644. "businessType": segment.business_type,
  645. "quantity": float(segment.quantity) if segment.quantity is not None else None,
  646. "attachmentUrls": segment.attachment_urls,
  647. "products": [
  648. {
  649. "stopProductId": product.stop_product_id,
  650. "planProductId": product.plan_product_id,
  651. "productName": product.product_name,
  652. "model": product.model,
  653. "unit": product.unit,
  654. "packageSpec": product.package_spec,
  655. "quantity": float(product.plan_qty) if product.plan_qty is not None else None,
  656. "actualQty": float(product.actual_qty)
  657. if product.actual_qty is not None
  658. else None,
  659. "brandQtys": product.brand_qtys,
  660. }
  661. for product in segment.products
  662. if product.actual_qty is not None
  663. or (product.brand_qtys and len(product.brand_qtys) > 0)
  664. ],
  665. "remark": segment.remark,
  666. "feedbackTime": segment.feedback_time,
  667. }
  668. for segment in segments
  669. if segment.quantity is not None
  670. or segment.attachment_urls
  671. or segment.remark
  672. or any(
  673. product.actual_qty is not None
  674. or (product.brand_qtys and len(product.brand_qtys) > 0)
  675. for product in segment.products
  676. )
  677. ]
  678. CRM_PRODUCT_UNIT = "crm_product_unit"
  679. def _resolve_unit_label(unit_map: dict[str, str], unit_code: Optional[str]) -> str:
  680. code = (unit_code or "").strip()
  681. if not code:
  682. return "吨"
  683. return unit_map.get(code, code)
  684. def build_public_stop_reads_for_segments(
  685. db: Session,
  686. *,
  687. tenant_no: str,
  688. plan_id: str,
  689. segments: list[PublicStopSegment],
  690. ) -> list[dict[str, Any]]:
  691. """为公共页组装装货/送货段及段内产品(含别名、品牌选项)。"""
  692. from app.models.crm_models import CrmProductBrand
  693. from app.models.pl_models import PlPlanProduct
  694. from app.schemas.pl.transport import BrandOption, PublicTransportStopProductRead, PublicTransportStopRead
  695. from app.services.pl_product_display import load_crm_product_alias_maps, resolve_product_display_names
  696. from app.utils.excel_export import load_dict_label_maps
  697. plan_products = (
  698. db.query(PlPlanProduct)
  699. .filter(
  700. PlPlanProduct.plan_id == plan_id,
  701. PlPlanProduct.tenant_no == tenant_no,
  702. PlPlanProduct.del_flag == 0,
  703. )
  704. .order_by(PlPlanProduct.order_num.asc(), PlPlanProduct.create_time.asc())
  705. .all()
  706. )
  707. plan_products_by_id = {row.id: row for row in plan_products}
  708. crm_product_ids = {
  709. (row.product_id or "").strip() for row in plan_products if (row.product_id or "").strip()
  710. }
  711. brand_options_by_product: dict[str, list[BrandOption]] = {}
  712. if crm_product_ids:
  713. brand_rows = (
  714. db.query(CrmProductBrand)
  715. .filter(
  716. CrmProductBrand.product_id.in_(list(crm_product_ids)),
  717. CrmProductBrand.tenant_no == tenant_no,
  718. CrmProductBrand.status == "on",
  719. CrmProductBrand.del_flag == 0,
  720. )
  721. .order_by(CrmProductBrand.order_num.asc(), CrmProductBrand.create_time.asc())
  722. .all()
  723. )
  724. for row in brand_rows:
  725. brand_options_by_product.setdefault(row.product_id, []).append(
  726. BrandOption(brand_id=row.id, brand_name=row.brand_name or "")
  727. )
  728. standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
  729. db, tenant_no=tenant_no, product_ids=crm_product_ids
  730. )
  731. unit_map = load_dict_label_maps(db, [CRM_PRODUCT_UNIT], tenant_no=tenant_no).get(
  732. CRM_PRODUCT_UNIT, {}
  733. )
  734. reads: list[PublicTransportStopRead] = []
  735. for segment in segments:
  736. show_product_qty = is_internal_customer_name(segment.customer_name)
  737. product_reads: list[PublicTransportStopProductRead] = []
  738. if show_product_qty:
  739. for row in segment.products:
  740. plan_prod = plan_products_by_id.get(row.plan_product_id)
  741. product_id = (
  742. row.product_id or (plan_prod.product_id if plan_prod else "") or ""
  743. ).strip()
  744. display_name, alias_name = resolve_product_display_names(
  745. saved_product_name=row.product_name,
  746. product_id=product_id,
  747. standard_by_id=standard_by_id,
  748. alias_options_by_id=alias_options_by_id,
  749. )
  750. brand_qtys = None
  751. if row.brand_qtys:
  752. from app.schemas.pl.transport import BrandQtyItem
  753. brand_qtys = [
  754. BrandQtyItem(
  755. brand_id=str(item.get("brandId") or item.get("brand_id") or ""),
  756. brand_name=item.get("brandName") or item.get("brand_name"),
  757. qty=item.get("qty") or 0,
  758. )
  759. for item in row.brand_qtys
  760. if isinstance(item, dict)
  761. ] or None
  762. product_reads.append(
  763. PublicTransportStopProductRead(
  764. stop_product_id=row.stop_product_id,
  765. plan_product_id=row.plan_product_id,
  766. product_name=display_name,
  767. alias_name=alias_name,
  768. model=row.model,
  769. package_spec=row.package_spec,
  770. unit=_resolve_unit_label(unit_map, row.unit),
  771. quantity=row.plan_qty,
  772. remark=row.remark,
  773. brand_mode=plan_prod.brand_mode if plan_prod else None,
  774. brand_id=plan_prod.brand_id if plan_prod else None,
  775. brand_name=plan_prod.brand_name if plan_prod else None,
  776. brand_options=brand_options_by_product.get(product_id) or None,
  777. actual_qty=row.actual_qty,
  778. brand_qtys=brand_qtys,
  779. )
  780. )
  781. reads.append(
  782. PublicTransportStopRead(
  783. stop_type=segment.stop_type,
  784. stop_id=segment.stop_id,
  785. seq=segment.seq,
  786. label=segment.label,
  787. customer_name=segment.customer_name,
  788. address=segment.address,
  789. contact=segment.contact,
  790. notes=segment.notes,
  791. lng=segment.lng,
  792. lat=segment.lat,
  793. business_type=segment.business_type,
  794. plan_qty=segment.plan_qty,
  795. quantity=segment.quantity,
  796. show_product_qty=show_product_qty,
  797. products=product_reads,
  798. attachment_urls=segment.attachment_urls,
  799. remark=segment.remark,
  800. feedback_time=segment.feedback_time,
  801. )
  802. )
  803. return [row.model_dump(by_alias=True) for row in reads]