432 lines
16 KiB
Python
432 lines
16 KiB
Python
|
|
# =============================================================================
|
||
|
|
# 企微IT智能服务台 — 会议室预定 REST API 路由
|
||
|
|
# =============================================================================
|
||
|
|
# 说明:提供会议室预定的REST API,供终端前端和H5端调用
|
||
|
|
#
|
||
|
|
# API 端点列表:
|
||
|
|
# GET /itportal/meetingroom/list — 会议室列表
|
||
|
|
# GET /itportal/meetingroom/{meetingroom_id}/booking — 预定状态查询
|
||
|
|
# GET /itportal/meetingroom/{meetingroom_id}/status — 当前实时状态
|
||
|
|
# POST /itportal/meetingroom/book — 预定会议室
|
||
|
|
# DELETE /itportal/meetingroom/booking/{booking_id} — 取消预定
|
||
|
|
# GET /itportal/meetingroom/booking/{booking_id}/detail — 预定详情
|
||
|
|
# GET /itportal/meetingroom/terminal/{terminal_sn}/binding — 终端绑定查询
|
||
|
|
# =============================================================================
|
||
|
|
|
||
|
|
import logging
|
||
|
|
from typing import Optional
|
||
|
|
|
||
|
|
from fastapi import APIRouter, Depends, Query
|
||
|
|
from sqlalchemy import select
|
||
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||
|
|
|
||
|
|
from app.config import settings
|
||
|
|
from app.database import get_db
|
||
|
|
from app.dependencies import get_current_user, UserInfo
|
||
|
|
from app.models.terminal_room_binding import TerminalRoomBinding
|
||
|
|
from app.schemas.meetingroom import (
|
||
|
|
BookRequest,
|
||
|
|
BookResponse,
|
||
|
|
BookingDetailResponse,
|
||
|
|
BookingInfoResponse,
|
||
|
|
BookingItem,
|
||
|
|
MeetingroomItem,
|
||
|
|
MeetingroomListResponse,
|
||
|
|
RoomStatusResponse,
|
||
|
|
TerminalBindingResponse,
|
||
|
|
)
|
||
|
|
from app.services.meetingroom_service import MeetingroomService
|
||
|
|
from app.services.wecom_service import WecomService
|
||
|
|
from app.utils.response import AppException, success_response
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
# 创建路由器
|
||
|
|
router = APIRouter(prefix="/itportal/meetingroom", tags=["会议室预定"])
|
||
|
|
|
||
|
|
|
||
|
|
def _get_meetingroom_service(
|
||
|
|
redis_client=None,
|
||
|
|
) -> MeetingroomService:
|
||
|
|
"""构造 MeetingroomService 实例。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
redis_client: Redis 客户端(可选)
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
MeetingroomService: 会议室预定服务实例
|
||
|
|
"""
|
||
|
|
wecom_service = WecomService(redis_client or settings.create_redis_client())
|
||
|
|
return MeetingroomService(wecom_service, redis_client or settings.create_redis_client())
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# GET /itportal/meetingroom/list — 会议室列表
|
||
|
|
# =============================================================================
|
||
|
|
@router.get("/list", response_model=None)
|
||
|
|
async def get_meetingroom_list(
|
||
|
|
city: Optional[str] = Query(None, description="城市名称过滤"),
|
||
|
|
building: Optional[str] = Query(None, description="楼宇名称过滤"),
|
||
|
|
floor: Optional[str] = Query(None, description="楼层名称过滤"),
|
||
|
|
):
|
||
|
|
"""获取会议室列表。
|
||
|
|
|
||
|
|
无需认证(终端页面访客可查看)。
|
||
|
|
代理调用企微API获取会议室列表,结果缓存10分钟。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
city: 城市名称(可选过滤)
|
||
|
|
building: 楼宇名称(可选过滤)
|
||
|
|
floor: 楼层名称(可选过滤)
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含 rooms 列表
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
room_list = await service.get_room_list(city, building, floor)
|
||
|
|
|
||
|
|
# 格式化响应
|
||
|
|
rooms = [
|
||
|
|
MeetingroomItem(
|
||
|
|
meetingroom_id=room.get("meetingroom_id", 0),
|
||
|
|
name=room.get("name", ""),
|
||
|
|
capacity=room.get("capacity", 0),
|
||
|
|
location=room.get("location", ""),
|
||
|
|
devices=room.get("equipment", room.get("devices", [])),
|
||
|
|
need_approval=room.get("need_approval", 0),
|
||
|
|
).model_dump()
|
||
|
|
for room in room_list
|
||
|
|
]
|
||
|
|
|
||
|
|
return success_response(data={"rooms": rooms})
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"获取会议室列表异常: {e}", exc_info=True)
|
||
|
|
raise AppException(2001, f"获取会议室列表失败: {str(e)}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# GET /itportal/meetingroom/{meetingroom_id}/booking — 预定状态查询
|
||
|
|
# =============================================================================
|
||
|
|
@router.get("/{meetingroom_id}/booking", response_model=None)
|
||
|
|
async def get_booking_info(
|
||
|
|
meetingroom_id: int,
|
||
|
|
date: Optional[str] = Query(None, description="查询日期 YYYY-MM-DD(默认今天)"),
|
||
|
|
):
|
||
|
|
"""获取指定日期的预定状态。
|
||
|
|
|
||
|
|
无需认证(终端页面访客可查看)。
|
||
|
|
代理调用企微API获取预定记录,结果缓存30秒。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
meetingroom_id: 企微会议室ID
|
||
|
|
date: 查询日期(YYYY-MM-DD,默认今天)
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含 bookings 列表
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
booking_list = await service.get_room_status(meetingroom_id, date)
|
||
|
|
|
||
|
|
# 格式化预定记录
|
||
|
|
bookings = []
|
||
|
|
for booking in booking_list:
|
||
|
|
formatted = service._format_booking(booking)
|
||
|
|
bookings.append(BookingItem(
|
||
|
|
booking_id=str(formatted.get("booking_id", "")),
|
||
|
|
subject=formatted.get("subject", ""),
|
||
|
|
booker=formatted.get("booker", ""),
|
||
|
|
booker_name=formatted.get("booker_name", ""),
|
||
|
|
start_time=formatted.get("start_time", ""),
|
||
|
|
end_time=formatted.get("end_time", ""),
|
||
|
|
status=formatted.get("status", 0),
|
||
|
|
).model_dump())
|
||
|
|
|
||
|
|
return success_response(data={"bookings": bookings})
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"获取预定状态异常: room_id={meetingroom_id}, error={e}", exc_info=True)
|
||
|
|
raise AppException(2001, f"获取预定状态失败: {str(e)}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# GET /itportal/meetingroom/{meetingroom_id}/status — 当前实时状态
|
||
|
|
# =============================================================================
|
||
|
|
@router.get("/{meetingroom_id}/status", response_model=None)
|
||
|
|
async def get_current_status(meetingroom_id: int):
|
||
|
|
"""获取当前实时状态(综合判断空闲/使用中/即将开始)。
|
||
|
|
|
||
|
|
无需认证(终端页面访客可查看)。
|
||
|
|
结果缓存10秒(极短缓存防刷)。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
meetingroom_id: 企微会议室ID
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含 status/current_meeting/next_meeting/bookings
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
status_data = await service.get_current_status(meetingroom_id)
|
||
|
|
|
||
|
|
# 格式化响应
|
||
|
|
current_meeting = None
|
||
|
|
if status_data.get("current_meeting"):
|
||
|
|
cm = status_data["current_meeting"]
|
||
|
|
current_meeting = BookingItem(
|
||
|
|
booking_id=str(cm.get("booking_id", "")),
|
||
|
|
subject=cm.get("subject", ""),
|
||
|
|
booker=cm.get("booker", ""),
|
||
|
|
booker_name=cm.get("booker_name", ""),
|
||
|
|
start_time=cm.get("start_time", ""),
|
||
|
|
end_time=cm.get("end_time", ""),
|
||
|
|
status=cm.get("status", 0),
|
||
|
|
).model_dump()
|
||
|
|
|
||
|
|
next_meeting = None
|
||
|
|
if status_data.get("next_meeting"):
|
||
|
|
nm = status_data["next_meeting"]
|
||
|
|
next_meeting = BookingItem(
|
||
|
|
booking_id=str(nm.get("booking_id", "")),
|
||
|
|
subject=nm.get("subject", ""),
|
||
|
|
booker=nm.get("booker", ""),
|
||
|
|
booker_name=nm.get("booker_name", ""),
|
||
|
|
start_time=nm.get("start_time", ""),
|
||
|
|
end_time=nm.get("end_time", ""),
|
||
|
|
status=nm.get("status", 0),
|
||
|
|
).model_dump()
|
||
|
|
|
||
|
|
bookings = []
|
||
|
|
for b in status_data.get("bookings", []):
|
||
|
|
bookings.append(BookingItem(
|
||
|
|
booking_id=str(b.get("booking_id", "")),
|
||
|
|
subject=b.get("subject", ""),
|
||
|
|
booker=b.get("booker", ""),
|
||
|
|
booker_name=b.get("booker_name", ""),
|
||
|
|
start_time=b.get("start_time", ""),
|
||
|
|
end_time=b.get("end_time", ""),
|
||
|
|
status=b.get("status", 0),
|
||
|
|
).model_dump())
|
||
|
|
|
||
|
|
response_data = RoomStatusResponse(
|
||
|
|
status=status_data.get("status", "free"),
|
||
|
|
current_meeting=current_meeting,
|
||
|
|
next_meeting=next_meeting,
|
||
|
|
minutes_to_next=status_data.get("minutes_to_next"),
|
||
|
|
bookings=bookings,
|
||
|
|
).model_dump()
|
||
|
|
|
||
|
|
return success_response(data=response_data)
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"获取实时状态异常: room_id={meetingroom_id}, error={e}", exc_info=True)
|
||
|
|
raise AppException(2001, f"获取实时状态失败: {str(e)}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# POST /itportal/meetingroom/book — 预定会议室
|
||
|
|
# =============================================================================
|
||
|
|
@router.post("/book", response_model=None)
|
||
|
|
async def book_meetingroom(
|
||
|
|
body: BookRequest,
|
||
|
|
current_user: UserInfo = Depends(get_current_user),
|
||
|
|
):
|
||
|
|
"""预定会议室。
|
||
|
|
|
||
|
|
需要认证(Bearer Token),预定人使用当前登录用户userid。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
body: 预定请求参数
|
||
|
|
current_user: 当前登录用户
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含 booking_id
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
|
||
|
|
# 使用当前登录用户作为预定人
|
||
|
|
result = await service.book_room(
|
||
|
|
meetingroom_id=body.meetingroom_id,
|
||
|
|
subject=body.subject,
|
||
|
|
start_time=body.start_time,
|
||
|
|
end_time=body.end_time,
|
||
|
|
booker=current_user.employee_id,
|
||
|
|
attendees=body.attendees,
|
||
|
|
)
|
||
|
|
|
||
|
|
booking_id = result.get("booking_id", "")
|
||
|
|
|
||
|
|
# 通过WS通知绑定该会议室的终端
|
||
|
|
try:
|
||
|
|
from sqlalchemy import select as sa_select
|
||
|
|
from app.database import _get_session_factory
|
||
|
|
|
||
|
|
session_factory = _get_session_factory()
|
||
|
|
async with session_factory() as notify_db:
|
||
|
|
stmt = select(TerminalRoomBinding).where(
|
||
|
|
TerminalRoomBinding.meetingroom_id == body.meetingroom_id,
|
||
|
|
TerminalRoomBinding.is_active == True, # noqa: E712
|
||
|
|
)
|
||
|
|
result_bindings = await notify_db.execute(stmt)
|
||
|
|
bindings = result_bindings.scalars().all()
|
||
|
|
for binding in bindings:
|
||
|
|
await service.notify_terminal_update(binding.terminal_sn, body.meetingroom_id)
|
||
|
|
except Exception as notify_err:
|
||
|
|
logger.warning(f"预定后WS通知终端失败(不影响主流程): {notify_err}")
|
||
|
|
|
||
|
|
return success_response(data=BookResponse(booking_id=booking_id).model_dump())
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"预定会议室异常: {e}", exc_info=True)
|
||
|
|
error_msg = str(e)
|
||
|
|
# 常见错误码映射
|
||
|
|
if "时间冲突" in error_msg or "冲突" in error_msg:
|
||
|
|
raise AppException(3102, "该时段已被预定(时间冲突)")
|
||
|
|
raise AppException(2001, f"预定会议室失败: {error_msg}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# DELETE /itportal/meetingroom/booking/{booking_id} — 取消预定
|
||
|
|
# =============================================================================
|
||
|
|
@router.delete("/booking/{booking_id}", response_model=None)
|
||
|
|
async def cancel_booking(
|
||
|
|
booking_id: str,
|
||
|
|
meetingroom_id: int = Query(..., description="企微会议室ID"),
|
||
|
|
current_user: UserInfo = Depends(get_current_user),
|
||
|
|
):
|
||
|
|
"""取消预定。
|
||
|
|
|
||
|
|
需要认证(Bearer Token)。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
booking_id: 企微预定ID
|
||
|
|
meetingroom_id: 企微会议室ID
|
||
|
|
current_user: 当前登录用户
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
await service.cancel_booking(booking_id, meetingroom_id)
|
||
|
|
|
||
|
|
# 通过WS通知绑定该会议室的终端
|
||
|
|
try:
|
||
|
|
# 查询绑定该会议室的终端
|
||
|
|
from sqlalchemy import select as sa_select
|
||
|
|
from app.database import _get_session_factory
|
||
|
|
|
||
|
|
session_factory = _get_session_factory()
|
||
|
|
async with session_factory() as notify_db:
|
||
|
|
stmt = select(TerminalRoomBinding).where(
|
||
|
|
TerminalRoomBinding.meetingroom_id == meetingroom_id,
|
||
|
|
TerminalRoomBinding.is_active == True, # noqa: E712
|
||
|
|
)
|
||
|
|
result = await notify_db.execute(stmt)
|
||
|
|
bindings = result.scalars().all()
|
||
|
|
for binding in bindings:
|
||
|
|
await service.notify_terminal_update(binding.terminal_sn, meetingroom_id)
|
||
|
|
except Exception as notify_err:
|
||
|
|
logger.warning(f"取消预定后WS通知终端失败(不影响主流程): {notify_err}")
|
||
|
|
|
||
|
|
return success_response(data={})
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"取消预定异常: booking_id={booking_id}, error={e}", exc_info=True)
|
||
|
|
error_msg = str(e)
|
||
|
|
if "非预定人" in error_msg or "权限" in error_msg:
|
||
|
|
raise AppException(3105, "非预定人无法取消")
|
||
|
|
raise AppException(2001, f"取消预定失败: {error_msg}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# GET /itportal/meetingroom/booking/{booking_id}/detail — 预定详情
|
||
|
|
# =============================================================================
|
||
|
|
@router.get("/booking/{booking_id}/detail", response_model=None)
|
||
|
|
async def get_booking_detail(
|
||
|
|
booking_id: str,
|
||
|
|
meetingroom_id: int = Query(..., description="企微会议室ID"),
|
||
|
|
):
|
||
|
|
"""获取预定详情。
|
||
|
|
|
||
|
|
无需认证(终端页面访客可查看)。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
booking_id: 企微预定ID
|
||
|
|
meetingroom_id: 企微会议室ID
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含预定详情
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
service = _get_meetingroom_service()
|
||
|
|
detail = await service.get_booking_detail(meetingroom_id, booking_id)
|
||
|
|
|
||
|
|
response_data = BookingDetailResponse(
|
||
|
|
booking_id=str(detail.get("booking_id", booking_id)),
|
||
|
|
subject=detail.get("subject", ""),
|
||
|
|
booker=detail.get("booker", ""),
|
||
|
|
booker_name=detail.get("booker_name", ""),
|
||
|
|
attendees=detail.get("attendees", []),
|
||
|
|
start_time=detail.get("start_time", ""),
|
||
|
|
end_time=detail.get("end_time", ""),
|
||
|
|
).model_dump()
|
||
|
|
|
||
|
|
return success_response(data=response_data)
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"获取预定详情异常: booking_id={booking_id}, error={e}", exc_info=True)
|
||
|
|
raise AppException(2001, f"获取预定详情失败: {str(e)}")
|
||
|
|
|
||
|
|
|
||
|
|
# =============================================================================
|
||
|
|
# GET /itportal/meetingroom/terminal/{terminal_sn}/binding — 终端绑定查询
|
||
|
|
# =============================================================================
|
||
|
|
@router.get("/terminal/{terminal_sn}/binding", response_model=None)
|
||
|
|
async def get_terminal_binding(
|
||
|
|
terminal_sn: str,
|
||
|
|
db: AsyncSession = Depends(get_db),
|
||
|
|
):
|
||
|
|
"""根据终端SN查询绑定的会议室信息。
|
||
|
|
|
||
|
|
无需认证(终端页面加载时调用)。
|
||
|
|
|
||
|
|
Args:
|
||
|
|
terminal_sn: 终端序列号
|
||
|
|
db: 数据库会话
|
||
|
|
|
||
|
|
Returns:
|
||
|
|
Dict: 统一响应格式,data 含绑定信息(未绑定时返回 null)
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
stmt = select(TerminalRoomBinding).where(
|
||
|
|
TerminalRoomBinding.terminal_sn == terminal_sn,
|
||
|
|
TerminalRoomBinding.is_active == True, # noqa: E712
|
||
|
|
)
|
||
|
|
result = await db.execute(stmt)
|
||
|
|
binding = result.scalar_one_or_none()
|
||
|
|
|
||
|
|
if not binding:
|
||
|
|
return success_response(data=None)
|
||
|
|
|
||
|
|
response_data = TerminalBindingResponse(
|
||
|
|
id=binding.id,
|
||
|
|
terminal_sn=binding.terminal_sn,
|
||
|
|
terminal_name=binding.terminal_name,
|
||
|
|
meetingroom_id=binding.meetingroom_id,
|
||
|
|
meetingroom_name=binding.meetingroom_name,
|
||
|
|
location=binding.location,
|
||
|
|
is_active=binding.is_active,
|
||
|
|
created_at=binding.created_at.isoformat() if binding.created_at else "",
|
||
|
|
updated_at=binding.updated_at.isoformat() if binding.updated_at else "",
|
||
|
|
).model_dump()
|
||
|
|
|
||
|
|
return success_response(data=response_data)
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
logger.error(f"查询终端绑定异常: sn={terminal_sn}, error={e}", exc_info=True)
|
||
|
|
raise AppException(1005, f"查询终端绑定失败: {str(e)}")
|