Browse Source

250115-1代码。

baoyubo 4 tháng trước cách đây
mục cha
commit
8d253e35aa

+ 14 - 1
models/three_proofing_responsible_base.py

@@ -92,4 +92,17 @@ class ThreeProofingResponsiblePersonOtherType(Base):
     create_dept = Column(BigInteger, default=None, comment='创建部门')
     create_by = Column(BigInteger, default=None, comment='创建者')
     update_by = Column(BigInteger, default=None, comment='更新者')
-    del_flag = Column(String(1), default='0', comment='删除标志(0代表存在 2代表删除)')
+    del_flag = Column(String(1), default='0', comment='删除标志(0代表存在 2代表删除)')
+
+
+class ThreeProofingResponsiblePersonImportFileStatus(Base):
+    __tablename__ = 'three_proofing_responsible_person_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='文件名称')
+    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='备注')

+ 278 - 125
routers/api/ThreeProofingResponsible/person.py

@@ -1,4 +1,4 @@
-from fastapi import APIRouter, Request, Depends, HTTPException, Query
+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
@@ -20,6 +20,7 @@ import traceback
 from utils import *
 from datetime import datetime, timedelta
 import pandas as pd
+import xlrd
 from common.db import db_dept
 from exceptions import AppException
 
@@ -241,8 +242,21 @@ async def get_emergency_contact_list(
             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==area_code)
+            query = query.filter(ThreeProofingResponsiblePerson.area_code.in_(get_area_chli([area_code],area_code)))
+
+        # if area_code:
+        #     query = query.filter(ThreeProofingResponsiblePerson.area_code==area_code)
 
         # 计算总条目数
         total_items = query.count()
@@ -450,126 +464,265 @@ async def delete_emergency_plans(
         traceback.print_exc()
         raise HTTPException(status_code=500, detail=str(e))
 
-#
-# @router.post('/createImport')
-# async def create_contact(
-#         db: Session = Depends(get_db),
-#         body=Depends(remove_xss_json),
-#         user_id=Depends(valid_access_token)
-# ):
-#     try:
-#         # 提取请求数据
-#         filename = body['filename']
-#         if len(filename) == 0:
-#             raise Exception()
-#
-#         file_name = filename[0]['url']
-#         file_path = f'/data/upload/mergefile/uploads/{file_name}'
-#
-#         # 检查文件是否存在
-#         if not os.path.isfile(file_path):
-#             return JSONResponse(status_code=404, content={
-#                 'errcode': 404,
-#                 'errmsg': f'{file_name}不存在'
-#             })
-#
-#         # 定义预期的列名和对应的最大长度
-#         expected_columns = {
-#             '单位名称': 255,
-#             '联系人': 255,
-#             '职务': 255,
-#             '粤政易手机号码': 20
-#         }
-#         try:
-#             df = pd.read_excel(file_path, engine='openpyxl', header=0)
-#         except Exception as e:
-#             raise AppException(500, "请按模板上传!")
-#
-#         # 读取Excel文件
-#         # try:
-#         #     df = pd.read_excel(file_path, engine='openpyxl', header=0)
-#         # except Exception as e:
-#         #     return f"读取Excel文件时出错: {e}"
-#
-#         # 获取前两行的数据
-#         first_two_rows = df
-#         # print(first_two_rows)
-#         # 检查列名是否匹配
-#         actual_columns = first_two_rows.columns.tolist()
-#         # print('actual_columns', actual_columns)
-#         missing_columns = [col for col in expected_columns.keys() if col not in actual_columns]
-#
-#         if len(missing_columns) > 0:
-#             raise AppException(500, "请按模板上传")
-#
-#         head1 = df.head(1)
-#         head1data = head1.to_dict(orient='records')[0]
-#         print(head1data)
-#         if head1data['单位名称'] == '填写单位名称' and head1data['联系人'] == '填写单位联系人' and head1data['职务'] == '填写联系人职务' and \
-#                 head1data['粤政易手机号码'] == '填写联系人的粤政易注册手机号码':
-#             df = df.drop(index=0)
-#         else:
-#             raise AppException(500, "请按模板上传。")
-#
-#         # 检查前两行的字段长度
-#         for index, row in first_two_rows.iterrows():
-#             for col, max_length in expected_columns.items():
-#                 # if pd.isna(row[col]):
-#                 #     return f"第{index + 1}行的'{col}'字段不能为空。"
-#                 if pd.notna(row[col]) and len(str(row[col])) > max_length:
-#                     raise AppException(500, f"第{index + 1}行的'{col}'字段长度超过{max_length}字符。")
-#
-#         data = df.to_dict(orient='records')
-#         # print(data)
-#         infos = []
-#         for info in data:
-#             if pd.isna(info['单位名称']) and pd.isna(info['联系人']) and pd.isna(info['粤政易手机号码']):
-#                 continue
-#             if pd.isna(info['单位名称']) or pd.isna(info['联系人']) or pd.isna(info['粤政易手机号码']):
-#                 return "单位名称、联系人、粤政易手机号码为必填"
-#             if pd.isna(info['职务']):
-#                 info['职务'] = None
-#             infos.append(info)
-#
-#         # 创建新的预案记录
-#         for contact in infos:
-#             unit_id = db_dept.get_dept_id_by_name(db, contact['单位名称'])
-#             if unit_id == '':
-#                 raise AppException(500, "单位名称不正确")
-#
-#             # 删除之前同一个部门的人员
-#             db.query(EmergencyContactInfo).filter(
-#                 and_(EmergencyContactInfo.del_flag == "0", EmergencyContactInfo.unit_id == unit_id, )).update(
-#                 {"del_flag": "2"})
-#
-#             new_contact = EmergencyContactInfo(
-#                 unit_id=unit_id,
-#                 unit_name=contact['单位名称'],
-#                 contact_name=contact['联系人'],
-#                 position=contact['职务'],
-#                 yue_gov_ease_phone=contact['粤政易手机号码'],
-#                 create_by=user_id
-#             )
-#
-#             # 添加到数据库会话
-#             db.add(new_contact)
-#         # 提交
-#         db.commit()
-#
-#         # 返回创建成功的响应
-#         return {
-#             "code": 200,
-#             "msg": "创建成功",
-#             "data": None
-#         }
-#
-#     except AppException as e:
-#         return {
-#             "code": 500,
-#             "msg": e.msg
-#         }
-#
-#     except Exception as e:
-#         traceback.print_exc()
-#         # 处理异常
-#         raise HTTPException(status_code=500, detail=str(e))
+def string_type_parent_id_create_data(db,string,type_parent_id,file_info,new_person,user_id,row) :
+    type_name_list = [i for i in string.split(',')]
+    reslte = []
+    for type_name in type_name_list:
+        type_id = get_type_id_by_type_parent_id_and_type_name(db, '1', type_name)
+        if type_id:
+            new_person_type = ThreeProofingResponsiblePersonType(
+                type_parent_id=type_parent_id,
+                type_id=type_id,
+                person_id=new_person.id,
+                create_by=user_id
+            )
+            reslte.append(new_person_type)
+        else:
+            file_info.remark= file_info.remark+f'\n行<{row+1}>责任类别未找到<{type_name}>'
+            return reslte ,False
+    return reslte ,True
+def import_data(db,file_path,user_id,file_info):
+    book = xlrd.open_workbook(file_path)
+    sheet = book.sheet_by_index(0)
+
+    data = []
+    import_status = True
+    for row in range(4, sheet.nrows):
+        # 姓名
+        name = sheet.cell(row, 0).value
+        if name == '':
+            file_info.remark = file_info.remark+f'\n行<{row+1}>姓名不能为空<{name}>'
+            import_status = False
+            continue
+        # 所属单位
+        unit_name = sheet.cell(row, 1).value
+        if unit_name == '':
+            file_info.remark = file_info.remark+f'\n行<{row+1}>所属单位不能为空<{unit_name}>'
+            import_status = False
+            continue
+        unit_id = db_dept.get_dept_id_by_name(db, unit_name)
+        # 职务
+        position = sheet.cell(row, 2).value
+        if position =='':
+            file_info.remark = file_info.remark+f'\n行<{row+1}>职务不能为空<{position}>'
+            import_status = False
+            continue
+
+        # 电话号码(如有多个手机号请用“,”分隔)
+        phone = int(sheet.cell(row, 3).value)
+        if phone =='':
+            file_info.remark = file_info.remark+f'\n行<{row+1}>电话号码不能为空<{phone}>'
+            import_status = False
+            continue
+        phone_list = [i for i in phone.split(',')]
+        user_id_1=-1
+        for i in phone_list:
+            user_id_1 = db_user.get_user_id_by_phonenumber(db,i)
+            if user_id_1 != -1:
+                break
+
+        # 办公电话
+        # (选填,格式:区号-电话号码)
+        telephone = sheet.cell(row, 4).value
+
+        # 排位顺序
+        # (选填,请输入排序号1-9999,排序号数值越小越靠前,不填则默认排至最末)
+        order_num = sheet.cell(row, 5).value
+        if order_num == '':
+            order_num=-1
+        area_name = sheet.cell(row, 7).value
+        if area_name=='':
+            area_code=2
+        else:
+            area_code=get_area_info_by_area_name(db,area_name)
+            if area_code is None:
+                file_info.remark = file_info.remark+f'\n行<{row+1}>责任区域未找到<{area_name}>'
+                import_status = False
+                continue
+
+        new_person = ThreeProofingResponsiblePerson(
+            unit_id=unit_id,
+            unit_name=unit_name,
+            name=name,
+            area_code=area_code,
+            position=position,
+            phone=phone,
+            telephone=telephone,
+            user_id=user_id_1,
+            order_num=order_num,
+            create_by=user_id
+        )
+        data.append(new_person)
+        db.add(new_person)
+        db.commit()
+        # 党委政府
+        a1 = sheet.cell(row, 6).value
+        if a1 != '':
+            new_type_list,status = string_type_parent_id_create_data(db,a1,'1',file_info,new_person,user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data +=new_type_list
+            # type_name_list = [i for i in a1.split(',')]
+            # for type_name in type_name_list:
+            #     type_id = get_type_id_by_type_parent_id_and_type_name(db, '1', type_name)
+            #     if type_id:
+            #         pass
+        # 三防指挥部
+        b1 = sheet.cell(row, 8).value
+        if b1 != '':
+            new_type_list,status = string_type_parent_id_create_data(db,b1,'2',file_info,new_person,user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data +=new_type_list
+
+        b2 = sheet.cell(row, 9).value
+
+        # 应急部门
+        c1 = sheet.cell(row, 10).value
+        if c1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, c1, '3', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        # 成员单位
+        d1 = sheet.cell(row, 11).value
+        if d1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, d1, '4', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        d2 = sheet.cell(row, 12).value
+
+        # 重点部门
+        e1 = sheet.cell(row, 13).value
+        if e1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, e1, '5', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        e2 = sheet.cell(row, 14).value
+        e3 = sheet.cell(row, 15).value
+
+        # 行政村
+        f1 = sheet.cell(row, 16).value
+        if f1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, f1, '6', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+
+        # 水利工程
+        g1 = sheet.cell(row, 10).value
+        if g1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, g1, '7', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        g2 = sheet.cell(row, 11).value
+        g3 = sheet.cell(row, 12).value
+
+        # 受威胁转移
+        h1 = sheet.cell(row, 13).value
+        if h1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, h1, '8', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+
+        # 抢险队伍
+        j1 = sheet.cell(row, 14).value
+        if j1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, j1, '9', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        j2 = sheet.cell(row, 15).value
+
+        # 地质灾害
+        k1 = sheet.cell(row, 16).value
+        if k1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, k1, '10', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        k2 = sheet.cell(row, 17).value
+
+        # 其他
+        l1 = sheet.cell(row, 18).value
+        if l1!='':
+            new_type_list, status = string_type_parent_id_create_data(db, l1, '11', file_info, new_person, user_id)
+            import_status = status
+            if status:
+                db.add_all(new_type_list)
+                data += new_type_list
+        l2 = sheet.cell(row, 19).value
+
+
+    if import_status == False:
+        for info in data:
+            db.delete(info)
+    db.commit()
+@router.post('/createImport')
+async def create_contact(
+        background_tasks: BackgroundTasks,
+        db: Session = Depends(get_db),
+        body=Depends(remove_xss_json),
+        user_id=Depends(valid_access_token),
+
+):
+    try:
+        # 提取请求数据
+        filename = body['filename']
+        file_name_desc = body['file_name_desc']
+        if len(filename) == 0:
+            raise Exception()
+
+        file_name = filename[0]['url']
+        file_path = f'/data/upload/mergefile/uploads/{file_name}'
+
+        # 检查文件是否存在
+        if not os.path.isfile(file_path):
+            return JSONResponse(status_code=404, content={
+                'errcode': 404,
+                'errmsg': f'{file_name}不存在'
+            })
+
+        new_file = ThreeProofingResponsiblePersonImportFileStatus(
+            file_uuid=filename,
+            file_name = file_name_desc,
+            status = '1',
+            user_id=user_id
+        )
+        db.add(new_file)
+        db.commit()
+        background_tasks.add_task(import_data,db,file_path, user_id,new_file)
+
+
+        # 返回创建成功的响应
+        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))

+ 15 - 1
utils/three_proofing_responsible_util.py

@@ -18,6 +18,12 @@ def get_type_parent_id_by_type_id(db,type_id):
     query = db.query(ThreeProofingResponsibleType)
     query = query.filter_by(id = type_id,del_flag = '0')
     return query.first().type_parent_id
+
+def get_type_id_by_type_parent_id_and_type_name(db,type_parent_id,type_name):
+    query = db.query(ThreeProofingResponsibleType)
+    query = query.filter_by(type_parent_id = type_parent_id,type_name=type_name,del_flag = '0')
+    return query.first().id
+
 def get_type_parent_id_by_type_list(db,type_parent_id):
     query = db.query(ThreeProofingResponsibleType)
     query = query.filter_by(type_parent_id = type_parent_id,del_flag = '0')
@@ -65,4 +71,12 @@ def get_type_parent_id_by_person_id(db,person_id):
 def id_get_area_info(db,id):
     query = db.query(GovdataArea)
     query = query.filter(GovdataArea.id == id)
-    return query.first()
+    return query.first()
+def get_area_info_by_area_name(db,name):
+    query = db.query(GovdataArea)
+    query = query.filter(GovdataArea.area_name == name)
+    return query.first()
+def parent_id_get_area_info(db,parent_id):
+    query = db.query(GovdataArea)
+    query = query.filter(GovdataArea.parent_id == parent_id)
+    return query.all()