item_unit.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. """物品单位 CRUD(biz_item_unit)"""
  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 BizItemUnit
  10. def _row_to_dict(u: BizItemUnit) -> Dict[str, Any]:
  11. return {
  12. "id": u.id,
  13. "unitCode": u.unit_code,
  14. "unitName": u.unit_name,
  15. "tenantNo": u.tenant_no,
  16. "orderNum": u.order_num if u.order_num is not None else 0,
  17. "remark": u.remark or "",
  18. "createTime": u.create_time.strftime("%Y-%m-%d %H:%M:%S") if u.create_time else "",
  19. "updateTime": u.update_time.strftime("%Y-%m-%d %H:%M:%S") if u.update_time else "",
  20. }
  21. def list_item_units(
  22. db: Session,
  23. *,
  24. page: int = 1,
  25. page_size: int = 10,
  26. keyword: Optional[str] = None,
  27. tenant_no: Optional[str] = None,
  28. user_info=None,
  29. ) -> Tuple[List[Dict[str, Any]], int]:
  30. def _filtered():
  31. q0 = db.query(BizItemUnit).filter(BizItemUnit.del_flag == 0)
  32. if tenant_no:
  33. q0 = q0.filter(BizItemUnit.tenant_no == tenant_no)
  34. kw = (keyword or "").strip()
  35. if kw:
  36. like = f"%{kw}%"
  37. q0 = q0.filter(or_(BizItemUnit.unit_code.like(like), BizItemUnit.unit_name.like(like)))
  38. if user_info:
  39. from app.core.data_scope import apply_data_scope
  40. q0 = apply_data_scope(q0, BizItemUnit, user_info, db, tenant_no)
  41. return q0
  42. total = _filtered().order_by(None).with_entities(func.count(BizItemUnit.id)).scalar() or 0
  43. page = max(1, page)
  44. page_size = min(max(1, page_size), 100)
  45. rows = (
  46. _filtered()
  47. .order_by(BizItemUnit.create_time.desc())
  48. .offset((page - 1) * page_size)
  49. .limit(page_size)
  50. .all()
  51. )
  52. return [_row_to_dict(x) for x in rows], int(total)
  53. def get_item_unit(db: Session, unit_id: str) -> Optional[BizItemUnit]:
  54. return (
  55. db.query(BizItemUnit)
  56. .filter(and_(BizItemUnit.id == unit_id, BizItemUnit.del_flag == 0))
  57. .first()
  58. )
  59. def unit_code_exists(db: Session, code: str, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
  60. q = db.query(BizItemUnit).filter(and_(BizItemUnit.unit_code == code.strip(), BizItemUnit.tenant_no == tenant_no, BizItemUnit.del_flag == 0))
  61. if exclude_id:
  62. q = q.filter(BizItemUnit.id != exclude_id)
  63. return q.first() is not None
  64. def create_item_unit(
  65. db: Session,
  66. *,
  67. unit_code: str,
  68. unit_name: str,
  69. tenant_no: str = "zkxw",
  70. order_num: Optional[int] = None,
  71. remark: Optional[str] = None,
  72. user_id: Optional[str] = None,
  73. ) -> BizItemUnit:
  74. uc = (unit_code or "").strip()
  75. if not uc:
  76. raise ValueError("单位编码不能为空")
  77. if unit_code_exists(db, uc, tenant_no):
  78. raise ValueError("单位编码已存在")
  79. obj = BizItemUnit(
  80. id=generate_uuid(),
  81. unit_code=uc,
  82. unit_name=(unit_name or "").strip() or uc,
  83. tenant_no=tenant_no,
  84. order_num=order_num if order_num is not None else 0,
  85. remark=(remark or "").strip() or None,
  86. create_by=user_id,
  87. create_dept_id="",
  88. create_time=datetime.now(),
  89. update_by=user_id,
  90. update_time=datetime.now(),
  91. del_flag=0,
  92. )
  93. db.add(obj)
  94. db.commit()
  95. db.refresh(obj)
  96. return obj
  97. def update_item_unit(
  98. db: Session,
  99. unit_id: str,
  100. *,
  101. unit_code: Optional[str] = None,
  102. unit_name: Optional[str] = None,
  103. order_num: Optional[int] = None,
  104. remark: Optional[str] = None,
  105. user_id: Optional[str] = None,
  106. ) -> BizItemUnit:
  107. obj = get_item_unit(db, unit_id)
  108. if not obj:
  109. raise ValueError("物品单位不存在")
  110. if unit_code is not None:
  111. new_code = unit_code.strip()
  112. if not new_code:
  113. raise ValueError("单位编码不能为空")
  114. if new_code != obj.unit_code and unit_code_exists(db, new_code, obj.tenant_no, exclude_id=unit_id):
  115. raise ValueError("单位编码已存在")
  116. obj.unit_code = new_code
  117. if unit_name is not None:
  118. obj.unit_name = (unit_name or "").strip() or obj.unit_name
  119. if order_num is not None:
  120. obj.order_num = order_num
  121. if remark is not None:
  122. obj.remark = (remark or "").strip() or None
  123. obj.update_by = user_id
  124. obj.update_time = datetime.now()
  125. db.add(obj)
  126. db.commit()
  127. db.refresh(obj)
  128. return obj
  129. def soft_delete_item_unit(db: Session, unit_id: str) -> None:
  130. obj = get_item_unit(db, unit_id)
  131. if not obj:
  132. raise ValueError("物品单位不存在")
  133. obj.del_flag = 1
  134. obj.update_time = datetime.now()
  135. db.add(obj)
  136. db.commit()
  137. def total_pages(total: int, page_size: int) -> int:
  138. if total <= 0:
  139. return 0
  140. return int(math.ceil(total / float(page_size)))