Files
d3i-szct/models/govc_task_supervision.py
T
2026-06-02 17:46:38 +08:00

504 lines
19 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.
import datetime
import random
from typing import Union
import pandas as pd
from sqlalchemy import select, delete
from tornado_swagger.model import register_swagger_model
from wtforms import StringField, DateTimeField, IntegerField
from wtforms.validators import Length, Optional
import models
from models.common_model import CommonModel
from models.db_models import TD3iGovcTaskSupervision
from paste.core.logging import echo_log
from paste.rbac.rbac_user import RbacUser
from paste.util.pagination import Pagination
from paste.web.form import ModelForm
class GovcTaskSupervisionForm(ModelForm):
"""
工单监察信息表单验证类(完全映射 TD3iGovcTaskSupervision 字段)。
用于验证和处理市12345工单监察信息的创建/修改表单数据。
字段完全映射数据库表 t_d3i_govc_task_supervision 的字段结构。
"""
# 基础信息
id = IntegerField('记录ID')
task_id = IntegerField('关联工单主表ID', validators=[Optional()]) # 非空在数据库层约束
supervision_name = StringField('监察点名称', validators=[Length(max=255, message='监察点名称长度不能超过255字符')])
supervision_type = StringField('监察点类型', validators=[Length(max=255, message='监察点类型长度不能超过255字符')])
supervision_date = DateTimeField('监察点时间', validators=[Optional()])
supervision_ou_name = StringField('部门', validators=[Length(max=255, message='部门长度不能超过255字符')])
hj_date = DateTimeField('核减时间', validators=[Optional()])
supervise_type = StringField('监察类别', validators=[Length(max=32, message='监察类别长度不能超过32字符')])
def process(self, formdata=None, obj=None, **kwargs):
"""
处理表单数据,在数据绑定前进行预处理。
主要功能:
- 遍历所有表单字段
- 对字符串类型的值去除两端空白字符
- 调用父类的process方法继续处理
"""
if formdata:
for name, values in formdata.items():
if isinstance(values, list) and values:
formdata[name] = [v.strip() if isinstance(v, str) else v for v in values]
elif isinstance(values, str):
formdata[name] = values.strip()
super().process(formdata, obj, **kwargs)
class GovcTaskSupervisionBase(TD3iGovcTaskSupervision, CommonModel):
"""
工单监察信息基础类(完全映射 TD3iGovcTaskSupervision 字段)。
继承自数据库模型 TD3iGovcTaskSupervision 和通用模型 CommonModel。
封装所有与工单监察相关的通用操作方法。
"""
FieldMapping = {
'id': 'id',
'task_id': 'task_id',
'supervision_name': 'supervision_name',
'supervision_type': 'supervision_type',
'supervision_date': 'supervision_date',
'supervision_ou_name': 'supervision_ou_name',
'hj_date': 'hj_date',
'supervise_type': 'supervise_type',
'created_at': 'created_at',
'created_by': 'created_by',
'updated_at': 'updated_at',
'updated_by': 'updated_by',
}
"""
工单监察数据映射
"""
@classmethod
async def is_exist(cls, task_id: int, supervise_type: str = None):
"""
检查监察记录是否已存在(根据工单ID+监察类别组合,可扩展)。
:param task_id: 关联工单主表ID
:param supervise_type: 监察类别(可选)
:return: 存在返回对象,不存在返回None
"""
_query = select(cls).where(cls.task_id == task_id)
if supervise_type:
_query = _query.where(cls.supervise_type == supervise_type)
_supervision: cls = await cls.query_first(_query)
return _supervision
@classmethod
async def search_base(cls, is_paging=True, **kwargs):
"""
按参数搜索工单监察数据的基础方法。
支持字段:
- task_id, supervision_name, supervision_type, supervise_type
- 支持模糊匹配:supervision_ou_name
- 支持精确匹配:id, supervise_type
:param is_paging: 是否分页
:param kwargs: 查询参数
:key int page_number: 页码(缺省随机1~100
:key int page_size: 每页数量(缺省20
:key dict sort_clause: 排序配置,如 {'supervision_date': 'desc'}
:key int id: 精确匹配记录ID
:key int task_id: 精确匹配工单ID
:key str supervision_name: 精确匹配监察点名称
:key str supervision_type: 精确匹配监察点类型
:key str supervision_ou_name: 模糊匹配部门
:key str supervise_type: 精确匹配监察类别
:key datetime supervision_date: 精确匹配监察点时间
:key datetime hj_date: 精确匹配核减时间
:return: (DataFrame, Pagination)
"""
page_number = kwargs.get('page_number', random.randint(1, 100))
page_size = kwargs.get('page_size', 20)
kwargs.update({'page_number': page_number, 'page_size': page_size})
# 模糊查询字段
_name_likes = {
cls.supervision_ou_name.key: '%{}%',
cls.supervision_name.key: '%{}%', # 补充名称模糊匹配
}
_query = select(cls).where(
*cls.search_wheres(likes=_name_likes, **kwargs)
).group_by(cls.id)
_paging = None
if is_paging:
_row_count = await cls.query_count(_query)
_paging = Pagination(_row_count).paging(page_number, page_size)
_data_query = _query.limit(page_size).offset(_paging.offset_size)
else:
_data_query = _query
_sort_clause = cls.sort_clauses(kwargs.get('sort_clause', {}))
if _sort_clause:
_data_query = _data_query.order_by(*_sort_clause)
else:
_data_query = _data_query.order_by(cls.task_id, cls.supervision_date.desc())
_supervision_df = await cls.query_as_df(_data_query)
if not _supervision_df.empty:
_supervision_df.replace(models.EmptyInDF + models.EmptyDatetimeInDF, '', inplace=True)
_supervision_df[cls.id.key] = _supervision_df[cls.id.key].astype(str)
# 日期字段格式化
for dt_field in ['supervision_date', 'hj_date', 'created_at', 'updated_at']:
if dt_field in _supervision_df.columns:
_supervision_df[dt_field] = _supervision_df[dt_field].dt.strftime('%Y-%m-%d %H:%M:%S')
return _supervision_df, _paging
@classmethod
async def search(cls, **kwargs):
"""
按参数搜索工单监察数据,返回分页格式数据。
"""
_supervision_df, _paging = await cls.search_base(** kwargs)
return {
'total': _paging.row_count,
'rows': _supervision_df.to_dict('records'),
'pagination': {
'page_number': _paging.page_number,
'page_count': _paging.page_count,
'page_size': _paging.page_size,
},
}
@classmethod
async def exists_task_id(cls, data_df: pd.DataFrame):
"""
查找 data_df 中在数据库中已存在和不存在的记录。根据 task_id+supervise_type 组合判断。
:param data_df: 输入的数据框架,必须包含 task_id 列(可选supervise_type
:return: (exists_df: pd.DataFrame, latest_df: pd.DataFrame)
- exists_df: 在数据库中存在的记录
- latest_df: 在数据库中不存在的记录
"""
if data_df.empty:
return pd.DataFrame(), pd.DataFrame()
# 获取待查询的 task_id 列表(去重)
task_ids = data_df[cls.task_id.key].unique().tolist()
if not task_ids:
return pd.DataFrame(), data_df.copy()
# 查询数据库中已存在的 task_id+supervise_type 组合
_query = select(cls.id, cls.task_id, cls.supervise_type).where(cls.task_id.in_(task_ids))
task_ids_df = await cls.query_as_df(_query)
if task_ids_df.empty:
return pd.DataFrame(), data_df.copy()
# 构建复合键映射 (task_id, supervise_type) -> id
task_supervise_map = {}
for _, row in task_ids_df.iterrows():
key = (row[cls.task_id.key], row[cls.supervise_type.key])
task_supervise_map[key] = row[cls.id.key]
# 根据复合键划分数据
def is_exist(row):
key = (row[cls.task_id.key], row.get(cls.supervise_type.key, ''))
return key in task_supervise_map
mask_exists = data_df.apply(is_exist, axis=1)
exists_df = data_df[mask_exists].copy()
# 自动补充从数据库查到的 id 字段
exists_df[cls.id.key] = exists_df.apply(
lambda row: task_supervise_map.get((row[cls.task_id.key], row.get(cls.supervise_type.key, '')), ''),
axis=1
)
latest_df = data_df[~mask_exists].copy()
return exists_df, latest_df
@register_swagger_model
class GovcTaskSupervision(GovcTaskSupervisionBase):
"""
工单监察信息模型类(主业务类,完全继承 TD3iGovcTaskSupervision 字段)。
---
description: 市12345工单监察信息接口
type: object
properties:
id:
description: 主键ID
type: integer
example: 1001
readOnly: true
task_id:
description: 关联工单主表ID
type: integer
example: 5001
supervision_name:
description: 监察点名称
type: string
example: "超时未办结监察"
maxLength: 255
supervision_type:
description: 监察点类型
type: string
example: "时限监察"
maxLength: 255
supervision_date:
description: 监察点时间
type: string
format: date-time
example: "2024-05-01 10:00:00"
supervision_ou_name:
description: 部门
type: string
example: "市政务服务中心"
maxLength: 255
hj_date:
description: 核减时间
type: string
format: date-time
example: "2024-05-02 15:30:00"
supervise_type:
description: 监察类别(zx/bm/bmhj
type: string
example: "zx"
maxLength: 32
created_at:
description: 创建时间,ISO格式的日期时间字符串
type: string
format: date-time
example: "2024-01-15 10:30:00"
readOnly: true
created_by:
description: 创建者用户名
type: string
example: "admin"
readOnly: true
updated_at:
description: 修改时间,ISO格式的日期时间字符串
type: string
format: date-time
example: "2024-01-16 14:25:00"
readOnly: true
updated_by:
description: 修改者用户名
type: string
example: "editor"
readOnly: true
"""
@classmethod
async def create(cls, user: RbacUser = None, **kwargs):
"""
创建新的工单监察记录。
业务流程:
1. 使用 GovcTaskSupervisionForm 验证表单数据完整性
2. 检查是否已存在相同 task_id+supervise_type 的记录(避免重复提交)
3. 创建新监察对象
4. 设置创建者和更新者为当前用户
5. 保存到数据库
6. 返回创建的对象
:param RbacUser user: 操作用户对象
:param kwargs: 监察参数字典
:return: 新建监察对象
:rtype: GovcTaskSupervision
:raises AssertionError: 当记录已存在时抛出
:raises ValidationError: 当表单验证失败时抛出
"""
# 处理字符串字段去除空格
for _k, _v in kwargs.items():
if isinstance(_v, str):
kwargs[_k] = _v.strip()
_form = GovcTaskSupervisionForm(formdata=kwargs)
_form.validate_form()
# 检查是否已存在相同 task_id+supervise_type 的记录
_existing = await cls.is_exist(_form.task_id.data, _form.supervise_type.data)
assert _existing is None, f"工单ID {_form.task_id.data} 已存在[{_form.supervise_type.data}]类型的监察记录,不能重复提交。"
# 创建对象
_supervision = cls().copy_from_dict(_form.data, skip_none=True).before_save()
if user:
_supervision.created_by = user.username
_supervision.updated_by = user.username
await _supervision.async_save()
return _supervision
@classmethod
async def delete(cls, supervision_id: Union[str, int]):
"""
删除工单监察记录。
业务流程:
1. 根据ID查找记录
2. 验证存在性
3. 执行删除
:param supervision_id: 要删除的监察记录ID
:return: 删除的记录对象
:rtype: GovcTaskSupervision
:raises AssertionError: 当记录不存在时抛出
"""
_supervision: cls = await cls.async_find_by_id(supervision_id)
assert _supervision, f"根据 ID {supervision_id} 未找到工单监察记录。"
_del_query = delete(cls).where(cls.id == _supervision.id)
_del_count = (await cls.raw_execute(_del_query)).rowcount
echo_log(f'已删除工单监察记录(工单ID{_supervision.task_id}ID{_supervision.id}.')
return _supervision
@classmethod
async def modify(cls, supervision_id: Union[str, int], user: RbacUser = None, **kwargs):
"""
修改已有工单监察记录。
业务流程:
1. 将 supervision_id 添加到参数中
2. 处理字符串字段去除首尾空格
3. 使用 GovcTaskSupervisionForm 验证表单数据
4. 查询原记录
5. 验证存在性
6. 更新字段并设置更新者
7. 保存到数据库
8. 返回更新后的对象
:param supervision_id: 要修改的监察记录ID
:param RbacUser user: 操作用户对象
:param kwargs: 需要更新的字段
:return: 修改后的监察对象
:rtype: GovcTaskSupervision
:raises AssertionError: 当记录不存在时抛出
:raises ValidationError: 当表单验证失败时抛出
"""
# 处理字符串字段去除空格
for _k, _v in kwargs.items():
if isinstance(_v, str):
kwargs[_k] = _v.strip()
# 表单验证
_form = GovcTaskSupervisionForm(formdata=kwargs)
_form.validate_form()
# 查询原记录
_supervision: cls = await cls.async_find_by_id(supervision_id)
assert _supervision, f'查无此工单监察信息。'
# 更新字段
_supervision.copy_from_dict(_form.data, skip_none=True).before_save()
_supervision.updated_by = user.username if user else _supervision.updated_by
await _supervision.async_save()
return _supervision
@classmethod
async def create_batch(cls, data_df: pd.DataFrame, user: RbacUser = None):
"""
批量创建工单监察记录(传入数据应为全新记录)。
:param data_df: 包含监察数据的 DataFrame
:param user: 操作用户对象,用于设置 created_by / updated_by
:return: 成功创建的数量
:rtype: int
"""
if data_df.empty:
return 0
# 补充创建者/更新者信息
if user:
data_df['created_by'] = user.username
data_df['updated_by'] = user.username
else:
data_df['created_by'] = 'D3I'
data_df['updated_by'] = 'D3I'
# 处理日期字段格式
for dt_field in ['supervision_date', 'hj_date']:
if dt_field in data_df.columns:
data_df[dt_field] = pd.to_datetime(data_df[dt_field], errors='coerce')
records = data_df.to_dict('records')
supervisions = [cls().copy_from_dict(record, skip_none=True).before_save() for record in records]
session = cls.get_aio_session()
try:
session.add_all(supervisions)
await session.commit()
except Exception as e:
await session.rollback()
raise e
finally:
await session.close()
echo_log(f"批量创建成功:创建 {len(supervisions)} 条工单监察记录。")
return len(supervisions)
@classmethod
async def modify_batch(cls, data_df: pd.DataFrame, user: RbacUser = None):
"""
批量修改已有工单监察记录。
:param data_df: 包含监察数据的 DataFrame(必须包含 id 列)
:param user: 操作用户对象,用于设置 updated_by
:return: 成功更新的数量
:rtype: int
"""
if data_df.empty:
return 0
# 必须包含 id 列
if 'id' not in data_df.columns:
echo_log(f"错误:modify_batch 要求输入数据必须包含 '{cls.id.key}' 列(主键)")
return 0
# 手动添加更新时间戳和更新者
data_df['updated_at'] = datetime.datetime.now()
if user:
data_df['updated_by'] = user.username
# 处理日期字段格式
for dt_field in ['supervision_date', 'hj_date']:
if dt_field in data_df.columns:
data_df[dt_field] = pd.to_datetime(data_df[dt_field], errors='coerce')
# 转换为字典列表
update_data = data_df.to_dict('records')
# 使用 bulk_update_mappings 批量更新
session = cls.get_aio_session()
try:
await session.run_sync(
lambda sync_session: sync_session.bulk_update_mappings(cls, update_data)
)
await session.commit()
updated_count = len(update_data)
except Exception as e:
await session.rollback()
raise e
finally:
await session.close()
echo_log(f"批量修改成功:更新 {updated_count} 条工单监察记录。")
return updated_count
@classmethod
async def save_batch(cls, data_df: pd.DataFrame, user: RbacUser = None):
"""
批量保存工单监察数据,自动处理新建和更新。
:param data_df: 要保存的数据框架
:param user: 用户
:return: 新建和更新的数量
"""
# 筛选数据状态(按task_id+supervise_type判断存在性)
_exists_df, _latest_df = await cls.exists_task_id(data_df)
# 保存到数据库
_created_count = await cls.create_batch(_latest_df, user)
_updated_count = await cls.modify_batch(_exists_df, user)
return _created_count, _updated_count