pl_io_order_service.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. """运输计划 · 入库单 / 出库单(安排运输落单、现场回传、作废)"""
  2. from __future__ import annotations
  3. import json
  4. import secrets
  5. from dataclasses import dataclass
  6. from datetime import date, datetime
  7. from decimal import Decimal
  8. from typing import Any, Optional, Union
  9. from sqlalchemy.orm import Session
  10. from app.core.config import settings
  11. from app.core.utils import generate_uuid
  12. from app.models.crm_models import CrmProduct, CrmProductBrand
  13. from app.models.db_models import DbInboundOutbound
  14. from app.models.pl_models import (
  15. PlInboundOrder,
  16. PlInboundOrderItem,
  17. PlInboundOrderItemBrandQty,
  18. PlOutboundOrder,
  19. PlOutboundOrderItem,
  20. PlOutboundOrderItemBrandQty,
  21. PlPlan,
  22. PlPlanProduct,
  23. PlPlanProductBrandQty,
  24. PlTransport,
  25. PlTransportDbLink,
  26. )
  27. from app.services.db.mappers import parse_date_str
  28. from app.services.pl_dibang_bridge_service import _product_quantity, resolve_partner_company
  29. from app.services.pl_feedback_brand_qty import (
  30. format_brand_qty_summary,
  31. persist_io_item_brand_qtys,
  32. require_brand_qtys_if_needed,
  33. )
  34. from app.services.pl_product_display import apply_product_alias_display, load_crm_product_alias_maps
  35. OrderHeader = Union[PlInboundOrder, PlOutboundOrder]
  36. OrderItem = Union[PlInboundOrderItem, PlOutboundOrderItem]
  37. @dataclass
  38. class IoOrderCreateResult:
  39. kind: str # inbound | outbound
  40. order_id: str
  41. order_no: str
  42. site_access_token: str
  43. site_url: str
  44. def build_io_order_site_url(kind: str, token: str) -> str:
  45. origin = (settings.PUBLIC_WEB_ORIGIN or "").rstrip("/")
  46. path = "inbound" if kind == "inbound" else "outbound"
  47. return f"{origin}/#/public/pl/{path}/{token}"
  48. def _normalize_plan_date(plan: PlPlan) -> date:
  49. plan_date = plan.plan_date
  50. if isinstance(plan_date, datetime):
  51. return plan_date.date()
  52. if isinstance(plan_date, str):
  53. return parse_date_str(plan_date) or date.today()
  54. if isinstance(plan_date, date):
  55. return plan_date
  56. return date.today()
  57. def _next_order_no(db: Session, tenant_no: str, prefix: str, model: type) -> str:
  58. day = datetime.now().strftime("%Y%m%d")
  59. like = f"{prefix}{day}%"
  60. last = (
  61. db.query(model.order_no)
  62. .filter(model.tenant_no == tenant_no, model.order_no.like(like), model.del_flag == 0)
  63. .order_by(model.order_no.desc())
  64. .first()
  65. )
  66. seq = 1
  67. if last and last[0] and len(last[0]) >= len(prefix) + 8 + 4:
  68. try:
  69. seq = int(last[0][-4:]) + 1
  70. except ValueError:
  71. seq = 1
  72. return f"{prefix}{day}{seq:04d}"
  73. def _dibang_qty_by_plan_product(
  74. db: Session, tenant_no: str, transport_id: str
  75. ) -> dict[str, Decimal]:
  76. links = (
  77. db.query(PlTransportDbLink)
  78. .filter(
  79. PlTransportDbLink.tenant_no == tenant_no,
  80. PlTransportDbLink.transport_id == transport_id,
  81. PlTransportDbLink.del_flag == 0,
  82. )
  83. .all()
  84. )
  85. if not links:
  86. return {}
  87. inv_ids = [x.db_inventory_id for x in links if x.db_inventory_id]
  88. if not inv_ids:
  89. return {}
  90. inv_rows = (
  91. db.query(DbInboundOutbound)
  92. .filter(DbInboundOutbound.id.in_(inv_ids), DbInboundOutbound.del_flag == 0)
  93. .all()
  94. )
  95. inv_map = {r.id: r for r in inv_rows}
  96. out: dict[str, Decimal] = {}
  97. for link in links:
  98. inv = inv_map.get(link.db_inventory_id)
  99. if not inv or inv.quantity is None:
  100. continue
  101. out[link.plan_product_id] = Decimal(str(inv.quantity))
  102. return out
  103. def create_io_order_for_transport(
  104. db: Session,
  105. *,
  106. tenant_no: str,
  107. plan: PlPlan,
  108. products: list[PlPlanProduct],
  109. transport: PlTransport,
  110. user_id: Optional[str],
  111. dept_id: str,
  112. after_dibang: bool = False,
  113. ) -> Optional[IoOrderCreateResult]:
  114. """安排运输后创建入库/出库单。直销返回 None。"""
  115. if plan.plan_type not in ("inbound", "outbound"):
  116. return None
  117. kind = plan.plan_type
  118. header_model = PlInboundOrder if kind == "inbound" else PlOutboundOrder
  119. item_model = PlInboundOrderItem if kind == "inbound" else PlOutboundOrderItem
  120. prefix = "RK" if kind == "inbound" else "CK"
  121. partner = resolve_partner_company(plan, plan.plan_type)
  122. if not partner:
  123. raise ValueError("无法解析往来单位,请检查合同供方/需方信息")
  124. token = secrets.token_urlsafe(32)[:64]
  125. order_no = _next_order_no(db, tenant_no, prefix, header_model)
  126. plan_date = _normalize_plan_date(plan)
  127. license_plate = (transport.license_plate or plan.license_plate or "").strip()
  128. dibang_map = _dibang_qty_by_plan_product(db, tenant_no, transport.id) if after_dibang else {}
  129. header = header_model(
  130. id=generate_uuid(),
  131. order_no=order_no,
  132. plan_id=plan.id,
  133. transport_id=transport.id,
  134. status="in_progress",
  135. partner_company=partner,
  136. vehicle_no=license_plate or None,
  137. plan_no=(plan.plan_no or "").strip() or None,
  138. plan_date=plan_date,
  139. site_access_token=token,
  140. create_by=user_id,
  141. create_dept_id=dept_id or "",
  142. tenant_no=tenant_no,
  143. )
  144. db.add(header)
  145. for idx, product in enumerate(products):
  146. plan_qty = Decimal(str(_product_quantity(product)))
  147. actual = dibang_map.get(product.id)
  148. qty_source = "dibang" if actual is not None else "plan"
  149. if actual is None:
  150. actual = plan_qty
  151. db.add(
  152. item_model(
  153. id=generate_uuid(),
  154. order_id=header.id,
  155. plan_product_id=product.id,
  156. product_id=product.product_id,
  157. product_name=product.product_name,
  158. specification=product.model,
  159. unit=product.unit,
  160. plan_qty=plan_qty,
  161. actual_qty=actual,
  162. qty_source=qty_source,
  163. order_num=idx + 1,
  164. create_by=user_id,
  165. create_dept_id=dept_id or "",
  166. tenant_no=tenant_no,
  167. )
  168. )
  169. db.flush()
  170. return IoOrderCreateResult(
  171. kind=kind,
  172. order_id=header.id,
  173. order_no=order_no,
  174. site_access_token=token,
  175. site_url=build_io_order_site_url(kind, token),
  176. )
  177. def apply_dibang_prefill_to_order(
  178. db: Session,
  179. *,
  180. tenant_no: str,
  181. plan: PlPlan,
  182. transport: PlTransport,
  183. ) -> None:
  184. """地磅单生成后,用数量预填尚未被现场改过的明细 actual_qty。"""
  185. if plan.plan_type not in ("inbound", "outbound"):
  186. return
  187. header_model = PlInboundOrder if plan.plan_type == "inbound" else PlOutboundOrder
  188. item_model = PlInboundOrderItem if plan.plan_type == "inbound" else PlOutboundOrderItem
  189. header = (
  190. db.query(header_model)
  191. .filter(
  192. header_model.tenant_no == tenant_no,
  193. header_model.plan_id == plan.id,
  194. header_model.transport_id == transport.id,
  195. header_model.status != "voided",
  196. header_model.del_flag == 0,
  197. )
  198. .order_by(header_model.create_time.desc())
  199. .first()
  200. )
  201. if not header:
  202. return
  203. dibang_map = _dibang_qty_by_plan_product(db, tenant_no, transport.id)
  204. if not dibang_map:
  205. return
  206. items = (
  207. db.query(item_model)
  208. .filter(item_model.order_id == header.id, item_model.del_flag == 0)
  209. .all()
  210. )
  211. for item in items:
  212. qty = dibang_map.get(item.plan_product_id)
  213. if qty is None:
  214. continue
  215. if item.qty_source == "manual":
  216. continue
  217. item.actual_qty = qty
  218. item.qty_source = "dibang"
  219. db.flush()
  220. def void_io_orders_for_plan(
  221. db: Session,
  222. *,
  223. tenant_no: str,
  224. plan_id: str,
  225. user_id: Optional[str],
  226. ) -> None:
  227. for model in (PlInboundOrder, PlOutboundOrder):
  228. rows = (
  229. db.query(model)
  230. .filter(
  231. model.tenant_no == tenant_no,
  232. model.plan_id == plan_id,
  233. model.status != "voided",
  234. model.del_flag == 0,
  235. )
  236. .all()
  237. )
  238. for row in rows:
  239. row.status = "voided"
  240. row.update_by = user_id
  241. db.flush()
  242. def get_active_io_order_for_plan(
  243. db: Session, tenant_no: str, plan: PlPlan
  244. ) -> Optional[tuple[str, OrderHeader]]:
  245. if plan.plan_type == "inbound":
  246. row = (
  247. db.query(PlInboundOrder)
  248. .filter(
  249. PlInboundOrder.tenant_no == tenant_no,
  250. PlInboundOrder.plan_id == plan.id,
  251. PlInboundOrder.del_flag == 0,
  252. )
  253. .order_by(PlInboundOrder.create_time.desc())
  254. .first()
  255. )
  256. return ("inbound", row) if row else None
  257. if plan.plan_type == "outbound":
  258. row = (
  259. db.query(PlOutboundOrder)
  260. .filter(
  261. PlOutboundOrder.tenant_no == tenant_no,
  262. PlOutboundOrder.plan_id == plan.id,
  263. PlOutboundOrder.del_flag == 0,
  264. )
  265. .order_by(PlOutboundOrder.create_time.desc())
  266. .first()
  267. )
  268. return ("outbound", row) if row else None
  269. return None
  270. def parse_feedback_images(raw: Optional[str]) -> list[str]:
  271. if not raw:
  272. return []
  273. try:
  274. parsed = json.loads(raw)
  275. if isinstance(parsed, list):
  276. return [str(item) for item in parsed if item]
  277. except (TypeError, json.JSONDecodeError):
  278. pass
  279. return [part.strip() for part in raw.split(",") if part.strip()]
  280. def dump_feedback_images(images: list[str]) -> str:
  281. return json.dumps(images, ensure_ascii=False)
  282. _VALID_SITE_FEEDBACK_STATUSES = frozenset({"in_progress", "completed", "voided"})
  283. def _io_item_brand_qty_model(kind: str):
  284. if kind == "inbound":
  285. return PlInboundOrderItemBrandQty
  286. return PlOutboundOrderItemBrandQty
  287. def update_io_order_items_qty_and_brand(
  288. db: Session,
  289. *,
  290. kind: str,
  291. tenant_no: str,
  292. order_id: str,
  293. items: list[OrderItem],
  294. item_qty: dict[str, Decimal],
  295. item_brand_qtys: Optional[dict[str, list[dict]]] = None,
  296. enforce_brand: bool = False,
  297. user_id: Optional[str] = None,
  298. ) -> None:
  299. """更新明细实际数量,并按需校验/持久化现场品牌数量。"""
  300. updating = [it for it in items if it.id in item_qty]
  301. if not updating:
  302. return
  303. plan_product_ids = [it.plan_product_id for it in updating if it.plan_product_id]
  304. products_by_id: dict[str, PlPlanProduct] = {}
  305. if plan_product_ids:
  306. rows = (
  307. db.query(PlPlanProduct)
  308. .filter(
  309. PlPlanProduct.id.in_(plan_product_ids),
  310. PlPlanProduct.tenant_no == tenant_no,
  311. PlPlanProduct.del_flag == 0,
  312. )
  313. .all()
  314. )
  315. products_by_id = {r.id: r for r in rows}
  316. # 明细仍指向已软删计划产品行时,用原行品牌约定(避免 brand_mode 空导致只删不写)
  317. missing_ids = [pid for pid in plan_product_ids if pid and pid not in products_by_id]
  318. if missing_ids:
  319. stale_rows = (
  320. db.query(PlPlanProduct)
  321. .filter(
  322. PlPlanProduct.id.in_(missing_ids),
  323. PlPlanProduct.tenant_no == tenant_no,
  324. )
  325. .all()
  326. )
  327. for row in stale_rows:
  328. products_by_id.setdefault(row.id, row)
  329. brand_model = _io_item_brand_qty_model(kind)
  330. for item in updating:
  331. actual_qty = item_qty[item.id]
  332. plan_product = products_by_id.get(item.plan_product_id or "")
  333. brand_mode = plan_product.brand_mode if plan_product else None
  334. required_brand_id = plan_product.brand_id if plan_product else None
  335. brand_touched = item_brand_qtys is not None and item.id in item_brand_qtys
  336. if brand_touched:
  337. rows = item_brand_qtys[item.id]
  338. # 客户端带了品牌明细时,即使计划行 brand_mode 丢失也按 any 规则校验/落库
  339. if not brand_mode and rows:
  340. brand_mode = "any"
  341. elif enforce_brand:
  342. rows = []
  343. else:
  344. rows = None
  345. if rows is not None:
  346. require_brand_qtys_if_needed(
  347. brand_mode=brand_mode,
  348. required_brand_id=required_brand_id,
  349. actual_qty=actual_qty,
  350. rows=rows,
  351. enforce=enforce_brand,
  352. )
  353. item.actual_qty = actual_qty
  354. item.qty_source = "manual"
  355. item.update_by = user_id
  356. if brand_touched:
  357. persist_io_item_brand_qtys(
  358. db,
  359. model=brand_model,
  360. tenant_no=tenant_no,
  361. order_id=order_id,
  362. order_item_id=item.id,
  363. plan_product_id=item.plan_product_id,
  364. brand_mode=brand_mode,
  365. rows=item_brand_qtys[item.id],
  366. user_id=user_id,
  367. )
  368. def apply_site_feedback(
  369. db: Session,
  370. *,
  371. kind: str,
  372. header: OrderHeader,
  373. items: list[OrderItem],
  374. item_qty: dict[str, Decimal],
  375. remark: Optional[str],
  376. images: list[str],
  377. status: str,
  378. item_brand_qtys: Optional[dict[str, list[dict]]] = None,
  379. enforce_brand: bool = False,
  380. user_id: Optional[str] = None,
  381. ) -> None:
  382. if header.status == "voided":
  383. raise ValueError("单据已作废,无法提交")
  384. if status not in _VALID_SITE_FEEDBACK_STATUSES:
  385. raise ValueError(f"无效状态: {status}")
  386. now = datetime.now()
  387. update_io_order_items_qty_and_brand(
  388. db,
  389. kind=kind,
  390. tenant_no=header.tenant_no,
  391. order_id=header.id,
  392. items=items,
  393. item_qty=item_qty,
  394. item_brand_qtys=item_brand_qtys,
  395. enforce_brand=enforce_brand,
  396. user_id=user_id,
  397. )
  398. header.site_feedback_remark = (remark or "").strip() or None
  399. header.site_feedback_images = dump_feedback_images(images) if images else header.site_feedback_images
  400. header.site_feedback_time = now
  401. if not header.site_first_submitted_at:
  402. header.site_first_submitted_at = now
  403. header.status = status
  404. header.update_by = user_id
  405. db.flush()
  406. CRM_PRODUCT_UNIT = "crm_product_unit"
  407. PLAN_TYPE_BUSINESS_LABEL = {
  408. "inbound": "入库",
  409. "outbound": "出库",
  410. "direct": "直销",
  411. }
  412. def resolve_unit_label(unit_map: dict[str, str], unit_code: Optional[str]) -> str:
  413. code = (unit_code or "").strip()
  414. if not code:
  415. return "吨"
  416. return unit_map.get(code, code)
  417. def merge_plan_logistics_into_order(data: dict, plan: Optional[PlPlan]) -> None:
  418. if not plan:
  419. data.setdefault("businessType", None)
  420. data.setdefault("planRemark", None)
  421. data.setdefault("pickupAddress", None)
  422. data.setdefault("pickupLng", None)
  423. data.setdefault("pickupLat", None)
  424. data.setdefault("pickupTime", None)
  425. data.setdefault("pickupNotes", None)
  426. data.setdefault("destinationName", None)
  427. data.setdefault("destinationAddress", None)
  428. data.setdefault("destinationLng", None)
  429. data.setdefault("destinationLat", None)
  430. data.setdefault("deliveryTime", None)
  431. data.setdefault("destinationNotes", None)
  432. return
  433. data["businessType"] = PLAN_TYPE_BUSINESS_LABEL.get(plan.plan_type, plan.plan_type)
  434. data["planRemark"] = (plan.remark or "").strip() or None
  435. data["pickupAddress"] = plan.pickup_address
  436. data["pickupLng"] = plan.pickup_lng
  437. data["pickupLat"] = plan.pickup_lat
  438. data["pickupTime"] = plan.pickup_time
  439. data["pickupNotes"] = plan.pickup_notes
  440. data["destinationName"] = plan.destination_name
  441. data["destinationAddress"] = plan.destination_address or plan.destination_name
  442. data["destinationLng"] = plan.destination_lng
  443. data["destinationLat"] = plan.destination_lat
  444. data["deliveryTime"] = plan.delivery_time
  445. data["destinationNotes"] = plan.destination_notes
  446. def merge_plan_product_into_item(
  447. item: dict,
  448. product: Optional[PlPlanProduct],
  449. *,
  450. unit_map: dict[str, str],
  451. crm_product_no: Optional[str] = None,
  452. ) -> None:
  453. if not product:
  454. item.setdefault("productNo", None)
  455. item.setdefault("categoryName", None)
  456. item.setdefault("packageSpec", None)
  457. item.setdefault("deliveryMethod", None)
  458. item.setdefault("remark", None)
  459. item["unitLabel"] = resolve_unit_label(unit_map, item.get("unit"))
  460. return
  461. # 优先 CRM 产品编码;计划冗余 product_no 可能被误存为 product_id
  462. product_id = (product.product_id or item.get("productId") or item.get("product_id") or "").strip()
  463. plan_no = (product.product_no or "").strip()
  464. resolved_no = (crm_product_no or "").strip()
  465. if not resolved_no and plan_no and plan_no != product_id:
  466. resolved_no = plan_no
  467. # CRM 缺失时仍回退计划 product_no,避免前端编码列空白
  468. if not resolved_no and plan_no:
  469. resolved_no = plan_no
  470. item["productNo"] = resolved_no or None
  471. item["categoryName"] = product.category_name
  472. item["packageSpec"] = product.package_spec or item.get("packageSpec")
  473. item["deliveryMethod"] = product.delivery_method
  474. item["remark"] = (product.remark or "").strip() or item.get("remark")
  475. if not item.get("specification") and product.model:
  476. item["specification"] = product.model
  477. item["unitLabel"] = resolve_unit_label(unit_map, item.get("unit") or product.unit)
  478. # 无品牌拆分量时,回退计划产品上的品牌快照
  479. if product.brand_name and not item.get("brandSummary"):
  480. item["brandName"] = product.brand_name
  481. if product.brand_mode:
  482. item.setdefault("brandMode", product.brand_mode)
  483. def _format_io_product_summary_line(item: dict) -> str:
  484. name = (item.get("productName") or "").strip()
  485. if not name:
  486. return ""
  487. bits: list[str] = []
  488. brand = (item.get("brandSummary") or item.get("brandName") or "").strip()
  489. if brand:
  490. bits.append(f"品牌 {brand}")
  491. spec = (item.get("specification") or "").strip()
  492. if spec:
  493. bits.append(f"型号/规格 {spec}")
  494. unit = (item.get("unitLabel") or item.get("unit") or "").strip()
  495. if unit:
  496. bits.append(f"单位 {unit}")
  497. package = (item.get("packageSpec") or "").strip()
  498. if package:
  499. bits.append(f"包装规格 {package}")
  500. delivery = (item.get("deliveryMethod") or "").strip()
  501. if delivery:
  502. delivery_labels = {
  503. "self_pick": "山峡自提",
  504. "one_ticket": "一票制",
  505. "customer_pick": "客户自提",
  506. }
  507. bits.append(f"送货方式 {delivery_labels.get(delivery, delivery)}")
  508. return f"{name},{','.join(bits)}" if bits else name
  509. def enrich_io_items_with_brand_feedback(
  510. db: Session,
  511. *,
  512. kind: str,
  513. tenant_no: str,
  514. items: list[dict],
  515. products_by_id: dict[str, PlPlanProduct],
  516. prefer_site_brand_summary: bool = False,
  517. ) -> None:
  518. """读时附加品牌模式、CRM 品牌选项与现场品牌数量子表。"""
  519. if not items:
  520. return
  521. crm_product_ids: set[str] = set()
  522. order_item_ids: list[str] = []
  523. for it in items:
  524. item_id = (it.get("id") or "").strip()
  525. if item_id:
  526. order_item_ids.append(item_id)
  527. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  528. pp = products_by_id.get(plan_product_id)
  529. product_id = (
  530. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  531. ).strip()
  532. if product_id:
  533. crm_product_ids.add(product_id)
  534. brand_options_by_product: dict[str, list[dict]] = {}
  535. if crm_product_ids:
  536. brand_rows = (
  537. db.query(CrmProductBrand)
  538. .filter(
  539. CrmProductBrand.product_id.in_(list(crm_product_ids)),
  540. CrmProductBrand.tenant_no == tenant_no,
  541. CrmProductBrand.status == "on",
  542. CrmProductBrand.del_flag == 0,
  543. )
  544. .order_by(CrmProductBrand.order_num.asc(), CrmProductBrand.create_time.asc())
  545. .all()
  546. )
  547. for row in brand_rows:
  548. brand_options_by_product.setdefault(row.product_id, []).append(
  549. {"brandId": row.id, "brandName": row.brand_name}
  550. )
  551. site_rows_by_item: dict[str, list[dict]] = {}
  552. if order_item_ids:
  553. brand_model = _io_item_brand_qty_model(kind)
  554. site_rows = (
  555. db.query(brand_model)
  556. .filter(
  557. brand_model.order_item_id.in_(order_item_ids),
  558. brand_model.tenant_no == tenant_no,
  559. brand_model.del_flag == 0,
  560. )
  561. .order_by(brand_model.order_num.asc())
  562. .all()
  563. )
  564. for row in site_rows:
  565. site_rows_by_item.setdefault(row.order_item_id, []).append(
  566. {
  567. "brandId": row.brand_id or "",
  568. "brandName": row.brand_name,
  569. "qty": row.qty,
  570. }
  571. )
  572. for it in items:
  573. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  574. pp = products_by_id.get(plan_product_id)
  575. product_id = (
  576. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  577. ).strip()
  578. if pp:
  579. it["brandMode"] = pp.brand_mode
  580. it["brandId"] = pp.brand_id
  581. if pp.brand_name:
  582. it["brandName"] = pp.brand_name
  583. else:
  584. it.setdefault("brandMode", None)
  585. it.setdefault("brandId", None)
  586. options = brand_options_by_product.get(product_id, [])
  587. it["brandOptions"] = options if options else None
  588. site_qtys = site_rows_by_item.get(it.get("id") or "", [])
  589. it["brandQtys"] = site_qtys if site_qtys else None
  590. if prefer_site_brand_summary:
  591. site_summary = format_brand_qty_summary(site_qtys)
  592. if site_summary:
  593. it["brandSummary"] = site_summary
  594. def enrich_io_order_dict(
  595. db: Session,
  596. data: dict,
  597. *,
  598. tenant_no: str,
  599. plan_id: Optional[str],
  600. items: list[Any] | None,
  601. public_unit_as_label: bool = False,
  602. kind: str = "inbound",
  603. ) -> dict:
  604. """读时附加计划取送货与产品扩展字段。"""
  605. from app.utils.excel_export import load_dict_label_maps
  606. plan = None
  607. if plan_id:
  608. plan = (
  609. db.query(PlPlan)
  610. .filter(
  611. PlPlan.id == plan_id,
  612. PlPlan.tenant_no == tenant_no,
  613. PlPlan.del_flag == 0,
  614. )
  615. .first()
  616. )
  617. merge_plan_logistics_into_order(data, plan)
  618. unit_map = load_dict_label_maps(
  619. db, [CRM_PRODUCT_UNIT], tenant_no=tenant_no
  620. ).get(CRM_PRODUCT_UNIT, {})
  621. raw_items = data.get("items")
  622. if raw_items is None:
  623. return data
  624. product_ids = [
  625. (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  626. for it in raw_items
  627. if (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  628. ]
  629. products_by_id: dict[str, PlPlanProduct] = {}
  630. if product_ids:
  631. rows = (
  632. db.query(PlPlanProduct)
  633. .filter(
  634. PlPlanProduct.id.in_(product_ids),
  635. PlPlanProduct.tenant_no == tenant_no,
  636. PlPlanProduct.del_flag == 0,
  637. )
  638. .all()
  639. )
  640. products_by_id = {r.id: r for r in rows}
  641. # 明细仍挂已软删计划产品时,保留原行用于品牌约定与 CRM 产品定位(勿误用其它在用产品)
  642. missing_ids = [pid for pid in product_ids if pid and pid not in products_by_id]
  643. if missing_ids:
  644. stale_rows = (
  645. db.query(PlPlanProduct)
  646. .filter(
  647. PlPlanProduct.id.in_(missing_ids),
  648. PlPlanProduct.tenant_no == tenant_no,
  649. )
  650. .all()
  651. )
  652. for row in stale_rows:
  653. products_by_id.setdefault(row.id, row)
  654. # 计划产品行可能被编辑重建导致 plan_product_id 失效:按计划再拉全量做 product_id / 序号兜底
  655. plan_products: list[PlPlanProduct] = []
  656. products_by_crm_id: dict[str, PlPlanProduct] = {}
  657. if plan_id:
  658. plan_products = (
  659. db.query(PlPlanProduct)
  660. .filter(
  661. PlPlanProduct.plan_id == plan_id,
  662. PlPlanProduct.tenant_no == tenant_no,
  663. PlPlanProduct.del_flag == 0,
  664. )
  665. .order_by(PlPlanProduct.order_num.asc(), PlPlanProduct.create_time.asc())
  666. .all()
  667. )
  668. for row in plan_products:
  669. products_by_id.setdefault(row.id, row)
  670. crm_key = (row.product_id or "").strip()
  671. if crm_key and crm_key not in products_by_crm_id:
  672. products_by_crm_id[crm_key] = row
  673. crm_ids = {
  674. (pp.product_id or "").strip()
  675. for pp in products_by_id.values()
  676. if (pp.product_id or "").strip()
  677. }
  678. for it in raw_items:
  679. pid = (it.get("productId") or it.get("product_id") or "").strip()
  680. if pid:
  681. crm_ids.add(pid)
  682. crm_no_by_id: dict[str, str] = {}
  683. if crm_ids:
  684. crm_rows = (
  685. db.query(CrmProduct.id, CrmProduct.product_no)
  686. .filter(
  687. CrmProduct.id.in_(list(crm_ids)),
  688. CrmProduct.tenant_no == tenant_no,
  689. CrmProduct.del_flag == 0,
  690. )
  691. .all()
  692. )
  693. for row in crm_rows:
  694. no = (row.product_no or "").strip()
  695. if no:
  696. crm_no_by_id[row.id] = no
  697. standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
  698. db, tenant_no=tenant_no, product_ids=crm_ids
  699. )
  700. for idx, it in enumerate(raw_items):
  701. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  702. if plan_product_id and not it.get("planProductId"):
  703. it["planProductId"] = plan_product_id
  704. pp = products_by_id.get(plan_product_id) if plan_product_id else None
  705. # 仅在明细未挂 planProductId 时用 CRM/序号兜底;已挂 id 时勿换成其它在用产品(会错带指定品牌)
  706. if not pp and not plan_product_id:
  707. crm_key = (it.get("productId") or it.get("product_id") or "").strip()
  708. if crm_key:
  709. pp = products_by_crm_id.get(crm_key)
  710. if not pp and len(plan_products) == len(raw_items):
  711. pp = plan_products[idx]
  712. if pp and not it.get("planProductId"):
  713. it["planProductId"] = pp.id
  714. product_id = (
  715. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  716. ).strip()
  717. # 优先用计划产品已存名(可能是别名)做拆分;明细行 productName 同步
  718. saved_name = (pp.product_name if pp else None) or it.get("productName") or it.get(
  719. "product_name"
  720. )
  721. if saved_name:
  722. it["productName"] = saved_name
  723. merge_plan_product_into_item(
  724. it,
  725. pp,
  726. unit_map=unit_map,
  727. crm_product_no=crm_no_by_id.get(product_id),
  728. )
  729. apply_product_alias_display(
  730. it,
  731. product_id=product_id,
  732. standard_by_id=standard_by_id,
  733. alias_options_by_id=alias_options_by_id,
  734. )
  735. if public_unit_as_label:
  736. it["unit"] = it.get("unitLabel") or resolve_unit_label(unit_map, it.get("unit"))
  737. brand_summary_by_pp: dict[str, str] = {}
  738. if product_ids:
  739. brand_rows = (
  740. db.query(PlPlanProductBrandQty)
  741. .filter(
  742. PlPlanProductBrandQty.plan_product_id.in_(product_ids),
  743. PlPlanProductBrandQty.tenant_no == tenant_no,
  744. PlPlanProductBrandQty.del_flag == 0,
  745. )
  746. .order_by(PlPlanProductBrandQty.order_num.asc())
  747. .all()
  748. )
  749. grouped: dict[str, list[str]] = {}
  750. for br in brand_rows:
  751. qty = Decimal(str(br.qty or 0))
  752. if qty <= 0:
  753. continue
  754. name = (br.brand_name or "").strip() or "未命名品牌"
  755. # 去掉多余尾零,如 6.000 -> 6
  756. qty_text = format(qty.normalize(), "f")
  757. grouped.setdefault(br.plan_product_id, []).append(f"{name} {qty_text}")
  758. brand_summary_by_pp = {k: " / ".join(v) for k, v in grouped.items()}
  759. for it in raw_items:
  760. pp_id = it.get("planProductId") or ""
  761. brand_summary = brand_summary_by_pp.get(pp_id) or None
  762. if brand_summary:
  763. it["brandSummary"] = brand_summary
  764. elif it.get("brandName"):
  765. it["brandSummary"] = it.get("brandName")
  766. else:
  767. it["brandSummary"] = None
  768. enrich_io_items_with_brand_feedback(
  769. db,
  770. kind=kind,
  771. tenant_no=tenant_no,
  772. items=raw_items,
  773. products_by_id=products_by_id,
  774. prefer_site_brand_summary=public_unit_as_label,
  775. )
  776. # 列表摘要:产品名 + 品牌/规格/单位/包装/送货方式
  777. summary_lines = [_format_io_product_summary_line(it) for it in raw_items]
  778. data["productSummary"] = ";".join(line for line in summary_lines if line)[:800]
  779. return data
  780. def order_header_to_dict(
  781. kind: str,
  782. row: OrderHeader,
  783. items: list[Any] | None = None,
  784. *,
  785. db: Session | None = None,
  786. public_unit_as_label: bool = False,
  787. ) -> dict:
  788. token = row.site_access_token or ""
  789. data = {
  790. "id": row.id,
  791. "orderNo": row.order_no,
  792. "planId": row.plan_id,
  793. "transportId": row.transport_id,
  794. "status": row.status,
  795. "partnerCompany": row.partner_company,
  796. "vehicleNo": row.vehicle_no,
  797. "planNo": row.plan_no,
  798. "planDate": row.plan_date.isoformat() if row.plan_date else None,
  799. "siteAccessToken": token,
  800. "siteUrl": build_io_order_site_url(kind, token) if token else None,
  801. "siteFeedbackRemark": row.site_feedback_remark,
  802. "siteFeedbackImages": parse_feedback_images(row.site_feedback_images),
  803. "siteFeedbackTime": row.site_feedback_time,
  804. "siteFirstSubmittedAt": row.site_first_submitted_at,
  805. "remark": row.remark,
  806. "tenantNo": row.tenant_no,
  807. "createTime": row.create_time,
  808. "updateTime": row.update_time,
  809. "kind": kind,
  810. }
  811. if items is not None:
  812. data["items"] = [
  813. {
  814. "id": it.id,
  815. "orderId": it.order_id,
  816. "planProductId": it.plan_product_id,
  817. "productId": it.product_id,
  818. "productName": it.product_name,
  819. "specification": it.specification,
  820. "unit": it.unit,
  821. "planQty": it.plan_qty,
  822. "actualQty": it.actual_qty,
  823. "qtySource": it.qty_source,
  824. }
  825. for it in items
  826. ]
  827. data["productSummary"] = "、".join(
  828. (it.product_name or "").strip() for it in items if (it.product_name or "").strip()
  829. )[:200]
  830. data["actualQtyTotal"] = float(sum(Decimal(str(it.actual_qty or 0)) for it in items))
  831. if db is not None:
  832. enrich_io_order_dict(
  833. db,
  834. data,
  835. tenant_no=row.tenant_no,
  836. plan_id=row.plan_id,
  837. items=items,
  838. public_unit_as_label=public_unit_as_label,
  839. kind=kind,
  840. )
  841. return data