pl_feedback_brand_qty.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. """现场入出库明细与运输回传的品牌数量校验与持久化"""
  2. from decimal import Decimal
  3. from typing import Any, Optional, Type
  4. from sqlalchemy.orm import Session
  5. from app.core.utils import generate_uuid
  6. from app.services.pl_brand_archive import validate_brand_qty_rows
  7. def format_brand_qty_summary(rows: list[dict]) -> Optional[str]:
  8. parts = []
  9. for r in rows:
  10. qty = Decimal(str(r.get("qty") or 0))
  11. if qty <= 0:
  12. continue
  13. name = (r.get("brandName") or r.get("brand_name") or "").strip() or "未命名品牌"
  14. qty_text = format(qty.normalize(), "f")
  15. parts.append(f"{name} {qty_text}")
  16. return " / ".join(parts) if parts else None
  17. def require_brand_qtys_if_needed(
  18. *,
  19. brand_mode: Optional[str],
  20. required_brand_id: Optional[str],
  21. actual_qty: Decimal,
  22. rows: list[dict],
  23. enforce: bool,
  24. ) -> None:
  25. if not brand_mode:
  26. return
  27. if not enforce:
  28. return
  29. positive = [r for r in rows if Decimal(str(r.get("qty") or 0)) > 0]
  30. if not positive:
  31. raise ValueError("有品牌产品须填写至少一个品牌数量")
  32. validate_brand_qty_rows(
  33. brand_mode=brand_mode,
  34. required_brand_id=required_brand_id,
  35. actual_qty=Decimal(str(actual_qty)),
  36. rows=rows,
  37. )
  38. def persist_io_item_brand_qtys(
  39. db: Session,
  40. *,
  41. model: Type[Any],
  42. tenant_no: str,
  43. order_id: str,
  44. order_item_id: str,
  45. plan_product_id: str,
  46. brand_mode: Optional[str],
  47. rows: list[dict],
  48. user_id: Optional[str] = None,
  49. ) -> None:
  50. existing = (
  51. db.query(model)
  52. .filter(
  53. model.order_item_id == order_item_id,
  54. model.tenant_no == tenant_no,
  55. model.del_flag == 0,
  56. )
  57. .all()
  58. )
  59. for row in existing:
  60. row.del_flag = 1
  61. row.update_by = user_id
  62. # 客户端显式提交了品牌明细时必须落库;勿因计划行 brand_mode 缺失/软删查找失败而只删不写
  63. positive = [item for item in rows if Decimal(str(item.get("qty") or 0)) > 0]
  64. if not brand_mode and not positive:
  65. return
  66. for idx, item in enumerate(rows):
  67. qty = Decimal(str(item.get("qty") or 0))
  68. if qty <= 0:
  69. continue
  70. db.add(
  71. model(
  72. id=generate_uuid(),
  73. tenant_no=tenant_no,
  74. order_id=order_id,
  75. order_item_id=order_item_id,
  76. plan_product_id=plan_product_id,
  77. brand_id=item.get("brandId") or item.get("brand_id") or "",
  78. brand_name=item.get("brandName") or item.get("brand_name"),
  79. qty=qty,
  80. order_num=idx,
  81. create_by=user_id,
  82. create_dept_id="",
  83. update_by=user_id,
  84. )
  85. )
  86. def _dict_field(item: dict, *keys: str):
  87. for key in keys:
  88. if key in item and item[key] is not None:
  89. return item[key]
  90. return None
  91. def persist_transport_product_feedback(
  92. db: Session,
  93. *,
  94. tenant_no: str,
  95. transport,
  96. plan_id: str,
  97. products: list[dict],
  98. user_id: Optional[str] = None,
  99. enforce_brand: bool = True,
  100. ) -> None:
  101. from app.models.pl_models import (
  102. PlPlanProduct,
  103. PlTransportProductBrandQty,
  104. PlTransportProductFeedback,
  105. )
  106. transport_id = transport.id
  107. for row in (
  108. db.query(PlTransportProductFeedback)
  109. .filter(
  110. PlTransportProductFeedback.transport_id == transport_id,
  111. PlTransportProductFeedback.tenant_no == tenant_no,
  112. PlTransportProductFeedback.del_flag == 0,
  113. )
  114. .all()
  115. ):
  116. row.del_flag = 1
  117. row.update_by = user_id
  118. for row in (
  119. db.query(PlTransportProductBrandQty)
  120. .filter(
  121. PlTransportProductBrandQty.transport_id == transport_id,
  122. PlTransportProductBrandQty.tenant_no == tenant_no,
  123. PlTransportProductBrandQty.del_flag == 0,
  124. )
  125. .all()
  126. ):
  127. row.del_flag = 1
  128. row.update_by = user_id
  129. total_qty = Decimal("0")
  130. for idx, item in enumerate(products):
  131. plan_product_id = _dict_field(item, "planProductId", "plan_product_id")
  132. actual_qty = Decimal(str(_dict_field(item, "actualQty", "actual_qty") or 0))
  133. brand_qtys = _dict_field(item, "brandQtys", "brand_qtys") or []
  134. total_qty += actual_qty
  135. plan_product = (
  136. db.query(PlPlanProduct)
  137. .filter(
  138. PlPlanProduct.id == plan_product_id,
  139. PlPlanProduct.tenant_no == tenant_no,
  140. PlPlanProduct.del_flag == 0,
  141. )
  142. .first()
  143. )
  144. brand_mode = _dict_field(item, "brandMode", "brand_mode")
  145. required_brand_id = _dict_field(item, "brandId", "brand_id")
  146. if plan_product:
  147. brand_mode = brand_mode or plan_product.brand_mode
  148. required_brand_id = required_brand_id if required_brand_id is not None else plan_product.brand_id
  149. require_brand_qtys_if_needed(
  150. brand_mode=brand_mode,
  151. required_brand_id=required_brand_id,
  152. actual_qty=actual_qty,
  153. rows=brand_qtys,
  154. enforce=enforce_brand,
  155. )
  156. feedback_id = generate_uuid()
  157. db.add(
  158. PlTransportProductFeedback(
  159. id=feedback_id,
  160. tenant_no=tenant_no,
  161. transport_id=transport_id,
  162. plan_id=plan_id,
  163. plan_product_id=plan_product_id,
  164. actual_qty=actual_qty,
  165. order_num=idx,
  166. create_by=user_id,
  167. create_dept_id="",
  168. update_by=user_id,
  169. )
  170. )
  171. if not brand_mode:
  172. continue
  173. for bidx, bitem in enumerate(brand_qtys):
  174. qty = Decimal(str(bitem.get("qty") or 0))
  175. if qty <= 0:
  176. continue
  177. db.add(
  178. PlTransportProductBrandQty(
  179. id=generate_uuid(),
  180. tenant_no=tenant_no,
  181. transport_id=transport_id,
  182. plan_product_id=plan_product_id,
  183. feedback_id=feedback_id,
  184. brand_id=bitem.get("brandId") or bitem.get("brand_id") or "",
  185. brand_name=bitem.get("brandName") or bitem.get("brand_name"),
  186. qty=qty,
  187. order_num=bidx,
  188. create_by=user_id,
  189. create_dept_id="",
  190. update_by=user_id,
  191. )
  192. )
  193. transport.feedback_qty = total_qty
  194. def load_transport_driver_product_feedbacks(
  195. db: Session,
  196. *,
  197. tenant_no: str,
  198. transport_id: str,
  199. ) -> list[dict]:
  200. """管理端读运输单时附司机按产品回传及品牌摘要。"""
  201. from app.models.pl_models import (
  202. PlPlanProduct,
  203. PlTransportProductBrandQty,
  204. PlTransportProductFeedback,
  205. )
  206. feedback_rows = (
  207. db.query(PlTransportProductFeedback)
  208. .filter(
  209. PlTransportProductFeedback.transport_id == transport_id,
  210. PlTransportProductFeedback.tenant_no == tenant_no,
  211. PlTransportProductFeedback.del_flag == 0,
  212. )
  213. .order_by(PlTransportProductFeedback.order_num.asc())
  214. .all()
  215. )
  216. if not feedback_rows:
  217. return []
  218. plan_product_ids = [fb.plan_product_id for fb in feedback_rows if fb.plan_product_id]
  219. products_by_id: dict[str, PlPlanProduct] = {}
  220. if plan_product_ids:
  221. product_rows = (
  222. db.query(PlPlanProduct)
  223. .filter(
  224. PlPlanProduct.id.in_(plan_product_ids),
  225. PlPlanProduct.tenant_no == tenant_no,
  226. PlPlanProduct.del_flag == 0,
  227. )
  228. .all()
  229. )
  230. products_by_id = {row.id: row for row in product_rows}
  231. brand_qtys_by_plan_product: dict[str, list[dict]] = {}
  232. feedback_ids = [fb.id for fb in feedback_rows]
  233. brand_qty_rows = (
  234. db.query(PlTransportProductBrandQty)
  235. .filter(
  236. PlTransportProductBrandQty.transport_id == transport_id,
  237. PlTransportProductBrandQty.tenant_no == tenant_no,
  238. PlTransportProductBrandQty.del_flag == 0,
  239. PlTransportProductBrandQty.feedback_id.in_(feedback_ids),
  240. )
  241. .order_by(PlTransportProductBrandQty.order_num.asc())
  242. .all()
  243. )
  244. for row in brand_qty_rows:
  245. brand_qtys_by_plan_product.setdefault(row.plan_product_id, []).append(
  246. {
  247. "brandId": row.brand_id or "",
  248. "brandName": row.brand_name,
  249. "qty": row.qty,
  250. }
  251. )
  252. result: list[dict] = []
  253. for fb in feedback_rows:
  254. brand_qtys = brand_qtys_by_plan_product.get(fb.plan_product_id, [])
  255. pp = products_by_id.get(fb.plan_product_id or "")
  256. result.append(
  257. {
  258. "planProductId": fb.plan_product_id,
  259. "productName": (pp.product_name if pp else None) or "",
  260. "productNo": (pp.product_no if pp else None) or None,
  261. "model": (pp.model if pp else None) or None,
  262. "unit": (pp.unit if pp else None) or None,
  263. "packageSpec": (pp.package_spec if pp else None) or None,
  264. "brandMode": (pp.brand_mode if pp else None) or None,
  265. "brandId": (pp.brand_id if pp else None) or None,
  266. "brandName": (pp.brand_name if pp else None) or None,
  267. "actualQty": fb.actual_qty,
  268. "brandQtys": brand_qtys or None,
  269. "brandSummary": format_brand_qty_summary(brand_qtys),
  270. }
  271. )
  272. return result