168 lines
5.2 KiB
Python
168 lines
5.2 KiB
Python
"""租户 CRUD(sys_tenant)"""
|
||
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.config import settings
|
||
from app.core.utils import generate_uuid
|
||
from app.models.models import SysTenant
|
||
|
||
|
||
def _row_to_dict(t: SysTenant) -> Dict[str, Any]:
|
||
return {
|
||
"id": t.id,
|
||
"tenantNo": t.tenant_no,
|
||
"tenantName": t.tenant_name,
|
||
"contactName": t.contact_name or "",
|
||
"contactPhone": t.contact_phone or "",
|
||
"orderNum": t.order_num if t.order_num is not None else 0,
|
||
"remark": t.remark or "",
|
||
"createTime": t.create_time.strftime("%Y-%m-%d %H:%M:%S") if t.create_time else "",
|
||
"updateTime": t.update_time.strftime("%Y-%m-%d %H:%M:%S") if t.update_time else "",
|
||
}
|
||
|
||
|
||
def list_tenants(
|
||
db: Session,
|
||
*,
|
||
page: int = 1,
|
||
page_size: int = 10,
|
||
keyword: Optional[str] = None,
|
||
) -> Tuple[List[Dict[str, Any]], int]:
|
||
def _filtered():
|
||
q0 = db.query(SysTenant).filter(SysTenant.del_flag == 0)
|
||
kw = (keyword or "").strip()
|
||
if kw:
|
||
like = f"%{kw}%"
|
||
q0 = q0.filter(or_(SysTenant.tenant_no.like(like), SysTenant.tenant_name.like(like)))
|
||
return q0
|
||
|
||
total = _filtered().order_by(None).with_entities(func.count(SysTenant.id)).scalar() or 0
|
||
page = max(1, page)
|
||
page_size = min(max(1, page_size), 100)
|
||
rows = (
|
||
_filtered()
|
||
.order_by(SysTenant.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_tenant(db: Session, tenant_id: str) -> Optional[SysTenant]:
|
||
return (
|
||
db.query(SysTenant)
|
||
.filter(and_(SysTenant.id == tenant_id, SysTenant.del_flag == 0))
|
||
.first()
|
||
)
|
||
|
||
|
||
def tenant_no_exists(db: Session, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
|
||
q = db.query(SysTenant).filter(and_(SysTenant.tenant_no == tenant_no.strip(), SysTenant.del_flag == 0))
|
||
if exclude_id:
|
||
q = q.filter(SysTenant.id != exclude_id)
|
||
return q.first() is not None
|
||
|
||
|
||
def create_tenant(
|
||
db: Session,
|
||
*,
|
||
tenant_no: str,
|
||
tenant_name: str,
|
||
contact_name: Optional[str] = None,
|
||
contact_phone: Optional[str] = None,
|
||
order_num: Optional[int] = None,
|
||
remark: Optional[str] = None,
|
||
user_id: Optional[str] = None,
|
||
) -> SysTenant:
|
||
tn = (tenant_no or "").strip()
|
||
if not tn:
|
||
raise ValueError("租户编号不能为空")
|
||
if tenant_no_exists(db, tn):
|
||
raise ValueError("租户编号已存在")
|
||
obj = SysTenant(
|
||
id=generate_uuid(),
|
||
tenant_no=tn,
|
||
tenant_name=(tenant_name or "").strip() or tn,
|
||
contact_name=(contact_name or "").strip() or None,
|
||
contact_phone=(contact_phone or "").strip() or None,
|
||
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_tenant(
|
||
db: Session,
|
||
tenant_id: str,
|
||
*,
|
||
tenant_no: Optional[str] = None,
|
||
tenant_name: Optional[str] = None,
|
||
contact_name: Optional[str] = None,
|
||
contact_phone: Optional[str] = None,
|
||
order_num: Optional[int] = None,
|
||
remark: Optional[str] = None,
|
||
user_id: Optional[str] = None,
|
||
) -> SysTenant:
|
||
obj = get_tenant(db, tenant_id)
|
||
if not obj:
|
||
raise ValueError("租户不存在")
|
||
if tenant_no is not None:
|
||
new_no = tenant_no.strip()
|
||
if not new_no:
|
||
raise ValueError("租户编号不能为空")
|
||
if obj.tenant_no == settings.DEFAULT_TENANT_NO and new_no != settings.DEFAULT_TENANT_NO:
|
||
raise ValueError("默认租户编号不可修改")
|
||
if new_no != obj.tenant_no and tenant_no_exists(db, new_no, exclude_id=tenant_id):
|
||
raise ValueError("租户编号已存在")
|
||
obj.tenant_no = new_no
|
||
if tenant_name is not None:
|
||
obj.tenant_name = (tenant_name or "").strip() or obj.tenant_name
|
||
if contact_name is not None:
|
||
obj.contact_name = (contact_name or "").strip() or None
|
||
if contact_phone is not None:
|
||
obj.contact_phone = (contact_phone 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_tenant(db: Session, tenant_id: str) -> None:
|
||
obj = get_tenant(db, tenant_id)
|
||
if not obj:
|
||
raise ValueError("租户不存在")
|
||
if obj.tenant_no == settings.DEFAULT_TENANT_NO:
|
||
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)))
|