Files
zkxw/backend/app/crud/contract_processing_category.py
T
cykjandCursor c22a0d1eb0 feat(market): 完善临床科研与委托加工上线能力
补齐项目组负责人审批、费用信息、合作客户、生产出库菜单、申请单号 LCKY 前缀及配套 SQL 迁移,并同步相关前后端与单测。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-30 18:51:37 +08:00

258 lines
7.7 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_contract_processing_category)"""
from __future__ import annotations
import math
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from app.constants.research_category import (
CLINICAL_RESEARCH_CATEGORY_LABELS,
CONTRACT_PROCESSING_CATEGORY_LABELS,
CUSTOM_CATEGORY_MAX_LEN,
)
from app.core.utils import generate_uuid
from app.models.models import BizContractProcessingCategory
_DEFAULT_BIZ_TYPE = "contract_processing"
_ALLOWED_BIZ_TYPES = ("basic_experiment", "contract_processing")
_RESERVED_NAMES = {
*CONTRACT_PROCESSING_CATEGORY_LABELS.keys(),
*CONTRACT_PROCESSING_CATEGORY_LABELS.values(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.keys(),
*CLINICAL_RESEARCH_CATEGORY_LABELS.values(),
"__other__",
"其他",
}
def _normalize_biz_type(biz_type: Optional[str]) -> str:
value = (biz_type or _DEFAULT_BIZ_TYPE).strip()
if value not in _ALLOWED_BIZ_TYPES:
raise ValueError("业务类型所属业务线无效")
return value
def _row_to_dict(row: BizContractProcessingCategory) -> Dict[str, Any]:
return {
"id": row.id,
"categoryName": row.category_name or "",
"bizType": getattr(row, "biz_type", None) or _DEFAULT_BIZ_TYPE,
"tenantNo": row.tenant_no,
"orderNum": row.order_num if row.order_num is not None else 0,
"remark": row.remark or "",
"createTime": row.create_time.strftime("%Y-%m-%d %H:%M:%S") if row.create_time else "",
"updateTime": row.update_time.strftime("%Y-%m-%d %H:%M:%S") if row.update_time else "",
}
def _normalize_name(name: Optional[str]) -> str:
return (name or "").strip()
def _assert_valid_name(name: str) -> str:
value = _normalize_name(name)
if not value:
raise ValueError("业务类型名称不能为空")
if len(value) > CUSTOM_CATEGORY_MAX_LEN:
raise ValueError(f"业务类型不能超过{CUSTOM_CATEGORY_MAX_LEN}个字符")
if value in _RESERVED_NAMES:
raise ValueError("该名称与系统预置业务类型冲突,请更换")
return value
def _exists_name(
db: Session,
tenant_no: str,
name: str,
*,
biz_type: str,
exclude_id: Optional[str] = None,
) -> bool:
q = db.query(BizContractProcessingCategory.id).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == biz_type,
BizContractProcessingCategory.category_name == name,
)
if exclude_id:
q = q.filter(BizContractProcessingCategory.id != exclude_id)
return q.first() is not None
def list_categories(
db: Session,
*,
page: int = 1,
page_size: int = 100,
keyword: Optional[str] = None,
tenant_no: Optional[str] = None,
biz_type: Optional[str] = None,
) -> Tuple[List[Dict[str, Any]], int]:
bt = _normalize_biz_type(biz_type)
def _filtered():
q0 = db.query(BizContractProcessingCategory).filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.biz_type == bt,
)
if tenant_no:
q0 = q0.filter(BizContractProcessingCategory.tenant_no == tenant_no)
kw = (keyword or "").strip()
if kw:
q0 = q0.filter(BizContractProcessingCategory.category_name.like(f"%{kw}%"))
return q0
total = (
_filtered()
.order_by(None)
.with_entities(func.count(BizContractProcessingCategory.id))
.scalar()
or 0
)
page = max(1, page)
page_size = min(max(1, page_size), 200)
rows = (
_filtered()
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.offset((page - 1) * page_size)
.limit(page_size)
.all()
)
return [_row_to_dict(x) for x in rows], int(total)
def list_all_categories(
db: Session, *, tenant_no: str, biz_type: Optional[str] = None
) -> List[Dict[str, Any]]:
bt = _normalize_biz_type(biz_type)
rows = (
db.query(BizContractProcessingCategory)
.filter(
BizContractProcessingCategory.del_flag == 0,
BizContractProcessingCategory.tenant_no == tenant_no,
BizContractProcessingCategory.biz_type == bt,
)
.order_by(
BizContractProcessingCategory.order_num.asc(),
BizContractProcessingCategory.create_time.desc(),
)
.all()
)
return [_row_to_dict(x) for x in rows]
def get_category(
db: Session, category_id: str, tenant_no: Optional[str] = None
) -> Optional[BizContractProcessingCategory]:
q = db.query(BizContractProcessingCategory).filter(
and_(
BizContractProcessingCategory.id == category_id,
BizContractProcessingCategory.del_flag == 0,
)
)
if tenant_no:
q = q.filter(BizContractProcessingCategory.tenant_no == tenant_no)
return q.first()
def create_category(
db: Session,
*,
category_name: str,
tenant_no: str = "zkxw",
biz_type: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
create_dept_id: str = "",
commit: bool = True,
) -> BizContractProcessingCategory:
bt = _normalize_biz_type(biz_type)
name = _assert_valid_name(category_name)
if _exists_name(db, tenant_no, name, biz_type=bt):
raise ValueError("业务类型已存在")
obj = BizContractProcessingCategory(
id=generate_uuid(),
category_name=name,
biz_type=bt,
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_dept_id or "",
create_time=datetime.now(),
update_by=user_id,
update_time=datetime.now(),
del_flag=0,
)
db.add(obj)
if commit:
db.commit()
db.refresh(obj)
else:
db.flush()
return obj
def update_category(
db: Session,
category_id: str,
*,
category_name: Optional[str] = None,
order_num: Optional[int] = None,
remark: Optional[str] = None,
user_id: Optional[str] = None,
tenant_no: Optional[str] = None,
) -> BizContractProcessingCategory:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
bt = _normalize_biz_type(getattr(obj, "biz_type", None) or _DEFAULT_BIZ_TYPE)
if category_name is not None:
name = _assert_valid_name(category_name)
if _exists_name(db, obj.tenant_no, name, biz_type=bt, exclude_id=obj.id):
raise ValueError("业务类型已存在")
obj.category_name = name
if order_num is not None:
obj.order_num = order_num
if remark is not None:
obj.remark = remark.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_category(
db: Session,
category_id: str,
tenant_no: Optional[str] = None,
*,
commit: bool = True,
) -> None:
obj = get_category(db, category_id, tenant_no=tenant_no)
if not obj:
raise ValueError("业务类型不存在")
obj.del_flag = 1
obj.update_time = datetime.now()
db.add(obj)
if commit:
db.commit()
else:
db.flush()
def total_pages(total: int, page_size: int) -> int:
if total <= 0:
return 0
return int(math.ceil(total / float(page_size)))