pl_io_order_service.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. PLAN_TYPE_BUSINESS_LABEL = {
  284. "inbound": "入库",
  285. "outbound": "出库",
  286. "direct": "直销",
  287. }
  288. def _io_item_brand_qty_model(kind: str):
  289. if kind == "inbound":
  290. return PlInboundOrderItemBrandQty
  291. return PlOutboundOrderItemBrandQty
  292. def update_io_order_items_qty_and_brand(
  293. db: Session,
  294. *,
  295. kind: str,
  296. tenant_no: str,
  297. order_id: str,
  298. items: list[OrderItem],
  299. item_qty: dict[str, Decimal],
  300. item_brand_qtys: Optional[dict[str, list[dict]]] = None,
  301. enforce_brand: bool = False,
  302. user_id: Optional[str] = None,
  303. ) -> None:
  304. """更新明细实际数量,并按需校验/持久化现场品牌数量。"""
  305. updating = [it for it in items if it.id in item_qty]
  306. if not updating:
  307. return
  308. plan_product_ids = [it.plan_product_id for it in updating if it.plan_product_id]
  309. products_by_id: dict[str, PlPlanProduct] = {}
  310. if plan_product_ids:
  311. rows = (
  312. db.query(PlPlanProduct)
  313. .filter(
  314. PlPlanProduct.id.in_(plan_product_ids),
  315. PlPlanProduct.tenant_no == tenant_no,
  316. PlPlanProduct.del_flag == 0,
  317. )
  318. .all()
  319. )
  320. products_by_id = {r.id: r for r in rows}
  321. # 明细仍指向已软删计划产品行时,用原行品牌约定(避免 brand_mode 空导致只删不写)
  322. missing_ids = [pid for pid in plan_product_ids if pid and pid not in products_by_id]
  323. if missing_ids:
  324. stale_rows = (
  325. db.query(PlPlanProduct)
  326. .filter(
  327. PlPlanProduct.id.in_(missing_ids),
  328. PlPlanProduct.tenant_no == tenant_no,
  329. )
  330. .all()
  331. )
  332. for row in stale_rows:
  333. products_by_id.setdefault(row.id, row)
  334. brand_model = _io_item_brand_qty_model(kind)
  335. for item in updating:
  336. actual_qty = item_qty[item.id]
  337. plan_product = products_by_id.get(item.plan_product_id or "")
  338. brand_mode = plan_product.brand_mode if plan_product else None
  339. required_brand_id = plan_product.brand_id if plan_product else None
  340. brand_touched = item_brand_qtys is not None and item.id in item_brand_qtys
  341. if brand_touched:
  342. rows = item_brand_qtys[item.id]
  343. # 客户端带了品牌明细时,即使计划行 brand_mode 丢失也按 any 规则校验/落库
  344. if not brand_mode and rows:
  345. brand_mode = "any"
  346. elif enforce_brand:
  347. rows = []
  348. else:
  349. rows = None
  350. if rows is not None:
  351. require_brand_qtys_if_needed(
  352. brand_mode=brand_mode,
  353. required_brand_id=required_brand_id,
  354. actual_qty=actual_qty,
  355. rows=rows,
  356. enforce=enforce_brand,
  357. )
  358. item.actual_qty = actual_qty
  359. item.qty_source = "manual"
  360. item.update_by = user_id
  361. if brand_touched:
  362. persist_io_item_brand_qtys(
  363. db,
  364. model=brand_model,
  365. tenant_no=tenant_no,
  366. order_id=order_id,
  367. order_item_id=item.id,
  368. plan_product_id=item.plan_product_id,
  369. brand_mode=brand_mode,
  370. rows=item_brand_qtys[item.id],
  371. user_id=user_id,
  372. )
  373. def apply_io_order_stop_site_feedbacks(
  374. db: Session,
  375. *,
  376. kind: str,
  377. header: OrderHeader,
  378. items: list[OrderItem],
  379. stops: list[dict[str, Any]],
  380. enforce_brand: bool = False,
  381. user_id: Optional[str] = None,
  382. ) -> tuple[dict[str, Decimal], Optional[dict[str, list[dict]]], list[str]]:
  383. """保存按段现场回传,并汇总为出入库明细数量。"""
  384. from collections import defaultdict
  385. from app.services.pl_feedback_brand_qty import require_brand_qtys_if_needed
  386. from app.services.pl_internal_customer import is_internal_customer_name
  387. from app.services.pl_transport_stop_feedback_service import (
  388. load_io_order_site_stop_segments,
  389. save_site_stop_feedback,
  390. )
  391. segments = load_io_order_site_stop_segments(
  392. db,
  393. tenant_no=header.tenant_no,
  394. plan_id=header.plan_id,
  395. transport_id=header.transport_id,
  396. )
  397. segment_map = {(seg.stop_type, seg.stop_id): seg for seg in segments}
  398. plan_products = (
  399. db.query(PlPlanProduct)
  400. .filter(
  401. PlPlanProduct.plan_id == header.plan_id,
  402. PlPlanProduct.tenant_no == header.tenant_no,
  403. PlPlanProduct.del_flag == 0,
  404. )
  405. .all()
  406. )
  407. plan_products_by_id = {row.id: row for row in plan_products}
  408. qty_by_plan_product: dict[str, Decimal] = defaultdict(lambda: Decimal("0"))
  409. brand_by_plan_product: dict[str, dict[str, dict[str, Any]]] = defaultdict(dict)
  410. merged_images: list[str] = []
  411. default_business_type = PLAN_TYPE_BUSINESS_LABEL.get(kind, kind)
  412. for stop_payload in stops:
  413. stop_type = (stop_payload.get("stopType") or stop_payload.get("stop_type") or "").strip()
  414. stop_id = (stop_payload.get("stopId") or stop_payload.get("stop_id") or "").strip()
  415. if stop_type not in ("load", "delivery") or not stop_id:
  416. raise ValueError("停靠段参数无效")
  417. segment = segment_map.get((stop_type, stop_id))
  418. if not segment:
  419. raise ValueError("停靠段不存在或不可回传")
  420. needs_product_qty = is_internal_customer_name(segment.customer_name)
  421. allowed_products = {row.stop_product_id: row for row in segment.products}
  422. products_payload: list[dict[str, Any]] | None = [] if needs_product_qty else None
  423. if needs_product_qty:
  424. for item in stop_payload.get("products") or []:
  425. stop_product_id = (
  426. item.get("stopProductId") or item.get("stop_product_id") or ""
  427. ).strip()
  428. stop_row = allowed_products.get(stop_product_id)
  429. if not stop_row:
  430. raise ValueError("产品不属于当前停靠段")
  431. actual_qty = Decimal(str(item.get("actualQty", item.get("actual_qty") or 0)))
  432. brand_qtys = item.get("brandQtys") or item.get("brand_qtys") or []
  433. plan_product = plan_products_by_id.get(stop_row.plan_product_id)
  434. require_brand_qtys_if_needed(
  435. brand_mode=plan_product.brand_mode if plan_product else None,
  436. required_brand_id=plan_product.brand_id if plan_product else None,
  437. actual_qty=actual_qty,
  438. rows=brand_qtys if isinstance(brand_qtys, list) else [],
  439. enforce=enforce_brand,
  440. )
  441. row_payload: dict[str, Any] = {
  442. "stopProductId": stop_product_id,
  443. "actualQty": float(actual_qty),
  444. }
  445. if brand_qtys:
  446. row_payload["brandQtys"] = brand_qtys
  447. products_payload.append(row_payload)
  448. pp_id = stop_row.plan_product_id
  449. if actual_qty > 0:
  450. qty_by_plan_product[pp_id] += actual_qty
  451. if brand_qtys:
  452. for brand_row in brand_qtys:
  453. if not isinstance(brand_row, dict):
  454. continue
  455. brand_id = str(brand_row.get("brandId") or brand_row.get("brand_id") or "")
  456. qty = Decimal(str(brand_row.get("qty") or 0))
  457. if qty <= 0:
  458. continue
  459. existing = brand_by_plan_product[pp_id].get(brand_id)
  460. if existing:
  461. existing["qty"] = float(Decimal(str(existing["qty"])) + qty)
  462. else:
  463. brand_by_plan_product[pp_id][brand_id] = {
  464. "brandId": brand_id,
  465. "brandName": brand_row.get("brandName") or brand_row.get("brand_name"),
  466. "qty": float(qty),
  467. }
  468. elif stop_payload.get("products"):
  469. raise ValueError("该停靠段无需填写产品数量")
  470. attachment_urls = stop_payload.get("attachmentUrls") or stop_payload.get("attachment_urls") or []
  471. merged_images.extend(
  472. [str(url).strip() for url in attachment_urls if str(url).strip()]
  473. )
  474. save_site_stop_feedback(
  475. db,
  476. tenant_no=header.tenant_no,
  477. transport_id=header.transport_id,
  478. plan_id=header.plan_id,
  479. stop_type=stop_type,
  480. stop_id=stop_id,
  481. business_type=segment.business_type or default_business_type,
  482. attachment_urls=list(attachment_urls),
  483. products=products_payload,
  484. user_id=user_id,
  485. require_qty_before_attachments=needs_product_qty,
  486. )
  487. item_by_plan_product = {it.plan_product_id: it for it in items if it.plan_product_id}
  488. qty_map: dict[str, Decimal] = {}
  489. brand_qty_map: dict[str, list[dict]] = {}
  490. for plan_product_id, qty in qty_by_plan_product.items():
  491. item = item_by_plan_product.get(plan_product_id)
  492. if item:
  493. qty_map[item.id] = qty
  494. for plan_product_id, brand_rows in brand_by_plan_product.items():
  495. item = item_by_plan_product.get(plan_product_id)
  496. if item and brand_rows:
  497. brand_qty_map[item.id] = list(brand_rows.values())
  498. return qty_map, brand_qty_map or None, merged_images
  499. def apply_site_feedback(
  500. db: Session,
  501. *,
  502. kind: str,
  503. header: OrderHeader,
  504. items: list[OrderItem],
  505. item_qty: dict[str, Decimal],
  506. remark: Optional[str],
  507. images: list[str],
  508. status: str,
  509. item_brand_qtys: Optional[dict[str, list[dict]]] = None,
  510. enforce_brand: bool = False,
  511. user_id: Optional[str] = None,
  512. ) -> None:
  513. if header.status == "voided":
  514. raise ValueError("单据已作废,无法提交")
  515. if status not in _VALID_SITE_FEEDBACK_STATUSES:
  516. raise ValueError(f"无效状态: {status}")
  517. now = datetime.now()
  518. update_io_order_items_qty_and_brand(
  519. db,
  520. kind=kind,
  521. tenant_no=header.tenant_no,
  522. order_id=header.id,
  523. items=items,
  524. item_qty=item_qty,
  525. item_brand_qtys=item_brand_qtys,
  526. enforce_brand=enforce_brand,
  527. user_id=user_id,
  528. )
  529. header.site_feedback_remark = (remark or "").strip() or None
  530. header.site_feedback_images = dump_feedback_images(images) if images else header.site_feedback_images
  531. header.site_feedback_time = now
  532. if not header.site_first_submitted_at:
  533. header.site_first_submitted_at = now
  534. header.status = status
  535. header.update_by = user_id
  536. db.flush()
  537. CRM_PRODUCT_UNIT = "crm_product_unit"
  538. def resolve_unit_label(unit_map: dict[str, str], unit_code: Optional[str]) -> str:
  539. code = (unit_code or "").strip()
  540. if not code:
  541. return "吨"
  542. return unit_map.get(code, code)
  543. def merge_plan_logistics_into_order(data: dict, plan: Optional[PlPlan]) -> None:
  544. if not plan:
  545. data.setdefault("businessType", None)
  546. data.setdefault("planRemark", None)
  547. data.setdefault("pickupAddress", None)
  548. data.setdefault("pickupLng", None)
  549. data.setdefault("pickupLat", None)
  550. data.setdefault("pickupTime", None)
  551. data.setdefault("pickupContact", None)
  552. data.setdefault("pickupNotes", None)
  553. data.setdefault("destinationName", None)
  554. data.setdefault("destinationAddress", None)
  555. data.setdefault("destinationLng", None)
  556. data.setdefault("destinationLat", None)
  557. data.setdefault("deliveryTime", None)
  558. data.setdefault("deliveryContact", None)
  559. data.setdefault("destinationNotes", None)
  560. return
  561. data["businessType"] = PLAN_TYPE_BUSINESS_LABEL.get(plan.plan_type, plan.plan_type)
  562. data["planRemark"] = (plan.remark or "").strip() or None
  563. data["pickupAddress"] = plan.pickup_address
  564. data["pickupLng"] = plan.pickup_lng
  565. data["pickupLat"] = plan.pickup_lat
  566. data["pickupTime"] = plan.pickup_time
  567. data["pickupContact"] = plan.pickup_contact
  568. data["pickupNotes"] = plan.pickup_notes
  569. data["destinationName"] = plan.destination_name
  570. data["destinationAddress"] = plan.destination_address or plan.destination_name
  571. data["destinationLng"] = plan.destination_lng
  572. data["destinationLat"] = plan.destination_lat
  573. data["deliveryTime"] = plan.delivery_time
  574. data["deliveryContact"] = plan.delivery_contact
  575. data["destinationNotes"] = plan.destination_notes
  576. def merge_plan_product_into_item(
  577. item: dict,
  578. product: Optional[PlPlanProduct],
  579. *,
  580. unit_map: dict[str, str],
  581. crm_product_no: Optional[str] = None,
  582. ) -> None:
  583. if not product:
  584. item.setdefault("productNo", None)
  585. item.setdefault("categoryName", None)
  586. item.setdefault("packageSpec", None)
  587. item.setdefault("deliveryMethod", None)
  588. item.setdefault("remark", None)
  589. item["unitLabel"] = resolve_unit_label(unit_map, item.get("unit"))
  590. return
  591. # 优先 CRM 产品编码;计划冗余 product_no 可能被误存为 product_id
  592. product_id = (product.product_id or item.get("productId") or item.get("product_id") or "").strip()
  593. plan_no = (product.product_no or "").strip()
  594. resolved_no = (crm_product_no or "").strip()
  595. if not resolved_no and plan_no and plan_no != product_id:
  596. resolved_no = plan_no
  597. # CRM 缺失时仍回退计划 product_no,避免前端编码列空白
  598. if not resolved_no and plan_no:
  599. resolved_no = plan_no
  600. item["productNo"] = resolved_no or None
  601. item["categoryName"] = product.category_name
  602. item["packageSpec"] = product.package_spec or item.get("packageSpec")
  603. item["deliveryMethod"] = product.delivery_method
  604. item["remark"] = (product.remark or "").strip() or item.get("remark")
  605. if not item.get("specification") and product.model:
  606. item["specification"] = product.model
  607. item["unitLabel"] = resolve_unit_label(unit_map, item.get("unit") or product.unit)
  608. # 无品牌拆分量时,回退计划产品上的品牌快照
  609. if product.brand_name and not item.get("brandSummary"):
  610. item["brandName"] = product.brand_name
  611. if product.brand_mode:
  612. item.setdefault("brandMode", product.brand_mode)
  613. def _format_io_product_summary_line(item: dict) -> str:
  614. name = (item.get("productName") or "").strip()
  615. if not name:
  616. return ""
  617. bits: list[str] = []
  618. brand = (item.get("brandSummary") or item.get("brandName") or "").strip()
  619. if brand:
  620. bits.append(f"品牌 {brand}")
  621. spec = (item.get("specification") or "").strip()
  622. if spec:
  623. bits.append(f"型号/规格 {spec}")
  624. unit = (item.get("unitLabel") or item.get("unit") or "").strip()
  625. if unit:
  626. bits.append(f"单位 {unit}")
  627. package = (item.get("packageSpec") or "").strip()
  628. if package:
  629. bits.append(f"包装规格 {package}")
  630. delivery = (item.get("deliveryMethod") or "").strip()
  631. if delivery:
  632. delivery_labels = {
  633. "self_pick": "山峡自提",
  634. "one_ticket": "一票制",
  635. "customer_pick": "客户自提",
  636. }
  637. bits.append(f"送货方式 {delivery_labels.get(delivery, delivery)}")
  638. return f"{name},{','.join(bits)}" if bits else name
  639. def enrich_io_items_with_brand_feedback(
  640. db: Session,
  641. *,
  642. kind: str,
  643. tenant_no: str,
  644. items: list[dict],
  645. products_by_id: dict[str, PlPlanProduct],
  646. prefer_site_brand_summary: bool = False,
  647. ) -> None:
  648. """读时附加品牌模式、CRM 品牌选项与现场品牌数量子表。"""
  649. if not items:
  650. return
  651. crm_product_ids: set[str] = set()
  652. order_item_ids: list[str] = []
  653. for it in items:
  654. item_id = (it.get("id") or "").strip()
  655. if item_id:
  656. order_item_ids.append(item_id)
  657. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  658. pp = products_by_id.get(plan_product_id)
  659. product_id = (
  660. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  661. ).strip()
  662. if product_id:
  663. crm_product_ids.add(product_id)
  664. brand_options_by_product: dict[str, list[dict]] = {}
  665. if crm_product_ids:
  666. brand_rows = (
  667. db.query(CrmProductBrand)
  668. .filter(
  669. CrmProductBrand.product_id.in_(list(crm_product_ids)),
  670. CrmProductBrand.tenant_no == tenant_no,
  671. CrmProductBrand.status == "on",
  672. CrmProductBrand.del_flag == 0,
  673. )
  674. .order_by(CrmProductBrand.order_num.asc(), CrmProductBrand.create_time.asc())
  675. .all()
  676. )
  677. for row in brand_rows:
  678. brand_options_by_product.setdefault(row.product_id, []).append(
  679. {"brandId": row.id, "brandName": row.brand_name}
  680. )
  681. site_rows_by_item: dict[str, list[dict]] = {}
  682. if order_item_ids:
  683. brand_model = _io_item_brand_qty_model(kind)
  684. site_rows = (
  685. db.query(brand_model)
  686. .filter(
  687. brand_model.order_item_id.in_(order_item_ids),
  688. brand_model.tenant_no == tenant_no,
  689. brand_model.del_flag == 0,
  690. )
  691. .order_by(brand_model.order_num.asc())
  692. .all()
  693. )
  694. for row in site_rows:
  695. site_rows_by_item.setdefault(row.order_item_id, []).append(
  696. {
  697. "brandId": row.brand_id or "",
  698. "brandName": row.brand_name,
  699. "qty": row.qty,
  700. }
  701. )
  702. for it in items:
  703. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  704. pp = products_by_id.get(plan_product_id)
  705. product_id = (
  706. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  707. ).strip()
  708. if pp:
  709. it["brandMode"] = pp.brand_mode
  710. it["brandId"] = pp.brand_id
  711. if pp.brand_name:
  712. it["brandName"] = pp.brand_name
  713. else:
  714. it.setdefault("brandMode", None)
  715. it.setdefault("brandId", None)
  716. options = brand_options_by_product.get(product_id, [])
  717. it["brandOptions"] = options if options else None
  718. site_qtys = site_rows_by_item.get(it.get("id") or "", [])
  719. it["brandQtys"] = site_qtys if site_qtys else None
  720. if prefer_site_brand_summary:
  721. site_summary = format_brand_qty_summary(site_qtys)
  722. if site_summary:
  723. it["brandSummary"] = site_summary
  724. def enrich_io_order_dict(
  725. db: Session,
  726. data: dict,
  727. *,
  728. tenant_no: str,
  729. plan_id: Optional[str],
  730. items: list[Any] | None,
  731. public_unit_as_label: bool = False,
  732. kind: str = "inbound",
  733. ) -> dict:
  734. """读时附加计划取送货与产品扩展字段。"""
  735. from app.utils.excel_export import load_dict_label_maps
  736. plan = None
  737. if plan_id:
  738. plan = (
  739. db.query(PlPlan)
  740. .filter(
  741. PlPlan.id == plan_id,
  742. PlPlan.tenant_no == tenant_no,
  743. PlPlan.del_flag == 0,
  744. )
  745. .first()
  746. )
  747. merge_plan_logistics_into_order(data, plan)
  748. unit_map = load_dict_label_maps(
  749. db, [CRM_PRODUCT_UNIT], tenant_no=tenant_no
  750. ).get(CRM_PRODUCT_UNIT, {})
  751. raw_items = data.get("items")
  752. if raw_items is None:
  753. return data
  754. product_ids = [
  755. (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  756. for it in raw_items
  757. if (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  758. ]
  759. products_by_id: dict[str, PlPlanProduct] = {}
  760. if product_ids:
  761. rows = (
  762. db.query(PlPlanProduct)
  763. .filter(
  764. PlPlanProduct.id.in_(product_ids),
  765. PlPlanProduct.tenant_no == tenant_no,
  766. PlPlanProduct.del_flag == 0,
  767. )
  768. .all()
  769. )
  770. products_by_id = {r.id: r for r in rows}
  771. # 明细仍挂已软删计划产品时,保留原行用于品牌约定与 CRM 产品定位(勿误用其它在用产品)
  772. missing_ids = [pid for pid in product_ids if pid and pid not in products_by_id]
  773. if missing_ids:
  774. stale_rows = (
  775. db.query(PlPlanProduct)
  776. .filter(
  777. PlPlanProduct.id.in_(missing_ids),
  778. PlPlanProduct.tenant_no == tenant_no,
  779. )
  780. .all()
  781. )
  782. for row in stale_rows:
  783. products_by_id.setdefault(row.id, row)
  784. # 计划产品行可能被编辑重建导致 plan_product_id 失效:按计划再拉全量做 product_id / 序号兜底
  785. plan_products: list[PlPlanProduct] = []
  786. products_by_crm_id: dict[str, PlPlanProduct] = {}
  787. if plan_id:
  788. plan_products = (
  789. db.query(PlPlanProduct)
  790. .filter(
  791. PlPlanProduct.plan_id == plan_id,
  792. PlPlanProduct.tenant_no == tenant_no,
  793. PlPlanProduct.del_flag == 0,
  794. )
  795. .order_by(PlPlanProduct.order_num.asc(), PlPlanProduct.create_time.asc())
  796. .all()
  797. )
  798. for row in plan_products:
  799. products_by_id.setdefault(row.id, row)
  800. crm_key = (row.product_id or "").strip()
  801. if crm_key and crm_key not in products_by_crm_id:
  802. products_by_crm_id[crm_key] = row
  803. crm_ids = {
  804. (pp.product_id or "").strip()
  805. for pp in products_by_id.values()
  806. if (pp.product_id or "").strip()
  807. }
  808. for it in raw_items:
  809. pid = (it.get("productId") or it.get("product_id") or "").strip()
  810. if pid:
  811. crm_ids.add(pid)
  812. crm_no_by_id: dict[str, str] = {}
  813. if crm_ids:
  814. crm_rows = (
  815. db.query(CrmProduct.id, CrmProduct.product_no)
  816. .filter(
  817. CrmProduct.id.in_(list(crm_ids)),
  818. CrmProduct.tenant_no == tenant_no,
  819. CrmProduct.del_flag == 0,
  820. )
  821. .all()
  822. )
  823. for row in crm_rows:
  824. no = (row.product_no or "").strip()
  825. if no:
  826. crm_no_by_id[row.id] = no
  827. standard_by_id, alias_options_by_id = load_crm_product_alias_maps(
  828. db, tenant_no=tenant_no, product_ids=crm_ids
  829. )
  830. for idx, it in enumerate(raw_items):
  831. plan_product_id = (it.get("planProductId") or it.get("plan_product_id") or "").strip()
  832. if plan_product_id and not it.get("planProductId"):
  833. it["planProductId"] = plan_product_id
  834. pp = products_by_id.get(plan_product_id) if plan_product_id else None
  835. # 仅在明细未挂 planProductId 时用 CRM/序号兜底;已挂 id 时勿换成其它在用产品(会错带指定品牌)
  836. if not pp and not plan_product_id:
  837. crm_key = (it.get("productId") or it.get("product_id") or "").strip()
  838. if crm_key:
  839. pp = products_by_crm_id.get(crm_key)
  840. if not pp and len(plan_products) == len(raw_items):
  841. pp = plan_products[idx]
  842. if pp and not it.get("planProductId"):
  843. it["planProductId"] = pp.id
  844. product_id = (
  845. (pp.product_id if pp else None) or it.get("productId") or it.get("product_id") or ""
  846. ).strip()
  847. # 优先用计划产品已存名(可能是别名)做拆分;明细行 productName 同步
  848. saved_name = (pp.product_name if pp else None) or it.get("productName") or it.get(
  849. "product_name"
  850. )
  851. if saved_name:
  852. it["productName"] = saved_name
  853. merge_plan_product_into_item(
  854. it,
  855. pp,
  856. unit_map=unit_map,
  857. crm_product_no=crm_no_by_id.get(product_id),
  858. )
  859. apply_product_alias_display(
  860. it,
  861. product_id=product_id,
  862. standard_by_id=standard_by_id,
  863. alias_options_by_id=alias_options_by_id,
  864. )
  865. if public_unit_as_label:
  866. it["unit"] = it.get("unitLabel") or resolve_unit_label(unit_map, it.get("unit"))
  867. brand_summary_by_pp: dict[str, str] = {}
  868. if product_ids:
  869. brand_rows = (
  870. db.query(PlPlanProductBrandQty)
  871. .filter(
  872. PlPlanProductBrandQty.plan_product_id.in_(product_ids),
  873. PlPlanProductBrandQty.tenant_no == tenant_no,
  874. PlPlanProductBrandQty.del_flag == 0,
  875. )
  876. .order_by(PlPlanProductBrandQty.order_num.asc())
  877. .all()
  878. )
  879. grouped: dict[str, list[str]] = {}
  880. for br in brand_rows:
  881. qty = Decimal(str(br.qty or 0))
  882. if qty <= 0:
  883. continue
  884. name = (br.brand_name or "").strip() or "未命名品牌"
  885. # 去掉多余尾零,如 6.000 -> 6
  886. qty_text = format(qty.normalize(), "f")
  887. grouped.setdefault(br.plan_product_id, []).append(f"{name} {qty_text}")
  888. brand_summary_by_pp = {k: " / ".join(v) for k, v in grouped.items()}
  889. for it in raw_items:
  890. pp_id = it.get("planProductId") or ""
  891. brand_summary = brand_summary_by_pp.get(pp_id) or None
  892. if brand_summary:
  893. it["brandSummary"] = brand_summary
  894. elif it.get("brandName"):
  895. it["brandSummary"] = it.get("brandName")
  896. else:
  897. it["brandSummary"] = None
  898. enrich_io_items_with_brand_feedback(
  899. db,
  900. kind=kind,
  901. tenant_no=tenant_no,
  902. items=raw_items,
  903. products_by_id=products_by_id,
  904. prefer_site_brand_summary=public_unit_as_label,
  905. )
  906. # 列表摘要:产品名 + 品牌/规格/单位/包装/送货方式
  907. summary_lines = [_format_io_product_summary_line(it) for it in raw_items]
  908. data["productSummary"] = ";".join(line for line in summary_lines if line)[:800]
  909. return data
  910. def order_header_to_dict(
  911. kind: str,
  912. row: OrderHeader,
  913. items: list[Any] | None = None,
  914. *,
  915. db: Session | None = None,
  916. public_unit_as_label: bool = False,
  917. ) -> dict:
  918. token = row.site_access_token or ""
  919. data = {
  920. "id": row.id,
  921. "orderNo": row.order_no,
  922. "planId": row.plan_id,
  923. "transportId": row.transport_id,
  924. "status": row.status,
  925. "partnerCompany": row.partner_company,
  926. "vehicleNo": row.vehicle_no,
  927. "planNo": row.plan_no,
  928. "planDate": row.plan_date.isoformat() if row.plan_date else None,
  929. "siteAccessToken": token,
  930. "siteUrl": build_io_order_site_url(kind, token) if token else None,
  931. "siteFeedbackRemark": row.site_feedback_remark,
  932. "siteFeedbackImages": parse_feedback_images(row.site_feedback_images),
  933. "siteFeedbackTime": row.site_feedback_time,
  934. "siteFirstSubmittedAt": row.site_first_submitted_at,
  935. "remark": row.remark,
  936. "tenantNo": row.tenant_no,
  937. "createTime": row.create_time,
  938. "updateTime": row.update_time,
  939. "kind": kind,
  940. }
  941. if items is not None:
  942. data["items"] = [
  943. {
  944. "id": it.id,
  945. "orderId": it.order_id,
  946. "planProductId": it.plan_product_id,
  947. "productId": it.product_id,
  948. "productName": it.product_name,
  949. "specification": it.specification,
  950. "unit": it.unit,
  951. "planQty": it.plan_qty,
  952. "actualQty": it.actual_qty,
  953. "qtySource": it.qty_source,
  954. }
  955. for it in items
  956. ]
  957. data["productSummary"] = "、".join(
  958. (it.product_name or "").strip() for it in items if (it.product_name or "").strip()
  959. )[:200]
  960. data["actualQtyTotal"] = float(sum(Decimal(str(it.actual_qty or 0)) for it in items))
  961. if db is not None:
  962. enrich_io_order_dict(
  963. db,
  964. data,
  965. tenant_no=row.tenant_no,
  966. plan_id=row.plan_id,
  967. items=items,
  968. public_unit_as_label=public_unit_as_label,
  969. kind=kind,
  970. )
  971. return data