| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195 |
- """职位 CRUD(sys_post)"""
- 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.delete_guard import assert_row_deletable_by_creator
- from app.core.utils import generate_uuid
- from app.models.models import SysPost
- def _row_to_dict(p: SysPost) -> Dict[str, Any]:
- return {
- "id": p.id,
- "postName": p.post_name,
- "postCode": p.post_code,
- "status": p.status,
- "tenantNo": p.tenant_no,
- "orderNum": p.order_num if p.order_num is not None else 0,
- "remark": p.remark or "",
- "createBy": p.create_by or "",
- "createTime": p.create_time.strftime("%Y-%m-%d %H:%M:%S") if p.create_time else "",
- "updateTime": p.update_time.strftime("%Y-%m-%d %H:%M:%S") if p.update_time else "",
- }
- def list_posts(
- db: Session,
- *,
- page: int = 1,
- page_size: int = 10,
- keyword: Optional[str] = None,
- post_name: Optional[str] = None,
- post_code: Optional[str] = None,
- post_name_in: Optional[str] = None,
- post_code_in: Optional[str] = None,
- status: Optional[str] = None,
- status_in: Optional[str] = None,
- tenant_no: Optional[str] = None,
- ids: Optional[List[str]] = None,
- max_page_size: Optional[int] = None,
- user_info=None,
- ) -> Tuple[List[Dict[str, Any]], int]:
- def _filtered():
- q0 = db.query(SysPost).filter(SysPost.del_flag == 0)
- if tenant_no:
- q0 = q0.filter(SysPost.tenant_no == tenant_no)
- kw = (keyword or "").strip()
- if kw:
- like = f"%{kw}%"
- q0 = q0.filter(or_(SysPost.post_name.like(like), SysPost.post_code.like(like)))
- pn = (post_name or "").strip()
- if pn:
- q0 = q0.filter(SysPost.post_name.like(f"%{pn}%"))
- pc = (post_code or "").strip()
- if pc:
- q0 = q0.filter(SysPost.post_code.like(f"%{pc}%"))
- pns_in = [s.strip() for s in str(post_name_in or "").split(",") if s.strip()]
- if pns_in:
- q0 = q0.filter(SysPost.post_name.in_(pns_in))
- pcs_in = [s.strip() for s in str(post_code_in or "").split(",") if s.strip()]
- if pcs_in:
- q0 = q0.filter(SysPost.post_code.in_(pcs_in))
- statuses = [s.strip() for s in str(status_in or "").split(",") if s.strip()]
- if not statuses and status:
- statuses = [status]
- if statuses:
- q0 = q0.filter(SysPost.status.in_(statuses))
- if ids:
- q0 = q0.filter(SysPost.id.in_(ids))
- # 职位为租户主数据,不做 create_by 数据范围过滤
- return q0
- total = _filtered().order_by(None).with_entities(func.count(SysPost.id)).scalar() or 0
- page = max(1, page)
- cap = int(max_page_size) if max_page_size else 500
- page_size = min(max(1, page_size), cap)
- rows = (
- _filtered()
- .order_by(SysPost.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_post(db: Session, post_id: str) -> Optional[SysPost]:
- return (
- db.query(SysPost)
- .filter(and_(SysPost.id == post_id, SysPost.del_flag == 0))
- .first()
- )
- def post_code_exists(db: Session, code: str, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
- q = db.query(SysPost).filter(and_(SysPost.post_code == code.strip(), SysPost.tenant_no == tenant_no, SysPost.del_flag == 0))
- if exclude_id:
- q = q.filter(SysPost.id != exclude_id)
- return q.first() is not None
- def create_post(
- db: Session,
- *,
- post_name: str,
- post_code: str,
- status: str = "1",
- tenant_no: str = "shanxia2.0",
- order_num: Optional[int] = None,
- remark: Optional[str] = None,
- user_id: Optional[str] = None,
- ) -> SysPost:
- pc = (post_code or "").strip()
- if not pc:
- raise ValueError("职位编码不能为空")
- if post_code_exists(db, pc, tenant_no):
- raise ValueError("职位编码已存在")
- obj = SysPost(
- id=generate_uuid(),
- post_name=(post_name or "").strip() or pc,
- post_code=pc,
- status=status or "1",
- 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_post(
- db: Session,
- post_id: str,
- *,
- post_name: Optional[str] = None,
- post_code: Optional[str] = None,
- status: Optional[str] = None,
- order_num: Optional[int] = None,
- remark: Optional[str] = None,
- user_id: Optional[str] = None,
- ) -> SysPost:
- obj = get_post(db, post_id)
- if not obj:
- raise ValueError("职位不存在")
- if post_code is not None:
- new_code = post_code.strip()
- if not new_code:
- raise ValueError("职位编码不能为空")
- if new_code != obj.post_code and post_code_exists(db, new_code, obj.tenant_no, exclude_id=post_id):
- raise ValueError("职位编码已存在")
- obj.post_code = new_code
- if post_name is not None:
- obj.post_name = (post_name or "").strip() or obj.post_name
- if status is not None:
- obj.status = status
- 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_post(db: Session, post_id: str, *, user_info: dict = None) -> None:
- obj = get_post(db, post_id)
- if not obj:
- raise ValueError("职位不存在")
- assert_row_deletable_by_creator(obj, user_info)
- 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)))
|