Pārlūkot izejas kodu

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

libushang 1 mēnesi atpakaļ
vecāks
revīzija
b5d0c10ced

+ 94 - 18
routers/api/dataFilling/__init__.py

@@ -129,6 +129,21 @@ async def get_report_structure(
 
     user_ids = [user[0] for user in users.all()]
 
+    reported = db.query(FormSubmission).filter(
+        FormSubmission.report_id == report_id,
+        FormSubmission.submission_status == 1
+    ).all()
+    num_reported = len(reported)
+    reported_user_ids = [submission.user_id for submission in reported]
+
+    unreported = db.query(FormSubmission).filter(
+        FormSubmission.report_id == report_id,
+        FormSubmission.submission_status == 0
+    ).all()
+    # print(unreported)
+    num_unreported = len(unreported)
+
+
     # 查询每个用户的提交状态和昵称
     for user_id in user_ids:
         user = db.query(SysUser.nick_name).filter(SysUser.user_id == user_id).first()
@@ -172,8 +187,11 @@ async def get_report_structure(
             "creator_id": creator_id,
             "created_at": report.created_at,
             "updated_at": report.updated_at,
+            "num_reported": num_reported,
+            "num_unreported": num_unreported,
             "creator_phone": report.creator_phone,
             "user_filling_status": user_submission_status,  # 用户提交状态列表
+
             "user_ids": user_ids
         },
         "table_structure": table_structures,
@@ -439,8 +457,8 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
     # 定义需要保留的基础字段
     columns_to_keep = {'id', 'user_id', 'create_id', 'collect_status','add_time'}
     existing_column_names -= columns_to_keep  # 排除基础字段
-    print(existing_column_names)
-    print(field_names)
+    # print(existing_column_names)
+    # print(field_names)
     # 将新字段名转换为拼音首字母
     new_field_names = {to_first_letter(field) for field in field_names}
 
@@ -452,7 +470,7 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
 
     # 删除不再需要的字段
     for column_name in columns_to_drop:
-        print(text(f"ALTER TABLE {table_name} DROP COLUMN {column_name}"))
+        # print(text(f"ALTER TABLE {table_name} DROP COLUMN {column_name}"))
         try:
             db.execute(text(f"ALTER TABLE {table_name} DROP COLUMN {column_name}"))
         except Exception as e:
@@ -475,7 +493,7 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
             # 添加字段
             try:
                 unique_column_name = "col"+unique_column_name
-                print(text(f"ALTER TABLE {table_name} ADD COLUMN {unique_column_name} VARCHAR(255) COMMENT '{field_name}'"))
+                # print(text(f"ALTER TABLE {table_name} ADD COLUMN {unique_column_name} VARCHAR(255) COMMENT '{field_name}'"))
                 db.execute(text(f"ALTER TABLE {table_name} ADD COLUMN {unique_column_name} VARCHAR(255) COMMENT '{field_name}'"))
                 added_columns.add(unique_column_name)  # 记录已添加的字段名
             except Exception as e:
@@ -565,7 +583,8 @@ async def update_report(
         raise HTTPException(status_code=400, detail="当前表单已收取,无法修改")
 
 
-
+    # 这里要添加发布状态判断,如果是暂存状态则跳过,发布状态则要提供字段信息
+    # if update_data.issued_status  in ['0', 0]:
     # 检查表是否存在
     table_name = report.data_table_name
     if not table_exists(db, table_name):
@@ -575,7 +594,9 @@ async def update_report(
         create_dynamic_table(table_name, update_data.new_fields, db)
 
     elif table_exists(db, table_name) and update_data.new_fields:
-        print("修改")
+        # print("修改")
+        # print(table_name)
+        # print("新字段",update_data.new_fields)
         update_table_fields(table_name, update_data.new_fields, db)
 
         # 更新 creator_phone 和 creator_name
@@ -613,6 +634,17 @@ async def update_report(
     if update_data.end_time:
         report.end_time = datetime.fromisoformat(update_data.end_time)
 
+    if update_data.issued_status:
+        if update_data.issued_status == 2:
+            # 更新issued_status为2
+            report.issued_status = 2
+            report.issued_time = datetime.utcnow()
+
+    if update_data.status:
+        # print(11111111)
+        # 更新create_time为当前时间
+        report.status = update_data.status
+
     # if update_data.
 
     current_time = datetime.now()
@@ -681,7 +713,7 @@ async def update_report_status_and_time(
     ).distinct()
 
     user_ids = [user[0] for user in users.all()]
-    print(user_ids)
+    # print(user_ids)
 
     if len(table_structures) == 0 or len(user_ids) ==0:
         raise HTTPException(status_code=400, detail=str('信息未填写完整,无法发布'))
@@ -715,7 +747,9 @@ class TaskQuery(BaseModel):
 async def get_user_tasks(
     db: Session = Depends(get_db),
     query: TaskQuery = Body(...),
-    user_id = Depends(valid_access_token)
+    user_id: str = Depends(valid_access_token),
+    page: int = Query(default=1, gt=0),  # 分页参数:当前页码,默认为1
+    pageSize: int = Query(default=10, gt=0)  # 分页参数:每页大小,默认为10
 ):
     # 检查用户ID是否提供
     if not user_id:
@@ -735,16 +769,21 @@ async def get_user_tasks(
     if query.table_name:
         user_tasks = user_tasks.filter(ReportManagement.table_name.ilike(f'%{query.table_name}%'))
 
-        # 按 submission_status 升序排序
-        user_tasks = user_tasks.order_by(FormSubmission.submission_status.asc())
-    # 执行查询
-    tasks = user_tasks.all()
+    # 按 submission_status 升序排序
+    user_tasks = user_tasks.order_by(FormSubmission.submission_status.asc())
+
+    # 计算总数
+    total_count = user_tasks.count()
+
+    # 分页查询
+    offset = (page - 1) * pageSize
+    tasks = user_tasks.offset(offset).limit(pageSize).all()
 
     # 构造返回结果
     result_items = []
     for report, submission in tasks:
         result_item = {
-            "user_id":user_id,
+            "user_id": user_id,
             "table_name": report.table_name,
             "report_id": report.report_id,
             "submission_status": submission.submission_status,
@@ -753,12 +792,18 @@ async def get_user_tasks(
         }
         result_items.append(result_item)
 
-    return {
-        "code":200,
-        "msg":"查询成功",
+    # 构造分页结果
+    result = {
+        "code": 200,
+        "msg": "查询成功",
+        "total": total_count,
+        "totalPages": (total_count + pageSize - 1) // pageSize,
+        "page": page,
+        "pageSize": pageSize,
         "data": result_items
     }
 
+    return result
 
 
 @router.get("/report_fields")
@@ -804,13 +849,44 @@ async def get_report_fields(
             }
             result_fields.append(result_field)
 
+    # 构造返回结果
+    result_items = []
+    excluded_columns = ['id', 'user_id', 'create_id', 'collect_status']
+
+    # 构建查询SQL
+    query_sql = text(f"""
+                SELECT * FROM {data_table_name} WHERE user_id = :user_id
+            """)
+    result = db.execute(query_sql, {"user_id": user_id})
+    rows = result.fetchall()
+
+
+    # 提取列名和列注释
+    column_names = [column['name'] for column in columns]
+    column_comments = {column['name']: column['comment'] for column in columns if 'comment' in column}
+
+    # 添加字段名和字段注释作为第一行
+    first_row = {column: column_comments.get(column, '') for column in column_names if
+                 column not in excluded_columns}
+    result_items.append(first_row)
+    # print(result_items)
+    for row in rows:
+        # 过滤掉不需要的列
+        # print(row)
+        filtered_row = {column: row[idx] for idx, column in enumerate(column_names) if
+                        column not in excluded_columns}
+        # print(filtered_row)
+        result_items.append(filtered_row)
+
+
     # 返回用户ID、填报ID和字段信息
     return {
         "code":200,
         "msg":"查询成功",
         "user_id": user_id,
         "report_id": report_id,
-        "fields": result_fields
+        "fields": result_fields,
+        "data":result_items
     }
 
 
@@ -1039,7 +1115,7 @@ async def get_reports_by_creator(
         current_time = datetime.now()
 
         if end_time < current_time and collection_status in [0,'0'] and issued_status in [2,'2']:
-            print("符合自动收取")
+            # print("符合自动收取")
             report.collection_status=2
             report.collection_time = current_time
 

+ 4 - 95
routers/api/spatialAnalysis/__init__.py

@@ -43,7 +43,9 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
         # 行政镇、行政村数据
         # town_village_data,town_count,village_count = count_town_village(from_data.location,db)
         # town_village_data,town_count = get_town_list(body)
+        print(time.time())
         town_village_data,town_count,village_count = get_town_village_list(body,db) #[],0,0#
+        print(time.time())
         # emergency_expert_count = count_emergency_expert(from_data.location,db)
         # emergency_management_count = count_emergency_management(from_data.location,db)
 
@@ -123,91 +125,7 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
         list_1 = [{"name": point_type_to_list[dataType], "num": len(lst), "list": lst}
                   for dataType, lst in lists.items() if lst]
 
-        # list_1 = []
-        # point_list = get_point_list(body,db)
-        # emergency_expert_list = [] #专家 1
-        # rescue_materia_warehouse_list = [] #救援物资-仓库 2
-        # emergency_shelter_list = [] # 应急避难场所 3
-        # waterlogged_roads_list = [] # 易涝点 4
-        # school_list = [] # 学校 5
-        # hospital_list = [] #医院 6
-        # gasoline_station_list = [] #加油站 7
-        # mining_company_list = []# 非煤矿山企业 8
-        # chemical_company_list = [] #危化企业 9
-        # ship_realtilme_positioninfo_list = []# 船舶动态 10
-        # for point in point_list:
-        #     if point.dataType == 1:
-        #         emergency_expert_list.append({"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude, "latitude": point.latitude})
-        #     elif point.dataType == 2:
-        #         rescue_materia_warehouse_list.append({"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 3:
-        #         emergency_shelter_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 4:
-        #         waterlogged_roads_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 5:
-        #         school_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 6:
-        #         hospital_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 7:
-        #         gasoline_station_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 8:
-        #         mining_company_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 9:
-        #         chemical_company_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        #     elif point.dataType == 10:
-        #         ship_realtilme_positioninfo_list.append(
-        #             {"id": point.id, "dataType": point.dataType, "name": point.name, "longitude": point.longitude,
-        #              "latitude": point.latitude})
-        # num = len(emergency_expert_list)
-        # if num>0:
-        #     list_1.append({"name":"专家","num":num,"list":emergency_expert_list})
-        # num = len(rescue_materia_warehouse_list)
-        # if num>0:
-        #     list_1.append({"name":"救援物资仓库","num":num,"list":rescue_materia_warehouse_list})
-        # num = len(emergency_shelter_list)
-        # if num>0:
-        #     list_1.append({"name":"应急避难场所","num":num,"list":emergency_shelter_list})
-        # num = len(waterlogged_roads_list)
-        # if num>0:
-        #     list_1.append({"name":"易涝点","num":num,"list":waterlogged_roads_list})
-        # num = len(school_list)
-        # if num>0:
-        #     list_1.append({"name":"学校","num":num,"list":school_list})
-        # num = len(hospital_list)
-        # if num>0:
-        #     list_1.append({"name":"医院","num":num,"list":hospital_list})
-        # num = len(gasoline_station_list)
-        # if num>0:
-        #     list_1.append({"name":"加油站","num":num,"list":gasoline_station_list})
-        # num = len(mining_company_list)
-        # if num>0:
-        #     list_1.append({"name":"非煤矿山企业","num":num,"list":mining_company_list})
-        # num = len(chemical_company_list)
-        # if num>0:
-        #     list_1.append({"name":"危化企业","num":num,"list":chemical_company_list})
-        # num = len(ship_realtilme_positioninfo_list)
-        # if num>0:
-        #     list_1.append({"name":"船舶动态","num":num,"list":ship_realtilme_positioninfo_list})
-
-
-        # hospital_list = get_hospital_list(body,db)
-        # emergency_shelter_list = get_emergency_shelter_list(body,db)
-        # waterlogged_roads_list = get_waterlogged_roads_list(body,db)
+        print(time.time())
 
 
         return {
@@ -222,16 +140,7 @@ async def mine(request: Request,body = Depends(remove_xss_json),db: Session = De
                 "areaSize":0,
                 "GDP":0,
                 "list":list_1
-                #     [{
-                #     "name":"应急避难场所","num":len(emergency_shelter_list),"list":[{"name":shelter.name,"longitude":shelter.longitude,"latitude":shelter.latitude} for shelter in emergency_shelter_list]
-                # },{
-                #     "name":"易涝点","num":len(waterlogged_roads_list),"list":[{"name":waterlogged.name,"longitude":waterlogged.longitude,"latitude":waterlogged.latitude} for waterlogged in waterlogged_roads_list]
-                # },{
-                #     "name":"医院","num":len(hospital_list),"list":[{"name":hospital.name,"longitude":hospital.longitude,"latitude":hospital.latitude} for hospital in hospital_list]
-                # }
-                # ]
-                # "emergencyExpertCount":emergency_expert_count,
-                # "emergencyManagementCount":emergency_management_count
+
             }
         }
     except Exception as e:

+ 25 - 9
utils/spatial/__init__.py

@@ -85,7 +85,21 @@ def get_town_list(locations,):
                 })
 
     return intersected_names_and_pacs, len(intersected_names_and_pacs)
-
+def get_bqw_yj_quyu_data(area_code,db):
+    sql = text(
+        """SELECT ifnull(populationSize,0) as populationSize,
+        ifnull(populationSize_unit,'') as populationSize_unit,
+        ifnull(areaSize,0) as areaSize,
+         ifnull(areaSize_unit,'')as areaSize_unit,ifnull(GDP,0) as GDP,ifnull(GDP_unit,'') as GDP_unit FROM sharedb.`bqw_yj_quyu_data` where `area_code`like :code order by area_code,year desc """).bindparams(
+        code=f'%{area_code}%')
+    # 执行查询
+    result = db.execute(sql).fetchone()
+
+    # 处理结果
+    if result:
+        return dict(result)
+    else:
+        return {"populationSize":0,"populationSize_unit":"","areaSize":0,"areaSize_unit":"","GDP":0,"GDP_unit":""}
 def get_town_village_list(locations,db):
     # 初始化一个空的MultiPolygon来容纳所有多边形
 
@@ -110,12 +124,13 @@ def get_town_village_list(locations,db):
         # town_count+=1
         town_pac = town.pac
         properties = json.loads(town.properties)
+        quyu_data = get_bqw_yj_quyu_data(town.pac,db)
         town_data = {
             "townName": town.name,
             "code": town.pac,
-            "populationSize": 0,  # 假设值,需要从数据中获取
-            "areaSize": properties['GEO_AREA'],  # 交集区域的面积
-            "GDP": 0  # 假设值,需要从数据中获取
+            "populationSize": f"{quyu_data['populationSize']}{quyu_data['populationSize_unit']}",
+            "areaSize": f"{quyu_data['areaSize']}{quyu_data['areaSize_unit']}",
+            "GDP": f"{quyu_data['GDP']}{quyu_data['GDP_unit']}"  # 假设值,需要从数据中获取
         }
 
         # intersected_villages = db.query(TpCjSqGeoJSONData).filter(
@@ -124,15 +139,16 @@ def get_town_village_list(locations,db):
         intersected_villages = get_village_list(locations,db,pac=f""" where pac like '{town_pac}%'""")
         intersected_villages_names_and_pacs = []
         for village in intersected_villages:
-            town_data['populationSize']+=village.populationSize
-            town_data['GDP']+=village.GDP
+            quyu_data = get_bqw_yj_quyu_data(village.pac, db)
+            # town_data['populationSize']+=village.populationSize
+            # town_data['GDP']+=village.GDP
             # properties = json.loads(village.properties)
             village_data = {
                 "villageName": village.name,
                 "code": village.pac,
-                "populationSize": village.populationSize,  # 假设值,需要从数据中获取
-                "areaSize": properties['GEO_AREA'],  # 交集区域的面积  0,#
-                "GDP": village.GDP  # 假设值,需要从数据中获取
+                "populationSize": f"{quyu_data['populationSize']}{quyu_data['populationSize_unit']}",#village.populationSize,  # 假设值,需要从数据中获取
+                "areaSize": f"{quyu_data['areaSize']}{quyu_data['areaSize_unit']}",#properties['GEO_AREA'],  # 交集区域的面积  0,#
+                "GDP": f"{quyu_data['GDP']}{quyu_data['GDP_unit']}"#village.GDP  # 假设值,需要从数据中获取
             }
             intersected_villages_names_and_pacs.append(village_data)
         villageCount= len(intersected_villages_names_and_pacs)