xuguoyang 3 weeks ago
parent
commit
9c362108f6
1 changed files with 70 additions and 71 deletions
  1. 70 71
      routers/api/dataFilling/__init__.py

+ 70 - 71
routers/api/dataFilling/__init__.py

@@ -42,14 +42,12 @@ def get_next_event_id(db: Session):
             return reportId
 
 
-# 函数用于将中文转换为拼音首字母缩写
-def to_first_letter(chinese_str: str) -> str:
-    return ''.join([p[0][0] for p in lazy_pinyin(chinese_str, style=Style.FIRST_LETTER)]).lower()
 
 
 
 
 
+#
 # class ReportQuery(BaseModel):
 #     report_id: str
 
@@ -60,7 +58,7 @@ class TableStructure(BaseModel):
 # 表数据模型
 class TableData(BaseModel):
     row_data: dict
-#详情
+#详情   字段校验
 @router.get("/report_structure/{report_id}")
 async def get_report_structure(
     report_id: str,
@@ -201,40 +199,33 @@ async def get_report_structure(
 
     return result
 
-
+# 函数用于将中文转换为拼音首字母缩写
+def to_first_letter(chinese_str: str) -> str:
+    return ''.join([p[0][0] for p in lazy_pinyin(chinese_str, style=Style.FIRST_LETTER)]).lower()
 
 # 动态创建表
 def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
-    inspector = inspect(db.bind)
+    metadata = MetaData()
+    inspector = Inspector.from_engine(db.bind)
 
     # 检查表是否已存在
     if inspector.has_table(table_name):
-        return {"code": 500, "msg": "请检查表格"}
-        # raise HTTPException(status_code=400, detail="Table already exists")
+        return {"code": 500, "msg": "表已存在"}
 
     table = Table(table_name, metadata,
-                  Column('id', Integer, primary_key=True,comment="id"),
-                  Column('user_id', Integer,comment="用户ID"),
-                  Column('create_id', Integer,comment="创建者ID"),
-                  Column('collect_status', Boolean,comment="收取结果"),
-                  Column('add_time', DateTime, server_default=func.now(),comment="添加时间"),
-                  # Column('temporarily_store', Integer, default=0,comment="暂存状态"),
+                  Column('id', Integer, primary_key=True, comment="主键ID"),
+                  Column('user_id', Integer, comment="用户ID"),
+                  Column('create_id', Integer, comment="创建者ID"),
+                  Column('collect_status', Boolean, comment="收取结果"),
+                  Column('add_time', DateTime, server_default=func.now(), comment="添加时间"),
                   Column('temporarily_store', Integer, server_default='0', comment="暂存状态"),
                   extend_existing=True
                   )
 
-    existing_columns = set()
-    for field_name in field_names:
-        column_name = to_first_letter(field_name)
-        # 如果列名已存在,则添加一个唯一的后缀
-        unique_column_name = "col"+column_name
-        suffix = 1
-        while unique_column_name in existing_columns:
-            unique_column_name = f"{column_name}_{suffix}"
-            suffix += 1
-        existing_columns.add(unique_column_name)
-
-        table.append_column(Column(unique_column_name, String(255), comment=field_name))
+    # 为每个字段动态添加列
+    for i, field_name in enumerate(field_names, start=1):
+        column_name = f"col{i}"
+        table.append_column(Column(column_name, String(255), comment=field_name))
 
     # 创建表
     try:
@@ -242,9 +233,10 @@ def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
     except Exception as e:
         db.rollback()
         return {"code": 500, "msg": "创建表失败"}
-        # raise HTTPException(status_code=400, detail=f"创建表失败:{str(e)}")
 
+    return {"code": 200, "msg": "表创建成功"}
 
+####表名必填,其它非必填
 class ReportCreate(BaseModel):
     table_name: str = Field(..., description="表单名称,必填")
     end_time: str = Field(..., description="结束时间,必填,格式为 ISO8601")
@@ -455,18 +447,18 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
     # 检查表是否存在
     if not inspector.has_table(table_name):
         raise HTTPException(status_code=400, detail="表不存在,无法更新字段")
+        # return {"code": 403, "msg": "未找到对应的填报ID"}
 
     # 获取现有表的列信息
     existing_columns = inspector.get_columns(table_name)
     existing_column_names = {col['name'] for col in existing_columns}
 
     # 定义需要保留的基础字段
-    columns_to_keep = {'id', 'user_id', 'create_id', 'collect_status','add_time','temporarily_store'}
+    columns_to_keep = {'id', 'user_id', 'create_id', 'collect_status', 'add_time', 'temporarily_store'}
     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}
+
+    # 将新字段名转换为 col1, col2 这种形式
+    new_field_names = {f"col{i}" for i in range(1, len(field_names) + 1)}
 
     # 确定需要删除的字段(现有字段中不存在于新字段列表中的字段)
     columns_to_drop = existing_column_names - new_field_names
@@ -476,7 +468,6 @@ 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:
@@ -484,28 +475,16 @@ def update_table_fields(table_name: str, field_names: List[str], db: Session):
             raise HTTPException(status_code=400, detail=f"删除字段失败:{str(e)}")
 
     # 添加新字段
-    added_columns = set()  # 用于记录已添加的字段名
-    for field_name in field_names:
-        column_name = to_first_letter(field_name)  # 将字段名转换为拼音首字母
+    for i, field_name in enumerate(field_names, start=1):
+        column_name = f"col{i}"
         if column_name in columns_to_add:
-            unique_column_name = column_name
-            suffix = 1
-
-            # 确保字段名唯一
-            while unique_column_name in existing_column_names or unique_column_name in added_columns:
-                unique_column_name = f"{column_name}_{suffix}"
-                suffix += 1
-
-            # 添加字段
             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)  # 记录已添加的字段名
+                db.execute(text(f"ALTER TABLE {table_name} ADD COLUMN {column_name} VARCHAR(255) COMMENT '{field_name}'"))
             except Exception as e:
                 db.rollback()
                 return {"code": 500, "msg": "添加字段失败,请联系管理员排查"}
-                # raise HTTPException(status_code=400, detail=f"添加字段失败:{str(e)}")
+
+    return {"code": 200, "msg": "字段更新成功"}
 
 
 # class ReportCreate(BaseModel):
@@ -602,15 +581,22 @@ async def update_report(
         if not table_exists(db, table_name):
             # 如果表不存在,根据 new_fields 创建表
             if not update_data.new_fields:
-                raise HTTPException(status_code=400, detail="表不存在且未提供字段信息,无法创建表")
+                # raise HTTPException(status_code=400, detail="表不存在且未提供字段信息,无法创建表")
+                return {"code": 400, "msg": "表不存在且未提供字段信息,无法创建表"}
             create_dynamic_table(table_name, update_data.new_fields, db)
 
         elif table_exists(db, table_name) and update_data.new_fields:
-            # print("修改")
-            # print(table_name)
-            # print("新字段",update_data.new_fields)
             update_table_fields(table_name, update_data.new_fields, db)
 
+    elif update_data.issued_status in ['0', 0]:
+        if update_data.new_fields:
+            if len(update_data.new_fields)>0:
+                table_name = report.data_table_name
+                if not table_exists(db, table_name):
+                    create_dynamic_table(table_name, update_data.new_fields, db)
+                elif table_exists(db, table_name) and update_data.new_fields:
+                    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
@@ -647,8 +633,9 @@ async def update_report(
         report.end_time = datetime.fromisoformat(update_data.end_time)
 
     if update_data.issued_status:
-        if update_data.issued_status == 2:
+        if update_data.issued_status in [2,"2"]:
             # 更新issued_status为2
+            # 这里要判断是否
             report.issued_status = 2
             report.issued_time = datetime.utcnow()
 
@@ -731,7 +718,8 @@ async def update_report_status_and_time(
     # print(user_ids)
 
     if len(table_structures) == 0 or len(user_ids) ==0:
-        raise HTTPException(status_code=400, detail=str('信息未填写完整,无法发布'))
+        # raise HTTPException(status_code=400, detail=str('信息未填写完整,无法发布'))
+        return {"code": 400, "msg": "信息未填写完整,无法发布"}
 
     # 更新issued_status为2
     report.issued_status = 2
@@ -748,8 +736,8 @@ async def update_report_status_and_time(
         }
     except Exception as e:
         db.rollback()
-        raise HTTPException(status_code=400, detail=str(e))
-
+        # raise HTTPException(status_code=400, detail=str(e))
+        return {"code": 500, "msg": "未知报错"}
 
 
 class TaskQuery(BaseModel):
@@ -766,14 +754,13 @@ async def get_user_tasks(
 ):
     # 检查用户ID是否提供
     if not user_id:
-        raise HTTPException(status_code=400, detail="用户ID是必填项")
-
+        # raise HTTPException(status_code=400, detail="用户ID是必填项")
+        return {"code": 400, "msg": "用户ID是必填项"}
     # 查询用户的所有任务信息
     user_tasks = db.query(ReportManagement, FormSubmission).join(
         FormSubmission, ReportManagement.report_id == FormSubmission.report_id
     ).filter(
-        FormSubmission.user_id == user_id
-    )
+        FormSubmission.user_id == user_id    )
 
     # 如果提供了填报结果列表,则过滤结果
     if query.submission_status:
@@ -792,6 +779,7 @@ async def get_user_tasks(
     offset = (query.page - 1) * query.pageSize
     tasks = user_tasks.offset(offset).limit(query.pageSize).all()
 
+    # 收取状态
     # 构造返回结果
     result_items = []
     for report, submission in tasks:
@@ -802,6 +790,7 @@ async def get_user_tasks(
             "submission_status": submission.submission_status,
             "start_time": report.start_time,
             "end_time": report.end_time,
+            "collection_status":report.collection_status
         }
         result_items.append(result_item)
 
@@ -829,16 +818,19 @@ async def get_report_fields(
 ):
     # 检查用户ID和填报ID是否提供
     if not user_id or not report_id:
-        raise HTTPException(status_code=400, detail="用户ID和填报ID是必填项")
+        # raise HTTPException(status_code=400, detail="用户ID和填报ID是必填项")
+        return {"code": 400, "msg": "用户ID和填报ID是必填项"}
 
     # 获取对应填报ID的数据表名称
     report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id).first()
     if not report:
-        raise HTTPException(status_code=404, detail="未找到对应的填报ID")
+        # raise HTTPException(status_code=404, detail="未找到对应的填报ID")
+        return {"code": 404, "msg": "未找到对应的填报ID"}
 
     data_table_name = report.data_table_name
     if not data_table_name:
-        raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
+        # raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
+        return {"code": 404, "msg": "未找到对应的数据表名称"}
 
     # 检查用户是否有权限访问填报数据
     submission = db.query(FormSubmission).filter(
@@ -846,7 +838,8 @@ async def get_report_fields(
         FormSubmission.user_id == user_id
     ).first()
     if not submission:
-        raise HTTPException(status_code=403, detail="没有权限访问这个填报数据")
+        # raise HTTPException(status_code=403, detail="没有权限访问这个填报数据")
+        return {"code": 403, "msg": "没有权限访问这个填报数据"}
 
     # 使用SQLAlchemy的inspect功能来获取表的字段信息
     inspector = inspect(db.bind)
@@ -987,7 +980,7 @@ async def submit_data(
     }
 
 
-#数据保存
+#数据保存   覆盖旧的,删掉旧记录
 @router.post("/save_data")
 async def save_data(
     db: Session = Depends(get_db),
@@ -1035,6 +1028,8 @@ async def save_data(
     if 'temporarily_store' not in column_names:
         return {"code": 400, "msg": "目标表中缺失字段 'temporarily_store',保存失败"}
 
+    delete_sql = f"DELETE FROM {data_table_name} WHERE temporarily_store = 1 AND user_id = '{user_id}'"
+    db.execute(text(delete_sql))
 
     # 将数据写入数据库
     for item in save_data.data:
@@ -1150,6 +1145,7 @@ def get_columns_with_comment_like(
 ) -> List[str]:
     # 检查表是否存在
     if not table_exists1(inspector, table_name):
+        print(f"表 {table_name} 不存在")
         return []  # 或者可以选择抛出异常
 
     columns = inspector.get_columns(table_name)
@@ -1215,8 +1211,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
 
@@ -1405,11 +1400,15 @@ async def export_to_excel(
         ReportManagement.creator_id == creator_id
     ).first()
     if not report:
-        raise HTTPException(status_code=404, detail="未找到对应的填报ID")
+        # raise HTTPException(status_code=404, detail="未找到对应的填报ID")
+        return {"code": 403, "msg": "未找到对应的填报ID"}
+
 
     data_table_name = report.data_table_name
     if not data_table_name:
-        raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
+        # raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
+        return {"code": 404, "msg": "未找到对应的数据表名称"}
+
 
     # 获取表结构(用户填报的字段)
     inspector = inspect(db.bind)