Parcourir la source

Merge branch 'dev' of http://47.109.151.80:15030/CRBC-MaaS-Platform-Project/LQAdminPlatform into dev

lingmin_package@163.com il y a 1 mois
Parent
commit
2ef71fb70f

+ 22 - 16
src/app/server/app.py

@@ -1,29 +1,35 @@
-"""
-FastAPI应用服务器
-整合所有路由和中间件
-"""
 import sys
 import sys
 import os
 import os
-
-
-# 导入路径配置
-try:
-    import path_config  # 自动配置 Python 路径
-except ImportError:
-    # 手动配置路径(兼容性)
-    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))
-    sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../../..'))
-
+from contextlib import asynccontextmanager
 from fastapi import FastAPI, Request, status
 from fastapi import FastAPI, Request, status
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.middleware.cors import CORSMiddleware
 from fastapi.responses import JSONResponse
 from fastapi.responses import JSONResponse
 from fastapi.exceptions import RequestValidationError
 from fastapi.exceptions import RequestValidationError
-from contextlib import asynccontextmanager
 from datetime import datetime, timezone
 from datetime import datetime, timezone
 import logging
 import logging
 import logging.handlers
 import logging.handlers
 
 
-# 导入配置
+# 导入路径配置
+try:
+    import path_config  # 自动配置 Python 路径
+except ImportError:
+    # 手动配置路径(兼容性)
+    # D:\UGit\LQAdminPlatform\src\app\server\app.py -> D:\UGit\LQAdminPlatform\src
+    src_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
+    if src_path not in sys.path:
+        sys.path.insert(0, src_path)
+    
+    # D:\UGit\LQAdminPlatform\src\app\server\app.py -> D:\UGit\LQAdminPlatform
+    root_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..'))
+    if root_path not in sys.path:
+        sys.path.insert(0, root_path)
+    
+    # 尝试再次导入 path_config 以获取完整的路径配置(包括 app 目录等)
+    try:
+        import path_config
+    except ImportError:
+        pass
+
 from app.core.config import config_handler
 from app.core.config import config_handler
 from app.base import init_db, close_db, init_redis, close_redis
 from app.base import init_db, close_db, init_redis, close_redis
 from app.core.exceptions import BaseAPIException
 from app.core.exceptions import BaseAPIException

+ 163 - 35
src/app/services/sample_service.py

@@ -244,8 +244,13 @@ class SampleService:
             if table_type and table_type in TABLE_MAP:
             if table_type and table_type in TABLE_MAP:
                 # 如果指定了类型,使用 LEFT JOIN 关联查询,以便搜索子表字段
                 # 如果指定了类型,使用 LEFT JOIN 关联查询,以便搜索子表字段
                 sub_table = TABLE_MAP[table_type]
                 sub_table = TABLE_MAP[table_type]
-                from_sql = f"t_samp_document_main m LEFT JOIN {sub_table} s ON m.id = s.id"
-                fields_sql = "m.*, s.*"  # 获取所有字段,包括子表字段
+                from_sql = f"""
+                    t_samp_document_main m 
+                    LEFT JOIN {sub_table} s ON m.id = s.id
+                    LEFT JOIN t_sys_user u1 ON m.created_by = u1.id
+                    LEFT JOIN t_sys_user u2 ON m.updated_by = u2.id
+                """
+                fields_sql = "m.*, s.*, u1.username as creator_name, u2.username as updater_name, m.id as id"
                 where_clauses.append("m.source_type = %s")
                 where_clauses.append("m.source_type = %s")
                 params.append(table_type)
                 params.append(table_type)
                 order_sql = "m.created_time DESC"
                 order_sql = "m.created_time DESC"
@@ -265,14 +270,11 @@ class SampleService:
                     if level_4_classification:
                     if level_4_classification:
                         where_clauses.append("s.level_4_classification = %s")
                         where_clauses.append("s.level_4_classification = %s")
                         params.append(level_4_classification)
                         params.append(level_4_classification)
-                
-                # 特殊处理 id 冲突,确保返回的是主表 m.id
-                fields_sql = "m.*, s.*, m.id as id"
             else:
             else:
-                from_sql = "t_samp_document_main"
-                fields_sql = "*"
-                order_sql = "created_time DESC"
-                title_field = "title"
+                from_sql = "t_samp_document_main m LEFT JOIN t_sys_user u1 ON m.created_by = u1.id LEFT JOIN t_sys_user u2 ON m.updated_by = u2.id"
+                fields_sql = "m.*, u1.username as creator_name, u2.username as updater_name"
+                order_sql = "m.created_time DESC"
+                title_field = "m.title"
             
             
             if whether_to_enter is not None:
             if whether_to_enter is not None:
                 # 按照 search_replace_blocks 的逻辑,这里使用 conversion_status 过滤
                 # 按照 search_replace_blocks 的逻辑,这里使用 conversion_status 过滤
@@ -355,8 +357,14 @@ class SampleService:
         cursor = conn.cursor()
         cursor = conn.cursor()
         
         
         try:
         try:
-            # 1. 查询主表
-            cursor.execute("SELECT * FROM t_samp_document_main WHERE id = %s", (doc_id,))
+            # 1. 查询主表 (关联用户表获取姓名)
+            cursor.execute("""
+                SELECT m.*, u1.username as creator_name, u2.username as updater_name
+                FROM t_samp_document_main m
+                LEFT JOIN t_sys_user u1 ON m.created_by = u1.id
+                LEFT JOIN t_sys_user u2 ON m.updated_by = u2.id
+                WHERE m.id = %s
+            """, (doc_id,))
             doc = cursor.fetchone()
             doc = cursor.fetchone()
             if not doc:
             if not doc:
                 return None
                 return None
@@ -470,18 +478,56 @@ class SampleService:
             # 2. 插入子表 (仅存储业务字段)
             # 2. 插入子表 (仅存储业务字段)
             if table_type == 'basis':
             if table_type == 'basis':
                 cursor.execute(
                 cursor.execute(
-                    f"INSERT INTO {table_name} (id, chinese_name, standard_number, issuing_authority, release_date, document_type, professional_field, validity, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())",
-                    (doc_id, doc_data.get('title'), doc_data.get('standard_no'), doc_data.get('issuing_authority'), release_date, doc_data.get('document_type'), doc_data.get('professional_field'), doc_data.get('validity'), doc_data.get('note'), user_id)
+                    f"""
+                    INSERT INTO {table_name} (
+                        id, chinese_name, english_name, standard_number, issuing_authority, 
+                        release_date, implementation_date, drafting_unit, approving_department,
+                        participating_units, document_type, professional_field, engineering_phase,
+                        validity, reference_basis, source_url, note,
+                        created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                    """,
+                    (
+                        doc_id, doc_data.get('title'), doc_data.get('english_name'), doc_data.get('standard_no'), 
+                        doc_data.get('issuing_authority'), release_date, self._to_date(doc_data.get('implementation_date')),
+                        doc_data.get('drafting_unit'), doc_data.get('approving_department'), doc_data.get('participating_units'),
+                        doc_data.get('document_type'), doc_data.get('professional_field'), doc_data.get('engineering_phase'),
+                        doc_data.get('validity'), doc_data.get('reference_basis'), doc_data.get('source_url'), doc_data.get('note'),
+                        user_id, user_id
+                    )
                 )
                 )
             elif table_type == 'work':
             elif table_type == 'work':
                 cursor.execute(
                 cursor.execute(
-                    f"INSERT INTO {table_name} (id, plan_name, project_name, project_section, compiling_unit, compiling_date, plan_summary, compilation_basis, plan_category, level_1_classification, level_2_classification, level_3_classification, level_4_classification, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())",
-                    (doc_id, doc_data.get('title'), doc_data.get('project_name'), doc_data.get('project_section'), doc_data.get('issuing_authority'), release_date, doc_data.get('plan_summary'), doc_data.get('compilation_basis'), doc_data.get('plan_category'), doc_data.get('level_1_classification'), doc_data.get('level_2_classification'), doc_data.get('level_3_classification'), doc_data.get('level_4_classification'), doc_data.get('note'), user_id)
+                    f"""
+                    INSERT INTO {table_name} (
+                        id, plan_name, project_name, project_section, compiling_unit, 
+                        compiling_date, plan_summary, compilation_basis, plan_category, 
+                        level_1_classification, level_2_classification, level_3_classification, level_4_classification, 
+                        note, created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                    """,
+                    (
+                        doc_id, doc_data.get('title'), doc_data.get('project_name'), doc_data.get('project_section'), 
+                        doc_data.get('issuing_authority'), release_date, doc_data.get('plan_summary'), 
+                        doc_data.get('compilation_basis'), doc_data.get('plan_category'), doc_data.get('level_1_classification'), 
+                        doc_data.get('level_2_classification'), doc_data.get('level_3_classification'), doc_data.get('level_4_classification'), 
+                        doc_data.get('note'), user_id, user_id
+                    )
                 )
                 )
             elif table_type == 'job':
             elif table_type == 'job':
                 cursor.execute(
                 cursor.execute(
-                    f"INSERT INTO {table_name} (id, file_name, issuing_department, document_type, publish_date, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW())",
-                    (doc_id, doc_data.get('title'), doc_data.get('issuing_authority'), doc_data.get('document_type'), release_date, doc_data.get('note'), user_id)
+                    f"""
+                    INSERT INTO {table_name} (
+                        id, file_name, issuing_department, document_type, publish_date, 
+                        effective_start_date, effective_end_date, note, 
+                        created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                    """,
+                    (
+                        doc_id, doc_data.get('title'), doc_data.get('issuing_authority'), doc_data.get('document_type'), 
+                        release_date, self._to_date(doc_data.get('effective_start_date')), self._to_date(doc_data.get('effective_end_date')),
+                        doc_data.get('note'), user_id, user_id
+                    )
                 )
                 )
             
             
             # 3. 添加到任务管理中心 (类型为 data)
             # 3. 添加到任务管理中心 (类型为 data)
@@ -536,18 +582,54 @@ class SampleService:
             # 2. 更新子表
             # 2. 更新子表
             if table_type == 'basis':
             if table_type == 'basis':
                 cursor.execute(
                 cursor.execute(
-                    f"UPDATE {table_name} SET chinese_name = %s, standard_number = %s, issuing_authority = %s, release_date = %s, document_type = %s, professional_field = %s, validity = %s, note = %s, updated_by = %s, updated_time = NOW() WHERE id = %s",
-                    (doc_data.get('title'), doc_data.get('standard_no'), doc_data.get('issuing_authority'), release_date, doc_data.get('document_type'), doc_data.get('professional_field'), doc_data.get('validity'), doc_data.get('note'), updater_id, doc_id)
+                    f"""
+                    UPDATE {table_name} SET 
+                        chinese_name = %s, english_name = %s, standard_number = %s, issuing_authority = %s, 
+                        release_date = %s, implementation_date = %s, drafting_unit = %s, approving_department = %s,
+                        participating_units = %s, document_type = %s, professional_field = %s, engineering_phase = %s,
+                        validity = %s, reference_basis = %s, source_url = %s, note = %s, 
+                        updated_by = %s, updated_time = NOW() 
+                    WHERE id = %s
+                    """,
+                    (
+                        doc_data.get('title'), doc_data.get('english_name'), doc_data.get('standard_no'), doc_data.get('issuing_authority'), 
+                        release_date, self._to_date(doc_data.get('implementation_date')), doc_data.get('drafting_unit'), doc_data.get('approving_department'),
+                        doc_data.get('participating_units'), doc_data.get('document_type'), doc_data.get('professional_field'), doc_data.get('engineering_phase'),
+                        doc_data.get('validity'), doc_data.get('reference_basis'), doc_data.get('source_url'), doc_data.get('note'),
+                        updater_id, doc_id
+                    )
                 )
                 )
             elif table_type == 'work':
             elif table_type == 'work':
                 cursor.execute(
                 cursor.execute(
-                    f"UPDATE {table_name} SET plan_name = %s, project_name = %s, project_section = %s, compiling_unit = %s, compiling_date = %s, plan_summary = %s, compilation_basis = %s, plan_category = %s, level_1_classification = %s, level_2_classification = %s, level_3_classification = %s, level_4_classification = %s, note = %s, updated_by = %s, updated_time = NOW() WHERE id = %s",
-                    (doc_data.get('title'), doc_data.get('project_name'), doc_data.get('project_section'), doc_data.get('issuing_authority'), release_date, doc_data.get('plan_summary'), doc_data.get('compilation_basis'), doc_data.get('plan_category'), doc_data.get('level_1_classification'), doc_data.get('level_2_classification'), doc_data.get('level_3_classification'), doc_data.get('level_4_classification'), doc_data.get('note'), updater_id, doc_id)
+                    f"""
+                    UPDATE {table_name} SET 
+                        plan_name = %s, project_name = %s, project_section = %s, compiling_unit = %s, 
+                        compiling_date = %s, plan_summary = %s, compilation_basis = %s, plan_category = %s, 
+                        level_1_classification = %s, level_2_classification = %s, level_3_classification = %s, level_4_classification = %s, 
+                        note = %s, updated_by = %s, updated_time = NOW() 
+                    WHERE id = %s
+                    """,
+                    (
+                        doc_data.get('title'), doc_data.get('project_name'), doc_data.get('project_section'), doc_data.get('issuing_authority'), 
+                        release_date, doc_data.get('plan_summary'), doc_data.get('compilation_basis'), doc_data.get('plan_category'), 
+                        doc_data.get('level_1_classification'), doc_data.get('level_2_classification'), doc_data.get('level_3_classification'), doc_data.get('level_4_classification'), 
+                        doc_data.get('note'), updater_id, doc_id
+                    )
                 )
                 )
             elif table_type == 'job':
             elif table_type == 'job':
                 cursor.execute(
                 cursor.execute(
-                    f"UPDATE {table_name} SET file_name = %s, issuing_department = %s, document_type = %s, publish_date = %s, note = %s, updated_by = %s, updated_time = NOW() WHERE id = %s",
-                    (doc_data.get('title'), doc_data.get('issuing_authority'), doc_data.get('document_type'), release_date, doc_data.get('note'), updater_id, doc_id)
+                    f"""
+                    UPDATE {table_name} SET 
+                        file_name = %s, issuing_department = %s, document_type = %s, publish_date = %s, 
+                        effective_start_date = %s, effective_end_date = %s, note = %s, 
+                        updated_by = %s, updated_time = NOW() 
+                    WHERE id = %s
+                    """,
+                    (
+                        doc_data.get('title'), doc_data.get('issuing_authority'), doc_data.get('document_type'), release_date, 
+                        self._to_date(doc_data.get('effective_start_date')), self._to_date(doc_data.get('effective_end_date')), doc_data.get('note'), 
+                        updater_id, doc_id
+                    )
                 )
                 )
 
 
             conn.commit()
             conn.commit()
@@ -588,8 +670,9 @@ class SampleService:
                 fields = """
                 fields = """
                     s.id, s.chinese_name as title, s.standard_number as standard_no, 
                     s.id, s.chinese_name as title, s.standard_number as standard_no, 
                     s.issuing_authority, s.release_date, s.document_type, 
                     s.issuing_authority, s.release_date, s.document_type, 
-                    s.professional_field, s.validity, s.note, s.created_by, s.created_time,
-                    s.updated_by, s.updated_time,
+                    s.professional_field, s.validity, s.note, 
+                    s.created_by, u1.username as creator_name, s.created_time,
+                    s.updated_by, u2.username as updater_name, s.updated_time,
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                 """
                 """
                 field_map = {
                 field_map = {
@@ -611,7 +694,9 @@ class SampleService:
                     s.plan_summary, s.compilation_basis,
                     s.plan_summary, s.compilation_basis,
                     s.plan_category, s.level_1_classification, s.level_2_classification,
                     s.plan_category, s.level_1_classification, s.level_2_classification,
                     s.level_3_classification, s.level_4_classification,
                     s.level_3_classification, s.level_4_classification,
-                    s.note, s.created_by, s.created_time, s.updated_by, s.updated_time,
+                    s.note, 
+                    s.created_by, u1.username as creator_name, s.created_time,
+                    s.updated_by, u2.username as updater_name, s.updated_time,
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                 """
                 """
                 field_map = {
                 field_map = {
@@ -630,7 +715,9 @@ class SampleService:
                     s.id, s.file_name as title, NULL as standard_no, 
                     s.id, s.file_name as title, NULL as standard_no, 
                     s.issuing_department as issuing_authority, s.publish_date as release_date, 
                     s.issuing_department as issuing_authority, s.publish_date as release_date, 
                     s.document_type, NULL as professional_field, NULL as validity, 
                     s.document_type, NULL as professional_field, NULL as validity, 
-                    s.note, s.created_by, s.created_time, s.updated_by, s.updated_time,
+                    s.note, 
+                    s.created_by, u1.username as creator_name, s.created_time,
+                    s.updated_by, u2.username as updater_name, s.updated_time,
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                     m.file_url, m.conversion_status, m.md_url, m.json_url
                 """
                 """
                 field_map = {
                 field_map = {
@@ -670,11 +757,13 @@ class SampleService:
             where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
             where_sql = " WHERE " + " AND ".join(where_clauses) if where_clauses else ""
             offset = (page - 1) * size
             offset = (page - 1) * size
             
             
-            # 使用 LEFT JOIN 关联主表
+            # 使用 LEFT JOIN 关联主表和用户表获取姓名
             sql = f"""
             sql = f"""
                 SELECT {fields} 
                 SELECT {fields} 
                 FROM {table_name} s
                 FROM {table_name} s
                 LEFT JOIN t_samp_document_main m ON s.id = m.id
                 LEFT JOIN t_samp_document_main m ON s.id = m.id
+                LEFT JOIN t_sys_user u1 ON s.created_by = u1.id
+                LEFT JOIN t_sys_user u2 ON s.updated_by = u2.id
                 {where_sql} 
                 {where_sql} 
                 ORDER BY s.created_time DESC 
                 ORDER BY s.created_time DESC 
                 LIMIT %s OFFSET %s
                 LIMIT %s OFFSET %s
@@ -829,14 +918,52 @@ class SampleService:
             
             
             # 2. 插入子表 (移除 file_url,因为它现在只存储在主表中)
             # 2. 插入子表 (移除 file_url,因为它现在只存储在主表中)
             if type == 'basis':
             if type == 'basis':
-                sql = f"INSERT INTO {table_name} (id, chinese_name, standard_number, issuing_authority, release_date, document_type, professional_field, validity, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())"
-                params = (doc_id, data.get('title'), data.get('standard_no'), data.get('issuing_authority'), self._to_date(data.get('release_date')), data.get('document_type'), data.get('professional_field'), data.get('validity', '现行'), data.get('note'), user_id)
+                sql = f"""
+                    INSERT INTO {table_name} (
+                        id, chinese_name, english_name, standard_number, issuing_authority, 
+                        release_date, implementation_date, drafting_unit, approving_department,
+                        participating_units, document_type, professional_field, engineering_phase,
+                        validity, reference_basis, source_url, note,
+                        created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                """
+                params = (
+                    doc_id, data.get('title'), data.get('english_name'), data.get('standard_no'), 
+                    data.get('issuing_authority'), self._to_date(data.get('release_date')), self._to_date(data.get('implementation_date')),
+                    data.get('drafting_unit'), data.get('approving_department'), data.get('participating_units'),
+                    data.get('document_type'), data.get('professional_field'), data.get('engineering_phase'),
+                    data.get('validity', '现行'), data.get('reference_basis'), data.get('source_url'), data.get('note'),
+                    user_id, user_id
+                )
             elif type == 'work':
             elif type == 'work':
-                sql = f"INSERT INTO {table_name} (id, plan_name, project_name, project_section, compiling_unit, compiling_date, plan_summary, compilation_basis, plan_category, level_1_classification, level_2_classification, level_3_classification, level_4_classification, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())"
-                params = (doc_id, data.get('title'), data.get('project_name'), data.get('project_section'), data.get('issuing_authority'), self._to_date(data.get('release_date')), data.get('plan_summary'), data.get('compilation_basis'), data.get('plan_category'), data.get('level_1_classification'), data.get('level_2_classification'), data.get('level_3_classification'), data.get('level_4_classification'), data.get('note'), user_id)
+                sql = f"""
+                    INSERT INTO {table_name} (
+                        id, plan_name, project_name, project_section, compiling_unit, 
+                        compiling_date, plan_summary, compilation_basis, plan_category, 
+                        level_1_classification, level_2_classification, level_3_classification, level_4_classification, 
+                        note, created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                """
+                params = (
+                    doc_id, data.get('title'), data.get('project_name'), data.get('project_section'), 
+                    data.get('issuing_authority'), self._to_date(data.get('release_date')), data.get('plan_summary'), 
+                    data.get('compilation_basis'), data.get('plan_category'), data.get('level_1_classification'), 
+                    data.get('level_2_classification'), data.get('level_3_classification'), data.get('level_4_classification'), 
+                    data.get('note'), user_id, user_id
+                )
             elif type == 'job':
             elif type == 'job':
-                sql = f"INSERT INTO {table_name} (id, file_name, issuing_department, document_type, publish_date, note, created_by, created_time, updated_time) VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW())"
-                params = (doc_id, data.get('title'), data.get('issuing_authority'), data.get('document_type'), self._to_date(data.get('release_date')), data.get('note'), user_id)
+                sql = f"""
+                    INSERT INTO {table_name} (
+                        id, file_name, issuing_department, document_type, publish_date, 
+                        effective_start_date, effective_end_date, note, 
+                        created_by, updated_by, created_time, updated_time
+                    ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
+                """
+                params = (
+                    doc_id, data.get('title'), data.get('issuing_authority'), data.get('document_type'), 
+                    self._to_date(data.get('release_date')), self._to_date(data.get('effective_start_date')), self._to_date(data.get('effective_end_date')),
+                    data.get('note'), user_id, user_id
+                )
             else:
             else:
                 return False, "不支持的类型"
                 return False, "不支持的类型"
             
             
@@ -916,7 +1043,8 @@ class SampleService:
                 """
                 """
                 
                 
                 params = (
                 params = (
-                    data.get('title'), data.get('project_name'), data.get('project_section'), data.get('issuing_authority'), self._to_date(data.get('release_date')),
+                    data.get('title'), data.get('project_name'), data.get('project_section'), 
+                    data.get('issuing_authority'), self._to_date(data.get('release_date')),
                     data.get('plan_summary'), data.get('compilation_basis'), data.get('plan_category'),
                     data.get('plan_summary'), data.get('compilation_basis'), data.get('plan_category'),
                     data.get('level_1_classification'), data.get('level_2_classification'), data.get('level_3_classification'), data.get('level_4_classification'),
                     data.get('level_1_classification'), data.get('level_2_classification'), data.get('level_3_classification'), data.get('level_4_classification'),
                     data.get('note'), updater_id, info_id
                     data.get('note'), updater_id, info_id

+ 9 - 9
src/app/services/tag_category_service.py

@@ -286,13 +286,12 @@ class TagCategoryService:
         
         
         # 批量查询用户信息
         # 批量查询用户信息
         user_map = {}
         user_map = {}
-        for user_id in user_ids:
+        if user_ids:
             try:
             try:
-                user = await self.user_service.get_user_by_id(user_id)
-                if user:
-                    user_map[user_id] = user.username
+                users = await self.user_service.get_users_by_ids(list(user_ids))
+                user_map = {user.id: user.username for user in users}
             except Exception as e:
             except Exception as e:
-                logger.warning(f"查询用户 {user_id} 失败: {str(e)}")
+                logger.warning(f"批量查询用户信息失败: {str(e)}")
         
         
         # 递归填充每个节点
         # 递归填充每个节点
         self._enrich_node_with_names(tree, category_map, user_map)
         self._enrich_node_with_names(tree, category_map, user_map)
@@ -515,10 +514,11 @@ class TagCategoryService:
         # 批量查询用户名
         # 批量查询用户名
         user_map = {}
         user_map = {}
         if user_ids:
         if user_ids:
-            for user_id in user_ids:
-                user = await self.user_service.get_user_by_id(user_id)
-                if user:
-                    user_map[user_id] = user.username
+            try:
+                users = await self.user_service.get_users_by_ids(list(user_ids))
+                user_map = {user.id: user.username for user in users}
+            except Exception as e:
+                logger.warning(f"批量查询用户信息失败: {str(e)}")
         
         
         # 如果指定了 parent_id,所有分类都有相同的父分类,只需查询一次
         # 如果指定了 parent_id,所有分类都有相同的父分类,只需查询一次
         parent_name = None
         parent_name = None

+ 11 - 8
src/app/services/task_service.py

@@ -25,11 +25,12 @@ class TaskService:
                 sql = """
                 sql = """
                     SELECT 
                     SELECT 
                         t.id, 
                         t.id, 
+                        t.business_id,
                         t.task_id, 
                         t.task_id, 
                         t.type,
                         t.type,
                         d.title as name
                         d.title as name
                     FROM t_task_management t
                     FROM t_task_management t
-                    JOIN t_samp_document_main d ON t.id COLLATE utf8mb4_unicode_ci = d.id COLLATE utf8mb4_unicode_ci
+                    JOIN t_samp_document_main d ON t.business_id COLLATE utf8mb4_unicode_ci = d.id COLLATE utf8mb4_unicode_ci
                     WHERE t.type = 'data'
                     WHERE t.type = 'data'
                     ORDER BY d.created_time DESC
                     ORDER BY d.created_time DESC
                 """
                 """
@@ -38,11 +39,12 @@ class TaskService:
                 sql = """
                 sql = """
                     SELECT 
                     SELECT 
                         t.id, 
                         t.id, 
+                        t.business_id,
                         t.task_id, 
                         t.task_id, 
                         t.type,
                         t.type,
                         i.image_name as name
                         i.image_name as name
                     FROM t_task_management t
                     FROM t_task_management t
-                    JOIN t_image_info i ON t.id COLLATE utf8mb4_unicode_ci = i.id COLLATE utf8mb4_unicode_ci
+                    JOIN t_image_info i ON t.business_id COLLATE utf8mb4_unicode_ci = i.id COLLATE utf8mb4_unicode_ci
                     WHERE t.type = 'image'
                     WHERE t.type = 'image'
                     ORDER BY i.created_time DESC
                     ORDER BY i.created_time DESC
                 """
                 """
@@ -58,7 +60,7 @@ class TaskService:
             cursor.close()
             cursor.close()
             conn.close()
             conn.close()
 
 
-    async def add_task(self, id: str, task_type: str, task_id: str = None) -> Tuple[bool, str]:
+    async def add_task(self, business_id: str, task_type: str, task_id: str = None) -> Tuple[bool, str]:
         """添加任务记录"""
         """添加任务记录"""
         conn = get_db_connection()
         conn = get_db_connection()
         if not conn:
         if not conn:
@@ -66,12 +68,13 @@ class TaskService:
         
         
         cursor = conn.cursor()
         cursor = conn.cursor()
         try:
         try:
+            # 使用 business_id 作为外键关联,id 为自增主键
             sql = """
             sql = """
-                INSERT INTO t_task_management (id, task_id, type)
+                INSERT INTO t_task_management (business_id, task_id, type)
                 VALUES (%s, %s, %s)
                 VALUES (%s, %s, %s)
                 ON DUPLICATE KEY UPDATE task_id = VALUES(task_id)
                 ON DUPLICATE KEY UPDATE task_id = VALUES(task_id)
             """
             """
-            cursor.execute(sql, (id, task_id, task_type))
+            cursor.execute(sql, (business_id, task_id, task_type))
             conn.commit()
             conn.commit()
             return True, "添加成功"
             return True, "添加成功"
         except Exception as e:
         except Exception as e:
@@ -82,7 +85,7 @@ class TaskService:
             cursor.close()
             cursor.close()
             conn.close()
             conn.close()
 
 
-    async def delete_task(self, id: str) -> Tuple[bool, str]:
+    async def delete_task(self, business_id: str) -> Tuple[bool, str]:
         """删除任务记录"""
         """删除任务记录"""
         conn = get_db_connection()
         conn = get_db_connection()
         if not conn:
         if not conn:
@@ -90,8 +93,8 @@ class TaskService:
         
         
         cursor = conn.cursor()
         cursor = conn.cursor()
         try:
         try:
-            sql = "DELETE FROM t_task_management WHERE id = %s"
-            cursor.execute(sql, (id,))
+            sql = "DELETE FROM t_task_management WHERE business_id = %s"
+            cursor.execute(sql, (business_id,))
             conn.commit()
             conn.commit()
             return True, "删除成功"
             return True, "删除成功"
         except Exception as e:
         except Exception as e:

+ 13 - 0
src/app/services/user_service.py

@@ -29,4 +29,17 @@ class UserService:
         except Exception as e:
         except Exception as e:
             logger.error(f"根据ID获取用户失败: user_id={user_id}, error={str(e)}")
             logger.error(f"根据ID获取用户失败: user_id={user_id}, error={str(e)}")
             return None
             return None
+
+    async def get_users_by_ids(self, user_ids: List[str]) -> List[User]:
+        """批量根据用户ID获取用户对象"""
+        if not user_ids:
+            return []
+        try:
+            result = await self.session.execute(
+                select(User).where(User.id.in_(user_ids))
+            )
+            return result.scalars().all()
+        except Exception as e:
+            logger.error(f"批量获取用户失败: user_ids={user_ids}, error={str(e)}")
+            return []
     
     

+ 6 - 6
src/views/sample_view.py

@@ -228,7 +228,7 @@ async def batch_enter_knowledge_base(req: BatchEnterRequest, credentials: HTTPAu
         if not payload or not payload.get("is_superuser"):
         if not payload or not payload.get("is_superuser"):
             return ApiResponse(code=403, message="权限不足", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=403, message="权限不足", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
         
         
-        username = payload.get("username", "admin")
+        username = payload.get("sub", "admin")
         sample_service = SampleService()
         sample_service = SampleService()
         
         
         affected_rows, message = await sample_service.batch_enter_knowledge_base(req.ids, username)
         affected_rows, message = await sample_service.batch_enter_knowledge_base(req.ids, username)
@@ -329,7 +329,7 @@ async def add_document(doc: DocumentAdd, credentials: HTTPAuthorizationCredentia
         if not payload:
         if not payload:
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
         
         
-        user_id = payload.get("username", "admin")
+        user_id = payload.get("sub", "admin")
         sample_service = SampleService()
         sample_service = SampleService()
         
         
         # 将 DocumentAdd 对象转换为字典
         # 将 DocumentAdd 对象转换为字典
@@ -457,7 +457,7 @@ async def edit_document(doc: DocumentAdd, credentials: HTTPAuthorizationCredenti
         sample_service = SampleService()
         sample_service = SampleService()
         
         
         # 获取更新人ID
         # 获取更新人ID
-        updater_id = payload.get("username", "admin")
+        updater_id = payload.get("sub", "admin")
         
         
         # 将 DocumentAdd 对象转换为字典
         # 将 DocumentAdd 对象转换为字典
         doc_data = {
         doc_data = {
@@ -507,7 +507,7 @@ async def enter_document(data: dict, credentials: HTTPAuthorizationCredentials =
             return ApiResponse(code=400, message="缺少ID", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=400, message="缺少ID", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             
             
         payload = verify_token(credentials.credentials)
         payload = verify_token(credentials.credentials)
-        username = payload.get("username", "admin") if payload else "admin"
+        username = payload.get("sub", "admin") if payload else "admin"
         
         
         # 调用 service 层
         # 调用 service 层
         sample_service = SampleService()
         sample_service = SampleService()
@@ -608,7 +608,7 @@ async def add_basic_info(type: str, data: dict, credentials: HTTPAuthorizationCr
         if not payload:
         if not payload:
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
         
         
-        user_id = payload.get("username", "admin")
+        user_id = payload.get("sub", "admin")
         sample_service = SampleService()
         sample_service = SampleService()
         success, message, doc_id = await sample_service.add_basic_info(type, data, user_id)
         success, message, doc_id = await sample_service.add_basic_info(type, data, user_id)
         
         
@@ -629,7 +629,7 @@ async def edit_basic_info(type: str, id: str, data: dict, credentials: HTTPAutho
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=401, message="无效的访问令牌", timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
         
         
         sample_service = SampleService()
         sample_service = SampleService()
-        success, message = await sample_service.edit_basic_info(type, id, data, payload.get("username", "admin"))
+        success, message = await sample_service.edit_basic_info(type, id, data, payload.get("sub", "admin"))
         
         
         if success:
         if success:
             return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()
             return ApiResponse(code=0, message=message, timestamp=datetime.now(timezone.utc).isoformat()).model_dump()