table_game/backend/app/services/user_table_service.py
2025-03-10 08:35:19 +08:00

83 lines
2.7 KiB
Python

from fastapi import HTTPException
import mysql.connector
from ..db import get_connection
def get_table_availability_service():
"""获取桌子使用情况统计"""
connection = get_connection()
cursor = None
try:
cursor = connection.cursor(dictionary=True)
# 统计总桌数和被占用的桌子数量
cursor.execute("""
SELECT
COUNT(*) AS total_tables,
SUM(CASE WHEN o.order_id IS NOT NULL THEN 1 ELSE 0 END) AS occupied_tables
FROM game_tables gt
LEFT JOIN orders o ON gt.table_id = o.game_table_id
AND o.order_status = 'in_progress'
""")
return cursor.fetchone()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
if cursor: cursor.close()
connection.close()
def check_table_occupancy_service(table_id: int):
"""检查桌子是否被占用"""
connection = get_connection()
cursor = None
try:
cursor = connection.cursor(dictionary=True)
cursor.execute("""
SELECT EXISTS(
SELECT 1 FROM orders
WHERE game_table_id = %s
AND order_status = 'in_progress'
) AS is_occupied
""", (table_id,))
result = cursor.fetchone()
return {"is_occupied": bool(result['is_occupied'])}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
if cursor: cursor.close()
connection.close()
def list_tables_service():
connection = get_connection()
cursor = None
try:
cursor = connection.cursor(dictionary=True)
cursor.execute("SELECT * FROM game_tables")
return cursor.fetchall()
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
finally:
if cursor: cursor.close()
connection.close()
def get_table_number_service(table_id: int):
"""根据桌台ID获取桌号服务"""
connection = get_connection()
cursor = None
try:
cursor = connection.cursor(dictionary=True)
cursor.execute("""
SELECT game_table_number
FROM game_tables
WHERE table_id = %s
""", (table_id,))
result = cursor.fetchone()
if not result:
raise HTTPException(status_code=404, detail="桌台不存在")
return {"game_table_number": result['game_table_number']}
except Exception as e:
if isinstance(e, HTTPException):
raise e
raise HTTPException(status_code=500, detail=str(e))
finally:
if cursor: cursor.close()
connection.close()