nicer looking month view

This commit is contained in:
c-d-p
2025-04-20 23:52:29 +02:00
parent 6cee996fb3
commit 9e8e179a94
25 changed files with 329 additions and 125 deletions

View File

@@ -20,29 +20,57 @@ def create_calendar_event(db: Session, user_id: int, event_data: CalendarEventCr
return event
def get_calendar_events(db: Session, user_id: int, start: datetime | None, end: datetime | None):
"""
Retrieves calendar events for a user, optionally filtered by a date range.
Args:
db: The database session.
user_id: The ID of the user whose events are to be retrieved.
start: The start datetime of the filter range (inclusive).
end: The end datetime of the filter range (exclusive).
Returns:
A list of CalendarEvent objects matching the criteria, ordered by start time.
"""
print(f"Getting calendar events for user {user_id} in range [{start}, {end})")
query = db.query(CalendarEvent).filter(CalendarEvent.user_id == user_id)
# If start and end dates are provided, filter for events overlapping the range.
# An event overlaps if: event_start < query_end AND (event_end IS NULL OR event_end > query_start)
# If start and end dates are provided, filter for events overlapping the range [start, end).
if start and end:
# An event overlaps the range [start, end) if:
# 1. It has a duration (end is not None) AND its interval [event.start, event.end)
# intersects with [start, end). Intersection occurs if:
# event.start < end AND event.end > start
# 2. It's a point event (end is None) AND its start time falls within the range:
# start <= event.start < end
query = query.filter(
CalendarEvent.start < end, # Event starts before the query window ends
or_(
CalendarEvent.end == None, # Event has no end date (considered single point in time at start)
CalendarEvent.end > start # Event ends after the query window starts
# Case 1: Event has duration and overlaps
(CalendarEvent.end != None) & (CalendarEvent.start < end) & (CalendarEvent.end > start),
# Case 2: Event is a point event within the range
(CalendarEvent.end == None) & (CalendarEvent.start >= start) & (CalendarEvent.start < end)
)
)
# If only start is provided, filter events starting on or after start
elif start:
# Includes events with duration starting >= start
# Includes point events occurring >= start
query = query.filter(CalendarEvent.start >= start)
# If only end is provided, filter events ending on or before end (or starting before end if no end date)
# If only end is provided, filter events ending before end, or point events occurring before end
elif end:
# Includes events with duration ending <= end (or starting before end if end is None)
# Includes point events occurring < end
query = query.filter(
or_(
CalendarEvent.end <= end,
(CalendarEvent.end == None and CalendarEvent.start < end)
# Event ends before the specified end time
(CalendarEvent.end != None) & (CalendarEvent.end <= end),
# Point event occurs before the specified end time
(CalendarEvent.end == None) & (CalendarEvent.start < end)
)
)
# Alternative interpretation for "ending before end": include events that *start* before end
# query = query.filter(CalendarEvent.start < end)
return query.order_by(CalendarEvent.start).all() # Order by start time

View File

@@ -1,74 +1,103 @@
# modules/nlp/api.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from core.database import get_db
from modules.auth.dependencies import get_current_user
from modules.auth.models import User
from modules.nlp.service import process_request, ask_ai
from modules.nlp.schemas import ProcessCommandRequest
# Import the response schema
from modules.nlp.schemas import ProcessCommandRequest, ProcessCommandResponse
from modules.calendar.service import create_calendar_event, get_calendar_events, update_calendar_event, delete_calendar_event
# Import the CalendarEvent *model* for type hinting
from modules.calendar.models import CalendarEvent
# Import the CalendarEvent Pydantic schemas for data validation
from modules.calendar.schemas import CalendarEventCreate, CalendarEventUpdate
router = APIRouter(prefix="/nlp", tags=["nlp"])
@router.post("/process-command")
# Helper to format calendar events (expects list of CalendarEvent models)
def format_calendar_events(events: List[CalendarEvent]) -> List[str]:
if not events:
return ["You have no events matching that criteria."]
formatted = ["Here are the events:"]
for event in events:
# Access attributes directly from the model instance
start_str = event.start.strftime("%Y-%m-%d %H:%M") if event.start else "No start time"
end_str = event.end.strftime("%H:%M") if event.end else ""
title = event.title or "Untitled Event"
formatted.append(f"- {title} ({start_str}{' - ' + end_str if end_str else ''})")
return formatted
# Update the response model for the endpoint
@router.post("/process-command", response_model=ProcessCommandResponse)
def process_command(request_data: ProcessCommandRequest, current_user: User = Depends(get_current_user), db: Session = Depends(get_db)):
"""
Process the user command, execute the action, and return a user-friendly response.
Process the user command, execute the action, and return user-friendly responses.
"""
user_input = request_data.user_input
user_input = request_data.user_input
command_data = process_request(user_input)
intent = command_data["intent"]
params = command_data["params"]
response_text = command_data["response_text"]
responses = [response_text] # Start with the initial response
if intent == "error":
raise HTTPException(status_code=400, detail=response_text)
if intent == "clarification_needed":
return {"response": response_text}
if intent == "unknown":
return {"response": response_text}
if intent == "clarification_needed" or intent == "unknown":
return ProcessCommandResponse(responses=responses)
try:
match intent:
case "ask_ai":
ai_answer = ask_ai(**params)
return {"response": ai_answer}
responses.append(ai_answer)
return ProcessCommandResponse(responses=responses)
case "get_calendar_events":
result = get_calendar_events(db, current_user.id, **params)
return {"response": response_text, "details": result}
# get_calendar_events returns List[CalendarEvent models]
events: List[CalendarEvent] = get_calendar_events(db, current_user.id, **params)
responses.extend(format_calendar_events(events))
return ProcessCommandResponse(responses=responses)
case "add_calendar_event":
event = CalendarEventCreate(**params)
result = create_calendar_event(db, current_user.id, event)
return {"response": response_text, "details": result}
# Validate input with Pydantic schema
event_data = CalendarEventCreate(**params)
created_event = create_calendar_event(db, current_user.id, event_data)
start_str = created_event.start.strftime("%Y-%m-%d %H:%M") if created_event.start else "No start time"
title = created_event.title or "Untitled Event"
responses.append(f"Added: {title} starting at {start_str}.")
return ProcessCommandResponse(responses=responses)
case "update_calendar_event":
event_id = params.pop('event_id', None)
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for update.")
# Validate input with Pydantic schema
event_data = CalendarEventUpdate(**params)
result = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
return {"response": response_text, "details": result}
updated_event = update_calendar_event(db, current_user.id, event_id, event_data=event_data)
title = updated_event.title or "Untitled Event"
responses.append(f"Updated event ID {updated_event.id}: {title}.")
return ProcessCommandResponse(responses=responses)
case "delete_calendar_event":
event_id = params.get('event_id')
if event_id is None:
raise HTTPException(status_code=400, detail="Event ID is required for delete.")
result = delete_calendar_event(db, current_user.id, event_id)
return {"response": response_text, "details": {"deleted": True, "event_id": event_id}}
delete_calendar_event(db, current_user.id, event_id)
responses.append(f"Deleted event ID {event_id}.")
return ProcessCommandResponse(responses=responses)
case _:
print(f"Warning: Unhandled intent '{intent}' reached api.py match statement.")
raise HTTPException(status_code=500, detail="An unexpected error occurred processing the command.")
return ProcessCommandResponse(responses=responses)
except HTTPException as http_exc:
raise http_exc
except Exception as e:
print(f"Error executing intent '{intent}': {e}")
raise HTTPException(status_code=500, detail="Sorry, I encountered an error while trying to perform that action.")
return ProcessCommandResponse(responses=["Sorry, I encountered an error while trying to perform that action."])

View File

@@ -1,5 +1,11 @@
# modules/nlp/schemas.py
from pydantic import BaseModel
from typing import List
class ProcessCommandRequest(BaseModel):
user_input: str
class ProcessCommandResponse(BaseModel):
responses: List[str]
# Optional: Keep details if needed for specific frontend logic beyond display
# details: dict | None = None