product_helpers.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """地磅模块 — CRM 产品解析与快照写入。"""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. from fastapi import HTTPException, status
  5. from sqlalchemy.orm import Session
  6. from app.crud.crm.product import get_product
  7. @dataclass(frozen=True)
  8. class ProductSnapshot:
  9. product_id: str
  10. product_name: str
  11. specification: str | None
  12. def resolve_crm_product(
  13. db: Session,
  14. tenant_no: str,
  15. product_id: str,
  16. *,
  17. require_on_shelf: bool = True,
  18. ) -> ProductSnapshot:
  19. """校验 CRM 产品并返回名称/规格快照。新建单据 product_id 必填。
  20. require_on_shelf=False 用于运输计划联动地磅等历史单据场景:
  21. 合同/计划中的产品可能已下架,但仍允许按主数据快照继续业务。
  22. """
  23. pid = (product_id or "").strip()
  24. if not pid:
  25. raise HTTPException(
  26. status_code=status.HTTP_400_BAD_REQUEST,
  27. detail="请选择 CRM 产品",
  28. )
  29. row = get_product(db, pid)
  30. if row is None or row.tenant_no != tenant_no:
  31. raise HTTPException(
  32. status_code=status.HTTP_400_BAD_REQUEST,
  33. detail="产品不存在或不可用",
  34. )
  35. if require_on_shelf and row.status != "on":
  36. raise HTTPException(
  37. status_code=status.HTTP_400_BAD_REQUEST,
  38. detail="产品已下架,请重新选择",
  39. )
  40. name = (row.product_name or "").strip()
  41. if not name:
  42. raise HTTPException(
  43. status_code=status.HTTP_400_BAD_REQUEST,
  44. detail="产品名称无效",
  45. )
  46. model = (row.model or "").strip() or None
  47. return ProductSnapshot(product_id=row.id, product_name=name, specification=model)
  48. def apply_product_snapshot_to_plan(plan, snapshot: ProductSnapshot) -> None:
  49. plan.product_id = snapshot.product_id
  50. plan.product = snapshot.product_name
  51. plan.specification = snapshot.specification
  52. def apply_product_snapshot_to_inventory(row, snapshot: ProductSnapshot) -> None:
  53. row.product_id = snapshot.product_id
  54. row.product = snapshot.product_name
  55. row.specification = snapshot.specification
  56. def apply_product_snapshot_to_weighing(row, snapshot: ProductSnapshot) -> None:
  57. row.product_id = snapshot.product_id
  58. row.cargo_name = snapshot.product_name
  59. row.specification = snapshot.specification