qc_third_party_item.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. """第三方检测项目 CRUD"""
  2. from __future__ import annotations
  3. from datetime import datetime
  4. from decimal import Decimal
  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.crud.qc_third_party_company import get_company
  10. from app.models.models import BizQcThirdPartyCompany, BizQcThirdPartyItem
  11. def _dec(v: Any) -> float:
  12. if v is None:
  13. return 0.0
  14. return float(v)
  15. def _row_to_dict(r: BizQcThirdPartyItem, company_name: str = "") -> Dict[str, Any]:
  16. return {
  17. "id": r.id,
  18. "companyId": r.company_id,
  19. "companyName": company_name,
  20. "itemCode": r.item_code,
  21. "itemName": r.item_name,
  22. "feeAmount": _dec(r.fee_amount),
  23. "status": r.status or "1",
  24. "orderNum": r.order_num if r.order_num is not None else 0,
  25. "remark": r.remark or "",
  26. "createTime": r.create_time.strftime("%Y-%m-%d %H:%M:%S") if r.create_time else "",
  27. "updateTime": r.update_time.strftime("%Y-%m-%d %H:%M:%S") if r.update_time else "",
  28. }
  29. def item_code_exists(
  30. db: Session,
  31. company_id: str,
  32. code: str,
  33. tenant_no: str,
  34. exclude_id: Optional[str] = None,
  35. ) -> bool:
  36. c = (code or "").strip()
  37. if not c:
  38. return False
  39. q = db.query(BizQcThirdPartyItem).filter(
  40. BizQcThirdPartyItem.company_id == company_id,
  41. BizQcThirdPartyItem.item_code == c,
  42. BizQcThirdPartyItem.tenant_no == tenant_no,
  43. BizQcThirdPartyItem.del_flag == 0,
  44. )
  45. if exclude_id:
  46. q = q.filter(BizQcThirdPartyItem.id != exclude_id)
  47. return q.first() is not None
  48. def _company_name_map(db: Session, company_ids: List[str]) -> Dict[str, str]:
  49. if not company_ids:
  50. return {}
  51. rows = (
  52. db.query(BizQcThirdPartyCompany)
  53. .filter(BizQcThirdPartyCompany.id.in_(company_ids), BizQcThirdPartyCompany.del_flag == 0)
  54. .all()
  55. )
  56. return {r.id: r.company_name for r in rows}
  57. def list_items(
  58. db: Session,
  59. *,
  60. page: int = 1,
  61. page_size: int = 10,
  62. keyword: Optional[str] = None,
  63. status: Optional[str] = None,
  64. company_id: Optional[str] = None,
  65. tenant_no: Optional[str] = None,
  66. user_info=None,
  67. ) -> Tuple[List[Dict[str, Any]], int]:
  68. def _filtered():
  69. q0 = db.query(BizQcThirdPartyItem).filter(BizQcThirdPartyItem.del_flag == 0)
  70. if tenant_no:
  71. q0 = q0.filter(BizQcThirdPartyItem.tenant_no == tenant_no)
  72. if company_id:
  73. q0 = q0.filter(BizQcThirdPartyItem.company_id == company_id)
  74. kw = (keyword or "").strip()
  75. if kw:
  76. like = f"%{kw}%"
  77. q0 = q0.filter(
  78. or_(
  79. BizQcThirdPartyItem.item_code.like(like),
  80. BizQcThirdPartyItem.item_name.like(like),
  81. )
  82. )
  83. st = (status or "").strip()
  84. if st in ("0", "1"):
  85. q0 = q0.filter(BizQcThirdPartyItem.status == st)
  86. if user_info:
  87. from app.core.data_scope import apply_data_scope
  88. q0 = apply_data_scope(q0, BizQcThirdPartyItem, user_info, db, tenant_no)
  89. return q0
  90. total = _filtered().order_by(None).with_entities(func.count(BizQcThirdPartyItem.id)).scalar() or 0
  91. page = max(1, page)
  92. page_size = min(max(1, page_size), 100)
  93. rows = (
  94. _filtered()
  95. .order_by(BizQcThirdPartyItem.order_num.asc(), BizQcThirdPartyItem.create_time.desc())
  96. .offset((page - 1) * page_size)
  97. .limit(page_size)
  98. .all()
  99. )
  100. cids = list({r.company_id for r in rows})
  101. cmap = _company_name_map(db, cids)
  102. return [_row_to_dict(x, cmap.get(x.company_id, "")) for x in rows], int(total)
  103. def list_active_items(
  104. db: Session, tenant_no: str, company_id: Optional[str] = None, *, user_info=None
  105. ) -> List[Dict[str, Any]]:
  106. q = db.query(BizQcThirdPartyItem).filter(
  107. BizQcThirdPartyItem.tenant_no == tenant_no,
  108. BizQcThirdPartyItem.del_flag == 0,
  109. BizQcThirdPartyItem.status == "1",
  110. )
  111. if company_id:
  112. q = q.filter(BizQcThirdPartyItem.company_id == company_id)
  113. if user_info:
  114. from app.core.data_scope import apply_data_scope
  115. q = apply_data_scope(q, BizQcThirdPartyItem, user_info, db, tenant_no)
  116. rows = q.order_by(
  117. BizQcThirdPartyItem.order_num.asc(), BizQcThirdPartyItem.create_time.desc()
  118. ).all()
  119. cmap = _company_name_map(db, list({r.company_id for r in rows}))
  120. return [_row_to_dict(x, cmap.get(x.company_id, "")) for x in rows]
  121. def get_item(
  122. db: Session, row_id: str, tenant_no: Optional[str] = None
  123. ) -> Optional[BizQcThirdPartyItem]:
  124. q = db.query(BizQcThirdPartyItem).filter(
  125. BizQcThirdPartyItem.id == row_id, BizQcThirdPartyItem.del_flag == 0
  126. )
  127. if tenant_no:
  128. q = q.filter(BizQcThirdPartyItem.tenant_no == tenant_no)
  129. return q.first()
  130. def create_item(
  131. db: Session,
  132. *,
  133. company_id: str,
  134. item_code: str,
  135. item_name: str,
  136. fee_amount: float,
  137. status: str = "1",
  138. tenant_no: str,
  139. order_num: Optional[int] = None,
  140. remark: Optional[str] = None,
  141. user_id: Optional[str] = None,
  142. create_dept_id: str = "",
  143. ) -> BizQcThirdPartyItem:
  144. comp = get_company(db, company_id, tenant_no=tenant_no)
  145. if not comp:
  146. raise ValueError("所属公司不存在")
  147. code = (item_code or "").strip()
  148. if not code:
  149. raise ValueError("项目编码不能为空")
  150. if item_code_exists(db, company_id, code, tenant_no):
  151. raise ValueError("该公司下项目编码已存在")
  152. name = (item_name or "").strip()
  153. if not name:
  154. raise ValueError("项目名称不能为空")
  155. st = (status or "1").strip()
  156. if st not in ("0", "1"):
  157. raise ValueError("状态无效")
  158. fee = Decimal(str(fee_amount if fee_amount is not None else 0))
  159. obj = BizQcThirdPartyItem(
  160. id=generate_uuid(),
  161. company_id=company_id,
  162. item_code=code,
  163. item_name=name,
  164. fee_amount=fee,
  165. status=st,
  166. tenant_no=tenant_no,
  167. order_num=order_num if order_num is not None else 0,
  168. remark=(remark or "").strip() or None,
  169. create_by=user_id,
  170. create_dept_id=create_dept_id or "",
  171. create_time=datetime.now(),
  172. update_by=user_id,
  173. update_time=datetime.now(),
  174. del_flag=0,
  175. )
  176. db.add(obj)
  177. db.commit()
  178. db.refresh(obj)
  179. return obj
  180. def update_item(
  181. db: Session,
  182. row_id: str,
  183. *,
  184. company_id: Optional[str] = None,
  185. item_code: Optional[str] = None,
  186. item_name: Optional[str] = None,
  187. fee_amount: Optional[float] = None,
  188. status: Optional[str] = None,
  189. order_num: Optional[int] = None,
  190. remark: Optional[str] = None,
  191. user_id: Optional[str] = None,
  192. tenant_no: Optional[str] = None,
  193. ) -> BizQcThirdPartyItem:
  194. obj = get_item(db, row_id, tenant_no=tenant_no)
  195. if not obj:
  196. raise ValueError("项目不存在")
  197. cid = company_id or obj.company_id
  198. if company_id is not None:
  199. comp = get_company(db, company_id, tenant_no=obj.tenant_no)
  200. if not comp:
  201. raise ValueError("所属公司不存在")
  202. obj.company_id = company_id
  203. if item_code is not None:
  204. code = item_code.strip()
  205. if not code:
  206. raise ValueError("项目编码不能为空")
  207. if code != obj.item_code and item_code_exists(db, cid, code, obj.tenant_no, exclude_id=row_id):
  208. raise ValueError("该公司下项目编码已存在")
  209. obj.item_code = code
  210. if item_name is not None:
  211. name = (item_name or "").strip()
  212. if not name:
  213. raise ValueError("项目名称不能为空")
  214. obj.item_name = name
  215. if fee_amount is not None:
  216. obj.fee_amount = Decimal(str(fee_amount))
  217. if status is not None:
  218. st = status.strip()
  219. if st not in ("0", "1"):
  220. raise ValueError("状态无效")
  221. obj.status = st
  222. if order_num is not None:
  223. obj.order_num = order_num
  224. if remark is not None:
  225. obj.remark = (remark or "").strip() or None
  226. obj.update_by = user_id
  227. obj.update_time = datetime.now()
  228. db.add(obj)
  229. db.commit()
  230. db.refresh(obj)
  231. return obj
  232. def soft_delete_item(db: Session, row_id: str, tenant_no: Optional[str] = None) -> None:
  233. obj = get_item(db, row_id, tenant_no=tenant_no)
  234. if not obj:
  235. raise ValueError("项目不存在")
  236. obj.del_flag = 1
  237. obj.update_time = datetime.now()
  238. db.add(obj)
  239. db.commit()