123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- from fastapi import APIRouter, Request, Depends,Query, HTTPException, status
- from common.security import valid_access_token
- from fastapi.responses import JSONResponse
- from sqlalchemy.orm import Session
- from sqlalchemy import and_, or_
- from pydantic import BaseModel
- from datetime import datetime
- from database import get_db
- from typing import List
- from models import *
- from utils import *
- import json
- import traceback
- router = APIRouter()
- ####巡查人员####
- @router.get('/inspection/user/list')
- async def get_inspection_user_list(
- nickName: str = Query(None, description='姓名'),
- deptId :str = Query(None, description='部门id'),
- page: int = Query(1, gt=0, description='页码'),
- pageSize: int = Query(5, gt=0, description='每页条目数量'),
- db: Session = Depends(get_db),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 构建查询
- query = db.query(RiskManagementInspectionUser)
- query = query.filter(RiskManagementInspectionUser.del_flag != '2')
- # 应用查询条件
- if nickName:
- query = query.filter(RiskManagementInspectionUser.nick_name.like(f'%{nickName}%'))
- if deptId:
- query = query.filter(RiskManagementInspectionUser.dept_id == deptId)
- # 计算总条目数
- total_items = query.count()
- # 排序
- query = query.order_by(RiskManagementInspectionUser.create_time.desc())
- # 执行分页查询
- InspectionUsers = query.offset((page - 1) * pageSize).limit(pageSize).all()
- # 将查询结果转换为列表形式的字典
- InspectionUsers_list = [
- {
- "id": user.id,
- "user_id": user.user_id,
- "dept_id": user.dept_id,
- "dept_name": user.dept_name,
- "ancestors_names": user.ancestors_names,
- "user_name": user.user_name,
- "create_time": user.create_time.strftime('%Y-%m-%d'),
- "phonenumber": user.phonenumber,
- "nick_name": user.nick_name,
- "area_code": user.area_code,
- "area": user.area,
- "yzy_account":user.yzy_account
- }
- for user in InspectionUsers
- ]
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": InspectionUsers_list,
- "total": total_items,
- "page": page,
- "pageSize": pageSize,
- "totalPages": (total_items + pageSize - 1) // pageSize
- }
- except Exception as e:
- # 处理异常
- raise HTTPException(status_code=500, detail=str(e))
- @router.get('/inspection/user/{id}')
- async def get_inspection_user(
- id: str ,
- db: Session = Depends(get_db),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 构建查询
- query = db.query(RiskManagementInspectionUser)
- query = query.filter(RiskManagementInspectionUser.del_flag != '2')
- # 应用查询条件
- if id:
- query = query.filter(RiskManagementInspectionUser.id == id)
- # 执行查询
- user = query.first()
- if not user:
- detail = "用户不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- # 将查询结果转换为列表形式的字典
- inspection_user_result = {
- "id": user.id,
- "user_id": user.user_id,
- "dept_id": user.dept_id,
- "dept_name": user.dept_name,
- "ancestors_names": user.ancestors_names,
- "user_name": user.user_name,
- "create_time": user.create_time.strftime('%Y-%m-%d'),
- "phonenumber": user.phonenumber,
- "nick_name": user.nick_name,
- "area_code": user.area_code,
- "area": user.area,
- "yzy_account":user.yzy_account
- }
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": inspection_user_result
- }
- except Exception as e:
- # 处理异常
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.post('/inspection/user/create')
- async def create_inspection_user(
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 创建新的预案记录
- new_user = RiskManagementInspectionUser(
- user_id=body['user_id'],
- dept_id = body['dept_id'],
- dept_name = body['dept_name'],
- ancestors_names = body['ancestors_names'],
- user_name = body['user_name'],
- nick_name = body['nick_name'],
- phonenumber = body['phonenumber'],
- area_code = body['area_code'],
- area = body['area'],
- yzy_account = body['yzy_account'],
- create_by = user_id
- )
- # 添加到数据库会话并提交
- db.add(new_user)
- db.commit()
- db.refresh(new_user) # 可选,如果需要刷新实例状态
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- raise HTTPException(status_code=500, detail=str(e))
- @router.put('/inspection/user/update')
- async def update_inspection_user(
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionUser)
- query = query.filter(RiskManagementInspectionUser.id == body['id'])
- query = query.filter(RiskManagementInspectionUser.del_flag != '2')
- user = query.first()
- if not user:
- detail = "用户不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- if 'user_id' in body:
- user.user_id = body['user_id']
- if 'dept_id' in body:
- user.dept_id = body['dept_id']
- if 'dept_name' in body:
- user.dept_name = body['dept_name']
- if 'ancestors_names' in body:
- user.ancestors_names = body['ancestors_names']
- if 'user_name' in body:
- user.user_name = body['user_name']
- if 'nick_name' in body:
- user.nick_name = body['nick_name']
- if 'phonenumber' in body:
- user.phonenumber = body['phonenumber']
- if 'area_code' in body:
- user.area_code = body['area_code']
- if 'area' in body:
- user.area = body['area']
- if user_id:
- user.update_by = user_id
- # 更新到数据库会话并提交
- db.commit()
- db.refresh(user) # 可选,如果需要刷新实例状态
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.delete('/inspection/user/delete')
- async def delete_inspection_users(
- userIds: list,
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionUser)
- query = query.filter(RiskManagementInspectionUser.del_flag != '2')
- query = query.filter(RiskManagementInspectionUser.id.in_(userIds))
- users = query.all()
- if not users:
- detail = "用户不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- for user in users:
- user.del_flag = '2'
- user.update_by=user_id
- # 更新到数据库会话并提交
- db.commit()
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "删除成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e) == '':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.delete('/inspection/user/delete/{userId}')
- async def delete_inspection_user(
- userId: str,
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionUser)
- query = query.filter(RiskManagementInspectionUser.del_flag != '2')
- query = query.filter(RiskManagementInspectionUser.id==userId)
- user = query.first()
- if not user:
- detail = "用户不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- user.del_flag = '2'
- user.update_by = user_id
- # 更新到数据库会话并提交
- db.commit()
- db.refresh(user) # 可选,如果需要刷新实例状态
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "删除成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e) == '':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.get("/allAreas")
- def read_all_areas(db: Session = Depends(get_db)):
- def parent_id_get_area_info(parent_id):
- query = db.query(GovdataArea)
- query = query.filter(GovdataArea.parent_id == parent_id)
- return query.all()
- def build_area_tree(areas, parent_area):
- # 收集祖先部门名称
- area_tree = []
- for area_info in areas:
- # current_area = db.query(GovdataArea).filter(GovdataArea.id == area_info.id).first()
- # ancestors_names = []
- # while current_area:
- # ancestors_names.append(current_area.area_name)
- # current_area = db.query(GovdataArea).filter(GovdataArea.id == current_area.parent_id).first()
- # ancestors_names.reverse()
- area = {
- "id": area_info.id,
- "code": area_info.area_code,
- "label": area_info.area_name,
- "parentId": area_info.parent_id,
- # "ancestors": '/'.join(ancestors_names)
- }
- # print(dept_info.dept_id)
- children = parent_id_get_area_info(area_info.id)
- if len(children) > 0:
- children_areas = build_area_tree(children, area)
- area["children"] = children_areas
- area_tree.append(area)
- return area_tree
- # data = build_area_tree(parent_id_get_area_info(0),None)
- filename = '/home/python3/xh_twapi01/routers/api/riskManagement/area_tree.json'
- # 打开文件并读取内容
- with open(filename, 'r', encoding='utf-8') as file:
- # 加载JSON内容到一个字典
- data = json.load(file)
- return {
- "code": 200,
- "msg": "成功",
- "data": data
- }
- ####巡查任务####
- @router.get('/inspection/task/list')
- async def get_inspection_task_list(
- business: str = Query(None, description='巡查业务'),
- cycle :str = Query(None, description='巡查周期'),
- page: int = Query(1, gt=0, description='页码'),
- pageSize: int = Query(10, gt=0, description='每页条目数量'),
- db: Session = Depends(get_db),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 构建查询
- query = db.query(RiskManagementInspectionTask)
- query = query.filter(RiskManagementInspectionTask.del_flag != '2')
- # 应用查询条件
- if business:
- query = query.filter(RiskManagementInspectionTask.inspection_business == business)
- if cycle:
- query = query.filter(RiskManagementInspectionTask.inspection_cycle == cycle)
- # 计算总条目数
- total_items = query.count()
- # 排序
- query = query.order_by(RiskManagementInspectionTask.create_time.desc())
- # 执行分页查询
- InspectionTasks = query.offset((page - 1) * pageSize).limit(pageSize).all()
- # 将查询结果转换为列表形式的字典
- InspectionTasks_list = []
- for task in InspectionTasks:
- if task.task_status=='3':
- task_status = '3' #'已完结'
- else:
- if datetime.now()<task.start_time:
- task_status = '0' #'未开始'
- elif task.start_time<=datetime.now()<=task.end_time:
- task_status = '1' #'进行中'
- else:
- task_status = '2' #'未完成'
- task_info = {
- "id": task.id,
- "task_number": task.task_number,
- "business": task.inspection_business,
- "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
- "cycle": task.inspection_cycle,
- "inspection_range": task.inspection_range,
- "task_status": task_status,
- "create_time": task.create_time.strftime('%Y-%m-%d')
- }
- InspectionTasks_list.append(task_info)
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": InspectionTasks_list,
- "total": total_items,
- "page": page,
- "pageSize": pageSize,
- "totalPages": (total_items + pageSize - 1) // pageSize
- }
- except Exception as e:
- # 处理异常
- raise HTTPException(status_code=500, detail=str(e))
- @router.get('/inspection/task/{id}')
- async def get_inspection_task(
- id: str ,
- db: Session = Depends(get_db),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 构建查询
- query = db.query(RiskManagementInspectionTask)
- query = query.filter(RiskManagementInspectionTask.del_flag != '2')
- # 应用查询条件
- if id:
- query = query.filter(RiskManagementInspectionTask.id == id)
- # 执行查询
- task = query.first()
- if not task:
- detail = "巡查任务不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- # 将查询结果转换为列表形式的字典
- if task.task_status == '3':
- task_status = '3' # '已完结'
- else:
- if datetime.now() < task.start_time:
- task_status = '0' # '未开始'
- elif task.start_time <= datetime.now() <= task.end_time:
- task_status = '1' # '进行中'
- else:
- task_status = '2' # '未完成'
- inspection_task_result = {
- "id": task.id,
- "task_number": task.task_number,
- "business": task.inspection_business,
- "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
- "cycle": task.inspection_cycle,
- "inspection_range": task.inspection_range,
- "task_status": task_status,
- "create_time": task.create_time.strftime('%Y-%m-%d')
- }
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": inspection_task_result
- }
- except Exception as e:
- # 处理异常
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.post('/inspection/task/create')
- async def create_inspection_task(
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- cycle = body['cycle']
- # 0每年、1每月、2每周、3每日、4一次
- corn_query = body['corn_query']
- if cycle=='0':
- corn=f'0 0 {corn_query} *'
- elif cycle=='1':
- corn=f'0 0 {corn_query} * *'
- elif cycle == '2':
- corn = f'0 0 * * {corn_query}'
- elif cycle == '3':
- corn = f'0 0 * * *'
- else:
- corn=''
- # 创建新的预案记录
- new_task = RiskManagementInspectionTask(
- inspection_business=body['business'],
- start_time = body['start_time'],
- end_time = body['end_time'],
- inspection_cycle = cycle,
- corn_expression = corn,
- inspection_range = body['inspection_range'],
- task_status = '-1',
- create_by = user_id
- )
- # 添加到数据库会话并提交
- db.add(new_task)
- db.commit()
- db.refresh(new_task) # 可选,如果需要刷新实例状态
- new_task.task_number = f'YJXC{str(new_task.id).zfill(10)}'
- db.commit()
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- raise HTTPException(status_code=500, detail=str(e))
- @router.put('/inspection/task/update')
- async def update_inspection_task(
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionTask)
- query = query.filter(RiskManagementInspectionTask.id == body['id'])
- query = query.filter(RiskManagementInspectionTask.del_flag != '2')
- task = query.first()
- if not task:
- detail = "任务不存在"
- raise HTTPException(status_code=404, detail="任务不存在")
- if 'cycle' in body:
- cycle = body['cycle']
- # 0每年、1每月、2每周、3每日、4一次
- corn_query = body['corn_query']
- if cycle == '0':
- corn = f'0 0 {corn_query} *'
- elif cycle == '1':
- corn = f'0 0 {corn_query} * *'
- elif cycle == '2':
- corn = f'0 0 * * {corn_query}'
- elif cycle == '3':
- corn = f'0 0 * * *'
- else:
- corn = ''
- task.inspection_cycle = cycle
- task.corn_expression = corn
- if 'business' in body:
- task.inspection_business = body['business']
- if 'start_time' in body:
- task.start_time = body['start_time']
- if 'end_time' in body:
- task.end_time = body['end_time']
- if 'inspection_range' in body:
- task.inspection_range = body['inspection_range']
- if 'task_status' in body:
- task.task_status = body['task_status']
- if user_id:
- task.update_by = user_id
- # 更新到数据库会话并提交
- db.commit()
- db.refresh(task) # 可选,如果需要刷新实例状态
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.delete('/inspection/task/delete')
- async def delete_inspection_tasks(
- taskIds: list,
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionTask)
- query = query.filter(RiskManagementInspectionTask.del_flag != '2')
- query = query.filter(RiskManagementInspectionTask.id.in_(taskIds))
- tasks = query.all()
- if not tasks:
- detail = "任务不存在"
- raise HTTPException(status_code=404, detail="任务不存在")
- for task in tasks:
- task.del_flag = '2'
- task.update_by=user_id
- # 更新到数据库会话并提交
- db.commit()
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "删除成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e) == '':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.delete('/inspection/task/delete/{userId}')
- async def delete_inspection_task(
- userId: str,
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 提取请求数据
- query = db.query(RiskManagementInspectionTask)
- query = query.filter(RiskManagementInspectionTask.del_flag != '2')
- query = query.filter(RiskManagementInspectionTask.id==userId)
- task = query.first()
- if not task:
- detail = "用户不存在"
- raise HTTPException(status_code=404, detail="用户不存在")
- task.del_flag = '2'
- task.update_by = user_id
- # 更新到数据库会话并提交
- db.commit()
- db.refresh(task) # 可选,如果需要刷新实例状态
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "删除成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- if str(e) == '':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
|