123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332 |
- #!/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('/list')
- async def get_inspection_task_list(
- type: 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(RiskManagementRiskTask)
- query = query.filter(RiskManagementRiskTask.del_flag != '2')
- # 应用查询条件
- if type:
- query = query.filter(RiskManagementRiskTask.risk_type == type)
- if cycle:
- query = query.filter(RiskManagementRiskTask.task_cycle == cycle)
- # 计算总条目数
- total_items = query.count()
- # 排序
- query = query.order_by(RiskManagementRiskTask.create_time.desc())
- # 执行分页查询
- RiskTasks = query.offset((page - 1) * pageSize).limit(pageSize).all()
- # 将查询结果转换为列表形式的字典
- RiskTasks_list = []
- for task in RiskTasks:
- 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' #'未完成'
- create_by = task.create_by
- create_by = db.query(SysUser).filter(SysUser.user_id==create_by).first()
- task_info = {
- "id": task.id,
- "task_number": task.task_number,
- "type": task.risk_type,
- "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
- "cycle": task.task_cycle,
- "task_range": task.task_range,
- "task_status": task_status,
- "create_by":create_by.nick_name,
- "create_time": task.create_time#.strftime('%Y-%m-%d')
- }
- RiskTasks_list.append(task_info)
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": RiskTasks_list,
- "total": total_items,
- "page": page,
- "pageSize": pageSize,
- "totalPages": (total_items + pageSize - 1) // pageSize
- }
- except Exception as e:
- # 处理异常
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=str(e))
- @router.get('/{id}')
- async def get_inspection_task(
- id: str ,
- db: Session = Depends(get_db),
- user_id = Depends(valid_access_token)
- ):
- try:
- # 构建查询
- query = db.query(RiskManagementRiskTask)
- query = query.filter(RiskManagementRiskTask.del_flag != '2')
- # 应用查询条件
- if id:
- query = query.filter(RiskManagementRiskTask.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' # '未完成'
- create_by = task.create_by
- create_by = db.query(SysUser).filter(SysUser.user_id == create_by).first()
- risk_task_result = {
- "id": task.id,
- "task_number": task.task_number,
- "type": task.risk_type,
- "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
- "cycle": task.task_cycle,
- "task_range": task.task_range,
- "task_status": task_status,
- "create_by":create_by.nick_name,
- "create_time": task.create_time.strftime('%Y-%m-%d')
- }
- # 返回结果
- return {
- "code": 200,
- "msg": "成功",
- "data": risk_task_result
- }
- except Exception as e:
- # 处理异常
- traceback.print_exc()
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.post('/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 = RiskManagementRiskTask(
- risk_type=body['type'],
- start_time = body['start_time'],
- end_time = body['end_time'],
- task_cycle = cycle,
- corn_expression = corn,
- task_range = body['task_range'],
- task_status = '-1',
- create_by = user_id
- )
- # 添加到数据库会话并提交
- db.add(new_task)
- db.commit()
- db.refresh(new_task) # 可选,如果需要刷新实例状态
- new_task.task_number = f'YJFX{str(new_task.id).zfill(10)}'
- db.commit()
- # 返回创建成功的响应
- return {
- "code": 200,
- "msg": "成功",
- "data": None
- }
- except Exception as e:
- # 处理异常
- traceback.print_exc()
- raise HTTPException(status_code=500, detail=str(e))
- @router.put('/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(RiskManagementRiskTask)
- query = query.filter(RiskManagementRiskTask.id == body['id'])
- query = query.filter(RiskManagementRiskTask.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 'type' in body:
- task.risk_type = body['type']
- if 'start_time' in body:
- task.start_time = body['start_time']
- if 'end_time' in body:
- task.end_time = body['end_time']
- if 'task_range' in body:
- task.task_range = body['task_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:
- # 处理异常
- traceback.print_exc()
- if str(e)=='':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
- @router.delete('/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(RiskManagementRiskTask)
- query = query.filter(RiskManagementRiskTask.del_flag != '2')
- query = query.filter(RiskManagementRiskTask.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('/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(RiskManagementRiskTask)
- query = query.filter(RiskManagementRiskTask.del_flag != '2')
- query = query.filter(RiskManagementRiskTask.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:
- # 处理异常
- traceback.print_exc()
- if str(e) == '':
- e = detail
- raise HTTPException(status_code=500, detail=str(e))
|