Files
shanxia2.0/backend/app/crud/reagent.py
T
2026-05-18 16:21:38 +08:00

188 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""试剂 CRUD(biz_reagent)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app.core.utils import generate_uuid
from app.models.models import BizReagent
def _row_to_dict(r: BizReagent) -> Dict[str, Any]:
return {
"id": r.id,
"reagentCode": r.reagent_code,
"reagentName": r.reagent_name,
"spec": r.spec or "",
"standardUsage": r.standard_usage or "",
"unit": r.unit or "",
"description": r.description or "",
"tenantNo": r.tenant_no,
"orderNum": r.order_num if r.order_num is not None else 0,
"remark": r.remark or "",
"createTime": r.create_time.strftime("%Y-%m-%d %H:%M:%S") if r.create_time else "",
"updateTime": r.update_time.strftime("%Y-%m-%d %H:%M:%S") if r.update_time else "",
}
def list_reagents(
db: Session,
*,
page: int = 1,
page_size: int = 10,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
def _filtered():
q0 = db.query(BizReagent).filter(BizReagent.del_flag == 0)
if tenant_no:
q0 = q0.filter(BizReagent.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
like = f"%{kw}%"
q0 = q0.filter(
or_(
BizReagent.reagent_code.like(like),
BizReagent.reagent_name.like(like),
)
)
return q0
total = _filtered().order_by(None).with_entities(func.count(BizReagent.id)).scalar() or 0
page = max(1, page)
page_size = min(max(1, page_size), 100)
rows = (
_filtered()
.order_by(BizReagent.create_time.desc())
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def get_reagent(db: Session, reagent_id: str) -> Optional[BizReagent]:
return (
db.query(BizReagent)
.filter(and_(BizReagent.id == reagent_id, BizReagent.del_flag == 0))
.first()
)
def reagent_code_exists(db: Session, code: str, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
q = db.query(BizReagent).filter(
and_(BizReagent.reagent_code == code.strip(), BizReagent.tenant_no == tenant_no, BizReagent.del_flag == 0)
)
if exclude_id:
q = q.filter(BizReagent.id != exclude_id)
return q.first() is not None
def create_reagent(
db: Session,
*,
reagent_code: str,
reagent_name: str,
spec: Optional[str] = None,
standard_usage: Optional[str] = None,
unit: Optional[str] = None,
description: Optional[str] = None,
tenant_no: str = "zkxw",
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
) -> BizReagent:
rc = (reagent_code or "").strip()
if not rc:
raise ValueError("试剂编码不能为空")
if reagent_code_exists(db, rc, tenant_no):
raise ValueError("试剂编码已存在")
obj = BizReagent(
id=generate_uuid(),
reagent_code=rc,
reagent_name=(reagent_name or "").strip() or rc,
spec=(spec or "").strip() or None,
standard_usage=(standard_usage or "").strip() or None,
unit=(unit or "").strip() or None,
description=(description or "").strip() or None,
tenant_no=tenant_no,
order_num=order_num if order_num is not None else 0,
remark=(remark or "").strip() or None,
create_by=user_id,
create_dept_id="",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def update_reagent(
db: Session,
reagent_id: str,
*,
reagent_code: Optional[str] = None,
reagent_name: Optional[str] = None,
spec: Optional[str] = None,
standard_usage: Optional[str] = None,
unit: Optional[str] = None,
description: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
) -> BizReagent:
obj = get_reagent(db, reagent_id)
if not obj:
raise ValueError("试剂不存在")
if reagent_code is not None:
new_code = reagent_code.strip()
if not new_code:
raise ValueError("试剂编码不能为空")
if new_code != obj.reagent_code and reagent_code_exists(db, new_code, obj.tenant_no, exclude_id=reagent_id):
raise ValueError("试剂编码已存在")
obj.reagent_code = new_code
if reagent_name is not None:
obj.reagent_name = (reagent_name or "").strip() or obj.reagent_name
if spec is not None:
obj.spec = (spec or "").strip() or None
if standard_usage is not None:
obj.standard_usage = (standard_usage or "").strip() or None
if unit is not None:
obj.unit = (unit or "").strip() or None
if description is not None:
obj.description = (description or "").strip() or None
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = (remark or "").strip() or None
obj.update_by = user_id
obj.update_time = datetime.now()
db.add(obj)
db.commit()
db.refresh(obj)
return obj
def soft_delete_reagent(db: Session, reagent_id: str) -> None:
obj = get_reagent(db, reagent_id)
if not obj:
raise ValueError("试剂不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
db.commit()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))