customer.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. """客户 CRUD(biz_customer)"""
  2. from __future__ import annotations
  3. import math
  4. from datetime import datetime
  5. from typing import Any, Dict, List, Optional, Tuple
  6. from sqlalchemy import and_, func, or_
  7. from sqlalchemy.orm import Session
  8. from app.core.utils import generate_uuid
  9. from app.models.models import BizCustomer
  10. def _row_to_dict(c: BizCustomer) -> Dict[str, Any]:
  11. return {
  12. "id": c.id,
  13. "customerName": c.customer_name,
  14. "sex": (c.sex or "2").strip() if c.sex else "2",
  15. "idCardNo": c.id_card_no or "",
  16. "age": c.age,
  17. "phoneNo": c.phone_no or "",
  18. "customerTags": c.customer_tags or "",
  19. "tenantNo": c.tenant_no,
  20. "orderNum": c.order_num if c.order_num is not None else 0,
  21. "remark": c.remark or "",
  22. "createTime": c.create_time.strftime("%Y-%m-%d %H:%M:%S") if c.create_time else "",
  23. "updateTime": c.update_time.strftime("%Y-%m-%d %H:%M:%S") if c.update_time else "",
  24. }
  25. def id_card_taken(db: Session, id_card: str, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
  26. ic = (id_card or "").strip()
  27. if not ic:
  28. return False
  29. q = db.query(BizCustomer).filter(
  30. and_(BizCustomer.id_card_no == ic, BizCustomer.tenant_no == tenant_no, BizCustomer.del_flag == 0)
  31. )
  32. if exclude_id:
  33. q = q.filter(BizCustomer.id != exclude_id)
  34. return q.first() is not None
  35. def _normalize_date_bound(value: str, *, end_of_day: bool = False) -> str:
  36. val = (value or "").strip()
  37. if len(val) == 10:
  38. return f"{val} 23:59:59" if end_of_day else f"{val} 00:00:00"
  39. return val
  40. def list_customers(
  41. db: Session,
  42. *,
  43. page: int = 1,
  44. page_size: int = 10,
  45. keyword: Optional[str] = None,
  46. create_time_start: Optional[str] = None,
  47. create_time_end: Optional[str] = None,
  48. tenant_no: Optional[str] = None,
  49. ) -> Tuple[List[Dict[str, Any]], int]:
  50. def _filtered():
  51. q0 = db.query(BizCustomer).filter(BizCustomer.del_flag == 0)
  52. if tenant_no:
  53. q0 = q0.filter(BizCustomer.tenant_no == tenant_no)
  54. kw = (keyword or "").strip()
  55. if kw:
  56. like = f"%{kw}%"
  57. q0 = q0.filter(
  58. or_(
  59. BizCustomer.customer_name.like(like),
  60. BizCustomer.phone_no.like(like),
  61. BizCustomer.id_card_no.like(like),
  62. BizCustomer.customer_tags.like(like),
  63. )
  64. )
  65. if create_time_start:
  66. q0 = q0.filter(
  67. BizCustomer.create_time >= _normalize_date_bound(create_time_start)
  68. )
  69. if create_time_end:
  70. q0 = q0.filter(
  71. BizCustomer.create_time <= _normalize_date_bound(create_time_end, end_of_day=True)
  72. )
  73. return q0
  74. total = _filtered().order_by(None).with_entities(func.count(BizCustomer.id)).scalar() or 0
  75. page = max(1, page)
  76. page_size = min(max(1, page_size), 100)
  77. rows = (
  78. _filtered()
  79. .order_by(BizCustomer.create_time.desc())
  80. .offset((page - 1) * page_size)
  81. .limit(page_size)
  82. .all()
  83. )
  84. return [_row_to_dict(x) for x in rows], int(total)
  85. def get_customer(db: Session, customer_id: str, tenant_no: Optional[str] = None) -> Optional[BizCustomer]:
  86. q = db.query(BizCustomer).filter(and_(BizCustomer.id == customer_id, BizCustomer.del_flag == 0))
  87. if tenant_no:
  88. q = q.filter(BizCustomer.tenant_no == tenant_no)
  89. return q.first()
  90. def create_customer(
  91. db: Session,
  92. *,
  93. customer_name: str,
  94. sex: str = "2",
  95. id_card_no: Optional[str] = None,
  96. age: Optional[int] = None,
  97. phone_no: Optional[str] = None,
  98. customer_tags: Optional[str] = None,
  99. tenant_no: str = "zkxw",
  100. order_num: Optional[int] = None,
  101. remark: Optional[str] = None,
  102. user_id: Optional[str] = None,
  103. ) -> BizCustomer:
  104. name = (customer_name or "").strip()
  105. if not name:
  106. raise ValueError("客户姓名不能为空")
  107. ic = (id_card_no or "").strip() or None
  108. if ic and id_card_taken(db, ic, tenant_no):
  109. raise ValueError("该身份证号已存在客户,请勿重复创建")
  110. obj = BizCustomer(
  111. id=generate_uuid(),
  112. customer_name=name,
  113. sex=(sex or "2")[:1] if sex else "2",
  114. id_card_no=ic,
  115. age=age,
  116. phone_no=(phone_no or "").strip() or None,
  117. customer_tags=(customer_tags or "").strip() or None,
  118. tenant_no=tenant_no,
  119. order_num=order_num if order_num is not None else 0,
  120. remark=(remark or "").strip() or None,
  121. create_by=user_id,
  122. create_dept_id="",
  123. create_time=datetime.now(),
  124. update_by=user_id,
  125. update_time=datetime.now(),
  126. del_flag=0,
  127. )
  128. db.add(obj)
  129. db.commit()
  130. db.refresh(obj)
  131. return obj
  132. def update_customer(
  133. db: Session,
  134. customer_id: str,
  135. *,
  136. customer_name: Optional[str] = None,
  137. sex: Optional[str] = None,
  138. id_card_no: Optional[str] = None,
  139. age: Optional[int] = None,
  140. phone_no: Optional[str] = None,
  141. customer_tags: Optional[str] = None,
  142. order_num: Optional[int] = None,
  143. remark: Optional[str] = None,
  144. user_id: Optional[str] = None,
  145. tenant_no: Optional[str] = None,
  146. ) -> BizCustomer:
  147. obj = get_customer(db, customer_id, tenant_no=tenant_no)
  148. if not obj:
  149. raise ValueError("客户不存在")
  150. if customer_name is not None:
  151. n = customer_name.strip()
  152. if not n:
  153. raise ValueError("客户姓名不能为空")
  154. obj.customer_name = n
  155. if sex is not None:
  156. obj.sex = (sex or "2")[:1]
  157. if id_card_no is not None:
  158. ic = id_card_no.strip() or None
  159. if ic and id_card_taken(db, ic, obj.tenant_no, exclude_id=customer_id):
  160. raise ValueError("该身份证号已被其他客户使用")
  161. obj.id_card_no = ic
  162. if age is not None:
  163. obj.age = age
  164. if phone_no is not None:
  165. obj.phone_no = phone_no.strip() or None
  166. if customer_tags is not None:
  167. obj.customer_tags = customer_tags.strip() or None
  168. if order_num is not None:
  169. obj.order_num = order_num
  170. if remark is not None:
  171. obj.remark = remark.strip() or None
  172. obj.update_by = user_id
  173. obj.update_time = datetime.now()
  174. db.add(obj)
  175. db.commit()
  176. db.refresh(obj)
  177. return obj
  178. def soft_delete_customer(db: Session, customer_id: str, tenant_no: Optional[str] = None) -> None:
  179. obj = get_customer(db, customer_id, tenant_no=tenant_no)
  180. if not obj:
  181. raise ValueError("客户不存在")
  182. obj.del_flag = 1
  183. obj.update_time = datetime.now()
  184. db.add(obj)
  185. db.commit()
  186. def total_pages(total: int, page_size: int) -> int:
  187. if total <= 0:
  188. return 0
  189. return int(math.ceil(total / float(page_size)))