from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from typing import Optional, List from database import get_db from models.company import Company from models.template import Template from models.user import User from schemas.company import CompanyResponse, CompanyCreate, CompanyUpdate 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[CompanyResponse]) async def get_companies( current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): # 普通用户只能查看自己公司的信息 if not current_user.is_superadmin: companies = db.query(Company).filter( Company.company_code == current_user.company_code ).all() else: # 超级管理员可以查看所有公司 companies = db.query(Company).all() return companies # 通过公司编码获取公司信息 @router.get("/{company_code}", response_model=CompanyResponse) async def get_company_by_code( company_code: str, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): # 检查用户权限:超级管理员可以访问所有公司,普通用户只能访问自己公司 if not current_user.is_superadmin and current_user.company_code != company_code: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to access this company" ) company = db.query(Company).filter(Company.company_code == company_code).first() if company is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Company with code '{company_code}' not found" ) return company # 创建公司信息(仅超级管理员可操作) @router.post("/", response_model=CompanyResponse) async def create_company( company: CompanyCreate, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): # 自动生成11位字符串+数字组合的公司编码,确保全局唯一 import uuid while True: # 生成UUID并转换为字符串,取前8位字符和后3位数字 uuid_str = str(uuid.uuid4()).replace('-', '') # 取前8位字母和后3位数字,确保编码长度为11位 company_code = uuid_str[:8] + uuid_str[-3:] # 检查公司编码是否已存在 existing_company = db.query(Company).filter(Company.company_code == company_code).first() if not existing_company: break # 创建公司信息,使用自动生成的公司编码 company_data = company.model_dump() company_data['company_code'] = company_code # 如果没有指定模板,使用默认模板 Home if not company_data.get('template'): company_data['template'] = 'Home' db_company = Company(**company_data) db.add(db_company) db.commit() db.refresh(db_company) # 更新默认模板的统计数据 default_template = db.query(Template).filter(Template.key == db_company.template).first() if default_template: default_template.select_count = (default_template.select_count or 0) + 1 default_template.use_count = (default_template.use_count or 0) + 1 db.commit() # 记录操作日志 create_operation_log( db=db, user=current_user, module="company", operation_type="add", operation_detail=f"新增公司:{db_company.name}(编码:{db_company.company_code})", company_code=db_company.company_code ) return db_company # 通过公司编码更新公司信息 @router.put("/{company_code}", response_model=CompanyResponse) async def update_company( company_code: str, company_update: CompanyUpdate, current_user: User = Depends(get_current_user), db: Session = Depends(get_db) ): # 检查用户权限:超级管理员可以更新所有公司,普通用户只能更新自己公司 if not current_user.is_superadmin and current_user.company_code != company_code: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You don't have permission to update this company" ) company = db.query(Company).filter(Company.company_code == company_code).first() if company is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Company with code '{company_code}' not found" ) # 记录修改前的数据 before_data_dict = { "name": company.name, "level": company.level, "phone": company.phone, "email": company.email, "address": company.address, "description": company.description, "template": company.template } # 更新公司信息 update_data = company_update.model_dump(exclude_unset=True) # 处理模板更新逻辑 old_template_key = company.template new_template_key = update_data.get('template') if new_template_key and old_template_key != new_template_key: # 旧模板使用次数-1 if old_template_key: old_template = db.query(Template).filter(Template.key == old_template_key).first() if old_template: old_template.use_count = max(0, (old_template.use_count or 0) - 1) # 新模板选择次数+1,使用次数+1 new_template = db.query(Template).filter(Template.key == new_template_key).first() if new_template: new_template.select_count = (new_template.select_count or 0) + 1 new_template.use_count = (new_template.use_count or 0) + 1 for field, value in update_data.items(): setattr(company, field, value) db.commit() db.refresh(company) # 记录修改后的数据 after_data_dict = { "name": company.name, "level": company.level, "phone": company.phone, "email": company.email, "address": company.address, "description": company.description, "template": company.template } # 只记录有修改的字段,使用中文解析 modified_fields = [] field_names = { "name": "公司名称", "level": "会员等级", "phone": "联系电话", "email": "电子邮箱", "address": "公司地址", "description": "公司描述", "template": "模板选择" } 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="company", operation_type="edit", operation_detail=f"编辑公司:{company.name}(编码:{company.company_code})", before_data=modification_detail, after_data=None, company_code=company.company_code ) return company # 通过公司编码删除公司信息(仅超级管理员可操作) @router.delete("/{company_code}") async def delete_company( company_code: str, current_user: User = Depends(get_current_superadmin), db: Session = Depends(get_db) ): company = db.query(Company).filter(Company.company_code == company_code).first() if company is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Company with code '{company_code}' not found" ) # 记录公司名称和编码,用于日志 company_name = company.name company_code = company.company_code db.delete(company) db.commit() # 记录操作日志 create_operation_log( db=db, user=current_user, module="company", operation_type="delete", operation_detail=f"删除公司:{company_name}(编码:{company_code})", company_code=company_code ) return {"message": f"Company with code '{company_code}' deleted successfully"}