Browse Source

填报导出

xuguoyang 1 month ago
parent
commit
b8e993e68a

+ 0 - 2
models/datafilling_base.py

@@ -39,6 +39,4 @@ class FormSubmission(Base):
     user_id = Column(String(255),comment='用户ID')
     submission_status = Column(Integer,comment='填报结果')
     # fill_time = Column(DateTime,comment='填报时间')
-
-    #这里需要加上
     # collect_time = Column(DateTime,comment='填报时间')

+ 166 - 54
routers/api/dataFilling/__init__.py

@@ -60,8 +60,7 @@ class TableStructure(BaseModel):
 # 表数据模型
 class TableData(BaseModel):
     row_data: dict
-
-# 查看详情接口
+#详情
 @router.get("/report_structure/{report_id}")
 async def get_report_structure(
     report_id: str,
@@ -81,60 +80,80 @@ async def get_report_structure(
     # 查询对应表的表结构
     table_structure_query = db.execute(
         text("""
-        SELECT COLUMN_NAME, COLUMN_COMMENT
+        SELECT COLUMN_NAME, COLUMN_COMMENT, ORDINAL_POSITION
         FROM INFORMATION_SCHEMA.COLUMNS
         WHERE TABLE_NAME = :table_name AND TABLE_SCHEMA = (SELECT DATABASE())
+        ORDER BY ORDINAL_POSITION
         """),
         {"table_name": data_table_name}
     )
 
     table_structures = []
+    column_order = []  # 用于存储字段的顺序
     for row in table_structure_query.fetchall():
-        if row[0] not in ['collect_status', 'create_id', 'id', 'user_id','add_time']:
+        if row[0] not in ['collect_status', 'create_id', 'id', 'user_id', 'add_time']:
             table_structures.append(TableStructure(column_name=row[0], comment=row[1]))
-
+            column_order.append(row[0])  # 保存字段顺序
 
     # 查询表中的数据,排除指定字段
     excluded_columns = ['collect_status', 'create_id', 'id', 'user_id', 'add_time']
-    columns_to_select = ", ".join([col.column_name for col in table_structures])  # 使用表结构中的字段名
+    columns_to_select = ", ".join(column_order)  # 使用字段顺序
+    table_data_with_headers = []
+    # print("字段:",columns_to_select)
+    # print(len(columns_to_select))
+    # table_data_query =
+    if (len(columns_to_select)) != 0:
+        table_data_query = db.execute(
+            text(f"SELECT {columns_to_select} FROM {data_table_name}")
+        )
 
-    table_data_query = db.execute(
-        text(f"SELECT {columns_to_select} FROM {data_table_name}")
-    )
 
-    # 将查询结果转换为字典列表
-    table_data = [row._asdict() for row in table_data_query.fetchall()]
+        # 将查询结果转换为字典列表
+        table_data = [dict(zip(column_order, row)) for row in table_data_query.fetchall()]
 
-    # 构造表头的字段名和字段注释作为第一行
-    table_headers = {col.column_name: col.comment for col in table_structures}
+        # 构造表头的字段名和字段注释作为第一行
+        table_headers = {col.column_name: col.comment for col in table_structures}
 
-    # 在表数据中添加表头备注作为第一行
-    table_data_with_headers = [
-                                  {**table_headers}  # 表头备注,添加 add_time 为 null
-                              ] + table_data  # 表数据
+        # 在表数据中添加表头备注作为第一行
+        table_data_with_headers = [
+            table_headers  # 表头备注
+        ] + table_data  # 表数据
 
+    # 查询已提交和未提交的用户状态,并获取用户昵称
+    user_submission_status = []
 
+    # 查询所有相关用户
+    users = db.query(FormSubmission.user_id).filter(
+        FormSubmission.report_id == report_id
+    ).distinct()
 
+    user_ids = [user[0] for user in users.all()]
 
-    # 构造返回结果,包括 ReportManagement 表中的记录和其他相关信息
-    distinct_users = db.query(FormSubmission.user_id).filter(
-        FormSubmission.report_id == report_id
-    ).distinct().count()
+    # 查询每个用户的提交状态和昵称
+    for user_id in user_ids:
+        user = db.query(SysUser.nick_name).filter(SysUser.user_id == user_id).first()
+        if user:
+            nick_name = user[0]
+        else:
+            nick_name = "未知用户"
 
-    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]
+        submission_status = db.query(FormSubmission.submission_status).filter(
+            FormSubmission.report_id == report_id,
+            FormSubmission.user_id == user_id
+        ).first()
 
-    unreported = db.query(FormSubmission).filter(
-        FormSubmission.report_id == report_id,
-        FormSubmission.submission_status == 0
-    ).all()
-    num_unreported = len(unreported)
-    unreported_user_ids = [submission.user_id for submission in unreported]
+        if submission_status:
+            submission_status = str(submission_status[0])
+        else:
+            submission_status = "0"  # 默认为未提交
+
+        user_submission_status.append({
+            "name": nick_name,
+            "submission_status": submission_status,
+            "user_id":user_id
+        })
 
+    # 构造返回结果
     result = {
         "code": 200,
         "msg": "查询成功",
@@ -149,15 +168,13 @@ async def get_report_structure(
             "issued_status": report.issued_status,
             "period_type": report.period_type,
             "creator_name": report.creator_name,
-            "num_reporters": distinct_users,
+            "num_reporters": len(user_ids),
             "creator_id": creator_id,
             "created_at": report.created_at,
             "updated_at": report.updated_at,
             "creator_phone": report.creator_phone,
-            "num_reported": num_reported,
-            "num_unreported": num_unreported,
-            "unreported_user_ids": unreported_user_ids,
-            "reported_user_ids": reported_user_ids
+            "user_filling_status": user_submission_status,  # 用户提交状态列表
+            "user_ids": user_ids
         },
         "table_structure": table_structures,
         "table_data": table_data_with_headers  # 添加表数据
@@ -165,6 +182,8 @@ async def get_report_structure(
 
     return result
 
+
+
 # 动态创建表
 def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
     inspector = inspect(db.bind)
@@ -186,7 +205,7 @@ def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
     for field_name in field_names:
         column_name = to_first_letter(field_name)
         # 如果列名已存在,则添加一个唯一的后缀
-        unique_column_name = column_name
+        unique_column_name = "col"+column_name
         suffix = 1
         while unique_column_name in existing_columns:
             unique_column_name = f"{column_name}_{suffix}"
@@ -238,8 +257,6 @@ def create_report_and_table(report: ReportCreate, db: Session = Depends(get_db),
 
         if str(report.issued_status) == '2':
 
-
-
             # 登记填报管理
             new_report = ReportManagement(
                 report_id=get_next_event_id(db),
@@ -317,8 +334,8 @@ class ReportQuery(BaseModel):
     issued_status: Optional[str] = Field(None, description="Issued status filter (comma-separated values, e.g., '0,1')")
     page: int = Field(1, gt=0, description="Page number for pagination")
     pageSize: int = Field(10, gt=0, description="Page size for pagination")
-@router.post('/select')
-#@router.get("/select")
+
+@router.post("/select")
 async def select_report(
     db: Session = Depends(get_db),
     query: ReportQuery = Body(..., description="Report query parameters in the request body"),
@@ -361,6 +378,11 @@ async def select_report(
     # 构造结果
     result_items = []
     for item in data:
+        current_time = datetime.now()
+        is_filling_ended = 0
+        if item.end_time < current_time:
+            is_filling_ended = 2
+
         result_item = {
             "id": item.id,
             "report_id": item.report_id,
@@ -376,7 +398,8 @@ async def select_report(
             "created_at": item.created_at,
             "creator_phone": item.creator_phone,
             "updated_at": item.updated_at,
-            "num_reporters": item.num_reporters
+            "num_reporters": item.num_reporters,
+            "is_filling_ended":is_filling_ended
         }
         result_items.append(result_item)
 
@@ -416,7 +439,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)
     # 将新字段名转换为拼音首字母
     new_field_names = {to_first_letter(field) for field in field_names}
 
@@ -428,6 +452,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}"))
         try:
             db.execute(text(f"ALTER TABLE {table_name} DROP COLUMN {column_name}"))
         except Exception as e:
@@ -449,6 +474,8 @@ 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}'"))
                 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:
@@ -456,12 +483,29 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
                 raise HTTPException(status_code=400, detail=f"添加字段失败:{str(e)}")
 
 
+# class ReportCreate(BaseModel):
+#     table_name: str = Field(..., description="表单名称,必填")
+#     end_time: str = Field(..., description="结束时间,必填,格式为 ISO8601")
+#     # status: str = Field(..., description="状态,必填")
+#     issued_status: str = Field(..., description="发布状态,必填")
+#     creator_name: str = Field(..., description="创建者姓名,必填")
+#     creator_phone: str = Field(..., description="创建者电话,必填")
+#     user_ids: List[int] = Field(..., description="用户 ID 列表,必填")
+#
+#     period_type: Optional[str] = Field(None, description="周期,非必填")
+#     field_names: Optional[List[str]] = Field(None, description="字段名称列表,非必填")
+
+
 
 class ReportUpdate(BaseModel):
     table_name: Optional[str] = None
+    end_time: Optional[str] = None
     status: Optional[int] = None
+    issued_status: Optional[str] = None
     period_type: Optional[str] = None
-    end_time: Optional[str] = None
+    creator_phone: Optional[str] = None
+    creator_name: Optional[str] = None
+    user_ids: Optional[List[int]] = Field(None, description="字段名称列表,非必填")
     # comments: Optional[Dict[str, str]] = None
     new_fields: Optional[List[str]] = Field(None, description="字段名称列表,非必填")
 
@@ -515,8 +559,7 @@ async def update_report(
 
     if report.issued_status in ['2', 2]:
         raise HTTPException(status_code=400, detail="当前表单已发布,无法修改")
-    # if report.creator_id != creator_id:
-    #     raise HTTPException(status_code=403, detail="没有权限更新此报告")
+
 
     if report.collection_status in ['2',2]:
         raise HTTPException(status_code=400, detail="当前表单已收取,无法修改")
@@ -529,14 +572,35 @@ async def update_report(
         # 如果表不存在,根据 new_fields 创建表
         if not update_data.new_fields:
             raise HTTPException(status_code=400, detail="表不存在且未提供字段信息,无法创建表")
-
         create_dynamic_table(table_name, update_data.new_fields, db)
 
-    else:
-
+    elif table_exists(db, table_name) and update_data.new_fields:
+        print("修改")
         update_table_fields(table_name, update_data.new_fields, db)
 
-    # 更新字段
+        # 更新 creator_phone 和 creator_name
+    if update_data.creator_phone:
+        report.creator_phone = update_data.creator_phone
+
+    if update_data.creator_name:
+        report.creator_name = update_data.creator_name
+
+        # 删除旧的填报人 ID,并添加新的填报人 ID
+    if update_data.user_ids:
+        # 删除旧的填报记录
+        db.query(FormSubmission).filter(FormSubmission.report_id == report.report_id).delete()
+        # 添加新的填报记录
+        for user_id in update_data.user_ids:
+            submission = FormSubmission(
+                report_id=report.report_id,
+                user_id=user_id,
+                submission_status=0  # 默认状态为未填报
+            )
+            db.add(submission)
+        report.num_reporters = len(update_data.user_ids)
+
+
+        # 更新字段
     if update_data.table_name:
         report.table_name = update_data.table_name
 
@@ -549,6 +613,8 @@ async def update_report(
     if update_data.end_time:
         report.end_time = datetime.fromisoformat(update_data.end_time)
 
+    # if update_data.
+
     current_time = datetime.now()
     report.updated_at = current_time
 
@@ -587,6 +653,39 @@ async def update_report_status_and_time(
 
     if report.issued_status ==2:
         raise HTTPException(status_code=403, detail="不可重复发布")
+
+    data_table_name = report.data_table_name
+
+    # 查询对应表的表结构
+    table_structure_query = db.execute(
+        text("""
+            SELECT COLUMN_NAME, COLUMN_COMMENT, ORDINAL_POSITION
+            FROM INFORMATION_SCHEMA.COLUMNS
+            WHERE TABLE_NAME = :table_name AND TABLE_SCHEMA = (SELECT DATABASE())
+            ORDER BY ORDINAL_POSITION
+            """),
+        {"table_name": data_table_name}
+    )
+
+    table_structures = []
+    column_order = []  # 用于存储字段的顺序
+    for row in table_structure_query.fetchall():
+        if row[0] not in ['collect_status', 'create_id', 'id', 'user_id', 'add_time']:
+            table_structures.append(TableStructure(column_name=row[0], comment=row[1]))
+            column_order.append(row[0])  # 保存字段顺序
+    # print(table_structures)
+
+    # 查询所有相关用户
+    users = db.query(FormSubmission.user_id).filter(
+        FormSubmission.report_id == report_id
+    ).distinct()
+
+    user_ids = [user[0] for user in users.all()]
+    print(user_ids)
+
+    if len(table_structures) == 0 or len(user_ids) ==0:
+        raise HTTPException(status_code=400, detail=str('信息未填写完整,无法发布'))
+
     # 更新issued_status为2
     report.issued_status = 2
 
@@ -636,6 +735,8 @@ 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()
 
@@ -932,10 +1033,13 @@ async def get_reports_by_creator(
 
         #收取状态
         collection_status = report.collection_status
+        issued_status = report.issued_status
         #结束时间
         end_time = report.end_time
         current_time = datetime.now()
-        if end_time < current_time and collection_status==0:
+
+        if end_time < current_time and collection_status in [0,'0'] and issued_status in [2,'2']:
+            print("符合自动收取")
             report.collection_status=2
             report.collection_time = current_time
 
@@ -1094,6 +1198,8 @@ async def get_records_by_creator_and_report(
 
 
 
+
+
 from fastapi import status
 @router.get("/export_to_excel")
 @router.post("/export_to_excel")
@@ -1149,4 +1255,10 @@ async def export_to_excel(
     }
 
     # 返回文件流
-    return StreamingResponse(output, headers=headers)
+    return StreamingResponse(output, headers=headers)
+
+
+
+
+
+

+ 3 - 3
routers/api/temperaturePrecipitation/__init__.py

@@ -100,15 +100,15 @@ async def mine(request: Request,db: Session = Depends(get_db)):
         elif args == "24h_variable_temperature":
             result.append(
                 {"create_time": "",
-                 "pic_url": "https://soc.gd121.cn/skt24hdt/2024/10/MSP1_AGD_MANOBS_TD_L88_AGD_202410071300_02400-00000.PNG"}
+                 "pic_url": "https://soc.gd121.cn/skimg/dt/BA3F7CC721A162A2149136AFE95CD8FE/A754169EFBBB6FA567B77735CED069F4.png"}
             )
             result.append(
                 {"create_time": "",
-                 "pic_url": "https://soc.gd121.cn/skt24hdt/2024/10/MSP1_AGD_MANOBS_TD_L88_AGD_202410071400_02400-00000.PNG"}
+                 "pic_url": "https://soc.gd121.cn/skimg/dt/BA3F7CC721A162A2149136AFE95CD8FE/8A4271D80721F5497CEA242D0BD775BB.png"}
             )
             result.append(
                 {"create_time": "",
-                 "pic_url": "https://soc.gd121.cn/skt24hdt/2024/10/MSP1_AGD_MANOBS_TD_L88_AGD_202410071500_02400-00000.PNG"}
+                 "pic_url": "https://soc.gd121.cn/skimg/dt/BA3F7CC721A162A2149136AFE95CD8FE/368D21EBBEA399BC2A119D0E54316C48.png"}
             )