xuguoyang 2 bulan lalu
induk
melakukan
6627587fbb
2 mengubah file dengan 393 tambahan dan 120 penghapusan
  1. 8 0
      models/datafilling_base.py
  2. 385 120
      routers/api/dataFilling/__init__.py

+ 8 - 0
models/datafilling_base.py

@@ -1,8 +1,11 @@
 from fastapi import FastAPI, HTTPException, Depends
 from pydantic import BaseModel
 from datetime import datetime
+from typing import List
 from sqlalchemy import create_engine, Column, Integer, String, DateTime, Boolean, Text
 from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import sessionmaker, Session
+from pypinyin import lazy_pinyin
 
 Base = declarative_base()
 
@@ -18,6 +21,7 @@ class ReportManagement(Base):
     end_time = Column(DateTime, comment='结束时间')
     status = Column(Integer, comment='表格状态:0在用  2废除')
     issued_status = Column(Integer, comment='下发状态:1待发布  2已发布')
+    issued_time = Column(DateTime, comment='发布时间')
     collection_status = Column(Integer, comment='收取状态:0待收取  2已收取')
     collection_time = Column(DateTime,  comment='收取时间')
     period_type = Column(String(255), comment='周期类型')
@@ -34,3 +38,7 @@ class FormSubmission(Base):
     report_id = Column(String(255), comment='填报ID')
     user_id = Column(String(255),comment='用户ID')
     submission_status = Column(Integer,comment='填报结果')
+    # fill_time = Column(DateTime,comment='填报时间')
+
+    #这里需要加上
+    # collect_time = Column(DateTime,comment='填报时间')

+ 385 - 120
routers/api/dataFilling/__init__.py

@@ -4,12 +4,21 @@ from common.security import valid_access_token
 from pydantic import BaseModel,Extra,Field
 from datetime import datetime
 from typing import List, Optional,Any,Dict
-from sqlalchemy import create_engine, Column, Integer, String, Boolean, MetaData, Table, inspect, exists,or_,text,insert
+from sqlalchemy import create_engine, Column, Integer, String, Boolean, MetaData, Table, \
+    inspect, exists,or_,text,insert,asc,desc
 from sqlalchemy.orm import Session
 from pypinyin import lazy_pinyin, Style
 from database import get_db
 from models import *
 import random
+
+
+import pandas as pd
+from sqlalchemy import text
+from fastapi.responses import StreamingResponse
+from io import BytesIO
+
+
 router = APIRouter()
 metadata = MetaData()
 
@@ -47,7 +56,12 @@ def to_first_letter(chinese_str: str) -> str:
 class TableStructure(BaseModel):
     column_name: str
     comment: str
-#查看详情
+
+# 表数据模型
+class TableData(BaseModel):
+    row_data: dict
+
+# 查看详情接口
 @router.get("/report_structure/{report_id}")
 async def get_report_structure(
     report_id: str,
@@ -55,7 +69,10 @@ async def get_report_structure(
     creator_id = Depends(valid_access_token)
 ):
     # 查询 ReportManagement 表以获取 data_table_name
-    report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id).first()
+    report = db.query(ReportManagement).filter(
+        ReportManagement.report_id == report_id,
+        ReportManagement.creator_id == creator_id
+    ).first()
     if not report:
         raise HTTPException(status_code=404, detail="Report not found")
 
@@ -73,40 +90,55 @@ async def get_report_structure(
 
     table_structures = []
     for row in table_structure_query.fetchall():
-        if row[0] not in ['collect_status','create_id','id','user_id']:
+        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]))
 
 
+    # 查询表中的数据,排除指定字段
+    excluded_columns = ['collect_status', 'create_id', 'id', 'user_id', 'add_time']
+    columns_to_select = ", ".join([col.column_name for col in table_structures])  # 使用表结构中的字段名
+
+    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_headers = {col.column_name: col.comment for col in table_structures}
+
+    # 在表数据中添加表头备注作为第一行
+    table_data_with_headers = [
+                                  {**table_headers}  # 表头备注,添加 add_time 为 null
+                              ] + table_data  # 表数据
+
+
 
-    # # 查询 user_id 去重后的数量
-    # distinct_user_count_query = db.execute(
-    #     text("""
-    #        SELECT COUNT(DISTINCT user_id) AS distinct_user_count
-    #        FROM {}
-    #        """.format(data_table_name))
-    # )
-    # num_reported = distinct_user_count_query.scalar()
-    # num_unreported = report.num_reporters - num_reported
 
     # 构造返回结果,包括 ReportManagement 表中的记录和其他相关信息
-    # 计算去重用户数量
     distinct_users = db.query(FormSubmission.user_id).filter(
-        FormSubmission.report_id == report_id).distinct().count()
+        FormSubmission.report_id == report_id
+    ).distinct().count()
 
-    # 计算已填报数量(填报结果为1)
-    num_reported = db.query(FormSubmission).filter(FormSubmission.report_id == report_id,
-                                                      FormSubmission.submission_status == 1).count()
+    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]
 
-    # 计算未填报数量(填报结果为0)
-    num_unreported = db.query(FormSubmission).filter(FormSubmission.report_id == report_id,
-                                                          FormSubmission.submission_status == 0).count()
+    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]
 
-    print("xx")
-    print(distinct_users,num_reported,num_unreported)
     result = {
         "code": 200,
-        'msg': '查询成功',
-        'report_info': {
+        "msg": "查询成功",
+        "report_info": {
             "id": report.id,
             "report_id": report.report_id,
             "table_name": report.table_name,
@@ -121,15 +153,18 @@ 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,
+            "num_reported": num_reported,
+            "num_unreported": num_unreported,
+            "unreported_user_ids": unreported_user_ids,
+            "reported_user_ids": reported_user_ids
         },
-        'table_structure': table_structures
+        "table_structure": table_structures,
+        "table_data": table_data_with_headers  # 添加表数据
     }
 
     return result
 
-
 # 动态创建表
 def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
     inspector = inspect(db.bind)
@@ -139,10 +174,12 @@ def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
         raise HTTPException(status_code=400, detail="Table already exists")
 
     table = Table(table_name, metadata,
-                  Column('id', Integer, primary_key=True),
-                  Column('user_id', Integer),
-                  Column('create_id', Integer),
-                  Column('collect_status', Boolean)
+                  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="添加时间"),
+                  extend_existing=True
                   )
 
     existing_columns = set()
@@ -159,20 +196,25 @@ def create_dynamic_table(table_name: str, field_names: List[str], db: Session):
         table.append_column(Column(unique_column_name, String(255), comment=field_name))
 
     # 创建表
-    metadata.create_all(bind=db.bind)
+    try:
+        metadata.create_all(bind=db.bind)
+    except Exception as e:
+        db.rollback()
+        raise HTTPException(status_code=400, detail=f"创建表失败:{str(e)}")
+
 
 class ReportCreate(BaseModel):
-    table_name: str
-    #start_time: str
-    end_time: str
-    status: str
-    issued_status: str
-    period_type: str
-    creator_name: str
-    # creator_id: int
-    creator_phone:str
-    field_names: List[str]  # 用户只传递字段名称
-    user_ids: List[int]
+    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="字段名称列表,非必填")
+
 
 # 新建填报和创建新表的接口
 @router.post("/report/")
@@ -186,33 +228,68 @@ def create_report_and_table(report: ReportCreate, db: Session = Depends(get_db),
         table_name_pinyin=''
         for i in range(len(lazy_pinyin(report.table_name, style=Style.FIRST_LETTER))):
             table_name_pinyin += ''.join(lazy_pinyin(report.table_name, style=Style.FIRST_LETTER)[i]).lower()
-        data_table_name = f"{table_name_pinyin}_{current_time_str}"
-
-        # 动态创建新表
-        create_dynamic_table(data_table_name, report.field_names, db)
-        # 登记填报管理
-        new_report = ReportManagement(
-            report_id=get_next_event_id(db),
-            table_name=report.table_name,
-            data_table_name=data_table_name,
-            start_time=datetime.now(),
-            end_time=report.end_time,
-            status=report.status,
-            issued_status=report.issued_status,
-            collection_status=0,#未收取
-            period_type=report.period_type,
-            creator_name=report.creator_name,
-            creator_id=creator_id,
-            creator_phone=report.creator_phone,
-            num_reporters = len(report.user_ids)
-        )
-        db.add(new_report)
-        db.commit()
-        db.refresh(new_report)
+        data_table_name = f"tbxt_{table_name_pinyin}_{current_time_str}"
+        # 待发布状态(即暂时)需领处理,如果是待发布(issued_status 1待发布  2已发布),
+        # 那么只需要填联系人姓名,联系电话,填报人,截止时间和表名
+        # 可以先不创表,但是填报人先报上?
+        if str(report.issued_status) == '2' and not report.field_names:
+            #这里有bug
+            raise HTTPException(status_code=403, detail='发布状态下,需要填写字段信息')
+
+        if str(report.issued_status) == '2':
+
+
+
+            # 登记填报管理
+            new_report = ReportManagement(
+                report_id=get_next_event_id(db),
+                table_name=report.table_name,
+                data_table_name=data_table_name,
+                start_time=datetime.now(),
+                end_time=report.end_time,
+                status=0,
+                issued_status=report.issued_status,
+                collection_status=0,#未收取
+                period_type=report.period_type,
+                creator_name=report.creator_name,
+                creator_id=creator_id,
+                creator_phone=report.creator_phone,
+                num_reporters = len(report.user_ids),
+                issued_time = datetime.now()
+            )
+            db.add(new_report)
+            db.commit()
+            db.refresh(new_report)
+        else:
+            # 登记填报管理
+            new_report = ReportManagement(
+                report_id=get_next_event_id(db),
+                table_name=report.table_name,
+                data_table_name=data_table_name,
+                start_time=datetime.now(),
+                end_time=report.end_time,
+                status=0,
+                issued_status=report.issued_status,
+                collection_status=0,  # 未收取
+                period_type=report.period_type,
+                creator_name=report.creator_name,
+                creator_id=creator_id,
+                creator_phone=report.creator_phone,
+                num_reporters=len(report.user_ids)
+            )
+            db.add(new_report)
+            db.commit()
+            db.refresh(new_report)
+
+        if report.field_names :
+            if len(report.field_names) > 0:
+                # 动态创建新表
+                create_dynamic_table(data_table_name, report.field_names, db)
+
         # 为每个用户创建填报记录
         for user_id in report.user_ids:
             submission = FormSubmission(
-                report_id=new_report.report_id ,
+                report_id=new_report.report_id,
                 user_id=user_id,
                 submission_status=0  # 默认状态为未填报
             )
@@ -226,6 +303,11 @@ def create_report_and_table(report: ReportCreate, db: Session = Depends(get_db),
         raise HTTPException(status_code=400, detail=str(e))
 
 
+
+
+
+
+
 # 定义请求体的 Pydantic 模型
 class ReportQuery(BaseModel):
     table_name: Optional[str] = Field(None, description="Table name filter")
@@ -264,6 +346,11 @@ async def select_report(
         issued_status_list = [int(s) for s in query.issued_status.split(",")]
         data_query = data_query.filter(ReportManagement.issued_status.in_(issued_status_list))
 
+    data_query = data_query.order_by(
+        asc(ReportManagement.issued_status),  # 按 issued_status 升序
+        desc(ReportManagement.created_at)  # 按 created_at 降序
+    )
+
     # 计算总数
     total_count = data_query.count()
 
@@ -315,42 +402,100 @@ async def select_report(
 
 
 
-# class ReportUpdate(BaseModel):
-#     table_name: str = None
-#     status: int = None
-#     # issued_status: int = None
-#     period_type: str = None
-#     end_time: str = None
-#     comments: dict = None  # 字典,键为字段名,值为新的备注
-#     new_fields: List[dict] = None
+def update_table_fields(table_name: str, field_names: List[str], db: Session):
+    inspector = inspect(db.bind)
+
+    # 检查表是否存在
+    if not inspector.has_table(table_name):
+        raise HTTPException(status_code=400, detail="表不存在,无法更新字段")
+
+    # 获取现有表的列信息
+    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'}
+    existing_column_names -= columns_to_keep  # 排除基础字段
+
+    # 将新字段名转换为拼音首字母
+    new_field_names = {to_first_letter(field) for field in field_names}
+
+    # 确定需要删除的字段(现有字段中不存在于新字段列表中的字段)
+    columns_to_drop = existing_column_names - new_field_names
+
+    # 确定需要添加的字段(新字段列表中不存在于现有字段中的字段)
+    columns_to_add = new_field_names - existing_column_names
+
+    # 删除不再需要的字段
+    for column_name in columns_to_drop:
+        try:
+            db.execute(text(f"ALTER TABLE {table_name} DROP COLUMN {column_name}"))
+        except Exception as e:
+            db.rollback()
+            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)  # 将字段名转换为拼音首字母
+        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:
+                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:
+                db.rollback()
+                raise HTTPException(status_code=400, detail=f"添加字段失败:{str(e)}")
+
+
 
 class ReportUpdate(BaseModel):
     table_name: Optional[str] = None
     status: Optional[int] = None
     period_type: Optional[str] = None
     end_time: Optional[str] = None
-    comments: Optional[Dict[str, str]] = None
-    new_fields: Optional[List[Dict[str, str]]] = None
+    # comments: Optional[Dict[str, str]] = None
+    new_fields: Optional[List[str]] = Field(None, description="字段名称列表,非必填")
 
     class Config:
         extra = 'allow'
 
-# 动态添加字段到表
-def add_column_if_not_exists(table_name: str, column_name: str, column_type: str, comment: str, db: Session):
+
+
+
+
+def table_exists(db: Session, table_name: str) -> bool:
     inspector = inspect(db.bind)
-    columns = inspector.get_columns(table_name)
-    existing_column_names = {column['name'] for column in columns}
-    if column_name not in existing_column_names:
+    return inspector.has_table(table_name)
+
+
+# 删除表(如果存在)
+def drop_table_if_exists(db: Session, table_name: str):
+    inspector = inspect(db.bind)
+    if inspector.has_table(table_name):
         try:
-            db.execute(
-                text(f"""
-                ALTER TABLE {table_name} ADD COLUMN {column_name} {column_type} COMMENT :comment
-                """),
-                {"comment": comment}
-            )
+            # 删除表
+            db.execute(text(f"DROP TABLE {table_name}"))
+            # 清理 MetaData 中的表定义
+            metadata.reflect(bind=db.bind)
+            if table_name in metadata.tables:
+                del metadata.tables[table_name]
         except Exception as e:
             db.rollback()
-            raise HTTPException(status_code=400, detail=str(e))
+            raise HTTPException(status_code=400, detail=f"删除表失败:{str(e)}")
+
+
+
+
+
 
 #修改
 @router.put("/report/{report_id}/")
@@ -361,12 +506,35 @@ async def update_report(
     creator_id = Depends(valid_access_token)
 ):
     # creator_id = '1'  # 假设creator_id已经通过某种方式验证
-    report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id).first()
+    # 这里得添加下,如果是已经下发的,那就不能修改了,只有待发布(暂存状态)才可以修改   暂存:保存至“待发布”状态
+    #.filter(ReportManagement.creator_id == creator_id)
+    report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id,
+                                               ReportManagement.creator_id == creator_id).first()
     if not report:
         raise HTTPException(status_code=404, detail="Report not found")
 
-    if report.creator_id != creator_id:
-        raise HTTPException(status_code=403, detail="没有权限更新此报告")
+    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="当前表单已收取,无法修改")
+
+
+
+    # 检查表是否存在
+    table_name = report.data_table_name
+    if not table_exists(db, table_name):
+        # 如果表不存在,根据 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:
+
+        update_table_fields(table_name, update_data.new_fields, db)
 
     # 更新字段
     if update_data.table_name:
@@ -381,22 +549,13 @@ async def update_report(
     if update_data.end_time:
         report.end_time = datetime.fromisoformat(update_data.end_time)
 
-    # 更新字段备注
-    if update_data.comments:
-        for column_name, comment in update_data.comments.items():
-            db.execute(
-                text(f"""
-                ALTER TABLE {report.data_table_name} CHANGE {column_name} {column_name} TEXT COMMENT :comment
-                """),
-                {"comment": comment}
-            )
+    current_time = datetime.now()
+    report.updated_at = current_time
+
+    #先判断状态,未发布/暂存 的可以修改
+    #先看看传入参数有没有修改字段,有修改字段的时候,先看看有没有表,如果没有表,没有的话就读取表单里面的表名,再读取字段参数进行建表
+    #如果已经有表了,那就读取表单里的表名,再读取字段参数,然后删掉原有的表,再进行建表
 
-    # 添加新字段
-    if update_data.new_fields:
-        for field in update_data.new_fields:
-            column_name = field['field_name']
-            comment = field['comment']
-            add_column_if_not_exists(report.data_table_name, column_name, 'TEXT', comment, db)
 
     db.commit()
     db.refresh(report)
@@ -405,6 +564,10 @@ async def update_report(
         "code": 200,
         "msg": "操作成功"
     }
+
+
+
+
 #发布
 @router.put("/report/{report_id}/update_status/")
 async def update_report_status_and_time(
@@ -418,10 +581,9 @@ async def update_report_status_and_time(
     report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id).first()
     if not report:
         raise HTTPException(status_code=404, detail="Report not found")
-    print(report.creator_id,creator_id)
     # 验证请求者ID
     if str(report.creator_id) != str(creator_id):
-        raise HTTPException(status_code=403, detail="没有权限更新此报告")
+        raise HTTPException(status_code=403, detail="没有权限操作")
 
     if report.issued_status ==2:
         raise HTTPException(status_code=403, detail="不可重复发布")
@@ -429,7 +591,7 @@ async def update_report_status_and_time(
     report.issued_status = 2
 
     # 更新create_time为当前时间
-    report.start_time = datetime.utcnow()
+    report.issued_time = datetime.utcnow()
 
     try:
         db.commit()
@@ -575,7 +737,7 @@ async def submit_data(
 ):
     # 检查用户ID和填报ID是否提供
     if not user_id or not submit_data.report_id:
-        raise HTTPException(status_code=400, detail="用户ID和填报ID是必填项")
+        raise HTTPException(status_code=400, detail="填报ID是必填项")
 
     # 获取对应填报ID的数据表名称
     report = db.query(ReportManagement).filter(ReportManagement.report_id == submit_data.report_id).first()
@@ -586,6 +748,14 @@ async def submit_data(
     if not data_table_name:
         raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
 
+    if report.issued_status not in [2,'2']:
+        raise HTTPException(status_code=404, detail="当前未发布,不可填写")
+
+    is_collection = report.collection_status
+
+    if is_collection == 2 or is_collection == '2':
+        raise HTTPException(status_code=404, detail="管理员已收取信息,无法填写")
+
     # 检查用户是否有权限填报
     submission = db.query(FormSubmission).filter(
         FormSubmission.report_id == submit_data.report_id,
@@ -593,8 +763,13 @@ async def submit_data(
     ).first()
     if not submission:
         raise HTTPException(status_code=403, detail="用户没有填报权限")
-    # print(report.creator_id,submit_data.user_id)
-    # if submission.
+
+
+    current_time = datetime.now()
+
+    if report.end_time < current_time:
+        raise HTTPException(status_code=403, detail="填写时间已过")
+
 
     # 将数据写入数据库
     for item in submit_data.data:
@@ -603,7 +778,6 @@ async def submit_data(
         values = ', '.join(
             [f":{k}" for k in item.keys()] + [f"'{report.creator_id}'", f"'{user_id}'", '1'])
         sql = f"INSERT INTO {data_table_name} ({columns}) VALUES ({values})"
-        print(sql)
         # 执行插入操作
         db.execute(text(sql), item)
 
@@ -655,7 +829,6 @@ async def get_submission_status(
 
     start_time = report.start_time
     end_time = report.end_time
-    print(start_time,end_time)
 
     start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S')
     end_time_str = end_time.strftime('%Y-%m-%d %H:%M:%S')
@@ -713,7 +886,7 @@ def has_matching_column_comments(
 ) -> bool:
     return bool(get_columns_with_comment_like(inspector, table_name, comment_like))
 
-
+#【数据档案管理】-列表
 @router.post("/reports_by_creator")
 @router.get("/reports_by_creator")
 async def get_reports_by_creator(
@@ -729,6 +902,10 @@ async def get_reports_by_creator(
     # 查询 ReportManagement 表以获取所有相关的记录
     query = db.query(ReportManagement).filter(ReportManagement.creator_id == creator_id)
 
+    query = query.order_by(
+        asc(ReportManagement.collection_status)  # 按 collection_status 升序
+    )
+
     # 计算总数
     total_count = query.count()
 
@@ -750,6 +927,22 @@ async def get_reports_by_creator(
 
         # 如果匹配成功,添加到结果中
         collection_time_str = report.collection_time.isoformat().replace('T', ' ') if report.collection_time else None
+
+        #在这里判断数据库
+
+        #收取状态
+        collection_status = report.collection_status
+        #结束时间
+        end_time = report.end_time
+        current_time = datetime.now()
+        if end_time < current_time and collection_status==0:
+            report.collection_status=2
+            report.collection_time = current_time
+
+            db.add(report)
+            db.commit()
+            db.refresh(report)
+
         results.append({
             "table_name": report.table_name,
             "collection_status": report.collection_status,
@@ -776,6 +969,8 @@ async def get_reports_by_creator(
 
 
 
+
+
 @router.put("/update_collection_status/")
 async def update_collection_status(
     # creator_id: str,
@@ -794,12 +989,19 @@ async def update_collection_status(
         ReportManagement.report_id == report_id
     ).first()
 
+
     # 如果没有找到记录,返回404
     if not report:
         raise HTTPException(status_code=404, detail="Report not found")
 
+    if report.collection_status == 2 or report.collection_status == '2':
+        raise HTTPException(status_code=404, detail="当前已收取,无需重复收取")
+
+
+    current_time_str = datetime.now().strftime("%Y%m%d%H%M%S")
     # 更新 collection_status
     report.collection_status = new_status
+    report.collection_time = current_time_str
     db.add(report)
     db.commit()
     db.refresh(report)
@@ -823,7 +1025,7 @@ async def get_records_by_creator_and_report(
     db: Session = Depends(get_db),
     creator_id = Depends(valid_access_token)
 ):
-    creator_id
+    # creator_id
     # 查询 ReportManagement 表以获取对应记录
     report = db.query(ReportManagement).filter(
         ReportManagement.creator_id == creator_id,
@@ -868,7 +1070,8 @@ async def get_records_by_creator_and_report(
     rows_data = []
     for row in rows:
         # 过滤掉不需要的列,并添加到结果中
-        filtered_row = {column: row[idx] for idx, column in enumerate(column_names) if column not in ['id', 'user_id', 'create_id', 'collect_status']}
+        filtered_row = {column: row[idx] for idx, column in enumerate(column_names)
+                        if column not in ['id', 'user_id', 'create_id', 'collect_status']}
         filtered_row['user_name'] = row[-1]  # 添加用户昵称
         rows_data.append(filtered_row)
 
@@ -884,3 +1087,65 @@ async def get_records_by_creator_and_report(
         "columns": columns_info,
         "rows": rows_data
     }
+
+
+
+
+
+
+
+# 批量导出填报数据为 Excel 文件
+@router.get("/export_to_excel")
+@router.post("/export_to_excel")
+async def export_to_excel(
+    report_id: str = Query(..., description="填报ID"),
+    db: Session = Depends(get_db),
+    creator_id = Depends(valid_access_token)
+):
+    # 获取对应填报ID的数据表名称
+    report = db.query(ReportManagement).filter(ReportManagement.report_id == report_id,
+                                               ReportManagement.creator_id == creator_id).first()
+    if not report:
+        raise HTTPException(status_code=404, detail="未找到对应的填报ID")
+
+    data_table_name = report.data_table_name
+    if not data_table_name:
+        raise HTTPException(status_code=404, detail="未找到对应的数据表名称")
+
+    # 获取表结构(用户填报的字段)
+    inspector = inspect(db.bind)
+    columns = inspector.get_columns(data_table_name)
+
+    # 提取用户填报的字段注释
+    user_report_columns = [col for col in columns if
+                           col['name'] not in ['id', 'create_id', 'collect_status', 'add_time','user_id']]
+    column_comments = [col.get('comment', '') for col in user_report_columns]
+
+    # 构建查询SQL,关联 sys_user 表获取 nick_name
+    query_sql = text(f"""
+        SELECT su.nick_name AS user_name, {', '.join([f'rd.{col["name"]}' for col in user_report_columns])}
+        FROM {data_table_name} rd
+        JOIN sys_user su ON rd.user_id = su.user_id
+    """)
+    print(query_sql)
+    # 查询数据
+    result = db.execute(query_sql)
+    rows = result.fetchall()
+
+    # 将查询结果转换为 DataFrame
+    df = pd.DataFrame(rows, columns=["user_name"] + column_comments)
+
+    # 将 DataFrame 导出为 Excel 文件
+    output = BytesIO()
+    with pd.ExcelWriter(output, engine='openpyxl') as writer:
+        df.to_excel(writer, index=False, sheet_name='填报数据')
+
+    # 设置响应头
+    output.seek(0)
+    headers = {
+        'Content-Disposition': 'attachment; filename="report_data.xlsx"',
+        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
+    }
+
+    # 返回文件流
+    return StreamingResponse(output, headers=headers)