customer.py 7.8 KB

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