pl_plan_archive_export.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. """运输计划归档导出:按装货/送货段 × 段内产品展开,与列表展示规则一致。"""
  2. from __future__ import annotations
  3. from datetime import date, datetime
  4. from decimal import Decimal
  5. from typing import Optional, Union
  6. from sqlalchemy.orm import Session
  7. from app.models.pl_models import PlPlan, PlPlanProduct, PlTransport
  8. from app.schemas.pl.plan import PlanDeliveryRead, PlanLoadRead, PlanStopProductRead
  9. from app.services.pl.plan_list_filters import customer_name_matches_keywords
  10. from app.services.pl_internal_customer import is_internal_customer_name
  11. from app.services.pl_plan_stop_service import load_plan_stops_grouped
  12. StopKind = str # "load" | "delivery"
  13. PLAN_TYPE_LABELS = {
  14. "direct": "直销单",
  15. "inbound": "入库单",
  16. "outbound": "出库单",
  17. }
  18. ARCHIVE_STATUS_LABELS = {
  19. "archived": "已归档",
  20. "unarchived": "未归档",
  21. "draft": "已暂存",
  22. }
  23. FOLLOW_STATUS_LABELS = {
  24. "wait_notice": "等通知",
  25. "pending_arrange": "待安排",
  26. "arranged": "已安排",
  27. "completed": "已完成",
  28. "cancelled": "已取消",
  29. "draft": "待安排",
  30. "processing": "进行中",
  31. }
  32. FREIGHT_TYPE_LABELS = {
  33. "by_weight": "按重量",
  34. "by_trip": "按趟",
  35. }
  36. def resolve_archive_list_io_column(kind: StopKind, customer_name: Optional[str]) -> str:
  37. """装货/送货段入库出库列方向(与前端 resolveArchiveListIoColumn 一致)。"""
  38. internal = is_internal_customer_name(customer_name)
  39. if kind == "load":
  40. return "outbound" if internal else "inbound"
  41. return "inbound" if internal else "outbound"
  42. def _format_date_value(value: Optional[Union[date, datetime, str]]) -> str:
  43. if value is None:
  44. return ""
  45. return str(value)[:10]
  46. def _format_plate_display(license_plate: Optional[str], trailer_no: Optional[str]) -> str:
  47. plate = (license_plate or "").strip()
  48. trailer = (trailer_no or "").strip()
  49. if not plate and not trailer:
  50. return ""
  51. if plate and trailer:
  52. return f"{plate}{trailer}"
  53. return plate or trailer
  54. def _get_stop_archive_actual_qty(product: PlanStopProductRead, kind: StopKind) -> Optional[Decimal]:
  55. return product.inbound_qty if kind == "load" else product.outbound_qty
  56. def _get_stop_archive_unit_price(product: PlanStopProductRead, kind: StopKind) -> Optional[Decimal]:
  57. return product.inbound_price if kind == "load" else product.outbound_price
  58. def _get_stop_archive_amount(product: PlanStopProductRead, kind: StopKind) -> Optional[Decimal]:
  59. stored = product.inbound_amount if kind == "load" else product.outbound_amount
  60. if stored is not None:
  61. return stored
  62. qty = _get_stop_archive_actual_qty(product, kind)
  63. price = _get_stop_archive_unit_price(product, kind)
  64. if qty is not None and price is not None:
  65. return qty * price
  66. return None
  67. def _stop_kind_label(kind: StopKind, delivery_seq: Optional[int] = None) -> str:
  68. if kind == "load":
  69. return "装货"
  70. return f"送货 #{delivery_seq or 1}"
  71. def _stop_time(kind: StopKind, stop: Union[PlanLoadRead, PlanDeliveryRead]) -> str:
  72. if kind == "load":
  73. return _format_date_value(getattr(stop, "load_time", None))
  74. return _format_date_value(getattr(stop, "delivery_time", None))
  75. def _load_legacy_products_by_plan(
  76. db: Session, tenant_no: str, plan_ids: list[str]
  77. ) -> dict[str, list[PlPlanProduct]]:
  78. if not plan_ids:
  79. return {}
  80. products = (
  81. db.query(PlPlanProduct)
  82. .filter(
  83. PlPlanProduct.tenant_no == tenant_no,
  84. PlPlanProduct.del_flag == 0,
  85. PlPlanProduct.plan_id.in_(plan_ids),
  86. )
  87. .order_by(PlPlanProduct.order_num)
  88. .all()
  89. )
  90. grouped: dict[str, list[PlPlanProduct]] = {}
  91. for product in products:
  92. grouped.setdefault(product.plan_id, []).append(product)
  93. return grouped
  94. def _plan_common_export_fields(
  95. plan: PlPlan,
  96. transport: Optional[PlTransport],
  97. ) -> dict:
  98. freight_type_raw = transport.freight_type if transport else "by_weight"
  99. freight_type_label = FREIGHT_TYPE_LABELS.get(freight_type_raw, freight_type_raw or "")
  100. freight_price = transport.freight_price if transport else None
  101. freight_amount = plan.freight_amount
  102. if freight_amount is None and transport is not None:
  103. freight_amount = transport.freight_amount
  104. plan_date = _format_date_value(plan.plan_date)
  105. return {
  106. "planId": plan.id or "",
  107. "planNo": plan.plan_no or "",
  108. "planDate": plan_date,
  109. "archiveStatus": ARCHIVE_STATUS_LABELS.get(plan.archive_status or "", plan.archive_status or ""),
  110. "followStatus": FOLLOW_STATUS_LABELS.get(plan.follow_status or "", plan.follow_status or ""),
  111. "planType": PLAN_TYPE_LABELS.get(plan.plan_type or "", plan.plan_type or ""),
  112. "licensePlate": _format_plate_display(plan.license_plate, plan.trailer_no),
  113. "erpEntered": "是" if int(plan.erp_entered or 0) == 1 else "否",
  114. "freightType": freight_type_label,
  115. "freightPrice": freight_price,
  116. "freightAmount": freight_amount,
  117. "remark": plan.remark or "",
  118. }
  119. def _empty_product_fields() -> dict:
  120. return {
  121. "productName": "",
  122. "model": "",
  123. "packageSpec": "",
  124. "unit": "",
  125. "planQty": None,
  126. "actualQty": None,
  127. "inboundQty": None,
  128. "outboundQty": None,
  129. "unitPrice": None,
  130. "amount": None,
  131. }
  132. def _product_row_from_stop_product(
  133. product: PlanStopProductRead,
  134. kind: StopKind,
  135. customer_name: Optional[str],
  136. ) -> dict:
  137. actual_qty = _get_stop_archive_actual_qty(product, kind)
  138. unit_price = _get_stop_archive_unit_price(product, kind)
  139. amount = _get_stop_archive_amount(product, kind)
  140. io_col = resolve_archive_list_io_column(kind, customer_name)
  141. inbound_qty = actual_qty if io_col == "inbound" else None
  142. outbound_qty = actual_qty if io_col == "outbound" else None
  143. return {
  144. "productName": product.product_name or "",
  145. "model": product.model or "",
  146. "packageSpec": product.package_spec or "",
  147. "unit": product.unit or "",
  148. "planQty": product.plan_qty,
  149. "actualQty": actual_qty,
  150. "inboundQty": inbound_qty,
  151. "outboundQty": outbound_qty,
  152. "unitPrice": unit_price,
  153. "amount": amount,
  154. }
  155. def _append_stop_product_rows(
  156. rows: list[dict],
  157. row_no: int,
  158. plan_common: dict,
  159. kind: StopKind,
  160. stop: Union[PlanLoadRead, PlanDeliveryRead],
  161. delivery_seq: Optional[int],
  162. products: list[PlanStopProductRead],
  163. ) -> int:
  164. customer_name = stop.customer_name or ""
  165. stop_common = {
  166. **plan_common,
  167. "stopKind": _stop_kind_label(kind, delivery_seq),
  168. "stopCustomer": customer_name,
  169. "stopAddress": stop.address or "",
  170. "stopTime": _stop_time(kind, stop),
  171. }
  172. product_rows = products or [None]
  173. for product in product_rows:
  174. row_no += 1
  175. row = {
  176. **stop_common,
  177. "rowNo": row_no,
  178. **_empty_product_fields(),
  179. }
  180. if product is not None:
  181. row.update(_product_row_from_stop_product(product, kind, customer_name))
  182. rows.append(row)
  183. return row_no
  184. def _append_legacy_plan_product_rows(
  185. rows: list[dict],
  186. row_no: int,
  187. plan: PlPlan,
  188. plan_common: dict,
  189. products: list[PlPlanProduct],
  190. ) -> int:
  191. """无段表数据时回退计划产品级导出(兼容旧数据)。"""
  192. stop_common = {
  193. **plan_common,
  194. "stopKind": "",
  195. "stopCustomer": plan.customer_name or plan.supplier_name or "",
  196. "stopAddress": plan.destination_name or "",
  197. "stopTime": _format_date_value(plan.delivery_time),
  198. }
  199. product_rows = products or [None]
  200. for product in product_rows:
  201. row_no += 1
  202. row = {
  203. **stop_common,
  204. "rowNo": row_no,
  205. **_empty_product_fields(),
  206. }
  207. if product is not None:
  208. row.update(
  209. {
  210. "productName": product.product_name or "",
  211. "model": product.model or "",
  212. "packageSpec": product.package_spec or "",
  213. "unit": product.unit or "",
  214. "planQty": product.quantity,
  215. "actualQty": product.actual_qty,
  216. "inboundQty": product.inbound_qty,
  217. "outboundQty": product.outbound_qty,
  218. "unitPrice": product.inbound_price or product.outbound_price,
  219. "amount": product.inbound_amount or product.outbound_amount,
  220. }
  221. )
  222. rows.append(row)
  223. return row_no
  224. def build_plan_archive_export_rows(
  225. db: Session,
  226. tenant_no: str,
  227. plans: list[PlPlan],
  228. transports_by_id: dict[str, PlTransport],
  229. *,
  230. stop_kind: Optional[str] = None,
  231. stop_customer_keywords: Optional[list] = None,
  232. ) -> list[dict]:
  233. """构建归档导出数据行:每计划 × 每段次 × 每段产品一行。
  234. stop_kind 为 load / delivery 时只导出该类段次,与归档列表段次漏斗一致。
  235. stop_customer_keywords 非空时只导出客户名称包含任一关键字的段次。
  236. """
  237. if not plans:
  238. return []
  239. include_load = stop_kind != "delivery"
  240. include_delivery = stop_kind != "load"
  241. keywords = [str(item).strip() for item in (stop_customer_keywords or []) if str(item).strip()]
  242. def _keep_customer(name: Optional[str]) -> bool:
  243. if not keywords:
  244. return True
  245. return customer_name_matches_keywords(name, keywords)
  246. plan_ids = [plan.id for plan in plans]
  247. stops_by_plan = load_plan_stops_grouped(db, tenant_no, plan_ids)
  248. legacy_products_by_plan = _load_legacy_products_by_plan(db, tenant_no, plan_ids)
  249. rows: list[dict] = []
  250. row_no = 0
  251. for plan in plans:
  252. transport = transports_by_id.get(plan.transport_id) if plan.transport_id else None
  253. plan_common = _plan_common_export_fields(plan, transport)
  254. load_read, delivery_reads = stops_by_plan.get(plan.id, (None, []))
  255. has_stops = load_read is not None or bool(delivery_reads)
  256. if not has_stops:
  257. if not include_load:
  258. continue
  259. legacy_customer = plan.customer_name or plan.supplier_name or ""
  260. if not _keep_customer(legacy_customer):
  261. continue
  262. row_no = _append_legacy_plan_product_rows(
  263. rows,
  264. row_no,
  265. plan,
  266. plan_common,
  267. legacy_products_by_plan.get(plan.id, []),
  268. )
  269. continue
  270. if include_load and load_read is not None and _keep_customer(load_read.customer_name):
  271. row_no = _append_stop_product_rows(
  272. rows,
  273. row_no,
  274. plan_common,
  275. "load",
  276. load_read,
  277. None,
  278. load_read.products or [],
  279. )
  280. if include_delivery:
  281. for idx, delivery_read in enumerate(delivery_reads):
  282. if not _keep_customer(delivery_read.customer_name):
  283. continue
  284. delivery_seq = delivery_read.seq or (idx + 1)
  285. row_no = _append_stop_product_rows(
  286. rows,
  287. row_no,
  288. plan_common,
  289. "delivery",
  290. delivery_read,
  291. delivery_seq,
  292. delivery_read.products or [],
  293. )
  294. return rows