Spaces:
Sleeping
Sleeping
File size: 8,549 Bytes
551658a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | 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"}
|