product_helpers.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(db: Session, tenant_no: str, product_id: str) -> ProductSnapshot:
  13. """校验 CRM 产品并返回名称/规格快照。新建单据 product_id 必填。"""
  14. pid = (product_id or "").strip()
  15. if not pid:
  16. raise HTTPException(
  17. status_code=status.HTTP_400_BAD_REQUEST,
  18. detail="请选择 CRM 产品",
  19. )
  20. row = get_product(db, pid)
  21. if row is None or row.tenant_no != tenant_no:
  22. raise HTTPException(
  23. status_code=status.HTTP_400_BAD_REQUEST,
  24. detail="产品不存在或不可用",
  25. )
  26. if row.status != "on":
  27. raise HTTPException(
  28. status_code=status.HTTP_400_BAD_REQUEST,
  29. detail="产品已下架,请重新选择",
  30. )
  31. name = (row.product_name or "").strip()
  32. if not name:
  33. raise HTTPException(
  34. status_code=status.HTTP_400_BAD_REQUEST,
  35. detail="产品名称无效",
  36. )
  37. model = (row.model or "").strip() or None
  38. return ProductSnapshot(product_id=row.id, product_name=name, specification=model)
  39. def apply_product_snapshot_to_plan(plan, snapshot: ProductSnapshot) -> None:
  40. plan.product_id = snapshot.product_id
  41. plan.product = snapshot.product_name
  42. plan.specification = snapshot.specification
  43. def apply_product_snapshot_to_inventory(row, snapshot: ProductSnapshot) -> None:
  44. row.product_id = snapshot.product_id
  45. row.product = snapshot.product_name
  46. row.specification = snapshot.specification
  47. def apply_product_snapshot_to_weighing(row, snapshot: ProductSnapshot) -> None:
  48. row.product_id = snapshot.product_id
  49. row.cargo_name = snapshot.product_name
  50. row.specification = snapshot.specification