"""客户服务字典 CRUD。""" from __future__ import annotations from datetime import datetime from typing import List, Optional from sqlalchemy.orm import Session from app.core.utils import generate_uuid from app.models.models import BizCustomerServiceDict from app.services.sample_customer_service_register import normalize_dict_value def list_dict_values(db: Session, tenant_no: str, dict_type: str) -> List[str]: dtype = (dict_type or "").strip() if not dtype: return [] rows = ( db.query(BizCustomerServiceDict) .filter( BizCustomerServiceDict.tenant_no == tenant_no, BizCustomerServiceDict.dict_type == dtype, BizCustomerServiceDict.del_flag == 0, ) .order_by( BizCustomerServiceDict.order_num.asc(), BizCustomerServiceDict.dict_value.asc(), ) .all() ) return [row.dict_value for row in rows if row.dict_value] def ensure_dict_value( db: Session, tenant_no: str, dict_type: str, value, *, user_id: Optional[str], is_system: bool = False, ) -> Optional[str]: normalized = normalize_dict_value(value) if normalized is None: return None dtype = (dict_type or "").strip() if not dtype: return None existing = ( db.query(BizCustomerServiceDict) .filter( BizCustomerServiceDict.tenant_no == tenant_no, BizCustomerServiceDict.dict_type == dtype, BizCustomerServiceDict.dict_value == normalized, BizCustomerServiceDict.del_flag == 0, ) .first() ) if existing: return existing.dict_value now = datetime.now() row = BizCustomerServiceDict( id=generate_uuid(), dict_type=dtype, dict_value=normalized, is_system="1" if is_system else "0", tenant_no=tenant_no, create_by=user_id, create_dept_id="", create_time=now, update_by=user_id, update_time=now, del_flag=0, ) db.add(row) db.flush() return normalized