Переглянути джерело

Merge branch 'master' of https://gogs.tjp.com.cn/maoming/python-fastapi-mm-zhcs-yj-api

libushang 3 тижнів тому
батько
коміт
b23aa6fd0f

+ 21 - 0
models/resource_provision_base.py

@@ -69,6 +69,27 @@ class WaterResourceProject(Base):
         }
 
 
+class ResourceImportFileStatus(Base):
+    __tablename__ = 'resource_import_file_status'
+
+    id = Column(Integer, primary_key=True, autoincrement=True, comment='ID')
+    file_uuid = Column(String(255), nullable=False, comment='文件uuid名称')
+    file_name = Column(String(255), nullable=False, comment='文件名称')
+    error_num = Column(Integer, nullable=False,default=0, comment='错误数量')
+    warning_num = Column(Integer, nullable=False,default=0,comment='警告数量')
+    status = Column(String(50), nullable=False, comment='状态')
+    create_time = Column(DateTime, default=datetime.now, comment='创建时间')
+    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
+    user_id = Column(String(255), nullable=False, comment='操作账号')
+    remark = Column(Text, comment='备注')
+    resource_type = Column(String(255), nullable=False, comment='物资类型')
+    class Config:
+        orm_mode = True
+
+
+
+
+
 class Unit(Base):
     __tablename__ = 'rescue_units'
 

+ 114 - 4
routers/api/Knowledge/__init__.py

@@ -2,15 +2,19 @@ from fastapi import APIRouter, Request, Depends, HTTPException, Query,Response
 from sqlalchemy.exc import IntegrityError
 
 from common.security import valid_access_token
-from fastapi.responses import JSONResponse
+from fastapi.responses import JSONResponse,StreamingResponse
+from common.db import db_czrz
+from common.auth_user import *
 from database import get_db
 from sqlalchemy.orm import Session
 from models import *
+from utils.ry_system_util import *
 import json
 import random
 from sqlalchemy import create_engine, select, or_
 from typing import Optional
 import uuid
+import traceback
 router = APIRouter()
 
 
@@ -170,11 +174,117 @@ async def select_knowledge(
     return result
 
 
+@router.get('/export')
+async def select_knowledge(
+        request: Request,
+        db: Session = Depends(get_db),
+        sortBy: str = Query(..., description="排序字段"),
+        sortOrder: str = Query(..., description="排序顺序"),
+        pageNum: int = Query(1, gt=0, description="页码"),
+        pageSize: int = Query(10, gt=0, le=100, description="每页大小"),
+        eventType: str = Query(None, description="事件类型"),
+        publishDateRange: str = Query(None, description="发布日期范围"),
+        auth_user: AuthUser = Depends(find_auth_user),
+        query: str = Query(None, description="查询关键字", user_id=Depends(valid_access_token))
+):
+    try:
+        data_query = db.query(KnowledgeBase)
+        data_query = data_query.filter(KnowledgeBase.del_flag != '2')
+
+        if eventType:
+            data_query = data_query.filter(KnowledgeBase.eventType == eventType)
+
+        if publishDateRange:
+            start_date, end_date = publishDateRange.split('-')
+            data_query = data_query.filter(KnowledgeBase.publishDate.between(start_date, end_date))
+
+        if query:
+            search_fields = [getattr(KnowledgeBase, field) for field in ('reportName', 'publishingUnit', 'reportId') if
+                             hasattr(KnowledgeBase, field)]
+            search_conditions = [field.like(f'%{query}%') for field in search_fields]
+            data_query = data_query.filter(or_(*search_conditions))
+
+        if hasattr(KnowledgeBase, sortBy):
+            sort_attr = getattr(KnowledgeBase, sortBy)
+            data_query = data_query.order_by(sort_attr.asc() if sortOrder == 'asc' else sort_attr.desc())
+        total_count = data_query.count()
+        offset = (pageNum - 1) * pageSize
+        # data_query = data_query.offset(offset).limit(pageSize)
+
+        fields = ['reportId', 'reportName', 'eventType', 'publishDate', 'publishingUnit', 'summary', 'subject',
+                  'notificationType', 'base_code']
+        entities = [getattr(KnowledgeBase, field) for field in fields if hasattr(KnowledgeBase, field)]
+        data = data_query.with_entities(*entities).all()
+        # mm_event_type_list = dict_type_get_dict_data_info(db,'mm_event_type')
+        mm_event_type = {}
+        for i in dict_type_get_dict_data_info(db,'mm_event_type'):
+            mm_event_type[i.dict_value]=i.dict_label
+        result_items = []
+        for item in data:
+            item_dict = {field: getattr(item, field) for field in fields}
+            # print(item_dict)
+            # base_code = item_dict['base_code']
+            # kf_entries = db.query(KnowledgeFile).filter(KnowledgeFile.knowledge_base_code == base_code).filter(
+            #     KnowledgeFile.is_deleted != '2').all()
+            # item_dict['files'] = [
+            #     {
+            #         "fileIdentifier": file.file_identifier,
+            #         "fileName": file.file_name,
+            #         "url": file.storage_file_name,
+            #         "status": "success"
+            #     }
+            #     for file in kf_entries
+            # ]
+            item_dict = {"报告编号":item_dict["reportId"],
+                         "报告名称":item_dict["reportName"],
+                         "主题词":item_dict["subject"],
+                         "事件类型":mm_event_type[item_dict["eventType"]],
+                         "摘要":item_dict["summary"],
+                         "来源单位":item_dict["publishingUnit"],
+                         "发布日期":item_dict["publishDate"],
+                         "知识类型":item_dict["notificationType"]}
+            result_items.append(item_dict)
+        import pandas as pd
+        from io import BytesIO
+        # 将查询结果转换为 DataFrame
+        df = pd.DataFrame(result_items)
+
+        # 将 DataFrame 导出为 Excel 文件
+        output = BytesIO()
+        with pd.ExcelWriter(output, engine='openpyxl') as writer:
+            df.to_excel(writer, index=False)
+
+        # 设置响应头
+        output.seek(0)
+        from urllib.parse import quote
+        encoded_filename = f'知识管理{datetime.now().strftime("%Y%m%d%H%mi%s")}.xlsx'
+        encoded_filename = quote(encoded_filename, encoding='utf-8')
+        headers = {
+            'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
+            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+        }
 
+        db_czrz.log(db, auth_user, "知识库管理", f"知识管理导出数据成功", request.client.host)
+
+        # 返回文件流
+        return StreamingResponse(output, headers=headers)
+        # result = {
+        #     "code": 200,
+        #     'msg': '查询成功',
+        #     'pages': (total_count + pageSize - 1) // pageSize,
+        #     'total': total_count,
+        #     "currentPage": pageNum,
+        #     "pageSize": pageSize,
+        #     'data': result_items
+        # }
+        #
+        # return result
 
-
-
-
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
 
 @router.get('/detail')
 async def get_knowledge_detail(db: Session = Depends(get_db), reportID: Optional[str] = Query(None, description="报告ID"), user_id=Depends(valid_access_token)):

+ 143 - 1
routers/api/ThreeProofingResponsible/person.py

@@ -1,7 +1,7 @@
 from fastapi import APIRouter, Request, Depends, HTTPException, Query, BackgroundTasks
 from sqlalchemy.exc import IntegrityError
 from fastapi.responses import HTMLResponse, FileResponse
-from fastapi.responses import JSONResponse
+from fastapi.responses import JSONResponse,StreamingResponse
 from database import get_db
 from sqlalchemy import text, exists, and_, or_, not_
 from sqlalchemy.orm import Session
@@ -372,6 +372,148 @@ async def get_emergency_contact_list(
         raise HTTPException(status_code=500, detail=str(e))
 
 
+@router.get('/export')
+async def get_emergency_contact_list(
+        request: Request,
+        type_parent_id: str = Query(None, description='单位名称'),
+        area_code: str = Query(None, description='单位名称'),
+        Name: str = Query(None, description='联系人'),
+        page: int = Query(1, gt=0, description='页码'),
+        pageSize: int = Query(10, gt=0, description='每页条目数量'),
+        db: Session = Depends(get_db),
+        auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 构建查询
+        query = db.query(ThreeProofingResponsiblePerson)
+        query = query.filter(ThreeProofingResponsiblePerson.del_flag == '0')
+        # 应用查询条件
+        if type_parent_id:
+            person_list = get_person_list_by_type_parent_id(db, type_parent_id)
+            query = query.filter(ThreeProofingResponsiblePerson.id.in_(person_list))
+        if Name:
+            query = query.filter(ThreeProofingResponsiblePerson.name.like(f'%{Name}%'))
+
+        def get_area_chli(area_list: list, parent_id: int):
+
+            areas = parent_id_get_area_info(db, parent_id)
+            if areas:
+                for area in areas:
+                    area_list.append(area.id)
+                    get_area_chli(area_list, area.id)
+            return area_list
+
+        # if area_code:
+        #     query = query.filter(ThreeProofingResponsiblePerson.area_code.in_(get_area_chli([area_code],area_code)))
+        # '''440900000000'''
+        if area_code:
+            area_info = id_get_area_info(db, area_code)
+            if area_info:
+                area_code = area_info.area_code
+                area_code = area_code.replace('0000000000', '').replace('00000000', '').replace('000000', '').replace(
+                    '000', '')
+                query = query.filter(ThreeProofingResponsiblePerson.area_code2.like(f'%{area_code}%'))
+        # if area_code:
+        #     query = query.filter(ThreeProofingResponsiblePerson.area_code==area_code)
+
+        # 计算总条目数
+        total_items = query.count()
+
+        # 排序
+
+        query = query.order_by(ThreeProofingResponsiblePerson.order_num.asc())
+        query = query.order_by(ThreeProofingResponsiblePerson.create_time.desc())
+        # 执行分页查询
+        contact_infos = query.all()
+
+        for info in contact_infos:
+            if three_proofing_responsible_person_data.sign_valid_row(info) == False:
+                raise HmacException(500, "三防责任人管理人员信息表验证异常,已被非法篡改")
+
+        # 将查询结果转换为列表形式的字典
+        contact_infos_list = []
+        for info in contact_infos:
+            type_parent_id_list = get_type_parent_id_by_person_id(db, info.id)
+            type_parent_list = []
+            type_parent_list2 = []
+            for type_parent in type_parent_id_list:
+                if type_parent not in type_parent_list2:
+                    dict_data = get_dict_data_info(db, 'three_proofing', type_parent)
+                    type_parent_list2.append(type_parent)
+                    type_parent_list.append(dict_data.dict_label)
+            area_info = id_get_area_info(db, info.area_code)
+            user_info = user_id_get_user_info(db, info.create_by)
+            area_list = db_area.id_get_area_parent_list(db, info.area_code, [])
+            area_list = '/'.join([i['label'] for i in area_list])
+            if info.order_num == -1:
+                order_num = ''
+            else:
+                order_num = str(info.order_num)
+            contact_infos_list.append({
+                "id": info.id,
+                "单位ID": info.unit_id,
+                "单位名称": info.unit_name,
+                "姓名": info.name,
+                "区划列表": area_list,
+                "区划编码": info.area_code,
+                "区划": area_info.area_name,
+                "职务": info.position,
+                "手机号码": mpfun.dec_data(info.phone),
+                "办公电话": mpfun.dec_data(info.telephone),
+                "排序顺序": order_num,
+                "创建时间": info.create_time.strftime('%Y-%m-%d %H:%M:%S'),
+                "责任类型": '、'.join(type_parent_list)
+            })
+        # 返回结果+
+        import pandas as pd
+        from io import BytesIO
+        # 将查询结果转换为 DataFrame
+        df = pd.DataFrame(contact_infos_list)
+
+        # 将 DataFrame 导出为 Excel 文件
+        output = BytesIO()
+        with pd.ExcelWriter(output, engine='openpyxl') as writer:
+            df.to_excel(writer, index=False)
+
+        # 设置响应头
+        output.seek(0)
+        from urllib.parse import quote
+        encoded_filename = f'三防责任人清单{datetime.now().strftime("%Y%m%d%H%mi%s")}.xlsx'
+        encoded_filename = quote(encoded_filename, encoding='utf-8')
+        headers = {
+            'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
+            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+        }
+
+        db_czrz.log(db, auth_user, "三防责任人管理", f"三防责任人清单导出数据成功", request.client.host)
+
+        # 返回文件流
+        return StreamingResponse(output, headers=headers)
+        #
+        # return {
+        #     "code": 200,
+        #     "msg": "成功",
+        #     "data": contact_infos_list,
+        #     "total": total_items
+        # }
+
+    except HmacException as e:
+        return JSONResponse(status_code=e.code, content={
+            "code": e.code,
+            "msg": e.msg
+        })
+        # return {
+        #     "code": e.code,
+        #     "msg": e.msg
+        # }
+
+    except Exception as e:
+        # 处理异常
+        traceback.print_exc()
+        return JSONResponse(status_code=500, content={"code": 500, "msg": f"Internal server error: {str(e)}"})
+
+
 @router.get('/info/{id}')
 async def get_emergency_contact_id_info(
         id: str,

+ 5 - 3
routers/api/emergencyPlans/contact.py

@@ -399,7 +399,7 @@ async def create_contact(
             if pd.isna(info['职务']):
                 info['职务'] = None
             infos.append(info)
-
+        new_data = []
         # 创建新的预案记录
         for contact in infos:
             unit_id = db_dept.get_dept_id_by_name(db, contact['单位名称'])
@@ -418,9 +418,9 @@ async def create_contact(
                 create_by = user_id,
                 sign = ''
             )
-
+            new_data.append(new_contact)
             # 添加到数据库会话
-            db.add(new_contact)
+        db.add_all(new_data)
         # 提交
         db.commit()
 
@@ -437,6 +437,7 @@ async def create_contact(
         }
     
     except AppException as e:
+        db.rollback()
         return {
             "code": 500,
             "msg": e.msg
@@ -445,4 +446,5 @@ async def create_contact(
     except Exception as e:
         traceback.print_exc()
         # 处理异常
+        db.rollback()
         raise HTTPException(status_code=500, detail=str(e))

+ 8 - 3
routers/api/resourceProvison/MaterialReserveManagement/material.py

@@ -575,12 +575,17 @@ async def get_pattern_list(
         data = []
         for info in lists:
             material_info = material_id_get_material_info(db, info.material_code)
+            status = ""
+            if info.status == "1":
+                status = '启用'
+            else:
+                status='禁用'
             data.append({"id": info.id,
                 "物资名称": material_info.material_name,
                 "物资编号": info.material_code,
-                "条形码": info.barcode,
-                "二维码": info.qr_code,
-                "条码状态": info.status,
+                "条形码": 'http://120.241.74.139:8086/api/file/get_img/get_img_by_id/'+info.barcode,
+                "二维码": 'http://120.241.74.139:8086/api/file/get_img/get_img_by_id/'+info.qr_code,
+                "条码状态":  status,
                 "创建时间": info.create_time} )
 
         # 返回结果

+ 6 - 0
routers/api/resourceProvison/MaterialReserveManagement/material_type.py

@@ -84,7 +84,13 @@ async def get_pattern_info(
         info = type_id_get_material_type_info(db,id)
         if not info:
             return JSONResponse(status_code=404,content={"code":404,"msg":"type not found"})
+        parent_material_category_name = ''
+        parentinfo = type_id_get_material_type_info(db,info.parent_id)
+        if parentinfo is not None:
+            # print(parentinfo.material_category_name)
+            parent_material_category_name=parentinfo.material_category_name
         data = {"parent_id": info.parent_id,
+                "parent_material_category_name":parent_material_category_name,
                 "material_category_name": info.material_category_name,
                 "material_category_level": info.material_category_level,
                 "sort_order": info.sort_order,

+ 825 - 24
routers/api/resourceProvison/emergency_resources.py

@@ -1,7 +1,10 @@
-from fastapi import APIRouter, HTTPException, Depends, Body,Query
+# 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
 from models import *
 from typing import List, Optional
@@ -9,12 +12,10 @@ from pydantic import BaseModel,Extra, Field
 import uuid
 from common.security import valid_access_token
 from pydantic import BaseModel
-from common.enc import mpfun, sys_menu_data, sys_menu_layer_data
-from common.auth_user import *
-from common.db import db_czrz
+from exceptions import AppException, HmacException
+from common.security import valid_access_token
 import traceback
-from exceptions import HmacException
-
+from utils import *
 from sqlalchemy import create_engine, Column, Integer, String, Boolean, MetaData, Table, \
     inspect, exists,or_,text,insert,asc,desc
 
@@ -63,9 +64,32 @@ def create_projects(project_list_data: WaterResourceProjectListSchema, db: Sessi
     try:
         new_projects = []  # 创建一个空列表来存储新对象
         for project_data in projects:
-            new_project = WaterResourceProject(**project_data.dict(exclude_none=True))
+            # new_project = WaterResourceProject(**project_data.dict(exclude_none=True))
+            # db.add(new_project)
+            # new_projects.append(new_project)
+
+            project_data = project_data.dict(exclude_none=True)
+            n_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+            project_data["cd_time"] = n_time
+            project_data["etl_time"] = n_time
+            project_data["cd_operation"] = 'I'
+            project_data["cd_batch"] = ''
+
+            new_project = WaterResourceProject(**project_data)
             db.add(new_project)
             new_projects.append(new_project)
+
+        # new_units = []
+        # for unit_data in units:
+        #     unit_data = unit_data.dict(exclude_none=True)
+        #     n_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        #     unit_data["add_time"] = n_time
+        #
+        #     new_unit = Unit(**unit_data)
+        #     db.add(new_unit)
+        #     new_units.append(new_unit)
+
+
         db.commit()
         project_ids = [project.id for project in new_projects]  # 获取所有新对象的ID
         return {"code": 200, "msg": "创建成功", "project_ids": project_ids}
@@ -99,7 +123,7 @@ def get_projects(page: int = Query(default=1, gt=0),
                  pageSize: int = Query(default=10, gt=0),
                  db: Session = Depends(get_db), user_id=Depends(valid_access_token)):
     data_query = db.query(WaterResourceProject).filter(WaterResourceProject.is_delete == 0)
-
+    data_query = data_query.order_by(WaterResourceProject.cd_time.desc())
     # 计算总数
     total_count = data_query.count()
 
@@ -169,15 +193,7 @@ class UnitSchema(BaseModel):
     latitude: float = None,
     position:str = None,
     team_size:int = None,
-    supervisor_unit:str=None
-    unit_propt:str=None
-    unit_levelt:str=None
-    unit_favort:str=None
-    supervisor_unit_phonet:str=None
-    supervisor_unit_contactt:str=None
-    responsible_person_phonet:str=None
-    areat:str=None
-    founding_timet:str=None
+    supervisor_unit:str=None,
     is_delete: int = 0
 
 class UnitListSchema(BaseModel):
@@ -290,7 +306,7 @@ def update_unit(unit_id: int, update_data: UnitSchema, db: Session = Depends(get
         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))
 
 
@@ -648,8 +664,19 @@ def create_defense_projects(defense_project_list_data: DefenseProjectListSchema,
     try:
         new_projects = []  # 创建一个空列表来存储新对象
         for project_data in projects:
-            new_project = DefenseProject(**project_data.dict(exclude_none=True))
-            new_projects.append(new_project)
+            # new_project = DefenseProject(**project_data.dict(exclude_none=True))
+            # new_projects.append(new_project)
+
+            project_data = project_data.dict(exclude_none=True)
+            n_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+            project_data["add_time"] = n_time
+            project_data["cd_batch"] = ""
+            project_data["cd_operation"] = "I"
+
+            new_unit = DefenseProject(**project_data)
+            db.add(new_unit)
+            new_projects.append(new_unit)
+
         db.add_all(new_projects)
         db.commit()
         project_ids = [project.id for project in new_projects]  # 获取所有新对象的ID
@@ -687,7 +714,7 @@ def get_defense_projects(page: int = Query(default=1, gt=0),
                  pageSize: int = Query(default=10, gt=0), db: Session = Depends(get_db)):
     # 应用过滤条件,仅查询未被删除的项目
     data_query = db.query(DefenseProject).filter(DefenseProject.is_delete == False)
-
+    data_query = data_query.order_by(DefenseProject.add_time.desc())
     # 计算总数
     total_count = data_query.count()
 
@@ -777,8 +804,16 @@ def create_shelters(shelter_list_data: ShelterListSchema, db: Session = Depends(
     try:
         new_shelters = []
         for shelter_data in shelters:
-            new_shelter = Shelter(**shelter_data.dict(exclude_none=True))
-            new_shelters.append(new_shelter)
+            # new_shelter = Shelter(**shelter_data.dict(exclude_none=True))
+            # new_shelters.append(new_shelter)
+            shelter_data = shelter_data.dict(exclude_none=True)
+            n_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+            shelter_data["created_time"] = n_time
+            shelter_data["data_id"] = uuid.uuid1()
+
+            new_unit = Shelter(**shelter_data)
+            db.add(new_unit)
+            new_shelters.append(new_unit)
         db.add_all(new_shelters)
         db.commit()
         shelter_ids = [shelter.id for shelter in new_shelters]
@@ -808,6 +843,8 @@ def delete_shelter(shelter_id: int, db: Session = Depends(get_db)):
 def get_shelters(page: int = Query(default=1, gt=0),
                  pageSize: int = Query(default=10, gt=0), db: Session = Depends(get_db)):
     data_query = db.query(Shelter).filter(Shelter.is_delete == False)
+    data_query = data_query.order_by(Shelter.created_time.desc())
+
     total_count = data_query.count()
     offset = (page - 1) * pageSize
     shelters = data_query.offset(offset).limit(pageSize).all()
@@ -850,3 +887,767 @@ def update_shelter(shelter_id: int, update_data: ShelterSchema, db: Session = De
         raise HTTPException(status_code=400, detail=str(e))
 
 
+
+
+
+
+
+
+
+
+
+
+
+
+
+def import_data(db, file_path, user_id, file_info):
+    import_status = True
+    print(file_path)
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+
+        # 姓名
+        jsdwzjlx = sheet.cell(row, 0).value
+        lxfs = sheet.cell(row, 1).value
+        sjtgbmtyshxydm = sheet.cell(row, 2).value
+        jdgljgbm = sheet.cell(row, 3).value
+        cd_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        sjtgbmmc = sheet.cell(row, 4).value
+        ggmj = sheet.cell(row, 5).value
+        sjtgbmxzqhdm = sheet.cell(row, 6).value
+        jsdwzjhm = sheet.cell(row, 7).value
+        xzqhdm = sheet.cell(row, 8).value
+        cd_operation = "I"
+        zdmj = sheet.cell(row, 9).value
+        d_bmmc = sheet.cell(row, 10).value
+        etl_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        jssj = sheet.cell(row, 11).value
+        jsdwmc = sheet.cell(row, 12).value
+        slsshslgcmc = sheet.cell(row, 13).value
+        # cd_batch = Column(String(200), comment='数据批次号')
+        slsshslgcdd = sheet.cell(row, 14).value
+        jdgljg = sheet.cell(row, 15).value
+        jingdu = sheet.cell(row, 16).value
+        weidu = sheet.cell(row, 17).value
+
+        new_water = WaterResourceProject(
+            jsdwzjlx=jsdwzjlx,
+            lxfs=lxfs,
+            sjtgbmtyshxydm=sjtgbmtyshxydm,
+            jdgljgbm=jdgljgbm,
+            cd_time=cd_time,
+            sjtgbmmc=sjtgbmmc,
+            ggmj=ggmj,
+            sjtgbmxzqhdm=sjtgbmxzqhdm,
+            jsdwzjhm=jsdwzjhm,
+            xzqhdm=xzqhdm,
+            cd_operation=cd_operation,
+            zdmj=zdmj,
+            d_bmmc=d_bmmc,
+            etl_time=etl_time,
+            jssj=jssj,
+            jsdwmc=jsdwmc,
+            slsshslgcmc=slsshslgcmc,
+            slsshslgcdd=slsshslgcdd,
+            jdgljg=jdgljg,
+            jingdu=jingdu,
+            weidu=weidu
+        )
+        data.append(new_water)
+        db.add(new_water)
+        db.commit()
+    db.commit()
+
+
+
+
+@router.post('/createImport/projects')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '水利'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+
+
+
+
+
+def rescue_units_import_data(db, file_path, user_id, file_info):
+    import_status = True
+    print(file_path)
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+
+        # 姓名
+        name = sheet.cell(row, 0).value
+        category = sheet.cell(row, 1).value
+        address = sheet.cell(row, 2).value
+        equipment = sheet.cell(row, 3).value
+        training = sheet.cell(row, 4).value
+        responsible_person = sheet.cell(row, 5).value
+        contact_number = sheet.cell(row, 6).value
+        longitude = sheet.cell(row, 7).value
+        latitude = sheet.cell(row, 8).value
+        position = sheet.cell(row, 9).value
+        team_size = sheet.cell(row, 10).value
+        supervisor_unit = sheet.cell(row, 11).value
+        add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+        # 创建 Unit 对象
+        new_Unit = Unit(
+            name=name,
+            category=category,
+            address=address,
+            equipment=equipment,
+            training=training,
+            responsible_person=responsible_person,
+            contact_number=contact_number,
+            longitude=longitude,
+            latitude=latitude,
+            position=position,
+            team_size=team_size,
+            supervisor_unit=supervisor_unit,
+            add_time=add_time
+        )
+        data.append(new_Unit)
+        db.add(new_Unit)
+        db.commit()
+    db.commit()
+
+@router.post('/createImport/rescue_units')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '救援人员单位管理'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(rescue_units_import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+
+
+
+
+
+
+
+
+def rescue_personnel_import_data(db, file_path, user_id, file_info):
+    import_status = True
+    print(file_path)
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+
+        # 姓名
+        name = sheet.cell(row, 0).value
+        contact_number = sheet.cell(row, 1).value
+        gender = sheet.cell(row, 2).value
+        current_address = sheet.cell(row, 3).value
+        position = sheet.cell(row, 4).value
+        unit_id = sheet.cell(row, 5).value
+        unit_name = sheet.cell(row, 6).value
+        created_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+        # 创建 Unit 对象
+        new_RescuePersonnel = RescuePersonnel(
+            name=name,
+            contact_number=contact_number,
+            gender=gender,
+            current_address=current_address,
+            position=position,
+            unit_id=unit_id,
+            unit_name=unit_name,
+            created_time=created_time
+        )
+        data.append(new_RescuePersonnel)
+        db.add(new_RescuePersonnel)
+        db.commit()
+    db.commit()
+
+
+
+@router.post('/createImport/rescue_personnel')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '救援人员单位'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(rescue_personnel_import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+
+
+
+
+
+
+def rescue_stations_import_data(db, file_path, user_id, file_info):
+    import_status = True
+    print(file_path)
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+
+        # 姓名
+        data_id = uuid.uuid1()
+        fwdx = sheet.cell(row, 0).value
+        zj = sheet.cell(row, 1).value
+        lng = sheet.cell(row, 2).value
+        cd_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        fwdmc = sheet.cell(row, 3).value
+        fwnr = sheet.cell(row, 4).value
+        add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        cd_operation = "I"
+        fwdlx = sheet.cell(row, 5).value
+        lxdh = sheet.cell(row, 6).value
+        kfsj = sheet.cell(row, 7).value
+        lat = sheet.cell(row, 8).value
+        fwdjj = sheet.cell(row, 9).value
+        lxr = sheet.cell(row, 10).value
+        fid = sheet.cell(row, 11).value
+        fwdzt = sheet.cell(row, 12).value
+        fwdaddr = sheet.cell(row, 13).value
+        ssqx = sheet.cell(row, 14).value
+
+
+        new_RescueStation = RescueStation(
+            data_id=data_id,
+            fwdx=fwdx,
+            zj=zj,
+            lng=lng,
+            cd_time=cd_time,
+            fwdmc=fwdmc,
+            fwnr=fwnr,
+            add_time=add_time,
+            cd_operation=cd_operation,
+            fwdlx=fwdlx,
+            lxdh=lxdh,
+            kfsj=kfsj,
+            lat=lat,
+            fwdjj=fwdjj,
+            lxr=lxr,
+            fid=fid,
+            fwdzt=fwdzt,
+            fwdaddr=fwdaddr,
+            ssqx=ssqx
+        )
+        data.append(new_RescueStation)
+        db.add(new_RescueStation)
+        db.commit()
+    db.commit()
+
+@router.post('/createImport/rescue_stations')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '救助站'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(rescue_stations_import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+
+
+
+#人防工程
+def defense_projects_import_data(db, file_path, user_id, file_info):
+    import_status = True
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+        # print(row)
+        # print(sheet.cell(row, 0).value)
+
+        data_id = uuid.uuid1()
+        # id = Column(BigInteger, primary_key=True, autoincrement=True, comment='数字自增ID')
+        gcmc = sheet.cell(row, 0).value
+        jsdw = sheet.cell(row, 1).value
+        whdw = sheet.cell(row, 2).value
+        rfzyjlgcs = sheet.cell(row, 3).value
+        jsdd = sheet.cell(row, 4).value
+        cd_operation = "I"
+
+        yjdxsmj = sheet.cell(row, 5).value
+        sjdxsmj = sheet.cell(row, 6).value
+        cd_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        add_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        jldw = sheet.cell(row, 7).value
+        jsdwdm = sheet.cell(row, 8).value
+        kgsj = sheet.cell(row, 9).value
+        stdw = sheet.cell(row, 10).value
+        # cd_batch = Column(String(100), comment='批次号')  # 新增
+        rfsjdwdm = sheet.cell(row, 11).value
+        rfsjdw = sheet.cell(row, 12).value
+        ybrs = sheet.cell(row, 13).value
+        stdwdm = sheet.cell(row, 14).value
+        whdwdm = sheet.cell(row, 15).value
+        jldwdm = sheet.cell(row, 16).value
+        rfzjlgcs = sheet.cell(row, 17).value
+        # gcid = Column(String(50), comment='主键')
+        extend2 = sheet.cell(row, 18).value
+        data_area = sheet.cell(row, 19).value
+        extend1 = sheet.cell(row, 20).value
+        jgsj = sheet.cell(row, 21).value
+        rffhsbdw = sheet.cell(row, 22).value
+        rffhsbdwdm = sheet.cell(row, 23).value
+        jingdu = sheet.cell(row, 24).value
+        weidu = sheet.cell(row, 25).value
+
+        new_DefenseProject = DefenseProject(
+            data_id=data_id,
+            gcmc=gcmc,
+            jsdw=jsdw,
+            whdw=whdw,
+            rfzyjlgcs=rfzyjlgcs,
+            jsdd=jsdd,
+            cd_operation=cd_operation,
+            yjdxsmj=yjdxsmj,
+            sjdxsmj=sjdxsmj,
+            cd_time=cd_time,
+            add_time=add_time,
+            jldw=jldw,
+            jsdwdm=jsdwdm,
+            kgsj=kgsj,
+            stdw=stdw,
+            rfsjdwdm=rfsjdwdm,
+            rfsjdw=rfsjdw,
+            ybrs=ybrs,
+            stdwdm=stdwdm,
+            whdwdm=whdwdm,
+            jldwdm=jldwdm,
+            rfzjlgcs=rfzjlgcs,
+            extend2=extend2,
+            data_area=data_area,
+            extend1=extend1,
+            jgsj=jgsj,
+            rffhsbdw=rffhsbdw,
+            rffhsbdwdm=rffhsbdwdm,
+            jingdu=jingdu,
+            weidu=weidu
+        )
+        data.append(new_DefenseProject)
+        db.add(new_DefenseProject)
+        db.commit()
+    db.commit()
+
+
+
+@router.post('/createImport/defense_projects')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '人防工程'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(defense_projects_import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))
+
+
+
+
+
+
+
+#人防工程
+def shelters_import_data(db, file_path, user_id, file_info):
+    import_status = True
+    try:
+        book = xlrd.open_workbook(file_path)
+        sheet = book.sheet_by_index(0)
+    except:
+        file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
+        file_info.error_num += 1
+        import_status = False
+    data = []
+    for row in range(1, sheet.nrows):
+
+
+
+
+        data_id = uuid.uuid1()
+        admin_area = sheet.cell(row, 0).value
+        full_name = sheet.cell(row, 0).value
+        address = sheet.cell(row, 0).value
+        incident_type = sheet.cell(row, 0).value
+        shelter_type = sheet.cell(row, 0).value
+        total_area = sheet.cell(row, 0).value
+        indoor_area = sheet.cell(row, 0).value
+        capacity = sheet.cell(row, 0).value
+        supplies = sheet.cell(row, 0).value
+        facilities = sheet.cell(row, 0).value
+        modified_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        created_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+
+        new_Shelter = Shelter(
+            data_id=data_id,
+            admin_area=admin_area,
+            full_name=full_name,
+            address=address,
+            incident_type=incident_type,
+            shelter_type=shelter_type,
+            total_area=total_area,
+            indoor_area=indoor_area,
+            capacity=capacity,
+            supplies=supplies,
+            facilities=facilities,
+            modified_time=modified_time,
+            created_time=created_time
+        )
+        data.append(new_Shelter)
+        db.add(new_Shelter)
+        db.commit()
+    db.commit()
+
+
+
+@router.post('/createImport/shelters')
+async def create_contact(
+        request: Request,
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        # auth_user: AuthUser = Depends(find_auth_user),
+        user_id=Depends(valid_access_token)
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        # file_path = f'/data/upload/mergefile/uploads/{filename}'
+        file_path = f'D:\\Desktop\\mm\\{filename}'
+        # print(file_path)
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{filename}不存在'
+            })
+
+        new_file = ResourceImportFileStatus(
+            file_uuid=filename,
+            file_name=file_name_desc,
+            status='1',
+            remark='',
+            user_id=user_id,
+            resource_type = '避难场所'
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(shelters_import_data, db, file_path, user_id, new_file)
+
+        # db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
+
+        # 返回创建成功的响应
+        return {
+            "code": 200,
+            "msg": "成功",
+            "data": None
+        }
+
+    except AppException as e:
+        return {
+            "code": 500,
+            "msg": e.msg
+        }
+
+    except Exception as e:
+        traceback.print_exc()
+        # 处理异常
+        db.rollback()
+        raise HTTPException(status_code=500, detail=str(e))

+ 34 - 16
routers/api/riskManagement/risk_router.py

@@ -1153,26 +1153,44 @@ async def get_inspection_task_list(
             area = area_code_get_ancestors_names(db, area)
             task_info = {
                 "id": task.id,
-                "children_task_id": task.children_task_id,
-                "point_name":task.inspection_point_name,
-                "area": area,
-                "create_time": task.create_time.strftime('%Y-%m-%d'),
-                "nick_name": task.nick_name,
-                "result": task.inspection_result,
-                "fileList": get_file_query_fun(db=db,from_scenario='RiskManagementRiskTaskChildrenTaskResult', foreign_key=task.id),
-                "remark":task.remark
+                "子任务表id": task.children_task_id,
+                "经度":task.longitude,
+                "纬度":task.latitude,
+                "巡查点":task.inspection_point_name,
+                "区划": area,
+                "创建时间": task.create_time.strftime('%Y-%m-%d'),
+                "采集人员": task.nick_name,
+                "采集结果": task.inspection_result,
+                # "fileList": get_file_query_fun(db=db,from_scenario='RiskManagementRiskTaskChildrenTaskResult', foreign_key=task.id),
+                "备注":task.remark
             }
             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
+        import pandas as pd
+        from io import BytesIO
+        # 将查询结果转换为 DataFrame
+        df = pd.DataFrame(InspectionTasks_list)
+
+        # 将 DataFrame 导出为 Excel 文件
+        output = BytesIO()
+        with pd.ExcelWriter(output, engine='openpyxl') as writer:
+            df.to_excel(writer, index=False)
+
+        # 设置响应头
+        output.seek(0)
+        from urllib.parse import quote
+        encoded_filename = f'救援资源要素巡查结果{datetime.now().strftime("%Y%m%d%H%mi%s")}.xlsx'
+        encoded_filename = quote(encoded_filename, encoding='utf-8')
+        headers = {
+            'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
+            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
         }
+
+        db_czrz.log(db, auth_user, "救援资源要素管理", f"救援资源要素巡查结果导出数据成功", request.client.host)
+
+        # 返回文件流
+        return StreamingResponse(output, headers=headers)
+
     except Exception as e:
         # 处理异常
         traceback.print_exc()

+ 1 - 1
routers/api/spatialAnalysis/__init__.py

@@ -45,7 +45,7 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
         # town_village_data,town_count = get_town_list(body)
         print(time.time())
         town_village_data,town_count,village_count,populationSize,areaSize,GDP = get_town_village_list(body,db) #[],0,0#
-        print(time.time())
+        print(time.time(),town_village_data,town_count,village_count,populationSize,areaSize,GDP)
         # emergency_expert_count = count_emergency_expert(from_data.location,db)
         # emergency_management_count = count_emergency_management(from_data.location,db)
 

+ 35 - 25
routers/prod_api/system/menu/__init__.py

@@ -379,34 +379,44 @@ async def get_list(
     if status:
         query = query.filter(SysMenu.status.like(f'%{status}%'))
     # 应用查询
-    # menu_list = db.query(SysMenu).filter(
-    #     (SysMenu.menu_name.like(f'%{menu_name}%')) ,
-    #     (SysMenu.status.like(f'%{status}%'))
-    # ).all()
+
     query = query.order_by(SysMenu.order_num.asc())
     menu_list = query.all()
     # 将模型实例转换为字典
-    menu_list_dict = [{
-            "menuId": menu.menu_id,
-            "menuName": menu.menu_name,
-            "parentId": menu.parent_id,
-            "orderNum": menu.order_num,
-            "path": menu.path,
-            "component": menu.component,
-            "queryParam": menu.query_param,
-            "isFrame": str(menu.is_frame),
-            "isCache": str(menu.is_cache),
-            "menuType": menu.menu_type,
-            "visible": menu.visible,
-            "status": menu.status,
-            "perms": menu.perms,
-            "icon": menu.icon,
-            "createDept": menu.create_dept,
-            "remark": menu.remark,
-            "createTime": menu.create_time.strftime('%Y-%m-%d %H:%M:%S') if menu.create_time else '',
-            "children": []  # 递归调用以获取子菜单
-        } for menu in menu_list]
-
+    menu_list_dict = []
+    def menu_parent_life(menu_id):
+        query = db.query(SysMenu)
+        query = query.filter(SysMenu.menu_id==menu_id)
+        data = query.filter(SysMenu.del_flag != '2').first()
+        if data is None:
+            return False
+        if data.parent_id==0 or data.parent_id=='0':
+            return True
+        else:
+            return menu_parent_life(data.parent_id)
+
+    for menu in menu_list:
+        if menu_parent_life(menu.menu_id):
+            menu_list_dict.append({
+                "menuId": menu.menu_id,
+                "menuName": menu.menu_name,
+                "parentId": menu.parent_id,
+                "orderNum": menu.order_num,
+                "path": menu.path,
+                "component": menu.component,
+                "queryParam": menu.query_param,
+                "isFrame": str(menu.is_frame),
+                "isCache": str(menu.is_cache),
+                "menuType": menu.menu_type,
+                "visible": menu.visible,
+                "status": menu.status,
+                "perms": menu.perms,
+                "icon": menu.icon,
+                "createDept": menu.create_dept,
+                "remark": menu.remark,
+                "createTime": menu.create_time.strftime('%Y-%m-%d %H:%M:%S') if menu.create_time else '',
+                "children": []  # 递归调用以获取子菜单
+            })
     # 构建分页响应
     # pagination_info = {
     #     "total": total_count,

+ 31 - 16
utils/spatial/__init__.py

@@ -23,11 +23,12 @@ def convert_to_polygon(points):
 
 def get_town_list2(location_list:list,db):
     # resutl = []
+    # print(len(location_list))
     if len(location_list) ==0:
         return []
     query = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location,list):
             pass
         else:
             return []
@@ -35,7 +36,7 @@ def get_town_list2(location_list:list,db):
         query.append(f"ST_Intersects(geometry,ST_PolygonFromText( '{location}', 4326 ))")
     query=' or '.join(query)
     sql = text(f"""SELECT DISTINCT `name`,properties,pac FROM tp_geojson_data_zj WHERE {query}""")
-    # print(sql)
+    # print(sql.text)
     resutl=db.execute(sql).all()
     return resutl
 
@@ -45,7 +46,7 @@ def get_village_list(location_list:list,db,pac=''):
     resutl = []
     query = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location,list):
             pass
         else:
             return []
@@ -122,7 +123,7 @@ def get_town_village_list(locations,db):
     # 初始化一个空的MultiPolygon来容纳所有多边形
 
     intersected_towns = get_town_list2(locations,db)
-
+    print(intersected_towns)
     # 初始化一个空列表来存储结果
     intersected_names_and_pacs = []
     town_count = len(intersected_towns)
@@ -272,7 +273,7 @@ def count_emergency_management(location_list: list, db):
 def get_hospital_list(location_list:list,db):
     resutl = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location,list):
             pass
         else:
             return []
@@ -286,7 +287,7 @@ def get_emergency_shelter_list(location_list:list,db):
 
     resutl = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location,list):
             pass
         else:
             return []
@@ -302,7 +303,7 @@ def get_waterlogged_roads_list(location_list:list,db):
 
     resutl = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location,list):
             pass
         else:
             return []
@@ -314,16 +315,30 @@ def get_waterlogged_roads_list(location_list:list,db):
     return resutl
 
 def get_point_list(location_list:list,db):
-
-    resutl = []
+    if len(location_list) == 0:
+        return []
+    query = []
     for location in location_list:
-        if isinstance(location,dict):
+        if isinstance(location, list):
             pass
         else:
             return []
-        location = convert_to_polygon(location)
-
-        sql = text(f"""SELECT `id` ,`name`, longitude, latitude, `dataType` FROM point_data WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
-
-        resutl+=db.execute(sql).all()
-    return resutl
+        location = convert_to_polygon(location)  # ,geometry
+        query.append(f"ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))")
+    query = ' or '.join(query)
+    sql = text(f"""SELECT `id` ,`name`, longitude, latitude, `dataType` FROM point_data WHERE {query}""")
+    # print(sql.text)
+    resutl = db.execute(sql).all()
+    return resutl
+    # resutl = []
+    # for location in location_list:
+    #     if isinstance(location,list):
+    #         pass
+    #     else:
+    #         return []
+    #     location = convert_to_polygon(location)
+    #
+    #     sql = text(f"""SELECT `id` ,`name`, longitude, latitude, `dataType` FROM point_data WHERE ST_Contains(ST_PolygonFromText( '{location}', 4326 ),ST_PointFromText(CONCAT('POINT(', latitude, ' ', longitude, ')'), 4326))""")
+    #
+    #     resutl+=db.execute(sql).all()
+    # return resutl