from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from sqlalchemy import func from typing import List, Optional import json from database import get_db from models.template import Template from models.company import Company from models.user import User from schemas.template import TemplateResponse, TemplateCreate, TemplateUpdate, TemplateStatusUpdate from routers.auth import get_current_user, get_current_superadmin from routers.operation_log import create_operation_log router = APIRouter() # 获取模板列表 @router.get("/", response_model=List[TemplateResponse]) async def get_templates( current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): # 普通用户只能看到可用的模板,超级管理员可以看到所有模板 if current_user.is_superadmin: templates = db.query(Template).all() else: templates = db.query(Template).filter(Template.status == 1).all() # 转换features和regions字段从JSON字符串到列表 result = [] for template in templates: template_dict = { 'id': template.id, 'key': template.key, 'name': template.name, 'description': template.description, 'color': template.color, 'features': [], 'applicable_scene': template.applicable_scene, 'regions': [], 'select_count': template.select_count or 0, 'use_count': template.use_count or 0, 'status': template.status or 0, 'created_at': template.created_at, 'updated_at': template.updated_at } if template.features: try: template_dict['features'] = json.loads(template.features) except: template_dict['features'] = [] if template.regions: try: template_dict['regions'] = json.loads(template.regions) except: template_dict['regions'] = [] result.append(template_dict) return result # 通过模板key获取模板信息 @router.get("/{template_key}", response_model=TemplateResponse) async def get_template_by_key( template_key: str, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): template = db.query(Template).filter(Template.key == template_key).first() if template is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Template with key '{template_key}' not found" ) # 构造响应数据 template_dict = { 'id': template.id, 'key': template.key, 'name': template.name, 'description': template.description, 'color': template.color, 'features': [], 'applicable_scene': template.applicable_scene, 'regions': [], 'select_count': template.select_count or 0, 'use_count': template.use_count or 0, 'status': template.status or 1, 'created_at': template.created_at, 'updated_at': template.updated_at } # 转换features和regions字段从JSON字符串到列表 if template.features: try: template_dict['features'] = json.loads(template.features) except: template_dict['features'] = [] if template.regions: try: template_dict['regions'] = json.loads(template.regions) except: template_dict['regions'] = [] return template_dict # 创建模板(仅超级管理员可操作) @router.post("/", response_model=TemplateResponse) async def create_template( template: TemplateCreate, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): # 检查模板key是否已存在 existing_template = db.query(Template).filter(Template.key == template.key).first() if existing_template: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail=f"Template with key '{template.key}' already exists" ) # 转换features和regions列表为JSON字符串 template_data = template.model_dump() if template_data.get('features'): template_data['features'] = json.dumps(template_data['features'], ensure_ascii=False) if template_data.get('regions'): template_data['regions'] = json.dumps(template_data['regions'], ensure_ascii=False) db_template = Template(**template_data) db.add(db_template) db.commit() db.refresh(db_template) # 记录操作日志 create_operation_log( db=db, user=current_user, module="template", operation_type="add", operation_detail=f"新增模板:{db_template.name}(key:{db_template.key})", company_code=current_user.company_code ) # 转换features和regions字段从JSON字符串到列表 if db_template.features: try: db_template.features = json.loads(db_template.features) except: db_template.features = [] if db_template.regions: try: db_template.regions = json.loads(db_template.regions) except: db_template.regions = [] return db_template # 更新模板(仅超级管理员可操作) @router.put("/{template_key}", response_model=TemplateResponse) async def update_template( template_key: str, template_update: TemplateUpdate, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): template = db.query(Template).filter(Template.key == template_key).first() if template is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Template with key '{template_key}' not found" ) # 记录修改前的数据 before_data_dict = { "name": template.name, "description": template.description, "color": template.color, "features": template.features, "applicable_scene": template.applicable_scene, "regions": template.regions } # 更新模板信息 update_data = template_update.model_dump(exclude_unset=True) if 'features' in update_data: update_data['features'] = json.dumps(update_data['features'], ensure_ascii=False) if 'regions' in update_data: update_data['regions'] = json.dumps(update_data['regions'], ensure_ascii=False) for field, value in update_data.items(): setattr(template, field, value) db.commit() db.refresh(template) # 记录修改后的数据 after_data_dict = { "name": template.name, "description": template.description, "color": template.color, "features": template.features, "applicable_scene": template.applicable_scene, "regions": template.regions } # 只记录有修改的字段,使用中文解析 modified_fields = [] field_names = { "name": "模板名称", "description": "模板描述", "color": "模板主色调", "features": "模板特性", "applicable_scene": "适用场景", "regions": "适用区域" } for field, chinese_name in field_names.items(): if before_data_dict[field] != after_data_dict[field]: modified_fields.append(f"{chinese_name}:{before_data_dict[field]} → {after_data_dict[field]}") # 生成中文描述的修改内容 if modified_fields: modification_detail = ";".join(modified_fields) else: modification_detail = "无字段修改" # 记录操作日志 create_operation_log( db=db, user=current_user, module="template", operation_type="edit", operation_detail=f"编辑模板:{template.name}(key:{template.key})", before_data=modification_detail, after_data=None, company_code=current_user.company_code ) # 转换features和regions字段从JSON字符串到列表 if template.features: try: template.features = json.loads(template.features) except: template.features = [] if template.regions: try: template.regions = json.loads(template.regions) except: template.regions = [] return template # 删除模板(仅超级管理员可操作) @router.delete("/{template_key}") async def delete_template( template_key: str, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): template = db.query(Template).filter(Template.key == template_key).first() if template is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Template with key '{template_key}' not found" ) # 记录模板名称和key,用于日志 template_name = template.name template_key = template.key db.delete(template) db.commit() # 记录操作日志 create_operation_log( db=db, user=current_user, module="template", operation_type="delete", operation_detail=f"删除模板:{template_name}(key:{template_key})", company_code=current_user.company_code ) return {"message": f"Template with key '{template_key}' deleted successfully"} # 设置模板状态(仅超级管理员可操作) @router.put("/{template_key}/status", response_model=TemplateResponse) async def update_template_status( template_key: str, status_update: TemplateStatusUpdate, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): template = db.query(Template).filter(Template.key == template_key).first() if template is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Template with key '{template_key}' not found" ) # 验证状态值 if status_update.status not in [0, 1]: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Status must be 0 (unavailable) or 1 (available)" ) # 记录修改前的状态 old_status = template.status # 更新状态 template.status = status_update.status db.commit() db.refresh(template) # 记录操作日志 status_text = {0: "不可用", 1: "可用"} create_operation_log( db=db, user=current_user, module="template", operation_type="edit", operation_detail=f"设置模板状态:{template.name}(key:{template.key}),状态:{status_text.get(old_status, '未知')} → {status_text.get(status_update.status, '未知')}", company_code=current_user.company_code ) # 构造响应数据 template_dict = { 'id': template.id, 'key': template.key, 'name': template.name, 'description': template.description, 'color': template.color, 'features': [], 'applicable_scene': template.applicable_scene, 'regions': [], 'select_count': template.select_count or 0, 'use_count': template.use_count or 0, 'status': template.status or 1, 'created_at': template.created_at, 'updated_at': template.updated_at } # 转换features和regions字段从JSON字符串到列表 if template.features: try: template_dict['features'] = json.loads(template.features) except: template_dict['features'] = [] if template.regions: try: template_dict['regions'] = json.loads(template.regions) except: template_dict['regions'] = [] return template_dict