ymt-python / routers /customer_relationship.py
hsailorj's picture
Add application file
551658a
Raw
History Blame Contribute Delete
10 kB
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
import json
from database import get_db
from models.customer_relationship import CustomerRelationship
from models.user import User
from schemas.customer_relationship import CustomerRelationshipResponse, CustomerRelationshipCreate, CustomerRelationshipUpdate
from routers.auth import get_current_user, is_admin_user
from routers.operation_log import create_operation_log
router = APIRouter()
# 获取客户关系列表
@router.get("/", response_model=List[CustomerRelationshipResponse])
async def get_customer_relationships(
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
# admin用户和超级管理员可以查看所有客户关系
if is_admin_user(current_user) or current_user.is_superadmin:
customer_relationships = db.query(CustomerRelationship).all()
else:
# 普通用户只能查看自己公司的客户关系
customer_relationships = db.query(CustomerRelationship).filter(
CustomerRelationship.company_code == current_user.company_code
).all()
# 转换social_media字段从JSON字符串到字典
for cr in customer_relationships:
if cr.social_media:
try:
cr.social_media = json.loads(cr.social_media)
except:
cr.social_media = {}
return customer_relationships
# 通过ID获取客户关系详情
@router.get("/{customer_id}", response_model=CustomerRelationshipResponse)
async def get_customer_relationship(
customer_id: int,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
customer_relationship = db.query(CustomerRelationship).filter(CustomerRelationship.id == customer_id).first()
if customer_relationship is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Customer relationship with ID '{customer_id}' not found"
)
# 检查权限:admin用户和超级管理员可以查看所有客户关系,普通用户只能查看自己公司的
if not is_admin_user(current_user) and not current_user.is_superadmin and customer_relationship.company_code != current_user.company_code:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You don't have permission to access this customer relationship"
)
# 转换social_media字段从JSON字符串到字典
if customer_relationship.social_media:
try:
customer_relationship.social_media = json.loads(customer_relationship.social_media)
except:
customer_relationship.social_media = {}
return customer_relationship
# 创建客户关系
@router.post("/", response_model=CustomerRelationshipResponse)
async def create_customer_relationship(
customer_relationship: CustomerRelationshipCreate,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
# 检查权限:admin用户和超级管理员可以为任何公司创建客户关系,普通用户只能为自己公司创建
if not is_admin_user(current_user) and not current_user.is_superadmin and customer_relationship.company_code != current_user.company_code:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You don't have permission to create customer relationships for other companies"
)
# 转换social_media字典为JSON字符串
customer_data = customer_relationship.model_dump()
if customer_data.get('social_media'):
customer_data['social_media'] = json.dumps(customer_data['social_media'], ensure_ascii=False)
db_customer = CustomerRelationship(**customer_data)
db.add(db_customer)
db.commit()
db.refresh(db_customer)
# 记录操作日志
create_operation_log(
db=db,
user=current_user,
module="customer_relationship",
operation_type="add",
operation_detail=f"新增客户关系:{db_customer.customer_name}(联系人:{db_customer.contact_person})",
company_code=current_user.company_code
)
# 转换social_media字段从JSON字符串到字典
if db_customer.social_media:
try:
db_customer.social_media = json.loads(db_customer.social_media)
except:
db_customer.social_media = {}
return db_customer
# 更新客户关系
@router.put("/{customer_id}", response_model=CustomerRelationshipResponse)
async def update_customer_relationship(
customer_id: int,
customer_update: CustomerRelationshipUpdate,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
customer_relationship = db.query(CustomerRelationship).filter(CustomerRelationship.id == customer_id).first()
if customer_relationship is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Customer relationship with ID '{customer_id}' not found"
)
# 检查权限:admin用户和超级管理员可以更新所有客户关系,普通用户只能更新自己公司的
if not is_admin_user(current_user) and not current_user.is_superadmin and customer_relationship.company_code != current_user.company_code:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You don't have permission to update this customer relationship"
)
# 记录修改前的数据
before_data_dict = {
"customer_name": customer_relationship.customer_name,
"contact_person": customer_relationship.contact_person,
"phone": customer_relationship.phone,
"email": customer_relationship.email,
"social_media": customer_relationship.social_media,
"address": customer_relationship.address,
"notes": customer_relationship.notes
}
# 更新客户关系信息
update_data = customer_update.model_dump(exclude_unset=True)
if 'social_media' in update_data:
update_data['social_media'] = json.dumps(update_data['social_media'], ensure_ascii=False)
for field, value in update_data.items():
setattr(customer_relationship, field, value)
db.commit()
db.refresh(customer_relationship)
# 记录修改后的数据
after_data_dict = {
"customer_name": customer_relationship.customer_name,
"contact_person": customer_relationship.contact_person,
"phone": customer_relationship.phone,
"email": customer_relationship.email,
"social_media": customer_relationship.social_media,
"address": customer_relationship.address,
"notes": customer_relationship.notes
}
# 只记录有修改的字段,使用中文解析
modified_fields = []
field_names = {
"customer_name": "客户名称",
"contact_person": "联系人",
"phone": "电话",
"email": "邮箱",
"social_media": "社交平台账号",
"address": "地址",
"notes": "备注"
}
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="customer_relationship",
operation_type="edit",
operation_detail=f"编辑客户关系:{customer_relationship.customer_name}(联系人:{customer_relationship.contact_person})",
before_data=modification_detail,
after_data=None,
company_code=current_user.company_code
)
# 转换social_media字段从JSON字符串到字典
if customer_relationship.social_media:
try:
customer_relationship.social_media = json.loads(customer_relationship.social_media)
except:
customer_relationship.social_media = {}
return customer_relationship
# 删除客户关系
@router.delete("/{customer_id}")
async def delete_customer_relationship(
customer_id: int,
current_user: User = Depends(get_current_user),
db: Session = Depends(get_db)
):
customer_relationship = db.query(CustomerRelationship).filter(CustomerRelationship.id == customer_id).first()
if customer_relationship is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Customer relationship with ID '{customer_id}' not found"
)
# 检查权限:admin用户和超级管理员可以删除所有客户关系,普通用户只能删除自己公司的
if not is_admin_user(current_user) and not current_user.is_superadmin and customer_relationship.company_code != current_user.company_code:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You don't have permission to delete this customer relationship"
)
# 记录客户关系名称和联系人,用于日志
customer_name = customer_relationship.customer_name
contact_person = customer_relationship.contact_person
db.delete(customer_relationship)
db.commit()
# 记录操作日志
create_operation_log(
db=db,
user=current_user,
module="customer_relationship",
operation_type="delete",
operation_detail=f"删除客户关系:{customer_name}(联系人:{contact_person})",
company_code=current_user.company_code
)
return {"message": f"Customer relationship with ID '{customer_id}' deleted successfully"}