from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.ext.asyncio import AsyncSession from typing import List, Optional, Dict, Any from datetime import datetime, date from uuid import UUID from sqlmodel import select, col from sqlalchemy.orm import selectinload from app.core.database import get_session from app.core.logging import get_logger from app.api.deps import get_current_user from app.models import User from app.models.tenant import Tenant from app.models.booking import Appointment, AppointmentStatus, Service logger = get_logger(__name__) router = APIRouter(prefix="/bookings", tags=["Bookings"]) # ----------------------------------------------------------------------------- # BOOKING SETTINGS # ----------------------------------------------------------------------------- @router.get("/settings") async def get_booking_settings( session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Get company booking settings for the tenant.""" tenant = await session.get(Tenant, current_user.tenant_id) if not tenant: raise HTTPException(status_code=404, detail="Tenant not found") booking_settings = tenant.booking_settings or {} return { "working_hours": booking_settings.get("working_hours", {"start": "09:00", "end": "18:00"}), "working_days": booking_settings.get("working_days", [0, 1, 2, 3, 4]), # Mon-Fri "slot_duration": booking_settings.get("slot_duration", 30), "timezone": tenant.timezone or "Asia/Bishkek" } # ----------------------------------------------------------------------------- # APPOINTMENTS # ----------------------------------------------------------------------------- @router.get("/") async def list_appointments( start_date: Optional[date] = None, end_date: Optional[date] = None, status: Optional[str] = None, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """List appointments for the tenant with enriched data.""" from app.models.booking import Resource query = select(Appointment).where(Appointment.tenant_id == current_user.tenant_id) if start_date: query = query.where(Appointment.start_time >= datetime.combine(start_date, datetime.min.time())) if end_date: query = query.where(Appointment.start_time <= datetime.combine(end_date, datetime.max.time())) if status: query = query.where(Appointment.status == status) # Order by start time desc query = query.order_by(col(Appointment.start_time).desc()) # Eager load relationships query = query.options( selectinload(Appointment.lead), selectinload(Appointment.service), selectinload(Appointment.resource) ) result = await session.execute(query) appointments = result.scalars().all() # Return enriched data return [ { "id": str(a.id), "lead_id": str(a.lead_id) if a.lead_id else None, "lead_name": a.lead.name if a.lead and a.lead.name else None, "service_id": str(a.service_id) if a.service_id else None, "service_name": a.service.name if a.service else "Консультация", "resource_id": str(a.resource_id) if a.resource_id else None, "resource_name": a.resource.name if a.resource else None, "start_time": a.start_time.isoformat() if a.start_time else None, "end_time": a.end_time.isoformat() if a.end_time else None, "status": a.status.value if a.status else "scheduled", "notes": a.notes } for a in appointments ] @router.get("/lead/{lead_id}") async def get_appointments_by_lead( lead_id: UUID, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Get all appointments for a specific lead.""" query = select(Appointment).where( Appointment.tenant_id == current_user.tenant_id, Appointment.lead_id == lead_id ).options( selectinload(Appointment.service), selectinload(Appointment.resource) ).order_by(col(Appointment.start_time).desc()) result = await session.execute(query) appointments = result.scalars().all() return [ { "id": str(a.id), "start_time": a.start_time.isoformat() if a.start_time else None, "end_time": a.end_time.isoformat() if a.end_time else None, "status": a.status.value if a.status else "scheduled", "service_name": a.service.name if a.service else None, "resource_name": a.resource.name if a.resource else None, "notes": a.notes } for a in appointments ] @router.post("/", response_model=Appointment) async def create_appointment( appointment: Appointment, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Manually create an appointment.""" # Ensure tenant_id is set appointment.tenant_id = current_user.tenant_id # Check if service exists, or create default service = None if appointment.service_id: service = await session.get(Service, appointment.service_id) if not service or service.tenant_id != current_user.tenant_id: raise HTTPException(status_code=404, detail="Service not found") else: # Find or create default service stmt = select(Service).where( Service.tenant_id == current_user.tenant_id, Service.name == "Консультация" ).limit(1) result = await session.execute(stmt) service = result.scalar_one_or_none() if not service: service = Service( tenant_id=current_user.tenant_id, name="Консультация", duration_minutes=30, price=0.0, is_active=True ) session.add(service) await session.flush() appointment.service_id = service.id session.add(appointment) await session.commit() await session.refresh(appointment) # Notify resource (expert) if they have Telegram configured if appointment.resource_id: try: # 1. Notify Resource (Expert) resource = await session.get(Resource, appointment.resource_id) if resource and resource.telegram_chat_id: notification_service = get_notification_service() # Format date/time appt_date = appointment.start_time.strftime("%d.%m.%Y") appt_time = appointment.start_time.strftime("%H:%M") # Get client name lead = await session.get(Lead, appointment.lead_id) if appointment.lead_id else None client_name = lead.name if lead and lead.name else (appointment.notes or "Клиент") await notification_service.notify_resource_booking( session=session, resource_chat_id=resource.telegram_chat_id, resource_name=resource.name, client_name=client_name, appointment_time=appt_time, appointment_date=appt_date, service_name=service.name if service else None, notification_type="new" ) except Exception as e: logger.error(f"Failed to send resource notification: {e}") # [NEW] Notify Tenant (Manager/Channel) if enabled try: tenant = await session.get(Tenant, current_user.tenant_id) settings = tenant.notification_settings or {} if settings.get("notify_on_booking", True): # Determine where to send (Chat ID or Channel ID) # Prioritize Channel > Chat ID for general alerts like bookings # Actually, use telegram_chat_id from settings (which might be personal or channel) # OR telegram_channel_id if we want separate feed? # User said "add to settings notifications about bookings". # Usually bookings go to the main notification channel. target_chat_id = settings.get("telegram_channel_id") or settings.get("telegram_chat_id") if target_chat_id: from app.services.telegram_service import telegram_service from app.core.config import settings as app_settings token = app_settings.TELEGRAM_NOTIFICATION_TOKEN if token: appt_date = appointment.start_time.strftime("%d.%m") appt_time = appointment.start_time.strftime("%H:%M") lead_name = "Клиент" if appointment.lead_id: l = await session.get(Lead, appointment.lead_id) lead_name = l.name if l else "Клиент" msg = f"📅 НОВАЯ ЗАПИСЬ!\n\n👤 {lead_name}\n🕘 {appt_date} в {appt_time}\n🛠 {service.name if service else 'Услуга'}" await telegram_service.send_message( token=token, chat_id=target_chat_id, text=msg ) logger.info(f"📅 Booking notification sent to Tenant {target_chat_id}") except Exception as e: logger.error(f"Failed to send tenant booking notification: {e}") return appointment @router.delete("/{appointment_id}") async def cancel_appointment( appointment_id: UUID, hard: bool = False, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Cancel or delete an appointment. Args: hard: If True, permanently delete. If False (default), just mark as cancelled. """ appointment = await session.get(Appointment, appointment_id) if not appointment or appointment.tenant_id != current_user.tenant_id: raise HTTPException(status_code=404, detail="Appointment not found") if hard: # Hard delete - remove from database completely await session.delete(appointment) await session.commit() logger.info(f"Hard deleted appointment {appointment_id}") else: # Soft delete - just mark as cancelled appointment.status = AppointmentStatus.CANCELLED session.add(appointment) await session.commit() logger.info(f"Soft cancelled appointment {appointment_id}") return {"ok": True} from pydantic import BaseModel class AppointmentUpdateRequest(BaseModel): status: Optional[str] = None notes: Optional[str] = None start_time: Optional[datetime] = None end_time: Optional[datetime] = None resource_id: Optional[UUID] = None @router.patch("/{appointment_id}") async def update_appointment( appointment_id: UUID, update_data: AppointmentUpdateRequest, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Update appointment status, notes, time or resource. Sends Telegram notification to client if time is changed. """ from app.models.booking import Resource from app.models.lead import Lead appointment = await session.get(Appointment, appointment_id) if not appointment or appointment.tenant_id != current_user.tenant_id: raise HTTPException(status_code=404, detail="Appointment not found") old_start_time = appointment.start_time time_changed = False if update_data.status: try: appointment.status = AppointmentStatus(update_data.status) except ValueError: raise HTTPException(status_code=400, detail=f"Invalid status: {update_data.status}") if update_data.notes is not None: appointment.notes = update_data.notes if update_data.start_time is not None: if update_data.start_time != old_start_time: time_changed = True appointment.start_time = update_data.start_time if update_data.end_time is not None: appointment.end_time = update_data.end_time if update_data.resource_id is not None: # Verify resource exists and belongs to tenant resource = await session.get(Resource, update_data.resource_id) if resource and resource.tenant_id == current_user.tenant_id: appointment.resource_id = update_data.resource_id session.add(appointment) await session.commit() await session.refresh(appointment) # Send Telegram notification if time changed if time_changed and appointment.lead_id: try: lead = await session.get(Lead, appointment.lead_id) tenant = await session.get(Tenant, current_user.tenant_id) if lead and lead.telegram_id and tenant and tenant.telegram_bot_token: import httpx # Format times for message old_time_str = old_start_time.strftime("%d.%m в %H:%M") if old_start_time else "неизвестно" new_time_str = appointment.start_time.strftime("%d.%m в %H:%M") if appointment.start_time else "неизвестно" message = f"📅 Ваша запись перенесена!\n\n❌ Было: {old_time_str}\n✅ Стало: {new_time_str}\n\nЕсли это время вам не подходит, напишите нам." async with httpx.AsyncClient() as client: await client.post( f"https://api.telegram.org/bot{tenant.telegram_bot_token}/sendMessage", json={ "chat_id": lead.telegram_id, "text": message }, timeout=10.0 ) logger.info(f"📱 Sent reschedule notification to client {lead.telegram_id}") except Exception as e: logger.error(f"Failed to send reschedule notification: {e}") return { "id": str(appointment.id), "start_time": appointment.start_time.isoformat() if appointment.start_time else None, "end_time": appointment.end_time.isoformat() if appointment.end_time else None, "status": appointment.status.value if appointment.status else None, "resource_id": str(appointment.resource_id) if appointment.resource_id else None, "ok": True } # ----------------------------------------------------------------------------- # SERVICES # ----------------------------------------------------------------------------- @router.get("/services", response_model=List[Service]) async def list_services( session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """List available booking services.""" query = select(Service).where(Service.tenant_id == current_user.tenant_id) result = await session.execute(query) return result.scalars().all() @router.post("/services", response_model=Service) async def create_service( service: Service, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Create or update a booking service.""" service.tenant_id = current_user.tenant_id session.add(service) await session.commit() await session.refresh(service) return service # ----------------------------------------------------------------------------- # RESOURCES # ----------------------------------------------------------------------------- from app.models.booking import Resource, ResourceService from pydantic import BaseModel as PydanticBaseModel class ResourceCreateRequest(PydanticBaseModel): name: str description: Optional[str] = None working_hours: Optional[Dict[str, Any]] = None sort_order: int = 0 service_ids: Optional[List[UUID]] = None # Services this resource can provide telegram_chat_id: Optional[str] = None # Telegram notifications user_id: Optional[UUID] = None # Link to manager class ResourceUpdateRequest(PydanticBaseModel): name: Optional[str] = None description: Optional[str] = None working_hours: Optional[Dict[str, Any]] = None sort_order: Optional[int] = None is_active: Optional[bool] = None service_ids: Optional[List[UUID]] = None telegram_chat_id: Optional[str] = None # Telegram notifications user_id: Optional[UUID] = None # Link to manager @router.get("/resources") async def list_resources( session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """List all booking resources for the tenant.""" query = select(Resource).where( Resource.tenant_id == current_user.tenant_id ).order_by(Resource.sort_order, Resource.name) result = await session.execute(query) resources = result.scalars().all() # Get services for each resource resource_data = [] for resource in resources: # Get linked services services_query = select(Service).join(ResourceService).where( ResourceService.resource_id == resource.id ) services_result = await session.execute(services_query) services = [{"id": str(s.id), "name": s.name} for s in services_result.scalars().all()] resource_data.append({ "id": str(resource.id), "name": resource.name, "description": resource.description, "working_hours": resource.working_hours, "sort_order": resource.sort_order, "is_active": resource.is_active, "telegram_chat_id": resource.telegram_chat_id, "user_id": str(resource.user_id) if resource.user_id else None, "services": services }) return resource_data @router.post("/resources") async def create_resource( data: ResourceCreateRequest, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Create a new booking resource.""" resource = Resource( tenant_id=current_user.tenant_id, name=data.name, description=data.description, working_hours=data.working_hours, sort_order=data.sort_order, telegram_chat_id=data.telegram_chat_id, user_id=data.user_id ) session.add(resource) await session.flush() # Get ID # Link services if provided if data.service_ids: for service_id in data.service_ids: # Verify service exists and belongs to tenant service = await session.get(Service, service_id) if service and service.tenant_id == current_user.tenant_id: link = ResourceService(resource_id=resource.id, service_id=service_id) session.add(link) await session.commit() await session.refresh(resource) logger.info(f"✅ Created resource '{resource.name}' for tenant {current_user.tenant_id}") return {"id": str(resource.id), "name": resource.name, "ok": True} @router.patch("/resources/{resource_id}") async def update_resource( resource_id: UUID, data: ResourceUpdateRequest, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Update a booking resource with Telegram ID sync.""" resource = await session.get(Resource, resource_id) if not resource or resource.tenant_id != current_user.tenant_id: raise HTTPException(status_code=404, detail="Resource not found") # Prepare response for potential conflict telegram_conflict = None # Update fields if data.name is not None: resource.name = data.name if data.description is not None: resource.description = data.description if data.working_hours is not None: resource.working_hours = data.working_hours if data.sort_order is not None: resource.sort_order = data.sort_order if data.is_active is not None: resource.is_active = data.is_active if data.telegram_chat_id is not None: resource.telegram_chat_id = data.telegram_chat_id # Handle user_id linking with Telegram ID sync if data.user_id is not None: # Verify user exists and belongs to tenant linked_user = await session.get(User, data.user_id) if not linked_user or linked_user.tenant_id != current_user.tenant_id: raise HTTPException(status_code=400, detail="User not found or not in same tenant") resource.user_id = data.user_id # Telegram ID sync logic: # We'll use resource.telegram_chat_id as the canonical source # If resource has ID, user inherits it (via API call from frontend) # If user has ID but resource doesn't, copy to resource # Frontend handles conflict resolution by choosing one # Update service links if provided if data.service_ids is not None: # Remove existing links delete_query = select(ResourceService).where(ResourceService.resource_id == resource_id) result = await session.execute(delete_query) for link in result.scalars().all(): await session.delete(link) # Add new links for service_id in data.service_ids: service = await session.get(Service, service_id) if service and service.tenant_id == current_user.tenant_id: link = ResourceService(resource_id=resource_id, service_id=service_id) session.add(link) session.add(resource) await session.commit() await session.refresh(resource) return { "id": str(resource.id), "name": resource.name, "telegram_chat_id": resource.telegram_chat_id, "user_id": str(resource.user_id) if resource.user_id else None, "ok": True } @router.delete("/resources/{resource_id}") async def delete_resource( resource_id: UUID, hard: bool = False, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """Delete or deactivate a resource.""" resource = await session.get(Resource, resource_id) if not resource or resource.tenant_id != current_user.tenant_id: raise HTTPException(status_code=404, detail="Resource not found") if hard: # Delete service links first delete_query = select(ResourceService).where(ResourceService.resource_id == resource_id) result = await session.execute(delete_query) for link in result.scalars().all(): await session.delete(link) await session.delete(resource) logger.info(f"🗑️ Hard deleted resource {resource_id}") else: resource.is_active = False session.add(resource) logger.info(f"📴 Deactivated resource {resource_id}") await session.commit() return {"ok": True} @router.get("/resources/available") async def get_available_resources( start_time: datetime, end_time: datetime, service_id: Optional[UUID] = None, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Get available resources for a specific time slot. Checks working hours and existing appointments. """ tenant_id = current_user.tenant_id # Get resources query query = select(Resource).where( Resource.tenant_id == tenant_id, Resource.is_active == True ) # Filter by service if provided if service_id: query = query.join(ResourceService).where( ResourceService.service_id == service_id ) result = await session.execute(query) resources = result.scalars().all() # Check each resource for availability available = [] day_of_week = str(start_time.weekday()) # 0=Monday for resource in resources: # Check working hours if resource.working_hours: day_hours = resource.working_hours.get(day_of_week) if not day_hours: continue # Day off resource_start = datetime.strptime(day_hours.get("start", "00:00"), "%H:%M").time() resource_end = datetime.strptime(day_hours.get("end", "23:59"), "%H:%M").time() # Check if requested time is within working hours if start_time.time() < resource_start or end_time.time() > resource_end: continue # Check existing appointments conflict_query = select(Appointment).where( Appointment.resource_id == resource.id, Appointment.status == AppointmentStatus.SCHEDULED, Appointment.start_time < end_time, Appointment.end_time > start_time ) conflict_result = await session.execute(conflict_query) conflicts = conflict_result.scalars().all() if not conflicts: available.append({ "id": str(resource.id), "name": resource.name, "description": resource.description }) return {"available": available, "total": len(available)}