feat(a1-card): 新增A1名片路由和服务模块

添加a1_card_router路由模块,实现根据企业微信ID获取用户画像数据的功能
包含路由注册、服务层实现及MongoDB查询逻辑
This commit is contained in:
2025-12-22 18:35:22 +08:00
parent 03410f7583
commit 10e708df86
4 changed files with 129 additions and 3 deletions

View File

@@ -32,9 +32,10 @@ app.add_middleware(
) )
# 注册路由模块 # 注册路由模块
from src.routers import wechat_router, light_router from src.routers import wechat_router, light_router, a1_card_router
app.include_router(wechat_router, prefix=API_PREFIX+"/wechat", tags=["企业微信"]) app.include_router(wechat_router, prefix=API_PREFIX+"/wechat", tags=["企业微信"])
app.include_router(light_router, prefix=API_PREFIX+"/light", tags=["信息灯牌"]) app.include_router(light_router, prefix=API_PREFIX+"/light", tags=["信息灯牌"])
app.include_router(a1_card_router, prefix=API_PREFIX+"/a1-card", tags=["A1名片"])
# 根路径端点,返回欢迎信息 # 根路径端点,返回欢迎信息
@app.get(API_PREFIX+"/") @app.get(API_PREFIX+"/")

View File

@@ -2,5 +2,5 @@
from src.routers.wechat import wechat_router from src.routers.wechat import wechat_router
from src.routers.light import light_router from src.routers.light import light_router
from src.routers.a1_card import a1_card_router
__all__ = ["wechat_router", "light_router"] __all__ = ["wechat_router", "light_router", "a1_card_router"]

56
src/routers/a1_card.py Normal file
View File

@@ -0,0 +1,56 @@
from fastapi import APIRouter, HTTPException
from typing import Optional, Dict, Any
from src.services.a1_card import get_user_portrayal_small_by_wecom_id
from src.models.response import success_response, error_response
# 创建路由实例
a1_card_router = APIRouter()
@a1_card_router.get("/user-portrayal/{customer_wechat_id}", summary="根据customer_wechat_id获取用户画像数据")
async def get_user_portrayal_small(customer_wechat_id: str):
"""
根据customer_wechat_id查询customers集合中的user_portrayal_small数据
- **customer_wechat_id**: 用户的企业微信ID
Returns:
ResponseModel: 包含用户画像数据的统一响应格式
"""
if not customer_wechat_id:
return error_response(
message="customer_wechat_id不能为空",
code=400
)
try:
# 调用服务层获取用户画像数据
portrayal_data = get_user_portrayal_small_by_wecom_id(customer_wechat_id)
if portrayal_data is not None:
return success_response(
data=portrayal_data,
message="成功获取用户画像数据",
code=200
)
else:
return success_response(
data={},
message="未找到该用户的画像数据",
code=200
)
except ValueError as e:
return error_response(
message=str(e),
code=400
)
except RuntimeError as e:
return error_response(
message=str(e),
code=500
)
except Exception as e:
return error_response(
message=f"获取用户画像数据失败: {str(e)}",
code=500
)

69
src/services/a1_card.py Normal file
View File

@@ -0,0 +1,69 @@
import logging
from typing import Optional, Dict, Any
from src.utils.mongodb import get_mongodb_sync_db
# 配置日志
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
if not logger.handlers:
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.propagate = False # 防止重复记录
def get_customers_collection():
"""
获取customers集合
Returns:
Collection: MongoDB集合对象
"""
from src.utils.mongodb import MongoDB
# 确保MongoDB已初始化
if not MongoDB._sync_initialized:
MongoDB.initialize_sync()
db = MongoDB.get_sync_db()
collection = db["customers"]
return collection
def get_user_portrayal_small_by_wecom_id(wecom_id: str) -> Optional[Dict[str, Any]]:
"""
根据wecom_id对应customer_wechat_id查询customers集合中的user_portrayal_small数据
Args:
wecom_id (str): 用户的企业微信ID对应数据库中的customer_wechat_id字段
Returns:
Optional[Dict[str, Any]]: 用户画像数据如果未找到则返回None
Raises:
RuntimeError: 当数据库查询出现错误时抛出异常
"""
try:
# 获取customers集合
collection = get_customers_collection()
# 查询条件wecom_id对应customer_wechat_id字段
query = {"wecom_id": wecom_id}
# 只返回user_portrayal_small字段
projection = {"user_portrayal_small": 1, "_id": 0}
# 执行查询
doc = collection.find_one(query, projection)
# 如果找到了文档返回user_portrayal_small字段的值
if doc and "user_portrayal_small" in doc:
return doc["user_portrayal_small"]
# 如果没有找到匹配的文档或user_portrayal_small字段不存在返回None
return None
except Exception as e:
logger.error(f"根据wecom_id({wecom_id})查询用户画像数据时出错: {str(e)}")
raise RuntimeError(f"查询用户画像数据失败: {str(e)}")