| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- """物品单位 CRUD(biz_item_unit)"""
- 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 BizItemUnit
- def _row_to_dict(u: BizItemUnit) -> Dict[str, Any]:
- return {
- "id": u.id,
- "unitCode": u.unit_code,
- "unitName": u.unit_name,
- "tenantNo": u.tenant_no,
- "orderNum": u.order_num if u.order_num is not None else 0,
- "remark": u.remark or "",
- "createTime": u.create_time.strftime("%Y-%m-%d %H:%M:%S") if u.create_time else "",
- "updateTime": u.update_time.strftime("%Y-%m-%d %H:%M:%S") if u.update_time else "",
- }
- def list_item_units(
- db: Session,
- *,
- page: int = 1,
- page_size: int = 10,
- keyword: Optional[str] = None,
- tenant_no: Optional[str] = None,
- user_info=None,
- ) -> Tuple[List[Dict[str, Any]], int]:
- def _filtered():
- q0 = db.query(BizItemUnit).filter(BizItemUnit.del_flag == 0)
- if tenant_no:
- q0 = q0.filter(BizItemUnit.tenant_no == tenant_no)
- kw = (keyword or "").strip()
- if kw:
- like = f"%{kw}%"
- q0 = q0.filter(or_(BizItemUnit.unit_code.like(like), BizItemUnit.unit_name.like(like)))
- if user_info:
- from app.core.data_scope import apply_data_scope
- q0 = apply_data_scope(q0, BizItemUnit, user_info, db, tenant_no)
- return q0
- total = _filtered().order_by(None).with_entities(func.count(BizItemUnit.id)).scalar() or 0
- page = max(1, page)
- page_size = min(max(1, page_size), 100)
- rows = (
- _filtered()
- .order_by(BizItemUnit.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_item_unit(db: Session, unit_id: str) -> Optional[BizItemUnit]:
- return (
- db.query(BizItemUnit)
- .filter(and_(BizItemUnit.id == unit_id, BizItemUnit.del_flag == 0))
- .first()
- )
- def unit_code_exists(db: Session, code: str, tenant_no: str, exclude_id: Optional[str] = None) -> bool:
- q = db.query(BizItemUnit).filter(and_(BizItemUnit.unit_code == code.strip(), BizItemUnit.tenant_no == tenant_no, BizItemUnit.del_flag == 0))
- if exclude_id:
- q = q.filter(BizItemUnit.id != exclude_id)
- return q.first() is not None
- def create_item_unit(
- db: Session,
- *,
- unit_code: str,
- unit_name: str,
- tenant_no: str = "zkxw",
- order_num: Optional[int] = None,
- remark: Optional[str] = None,
- user_id: Optional[str] = None,
- ) -> BizItemUnit:
- uc = (unit_code or "").strip()
- if not uc:
- raise ValueError("单位编码不能为空")
- if unit_code_exists(db, uc, tenant_no):
- raise ValueError("单位编码已存在")
- obj = BizItemUnit(
- id=generate_uuid(),
- unit_code=uc,
- unit_name=(unit_name or "").strip() or uc,
- 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_item_unit(
- db: Session,
- unit_id: str,
- *,
- unit_code: Optional[str] = None,
- unit_name: Optional[str] = None,
- order_num: Optional[int] = None,
- remark: Optional[str] = None,
- user_id: Optional[str] = None,
- ) -> BizItemUnit:
- obj = get_item_unit(db, unit_id)
- if not obj:
- raise ValueError("物品单位不存在")
- if unit_code is not None:
- new_code = unit_code.strip()
- if not new_code:
- raise ValueError("单位编码不能为空")
- if new_code != obj.unit_code and unit_code_exists(db, new_code, obj.tenant_no, exclude_id=unit_id):
- raise ValueError("单位编码已存在")
- obj.unit_code = new_code
- if unit_name is not None:
- obj.unit_name = (unit_name or "").strip() or obj.unit_name
- 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_item_unit(db: Session, unit_id: str) -> None:
- obj = get_item_unit(db, unit_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)))
|