# Copyright (C) 2026 Mattia Zatelli # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . """ Endpoints for BIM element management These endpoints provide detailed access to processed BIM elements: - Listing with advanced filters (type, material, geometry) - Full-text search on properties and names - Cursor-based pagination for performance - Element aggregations and statistics - Selective export for analysis Supports complex combinable filters for specific analysis and optimized queries for large datasets. """ import logging from typing import List, Optional from fastapi import APIRouter, Depends, HTTPException, status, Request, Query as FastAPIQuery from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select, and_, or_, func, desc from app.core.database import get_async_session from app.models import Project, Element, ProjectStatus from app.schemas.element import ( ElementResponse, ElementListResponse, ElementFilterRequest, ElementSummaryResponse ) from app.schemas.common import ErrorResponse from app.core.exceptions import ProjectNotFoundError, ProjectNotReadyError logger = logging.getLogger(__name__) router = APIRouter() async def get_project_for_elements( project_id: str, session: AsyncSession, tenant_id: str ) -> Project: """Retrieve and validate project for element operations Verifies that the project is accessible to the tenant, processed and ready for element listing/filtering operations. Updates access timestamp for tiered storage. Args: project_id: Project ID in external format (prj_123) session: Async database session tenant_id: Tenant ID for security isolation Returns: Project: Validated project with accessible elements Raises: ProjectNotFoundError: If project not found or not accessible ProjectNotReadyError: If project not yet processed """ try: internal_id = int(project_id.replace('prj_', '')) except ValueError: raise ProjectNotFoundError(project_id) query = select(Project).where( and_( Project.id == internal_id, Project.tenant_id == tenant_id ) ) result = await session.execute(query) project = result.scalar_one_or_none() if not project: raise ProjectNotFoundError(project_id) if not project.is_ready(): raise ProjectNotReadyError(project_id, project.status.value) # Touch last access for tiered storage project.touch_last_access() await session.flush() return project @router.get("/{project_id}/elements", response_model=ElementListResponse) async def list_elements( project_id: str, request: Request, # === TYPE FILTERS === ifc_type: Optional[List[str]] = FastAPIQuery(None, description="Filter by IFC types (IfcWall, IfcWindow, etc.)"), element_type: Optional[List[str]] = FastAPIQuery(None, description="Filter by element types (wall, window, door, etc.)"), level_name: Optional[List[str]] = FastAPIQuery(None, description="Filter by level/floor names"), material_name: Optional[str] = FastAPIQuery(None, description="Filter by material name (partial match)", max_length=200), # === NUMERIC FILTERS === area_gt: Optional[float] = FastAPIQuery(None, description="Minimum area in m²"), area_lt: Optional[float] = FastAPIQuery(None, description="Maximum area in m²"), volume_gt: Optional[float] = FastAPIQuery(None, description="Minimum volume in m³"), volume_lt: Optional[float] = FastAPIQuery(None, description="Maximum volume in m³"), # === BOOLEAN FILTERS === has_geometry: Optional[bool] = FastAPIQuery(None, description="Has 3D geometry"), has_properties: Optional[bool] = FastAPIQuery(None, description="Has IFC properties"), is_external: Optional[bool] = FastAPIQuery(None, description="Is external element"), # === SEARCH AND PAGINATION === search: Optional[str] = FastAPIQuery(None, description="Full-text search on names and properties", max_length=200), limit: int = FastAPIQuery(50, description="Number of elements to return", ge=1, le=200), cursor: Optional[str] = FastAPIQuery(None, description="Pagination cursor for next elements"), session: AsyncSession = Depends(get_async_session) ): """ List project elements with advanced filter options **Supported Filters:** **By Type:** - `ifc_type`: Standard IFC types (IfcWall, IfcWindow, IfcDoor, etc.) - `element_type`: Simplified types (wall, window, door, beam, column) - `level_name`: Filter by specific floor/level - `material_name`: Partial match search on material names **Numeric Filters:** - `area_gt/lt`: Surface area range in m² - `volume_gt/lt`: Volume range in m³ - Supports combinations for precise ranges **Geometric Filters:** - `has_geometry`: Only elements with 3D representation - `has_properties`: Only elements with IFC properties - `is_external`: External envelope elements **Advanced Search:** - `search`: Full-text on names, descriptions and properties - Supports implicit AND operators for multiple words **Cursor-Based Pagination:** - More efficient for large datasets vs offset/limit - Consistent even with concurrent inserts/updates - `cursor` for forward/backward navigation **Usage Examples:** ``` # All windows with area > 2m² GET /prj_123/elements?element_type=window&area_gt=2.0 # External walls on ground floor GET /prj_123/elements?element_type=wall&is_external=true&level_name=Ground Floor # Search elements containing "acciaio" GET /prj_123/elements?search=acciaio # First 100 doors with geometry GET /prj_123/elements?element_type=door&has_geometry=true&limit=100 ``` Args: project_id: Project ID (prj_123) Various optional filter parameters Returns: ElementListResponse: Element list with pagination metadata Raises: ProjectNotFoundError: Project not found ProjectNotReadyError: Project not processed ValidationError: Invalid filter parameters """ tenant_id = getattr(request.state, "tenant_id", "unknown") # === PROJECT VALIDATION === project = await get_project_for_elements(project_id, session, tenant_id) # === BASE QUERY CONSTRUCTION === # Optimized query with indexes on project_id and common filter fields query = select(Element).where(Element.project_id == project.id) # === APPLY FILTERS === # Filter by IFC types (exact match, case insensitive) if ifc_type: query = query.where(Element.ifc_type.in_(ifc_type)) # Filter by simplified element types if element_type: query = query.where(Element.element_type.in_(element_type)) if level_name: query = query.where(Element.level_name.in_(level_name)) if material_name: query = query.where(Element.material_name.ilike(f"%{material_name}%")) # Numeric filters if area_gt is not None: query = query.where(Element.area >= area_gt) if area_lt is not None: query = query.where(Element.area <= area_lt) if volume_gt is not None: query = query.where(Element.volume >= volume_gt) if volume_lt is not None: query = query.where(Element.volume <= volume_lt) # Boolean filters if has_geometry is not None: query = query.where(Element.has_geometry == has_geometry) if has_properties is not None: query = query.where(Element.has_properties == has_properties) if is_external is not None: query = query.where(Element.is_external == is_external) # Search filter if search: search_term = f"%{search.lower()}%" query = query.where( or_( Element.name.ilike(search_term), Element.description.ilike(search_term), Element.tag.ilike(search_term), Element.material_name.ilike(search_term) ) ) # Apply cursor pagination if cursor: try: cursor_id = int(cursor) query = query.where(Element.id > cursor_id) except ValueError: pass # Invalid cursor, ignore # Apply limit and ordering query = query.order_by(Element.id).limit(limit + 1) # Execute query result = await session.execute(query) elements = result.scalars().all() # Check for more results has_next = len(elements) > limit if has_next: elements = elements[:-1] # Remove extra element # Generate next cursor next_cursor = str(elements[-1].id) if has_next and elements else None # Convert to summary format element_summaries = [] for element in elements: element_summaries.append({ "element_id": f"el_{element.id}", "ifc_global_id": element.ifc_global_id, "ifc_type": element.ifc_type, "element_type": element.element_type, "name": element.name, "level_name": element.level_name, "area": element.area, "volume": element.volume, "material_name": element.material_name, "bounding_box": element.bounding_box, "centroid": {"x": element.centroid[0], "y": element.centroid[1], "z": element.centroid[2]} if element.centroid else None, "has_geometry": element.has_geometry, "has_properties": element.has_properties }) # Get summary statistics for the filtered set count_query = select(func.count(Element.id)).where(Element.project_id == project.id) # Apply same filters to count query (simplified) if ifc_type: count_query = count_query.where(Element.ifc_type.in_(ifc_type)) total_result = await session.execute(count_query) total_count = total_result.scalar() return ElementListResponse( elements=element_summaries, pagination={ "limit": limit, "cursor": cursor, "has_next": has_next, "next_cursor": next_cursor, "total_count": total_count }, total_elements=total_count, by_type=None, # Could be expensive to calculate by_level=None ) @router.get("/{element_id}", response_model=ElementResponse) async def get_element_details( element_id: str, request: Request, include_geometry: bool = FastAPIQuery(False, description="Include detailed geometry"), include_relationships: bool = FastAPIQuery(False, description="Include relationships"), session: AsyncSession = Depends(get_async_session) ): """ Get detailed information about a specific element """ tenant_id = getattr(request.state, "tenant_id", "unknown") # Parse element ID try: internal_id = int(element_id.replace('el_', '')) except ValueError: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid element ID format" ) # Query element with project info for tenant validation query = select(Element).join(Project).where( and_( Element.id == internal_id, Project.tenant_id == tenant_id ) ) result = await session.execute(query) element = result.scalar_one_or_none() if not element: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Element not found" ) # Touch last access for tiered storage (element access implies project access) project_query = select(Project).where( and_( Project.id == element.project_id, Project.tenant_id == tenant_id ) ) project_result = await session.execute(project_query) project = project_result.scalar_one_or_none() if project: project.touch_last_access() await session.flush() # Build response response_data = { "element_id": element_id, "project_id": f"prj_{element.project_id}", "ifc_global_id": element.ifc_global_id, "ifc_type": element.ifc_type, "ifc_class": element.ifc_class, "element_type": element.element_type, "name": element.name, "description": element.description, "tag": element.tag, "level_name": element.level_name, "level_elevation": element.level_elevation, "building_name": element.building_name, "site_name": element.site_name, # Metrics with units "area": {"value": element.area, "unit": "m2"} if element.area else None, "volume": {"value": element.volume, "unit": "m3"} if element.volume else None, "length": {"value": element.length, "unit": "m"} if element.length else None, "width": {"value": element.width, "unit": "m"} if element.width else None, "height": {"value": element.height, "unit": "m"} if element.height else None, "perimeter": {"value": element.perimeter, "unit": "m"} if element.perimeter else None, # Material "material_name": element.material_name, "material_category": element.material_category, "material_properties": element.material_properties or {}, # Properties "properties": _format_properties(element.properties), "quantities": _format_quantities(element.quantities), "classifications": element.classifications or {}, # Special properties "fire_rating": element.fire_rating, "acoustic_rating": element.acoustic_rating, "thermal_transmittance": element.thermal_transmittance, "thermal_mass": element.thermal_mass, # Flags "has_geometry": element.has_geometry, "has_properties": element.has_properties, "has_materials": element.has_materials, "is_external": element.is_external, "is_load_bearing": element.is_load_bearing, "combustible": element.combustible, # Timestamps "created_at": element.created_at, "updated_at": element.updated_at } # Add detailed geometry if requested if include_geometry and element.has_geometry: response_data["geometry"] = { "has_geometry": True, "bounding_box": element.bounding_box, "centroid": {"x": element.centroid[0], "y": element.centroid[1], "z": element.centroid[2]} if element.centroid else None, "surface_area": element.area, # Placeholder "perimeter": element.perimeter, "lod": "medium" # Placeholder } # Add relationships if requested if include_relationships: response_data["relationships"] = { "parent_element_id": f"el_{element.parent_element_id}" if element.parent_element_id else None, "child_element_ids": [], # Would need additional query "adjacent_elements": [], # Would need spatial analysis "containing_space": None, # Would need spatial query "contained_elements": [], "assembly_id": element.assembly_id, "assembly_members": [], # Would need additional query "connected_elements": [], "supports": [], "supported_by": [] } return ElementResponse(**response_data) def _format_properties(properties_dict: dict) -> dict: """Format properties dictionary for API response""" if not properties_dict: return {} formatted = {} for key, value in properties_dict.items(): if isinstance(value, dict) and 'value' in value: # Already formatted formatted[key] = value else: # Simple value, format it formatted[key] = { "name": key, "value": value, "unit": None, "source": "IFC" } return formatted def _format_quantities(quantities_dict: dict) -> dict: """Format quantities dictionary for API response""" if not quantities_dict: return {} formatted = {} for key, value in quantities_dict.items(): if isinstance(value, dict): formatted[key] = value else: formatted[key] = { "value": value, "unit": "unknown" } return formatted @router.get("/{project_id}/elements/summary", response_model=ElementSummaryResponse) async def get_elements_summary( project_id: str, request: Request, session: AsyncSession = Depends(get_async_session) ): """ Get summary statistics for all elements in a project """ tenant_id = getattr(request.state, "tenant_id", "unknown") # Validate project project = await get_project_for_elements(project_id, session, tenant_id) # Get element counts by type type_query = select( Element.ifc_type, func.count(Element.id).label('count') ).where( Element.project_id == project.id ).group_by(Element.ifc_type) type_result = await session.execute(type_query) by_ifc_type = {row.ifc_type: row.count for row in type_result} # Get element counts by level level_query = select( Element.level_name, func.count(Element.id).label('count') ).where( and_( Element.project_id == project.id, Element.level_name.isnot(None) ) ).group_by(Element.level_name) level_result = await session.execute(level_query) by_level = {row.level_name: row.count for row in level_result} # Get material counts material_query = select( Element.material_name, func.count(Element.id).label('count') ).where( and_( Element.project_id == project.id, Element.material_name.isnot(None) ) ).group_by(Element.material_name) material_result = await session.execute(material_query) by_material = {row.material_name: row.count for row in material_result} # Get geometry/property statistics stats_query = select( func.count(Element.id).label('total'), func.count().filter(Element.has_geometry == True).label('with_geometry'), func.count().filter(Element.has_properties == True).label('with_properties'), func.count().filter(Element.has_materials == True).label('with_materials'), func.sum(Element.area).label('total_area'), func.sum(Element.volume).label('total_volume') ).where(Element.project_id == project.id) stats_result = await session.execute(stats_query) stats = stats_result.first() # Get unique levels and buildings spatial_query = select( func.array_agg(func.distinct(Element.level_name)).label('levels'), func.array_agg(func.distinct(Element.building_name)).label('buildings') ).where(Element.project_id == project.id) spatial_result = await session.execute(spatial_query) spatial = spatial_result.first() return ElementSummaryResponse( project_id=project_id, total_elements=stats.total, by_ifc_type=by_ifc_type, by_element_type={}, # Would need to calculate by_level=by_level, by_material=by_material, with_geometry=stats.with_geometry, with_properties=stats.with_properties, with_materials=stats.with_materials, levels=[level for level in (spatial.levels or []) if level], buildings=[building for building in (spatial.buildings or []) if building], data_completeness={ "geometry": (stats.with_geometry / stats.total * 100) if stats.total > 0 else 0, "properties": (stats.with_properties / stats.total * 100) if stats.total > 0 else 0, "materials": (stats.with_materials / stats.total * 100) if stats.total > 0 else 0 }, common_properties=[], # Would need to analyze property frequency total_area={"value": float(stats.total_area), "unit": "m2"} if stats.total_area else None, total_volume={"value": float(stats.total_volume), "unit": "m3"} if stats.total_volume else None, total_length=None # Would need to calculate )