Files
space-booking/backend/app/api/spaces.py
Claude Agent e21cf03a16 feat: add multi-tenant system with properties, organizations, and public booking
Implement complete multi-property architecture:
- Properties (groups of spaces) with public/private visibility
- Property managers (many-to-many) with role-based permissions
- Organizations with member management
- Anonymous/guest booking support via public API (/api/public/*)
- Property-scoped spaces, bookings, and settings
- Frontend: property selector, organization management, public booking views
- Migration script and updated seed data

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-15 00:17:21 +00:00

221 lines
7.3 KiB
Python

"""Space management endpoints."""
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.core.deps import get_current_admin, get_current_manager_or_superadmin, get_current_user, get_db
from app.core.permissions import get_manager_property_ids
from app.models.space import Space
from app.models.user import User
from app.schemas.space import SpaceCreate, SpaceResponse, SpaceStatusUpdate, SpaceUpdate
from app.services.audit_service import log_action
router = APIRouter(prefix="/spaces", tags=["spaces"])
admin_router = APIRouter(prefix="/admin/spaces", tags=["admin"])
@router.get("", response_model=list[SpaceResponse])
def list_spaces(
db: Annotated[Session, Depends(get_db)],
current_user: Annotated[User, Depends(get_current_user)],
property_id: int | None = None,
) -> list[SpaceResponse]:
"""
Get list of spaces.
- Users see only active spaces
- Admins/superadmins/managers see all spaces (active + inactive)
"""
query = db.query(Space)
# Filter by property_id if provided
if property_id is not None:
query = query.filter(Space.property_id == property_id)
# Filter by active status for non-admin users
if current_user.role not in ("admin", "superadmin", "manager"):
query = query.filter(Space.is_active == True) # noqa: E712
elif current_user.role == "manager":
managed_ids = get_manager_property_ids(db, current_user.id)
if property_id is not None:
# When filtering by specific property, manager sees all spaces (active + inactive) IF they manage it
if property_id not in managed_ids:
query = query.filter(Space.is_active == True) # noqa: E712
else:
# No property filter: manager sees only their managed properties' spaces
query = query.filter(Space.property_id.in_(managed_ids))
spaces = query.order_by(Space.name).all()
# Build response with property_name
result = []
for s in spaces:
resp = SpaceResponse.model_validate(s)
if s.property and hasattr(s.property, 'name'):
resp.property_name = s.property.name
result.append(resp)
return result
@admin_router.post("", response_model=SpaceResponse, status_code=status.HTTP_201_CREATED)
def create_space(
space_data: SpaceCreate,
db: Annotated[Session, Depends(get_db)],
current_admin: Annotated[User, Depends(get_current_manager_or_superadmin)],
) -> SpaceResponse:
"""
Create a new space (admin/manager).
- name: required, non-empty
- type: "sala" or "birou"
- capacity: must be > 0
- description: optional
- property_id: optional, assign to property
"""
# Check if space with same name exists
existing = db.query(Space).filter(Space.name == space_data.name).first()
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Space with name '{space_data.name}' already exists",
)
# If manager, verify they manage the property
if space_data.property_id and current_admin.role == "manager":
from app.core.permissions import verify_property_access
verify_property_access(db, current_admin, space_data.property_id, require_manager=True)
space = Space(
name=space_data.name,
type=space_data.type,
capacity=space_data.capacity,
description=space_data.description,
property_id=space_data.property_id,
is_active=True,
)
db.add(space)
db.commit()
db.refresh(space)
# Log the action
log_action(
db=db,
action="space_created",
user_id=current_admin.id,
target_type="space",
target_id=space.id,
details={"name": space.name, "type": space.type, "capacity": space.capacity}
)
resp = SpaceResponse.model_validate(space)
if space.property and hasattr(space.property, 'name'):
resp.property_name = space.property.name
return resp
@admin_router.put("/{space_id}", response_model=SpaceResponse)
def update_space(
space_id: int,
space_data: SpaceUpdate,
db: Annotated[Session, Depends(get_db)],
current_admin: Annotated[User, Depends(get_current_manager_or_superadmin)],
) -> Space:
"""
Update an existing space (admin only).
All fields are required (full update).
"""
space = db.query(Space).filter(Space.id == space_id).first()
if not space:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Space not found",
)
# Verify manager has access to this space's property
if current_admin.role == "manager" and space.property_id:
managed_ids = get_manager_property_ids(db, current_admin.id)
if space.property_id not in managed_ids:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
)
# Check if new name conflicts with another space
if space_data.name != space.name:
existing = db.query(Space).filter(Space.name == space_data.name).first()
if existing:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Space with name '{space_data.name}' already exists",
)
# Track what changed
updated_fields = []
if space.name != space_data.name:
updated_fields.append("name")
if space.type != space_data.type:
updated_fields.append("type")
if space.capacity != space_data.capacity:
updated_fields.append("capacity")
if space.description != space_data.description:
updated_fields.append("description")
setattr(space, "name", space_data.name)
setattr(space, "type", space_data.type)
setattr(space, "capacity", space_data.capacity)
setattr(space, "description", space_data.description)
db.commit()
db.refresh(space)
# Log the action
log_action(
db=db,
action="space_updated",
user_id=current_admin.id,
target_type="space",
target_id=space.id,
details={"updated_fields": updated_fields}
)
return space
@admin_router.patch("/{space_id}/status", response_model=SpaceResponse)
def update_space_status(
space_id: int,
status_data: SpaceStatusUpdate,
db: Annotated[Session, Depends(get_db)],
current_admin: Annotated[User, Depends(get_current_manager_or_superadmin)],
) -> Space:
"""
Activate or deactivate a space (admin only).
Deactivated spaces will not appear in booking lists for users.
"""
space = db.query(Space).filter(Space.id == space_id).first()
if not space:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Space not found",
)
# Verify manager has access to this space's property
if current_admin.role == "manager" and space.property_id:
managed_ids = get_manager_property_ids(db, current_admin.id)
if space.property_id not in managed_ids:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Not enough permissions",
)
setattr(space, "is_active", status_data.is_active)
db.commit()
db.refresh(space)
return space