123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- # from fastapi import APIRouter, HTTPException, Depends, Body,Query
- from fastapi import APIRouter, Request, Depends, HTTPException, Query, BackgroundTasks
- from fastapi.responses import JSONResponse
- import os
- # from sqlalchemy.orm import Session
- from sqlalchemy.orm import Session, joinedload
- import xlrd
- from database import get_db, get_db_share
- from models import *
- from typing import List, Optional
- from pydantic import BaseModel,Extra, Field
- import uuid
- from common.security import valid_access_token
- from pydantic import BaseModel
- from exceptions import AppException, HmacException
- from common.security import valid_access_token
- import traceback
- from utils import *
- from common.auth_user import *
- from common.db import db_czrz
- from sqlalchemy import create_engine, Column, Integer, String, Boolean, MetaData, Table, \
- inspect, exists,or_,text,insert,asc,desc
- # 目录在文档上传接口写死
- UPLOAD_mergefile_PATH = '/data/upload/mergefile'
- router = APIRouter()
- # 救灾人员单位
- # Pydantic 模型
- class UnitSchema(BaseModel):
- id: int = None
- name: str = None
- category: str = None
- contact_number: str = None
- responsible_person: str = None
- contact_number: str = None
- team_size: int = None
- supervisor_unit: str = None
- unit_prop: str = None
- unit_level: str = None
- unit_favor: str = None
- supervisor_unit_phone: str = None
- supervisor_unit_contact: str = None
- responsible_person_phone: str = None
- area: str = None
- founding_time: str = None
- address: str = None
- longitude: str = None
- latitude: str = None
- position: str = None
- is_delete: int = 0
- class UnitListSchema(BaseModel):
- units: List[UnitSchema] = Field(default_factory=list)
- class Config:
- orm_mode = True
- #创建
- # @router.post("/")
- # def create_units(unit_list_data: UnitListSchema, db: Session = Depends(get_db)):
- # units = unit_list_data.units
- # if not units: # 确保列表不为空
- # raise HTTPException(status_code=400, detail="单位列表不能为空")
- # try:
- # new_units = [] # 创建一个空列表来存储新对象
- # for unit_data in units:
- #
- # unit_data = unit_data.dict(exclude_none=True)
- # unit_data["add_time"] = datetime.now()
- # print(unit_data)
- # new_unit = RescueUnit(**unit_data)
- # db.add(new_unit)
- # db.commit()
- # db.refresh(new_unit)
- # new_units.append(new_unit)
- #
- # unit_ids = [unit.id for unit in new_units] # 获取所有新对象的ID
- # return {"code": 200, "msg": "创建成功", "unit_ids": unit_ids}
- # except Exception as e:
- # traceback.print_exc()
- # db.rollback()
- # raise HTTPException(status_code=400, detail=str(e))
- #删除
- # @router.delete("/{unit_id}")
- # def delete_unit(unit_id: int, db: Session = Depends(get_db), user_id=Depends(valid_access_token)):
- # unit = db.query(RescueUnit).get(unit_id)
- # if not unit:
- # raise HTTPException(status_code=404, detail="单位不存在")
- # try:
- # # 更新 is_delete 字段为 1,而不是删除记录
- # unit.is_delete = 1
- # db.commit()
- # return {"code": 200, "msg": "删除成功"}
- # except Exception as e:
- # traceback.print_exc()
- # db.rollback()
- # raise HTTPException(status_code=400, detail=str(e))
- @router.delete('/{unit_id}')
- async def delete(
- request: Request,
- unit_id: int,
- db: Session = Depends(get_db_share),
- body=Depends(remove_xss_json),
- user_id=Depends(valid_access_token)
- ):
- try:
- query = db.query(RescueTeams)
- query = query.filter(RescueTeams.id == unit_id)
- query = query.filter(RescueTeams.del_flag != '2')
- unit_to_delete = query.first()
- if not unit_to_delete:
- return JSONResponse(status_code=404, content={"code": 404, "msg": "该id不存在"})
- unit_to_delete.update_by = user_id
- unit_to_delete.update_time = datetime.now()
- unit_to_delete.del_flag = '2'
- db.commit()
- return {
- "code": 200,
- "msg": "菜单删除成功"
- }
- except Exception as e:
- traceback.print_exc()
- db.rollback()
- return JSONResponse(status_code=404, content={"code": 404, "msg": str(e)})
- # class UnitListQueryParams(BaseModel):
- # page: int = Field(default=1, gt=0)
- # page_size: int = Field(default=10, gt=0)
- #查询列表
- @router.get("/list")
- def get_units(page: int = Query(default=1, gt=0),
- pageSize: int = Query(default=10, gt=0),
- db: Session = Depends(get_db_share),
- user_id=Depends(valid_access_token)):
- # 应用过滤条件,仅查询未被删除的单位
- data_query = db.query(RescueTeams).filter(RescueTeams.del_flag == '0')
- data_query = data_query.order_by(RescueTeams.create_time.desc())
- # 计算总数
- total_count = data_query.count()
- # 分页查询
- offset = (page - 1) * pageSize
- units = data_query.offset(offset).limit(pageSize).all()
- # 构造结果
- result_items = [{'id' :unit.id,
- 'name' :unit.name,
- 'team_type' :unit.team_type,
- 'professional_category' :unit.professional_category,
- 'team_category' :unit.team_category,
- 'team_attribute' :unit.team_attribute,
- 'team_level' :unit.team_level,
- 'affiliated_unit' :unit.affiliated_unit,
- 'leader_name' :unit.leader_name,
- 'leader_phone' :unit.leader_phone,
- 'city' :unit.city,
- 'district' :unit.district,
- 'main_equipment' :unit.main_equipment,
- 'number_of_people' :unit.number_of_people,
- 'address' :unit.address,
- 'description' :unit.description,
- 'longitude' :unit.longitude,
- 'latitude' :unit.latitude,
- 's_last_updatetime' :unit.s_last_updatetime} for unit in units]
- result = {
- "code": 200,
- 'msg': '查询成功',
- 'total': total_count,
- 'totalPages': (total_count + pageSize - 1) // pageSize,
- 'page': page,
- 'pageSize': pageSize,
- 'data': result_items
- }
- return result
- #查询详情
- @router.get("/detail/{unit_id}")
- def get_unit_by_id(unit_id: int, db: Session = Depends(get_db_share), user_id=Depends(valid_access_token)):
- # unit = db.query(Unit).filter(Unit.is_delete == 0).get(unit_id)
- unit = db.query(RescueTeams).filter_by(id=unit_id, del_flag='0').first()
- if not unit:
- raise HTTPException(status_code=404, detail="单位不存在或已被标记为删除")
- return {"code": 200, "msg": "查询成功", "unit": {'id' :unit.id,
- 'name' :unit.name,
- 'team_type' :unit.team_type,
- 'professional_category' :unit.professional_category,
- 'team_category' :unit.team_category,
- 'team_attribute' :unit.team_attribute,
- 'team_level' :unit.team_level,
- 'affiliated_unit' :unit.affiliated_unit,
- 'leader_name' :unit.leader_name,
- 'leader_phone' :unit.leader_phone,
- 'city' :unit.city,
- 'district' :unit.district,
- 'main_equipment' :unit.main_equipment,
- 'number_of_people' :unit.number_of_people,
- 'address' :unit.address,
- 'description' :unit.description,
- 'longitude' :unit.longitude,
- 'latitude' :unit.latitude,
- 's_last_updatetime' :unit.s_last_updatetime}}
- #修改
- @router.put("/edit/{unit_id}")
- def update_unit(unit_id: int, update_data: UnitSchema, db: Session = Depends(get_db),
- user_id=Depends(valid_access_token)):
- return {"code": 404, "msg": "数据由数据整理团队提供,不能修改", "unit": None}
- # 根据id和is_delete字段获取单位
- # unit = db.query(RescueUnit).filter_by(id=unit_id, is_delete=0).first()
- # if not unit:
- # raise HTTPException(status_code=404, detail="单位不存在或已被标记为删除")
- #
- # try:
- # # 更新非空字段,排除id字段
- # for key, value in update_data.dict(exclude_none=True).items():
- # # 确保不更新id字段
- # if key != 'id':
- # setattr(unit, key, value)
- # db.commit()
- # db.refresh(unit)
- # return {"code": 200, "msg": "更新成功", "unit": unit.to_dict()}
- # except Exception as e:
- # traceback.print_exc()
- # db.rollback()
- # raise HTTPException(status_code=400, detail=str(e))
-
- # 导入
- @router.post('/import')
- async def import_doc(
- request: Request,
- db: Session = Depends(get_db),
- body = Depends(remove_xss_json),
- user_id = Depends(valid_access_token)
- ):
- # print(body)
-
- try:
- filename = body['filename']
- if len(filename) == 0:
- raise Exception()
-
- file = filename[0]
- url = file['url']
- file_path = f"{UPLOAD_mergefile_PATH}/uploads/{url}"
- file_path = os.path.abspath(file_path)
- print(file_path)
-
- book = xlrd.open_workbook(file_path)
- sheet = book.sheet_by_index(0)
- data = []
- '''
- for i in range(9, sheet.nrows):
- # 预案名称
- plan_name = sheet.cell(i, 0).value
- # 一级目录
- title1 = sheet.cell(i, 1).value
- # 二级目录
- title2 = sheet.cell(i, 2).value
- # 三级目录
- title3 = sheet.cell(i, 3).value
- # 正文
- content = sheet.cell(i, 4).value
- if len(plan_name) < 1 and len(title1) < 1 and len(title2) < 1 and len(title3) < 1 and len(content) < 1 :
- break
- data.append({
- 'plan_name': plan_name,
- 'title1': title1,
- 'title2': title2,
- 'title3': title3,
- 'content': content,
- })
- if len(data) > 0:
- db.query(EmergencyDoc).filter(EmergencyDoc.plan_id == plan_id).delete()
- db.commit()
- title1 = ''
- content = ''
- docs = []
- for n in data:
- if n['title1'] != '':
- if len(docs) > 0:
- add_doc_1(db, title1, content, docs, plan_id)
- docs = []
- title1 = n['title1']
- content = n['content']
- if n['title2'] != '':
- docs.append(n)
- continue
- docs.append(n)
- if len(docs) > 0:
- add_doc_1(db, title1, content, docs, plan_id)
- '''
- return {
- 'code': 200,
- 'msg': '导入成功'
- }
- except Exception:
- traceback.print_exc()
- return {
- 'code': 500,
- 'msg': '导入发生异常'
- }
-
|