from fastapi import APIRouter, Depends, HTTPException, status, Response from fastapi.responses import JSONResponse from datetime import datetime from ..dependencies import users_token, permissions_checker, database from ..models import events, users from pydantic import EmailStr from typing import Annotated from bson import ObjectId from datetime import datetime router = APIRouter() @router.get("/events", tags=["events"], response_model=list[events.EventOut]) async def read_events(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20, id_event: str | None = None, name: str | None = None, status: int = 1, tags: str | None = None, organizers: str | None = None, current_datetime: datetime | None = None, date_event: datetime |None = None, start_date: datetime | None = None, end_date: datetime | None = None): if limit < 1 or skip < 0 or limit < skip: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="skip should be greater than 0 and limit should be greater than 1. Limit should be greater than skip" ) limit = limit + skip listEvents = [] event_repository = events.EventRepository(database=database.database) object_search = {} date_selected: bool = False if date_event is not None: start_of_day = datetime.combine(date_event, datetime.min.time()) # 2024-11-23 00:00:00 end_of_day = datetime.combine(date_event, datetime.max.time()) date_selected = True if start_date is not None and end_date is not None: start_of_day = datetime.combine(start_date, datetime.min.time()) # 2024-11-23 00:00:00 end_of_day = datetime.combine(end_date, datetime.max.time()) date_selected = True if current_datetime is not None: object_search ={ "$or": [{"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } if date_selected is True: object_search ={ "$and": [{"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} # Upcoming events ] } if status is not 1: object_search = {"status":{"$eq": status}} if current_datetime is not None: object_search = { "$and": [ {"status":{"$eq": status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ]} if date_selected is True: object_search = { "$and": [ {"status":{"$eq": status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ]} if tags is not None: object_search = {"$and":[{"tags":{"$eq": tags}}, {"status":{"$eq":status}}]} if current_datetime is not None: object_search = {"$and":[{"tags":{"$eq": tags}}, {"status":{"$eq":status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ] } if date_selected is True: object_search = {"$and":[{"tags":{"$eq": tags}}, {"status":{"$eq":status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ] } if organizers is not None: object_search = {"$and":[{"organizers":{"$eq": organizers}}, {"status":{"$eq":status}}]} if current_datetime is not None: object_search = {"$and":[{"organizers":{"$eq": organizers}}, {"status":{"$eq":status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ]} if date_selected is True: object_search = {"$and":[{"organizers":{"$eq": organizers}}, {"status":{"$eq":status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ]} if id_event is not None: eventid = ObjectId(id_event) object_search = {"$and":[{"id":{"$regex": eventid}}, {"status":{"$eq":status}}]} if current_datetime is not None: object_search = {"$and":[{"id":{"$regex": eventid}}, {"status":{"$eq":status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ]} if date_selected is True: object_search = {"$and":[{"id":{"$regex": eventid}}, {"status":{"$eq":status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ]} if name is not None: object_search = {"$and":[{"name":{"$regex": name}}, {"status":{"$eq":status}}]} if current_datetime is not None: object_search = {"$and":[{"name":{"$regex": name}}, {"status":{"$eq":status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ]} if date_selected is True: object_search = {"$and":[{"name":{"$regex": name}}, {"status":{"$eq":status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ]} for event_index in event_repository.find_by(object_search, limit=limit, skip=skip): event = events.EventOut(id=event_index.id, tags=event_index.tags, imgUrl=event_index.imgUrl, name=event_index.name, description=event_index.description, place=event_index.place, status=event_index.status, start_date=event_index.start_date, end_date=event_index.end_date) listEvents.append(event) return listEvents @router.get("/events/search", tags=["events"], response_model=list[events.EventOut]) async def search_events(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], skip: int = 0, limit: int = 20, item: str | None = None, status: int = 1, min_lat: float | None = None, max_lat: float | None = None, min_lon: float | None = None, max_lon: float | None = None, current_datetime: datetime | None = None, date_event: datetime | None = None, start_date: datetime | None = None, end_date: datetime | None = None): if limit < 1 or skip < 0 or limit < skip: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="skip should be greater than 0 and limit should be greater than 1. Limit should be greater than skip" ) limit = limit + skip listEvents = [] event_repository = events.EventRepository(database=database.database) object_search = {} date_selected: bool = False if date_event is not None: start_of_day = datetime.combine(date_event, datetime.min.time()) # 2024-11-23 00:00:00 end_of_day = datetime.combine(date_event, datetime.max.time()) date_selected = True if start_date is not None and end_date is not None: start_of_day = datetime.combine(start_date, datetime.min.time()) # 2024-11-23 00:00:00 end_of_day = datetime.combine(end_date, datetime.max.time()) date_selected = True if min_lat is not None and max_lat is not None and min_lon is not None and max_lon is not None: object_search = { "$and": [ {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude } ] } if current_datetime is not None: object_search = { "$and": [ {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude }, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ] } if date_selected is True: object_search = { "$and": [ {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude }, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ] } if item is not None: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}} ] } if current_datetime is not None: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}}, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ] } if date_selected is True: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}}, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ] } if min_lat is not None and max_lat is not None and min_lon is not None and max_lon is not None: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude } ] } if current_datetime is not None: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude }, { "$or": [ {"start_date": {"$gte": current_datetime}}, # Upcoming events {"$and": [ # Ongoing events {"start_date": {"$lte": current_datetime}}, # Already started {"$or": [ {"end_date": {"$gte": current_datetime}}, # End date in the future {"end_date": None} # No end date set ]} ]} ] } ] } if date_selected is True: object_search = { "$and": [ { "$or": [ {"name": {"$regex": item}}, {"tags": {"$regex": item}}, {"organizers": {"$regex": item}} ] }, {"status": {"$eq": status}}, { "latitude": {"$gte": min_lat}, # Minimum latitude }, { "latitude": {"$lte": max_lat}, # Maximum latitude }, { "longitude": {"$gte": min_lon}, # Minimum longitude }, { "longitude": {"$lte": max_lon}, # Maximum longitude }, {"start_date": {"$gte": start_of_day}}, {"start_date": {"$lte": end_of_day}} ] } for event_index in event_repository.find_by(object_search, limit=limit, skip=skip): event = events.EventOut(id=event_index.id, tags=event_index.tags, imgUrl=event_index.imgUrl, name=event_index.name, description=event_index.description, place=event_index.place, status=event_index.status, start_date=event_index.start_date, end_date=event_index.end_date) listEvents.append(event) return listEvents @router.get("/events/me",tags=["events"]) async def read_users_me(current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]): event_repository = events.EventRepository(database=database.database) listOrganizers = [] for event_index in event_repository.find_by({"organizers":{"$eq": current_user.username}}, limit=limit, skip=skip): event = events.EventOut(id=event_index.id, name=event_index.name, tags=event_index.tags, imgUrl=event_index.imgUrl, description=event_index.description, place=event_index.place, status=event_index.status, start_date=event_index.start_date, end_date=event_index.end_date) listOrganizers.append(event) content = {"organizers":listOrganizers} response = JSONResponse(content=content) return response @router.get("/events/count", tags=["events"]) async def read_events_count(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))]): count = database.database.get_collection("events").estimated_document_count() content = {"count":count} response = JSONResponse(content=content) return response @router.get("/events/{item_id}", tags=["events"], response_model=events.Event) async def read_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]): event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by_id(ObjectId(item_id)) return event @router.delete("/events/me/{item_id}", tags=["events"]) async def delete_event_me(item_id: str, current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], remove: bool = False): event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by_id(ObjectId(item_id)) if remove is True: event.deleted_at = datetime.today() event.status = -1 content = {"message": "event is deleted"} else: event.status = 0 event.deleted_at = datetime.today() content = {"message": "event is disabled"} event_repository.save(event) response = JSONResponse(content=content) return response @router.delete("/events/groups",tags=["events"]) async def delete_events_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove: bool = False, eventids: events.EventIDS | None = None): if len(eventids.ids) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="eventids should be greater than 0" ) event_repository = event.EventRepository(database=database.database) for i in eventids.ids: event = event_repository.find_one_by_id(ObjectId(i)) if remove is True: event.status = -1 event.deleted_at = datetime.today() content = {"message": "events are deleted "} else: event.status = 0 event.disabled_at = datetime.today() content = {"message": "events are disabled"} event_repository.save(event) response = JSONResponse(content=content) return response @router.delete("/events/{item_id}", tags=["events"]) async def delete_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], remove : bool = False): event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by_id(ObjectId(item_id)) if remove is True: event.status = -1 event.deleted_at = datetime.today() content = {"message": "events are deleted"} else: event.status = 0 event.disabled_at = datetime.today() content = {"message": "events are disabled"} event_repository.save(event) response = JSONResponse(content=content) return response @router.put("/events/me/{item_id}",tags=["events"]) async def update_events_me(item_id: str, current_user: Annotated[users.User, Depends(users_token.get_current_active_user)], authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))], eventSingle: events.EventIn | None = None): event_repository = event.EventRepository(database=database.database) event = event_repository.find_one_by_id(ObjectId(item_id)) event.name = eventSingle.name event.description = eventSingle.description event.place = eventSingle.place event.start_date = eventSingle.start_date event.tags = eventSingle.tags event.end_date = eventSingle.end_date event.latitude = eventSingle.latitude event.longitude = eventSingle.longitude event.updated_at = datetime.today() event.imgUrl = eventSingle.imgUrl event_repository.save(event) content = {"message": "event is updated"} response = JSONResponse(content=content) return response @router.put("/events", tags=["events"], status_code=status.HTTP_201_CREATED) async def update_events(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventSingle: events.EventIn | None = None): if eventSingle is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Body request is empty" ) event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by({"name": {'$eq': eventSingle.name}}) if event is not None: raise HTTPException( status_code=status.HTTP_204_NO_CONTENT, detail="name" ) event = events.Event(name=eventSingle.name, description=eventSingle.description, place=eventSingle.place) event.start_date = eventSingle.start_date event.end_date = eventSingle.end_date event.organizers = eventSingle.organizers event.latitude = eventSingle.latitude event.longitude = eventSingle.longitude event.imgUrl = eventSingle.imgUrl event.tags = eventSingle.tags event.status = 1 event.created_at = datetime.today() event_repository.save(event) content = {"message": "event is created"} response = JSONResponse(content=content, status_code=status.HTTP_201_CREATED) return response @router.put("/events/{item_id}", tags=["events"], status_code=status.HTTP_200_OK) async def update_events_id(item_id: str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventSingle: events.EventIn | None = None, response: Response = Response): if eventSingle is None: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Body request is empty" ) event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by({"id": {'$eq': ObjectId(item_id)}}) if event is None: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Event not found" ) event.name = eventSingle.name event.place = eventSingle.place event.description = eventSingle.description event.start_date = eventSingle.start_date event.end_date = eventSingle.end_date event.organizers = eventSingle.organizers event.tags = eventSingle.tags event.latitude = eventSingle.latitude event.longitude = eventSingle.longitude event.updated_at = datetime.today() event.imgUrl = eventSingle.imgUrl event_repository.save(event) content = {"message": "event is updated"} response = JSONResponse(content=content) return response @router.patch("/events/groups",tags=["events"]) async def patch_events_groups(authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))], eventids: events.EventIDS | None = None): if len(eventids.ids) == 0: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="eventids should be greater than 0" ) event_repository = events.EventRepository(database=database.database) content = {"message": "events are enabled"} for i in eventids.ids: event = event_repository.find_one_by_id(ObjectId(i)) event.status = 1 event.disabled_at = None event.deleted_at = None event_repository.save(event) response = JSONResponse(content=content) return response @router.patch("/events/{item_id}", tags=["events"]) async def patch_events_id(item_id : str, authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin"]))]): event_repository = events.EventRepository(database=database.database) event = event_repository.find_one_by_id(ObjectId(item_id)) event.status = 1 event.disabled_at = None event.deleted_at = None event_repository.save(event) content = {"message": "event is enabled"} response = JSONResponse(content=content) return response