436 lines
17 KiB
Python
Raw Normal View History

2023-11-06 23:27:47 +01:00
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
2024-12-21 23:05:24 +01:00
from ..models import events, users, tags
2023-11-06 23:27:47 +01:00
from pydantic import EmailStr
2024-12-16 23:51:26 +01:00
from typing import Annotated, Union
2023-11-06 23:27:47 +01:00
from bson import ObjectId
2024-11-09 16:04:47 +01:00
from datetime import datetime
2023-11-06 23:27:47 +01:00
router = APIRouter()
2024-12-16 23:51:26 +01:00
def build_location_filter(min_lat, max_lat, min_lon, max_lon):
"""Build location-based query filters."""
if min_lat is not None and max_lat is not None and min_lon is not None and max_lon is not None:
return [
{"latitude": {"$gte": min_lat}},
{"latitude": {"$lte": max_lat}},
{"longitude": {"$gte": min_lon}},
{"longitude": {"$lte": max_lon}},
]
return []
def build_datetime_filter(current_datetime):
"""Build filters for current datetime."""
if current_datetime:
return {
"$or": [
{"start_date": {"$gte": current_datetime}}, # Upcoming events
{
"$and": [
{"start_date": {"$lte": current_datetime}}, # Already started
{"$or": [
{"end_date": {"$gte": current_datetime}}, # Ongoing
{"end_date": None}, # No end date
]},
],
},
],
}
return None
def build_date_filter(start_date, end_date):
"""Build date range filters."""
if start_date and end_date:
return [
{"start_date": {"$gte": datetime.combine(start_date, datetime.min.time())}},
{"start_date": {"$lte": datetime.combine(end_date, datetime.max.time())}},
]
return []
def build_text_filter(item):
"""Build text-based search filters."""
if item:
return {
"$or": [
{"name": {"$regex": item, "$options": "i"}},
{"tags": {"$regex": item, "$options": "i"}},
{"organizers": {"$regex": item, "$options": "i"}},
]
}
return None
2023-11-06 23:27:47 +01:00
@router.get("/events", tags=["events"], response_model=list[events.EventOut])
2024-12-16 23:51:26 +01:00
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,
):
# Validate `skip` and `limit`
2023-11-06 23:27:47 +01:00
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
2024-12-16 23:51:26 +01:00
detail="`skip` should be >= 0 and `limit` should be > 0 and greater than `skip`.",
2023-11-06 23:27:47 +01:00
)
limit = limit + skip
2024-12-16 23:51:26 +01:00
# Initialize filters
filters = []
# Add status filter
filters.append({"status": {"$eq": status}})
# Add date filters
if date_event:
start_of_day = datetime.combine(date_event, datetime.min.time())
2024-11-23 20:13:03 +01:00
end_of_day = datetime.combine(date_event, datetime.max.time())
2024-12-16 23:51:26 +01:00
filters.extend(build_date_filter(start_of_day, end_of_day))
elif start_date and end_date:
filters.extend(build_date_filter(start_date, end_date))
# Add current datetime filter
datetime_filter = build_datetime_filter(current_datetime)
if datetime_filter:
filters.append(datetime_filter)
# Add text-based filters
if name:
filters.append(build_text_filter(name))
if tags:
filters.append({"tags": {"$eq": tags}})
if organizers:
filters.append({"organizers": {"$eq": organizers}})
2023-11-06 23:27:47 +01:00
2024-12-16 23:51:26 +01:00
# Add ID filter
if id_event:
try:
event_id = ObjectId(id_event)
filters.append({"_id": {"$eq": event_id}})
except Exception:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid event ID format.")
# Combine all filters
object_search = {"$and": filters} if filters else {}
# Fetch and return results
event_repository = events.EventRepository(database=database.database)
list_events = []
2023-11-06 23:27:47 +01:00
for event_index in event_repository.find_by(object_search, limit=limit, skip=skip):
2024-12-16 23:51:26 +01:00
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,
)
list_events.append(event)
2023-11-06 23:27:47 +01:00
2024-12-16 23:51:26 +01:00
return list_events
2023-11-06 23:27:47 +01:00
2024-12-16 23:51:26 +01:00
2024-12-18 23:47:40 +01:00
@router.get("/events/search", tags=["events"], response_model=list[events.EventOut])
2024-12-16 23:51:26 +01:00
async def search_events(
authorize: Annotated[bool, Depends(permissions_checker.PermissionChecker(roles=["Admin", "User"]))],
skip: int = 0,
limit: int = 20,
item: Union[str, None] = None,
status: int = 1,
min_lat: Union[float, None] = None,
max_lat: Union[float, None] = None,
min_lon: Union[float, None] = None,
max_lon: Union[float, None] = None,
current_datetime: Union[datetime, None] = None,
date_event: Union[datetime, None] = None,
start_date: Union[datetime, None] = None,
end_date: Union[datetime, None] = None,
2024-12-21 20:47:33 +01:00
tags: Union[str, None] = None,
2024-12-16 23:51:26 +01:00
):
2024-10-23 21:44:33 +02:00
if limit < 1 or skip < 0 or limit < skip:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
2024-12-16 23:51:26 +01:00
detail="`skip` should be >= 0 and `limit` should be > 0 and greater than `skip`.",
2024-10-23 21:44:33 +02:00
)
limit = limit + skip
2024-12-16 23:51:26 +01:00
# Initialize filters
filters = [{"status": {"$eq": status}}]
# Date filters
if date_event:
start_of_day = datetime.combine(date_event, datetime.min.time())
2024-11-23 20:13:03 +01:00
end_of_day = datetime.combine(date_event, datetime.max.time())
2024-12-16 23:51:26 +01:00
filters.extend(build_date_filter(start_of_day, end_of_day))
else:
filters.extend(build_date_filter(start_date, end_date))
# Add location filter
filters.extend(build_location_filter(min_lat, max_lat, min_lon, max_lon))
# Add datetime filter
datetime_filter = build_datetime_filter(current_datetime)
if datetime_filter:
filters.append(datetime_filter)
# Add text filter
text_filter = build_text_filter(item)
if text_filter:
filters.append(text_filter)
2024-12-16 23:53:46 +01:00
if tags is not None:
2024-12-21 20:47:33 +01:00
filters.append({"tags": {"$eq": tags}})
2024-12-16 23:53:46 +01:00
2024-12-16 23:51:26 +01:00
# Combine filters
object_search = {"$and": filters} if filters else {}
# Fetch and return results
event_repository = events.EventRepository(database=database.database)
list_events = []
2024-10-23 21:44:33 +02:00
for event_index in event_repository.find_by(object_search, limit=limit, skip=skip):
2024-12-16 23:51:26 +01:00
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,
)
list_events.append(event)
return list_events
2024-10-23 21:44:33 +02:00
2023-11-08 22:43:53 +01:00
@router.get("/events/me",tags=["events"])
2023-11-06 23:27:47 +01:00
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"]))]):
2023-11-08 22:43:53 +01:00
event_repository = events.EventRepository(database=database.database)
listOrganizers = []
2023-11-14 00:21:15 +01:00
for event_index in event_repository.find_by({"organizers":{"$eq": current_user.username}}, limit=limit, skip=skip):
2024-11-07 17:54:12 +01:00
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)
2023-11-08 22:43:53 +01:00
listOrganizers.append(event)
2023-11-14 00:21:15 +01:00
content = {"organizers":listOrganizers}
2023-11-08 22:43:53 +01:00
response = JSONResponse(content=content)
return response
2023-11-06 23:27:47 +01:00
2023-11-08 22:43:53 +01:00
@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()
2023-11-06 23:27:47 +01:00
content = {"count":count}
response = JSONResponse(content=content)
return response
2023-11-08 22:43:53 +01:00
@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"]))]):
2023-11-12 21:18:49 +01:00
event_repository = events.EventRepository(database=database.database)
2023-11-08 22:43:53 +01:00
event = event_repository.find_one_by_id(ObjectId(item_id))
return event
2023-11-06 23:27:47 +01:00
2023-11-08 22:43:53 +01:00
@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):
2023-11-12 21:18:49 +01:00
event_repository = events.EventRepository(database=database.database)
2023-11-08 22:43:53 +01:00
event = event_repository.find_one_by_id(ObjectId(item_id))
2023-11-06 23:27:47 +01:00
if remove is True:
2023-11-08 22:43:53 +01:00
event.deleted_at = datetime.today()
event.status = -1
content = {"message": "event is deleted"}
2023-11-06 23:27:47 +01:00
else:
2023-11-08 22:43:53 +01:00
event.status = 0
event.deleted_at = datetime.today()
content = {"message": "event is disabled"}
event_repository.save(event)
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response
2023-11-08 22:43:53 +01:00
@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:
2023-11-06 23:27:47 +01:00
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
2023-11-08 22:43:53 +01:00
detail="eventids should be greater than 0"
2023-11-06 23:27:47 +01:00
)
2023-11-08 22:43:53 +01:00
event_repository = event.EventRepository(database=database.database)
for i in eventids.ids:
event = event_repository.find_one_by_id(ObjectId(i))
2023-11-06 23:27:47 +01:00
if remove is True:
2023-11-08 22:43:53 +01:00
event.status = -1
event.deleted_at = datetime.today()
content = {"message": "events are deleted "}
2023-11-06 23:27:47 +01:00
else:
2023-11-08 22:43:53 +01:00
event.status = 0
event.disabled_at = datetime.today()
content = {"message": "events are disabled"}
event_repository.save(event)
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response
2023-11-08 22:43:53 +01:00
@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):
2023-11-12 21:18:49 +01:00
event_repository = events.EventRepository(database=database.database)
2023-11-08 22:43:53 +01:00
event = event_repository.find_one_by_id(ObjectId(item_id))
2023-11-06 23:27:47 +01:00
if remove is True:
2023-11-08 22:43:53 +01:00
event.status = -1
event.deleted_at = datetime.today()
content = {"message": "events are deleted"}
2023-11-06 23:27:47 +01:00
else:
2023-11-08 22:43:53 +01:00
event.status = 0
event.disabled_at = datetime.today()
content = {"message": "events are disabled"}
2023-11-12 21:18:49 +01:00
event_repository.save(event)
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response
2023-11-08 23:10:45 +01:00
@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))
2024-09-02 22:56:08 +02:00
event.name = eventSingle.name
2024-09-03 15:41:37 +02:00
event.description = eventSingle.description
2024-09-02 22:56:08 +02:00
event.place = eventSingle.place
2023-11-08 23:10:45 +01:00
event.start_date = eventSingle.start_date
2024-10-14 18:03:51 +02:00
event.tags = eventSingle.tags
2023-11-08 23:10:45 +01:00
event.end_date = eventSingle.end_date
2023-11-20 22:40:42 +01:00
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
2023-11-08 23:10:45 +01:00
event.updated_at = datetime.today()
2024-09-15 23:54:47 +02:00
event.imgUrl = eventSingle.imgUrl
2023-11-08 23:10:45 +01:00
event_repository.save(event)
content = {"message": "event is updated"}
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
2023-11-08 23:10:45 +01:00
return response
2023-11-06 23:27:47 +01:00
2023-11-08 23:10:45 +01:00
@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:
2023-11-06 23:27:47 +01:00
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
2023-11-12 18:42:49 +01:00
event_repository = events.EventRepository(database=database.database)
2024-12-21 23:05:24 +01:00
tags_repository = tags.TagsRepository(database=database.database)
2023-11-08 23:10:45 +01:00
2024-12-22 18:21:26 +01:00
event = event_repository.find_one_by( {"$and": [
{"start_date": {"$eq": eventSingle.start_date}}, # Already started
{"name": {"$eq": eventSingle.name}},
]})
2023-11-08 23:10:45 +01:00
if event is not None:
raise HTTPException(
status_code=status.HTTP_204_NO_CONTENT,
detail="name"
)
2024-11-07 17:54:12 +01:00
event = events.Event(name=eventSingle.name, description=eventSingle.description, place=eventSingle.place)
2023-11-08 23:10:45 +01:00
event.start_date = eventSingle.start_date
event.end_date = eventSingle.end_date
2023-11-16 21:40:49 +01:00
event.organizers = eventSingle.organizers
2023-11-20 22:40:42 +01:00
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
2024-09-15 23:54:47 +02:00
event.imgUrl = eventSingle.imgUrl
2024-10-14 18:03:51 +02:00
event.tags = eventSingle.tags
2024-12-21 23:05:24 +01:00
for tag_name in eventSingle:
tag = tags_repository.find_one_by({"name": {'$eq': tag_name}})
if tag is None:
tag = Tags(name=tag_name)
tags_repository.save(tag)
2024-10-23 23:36:09 +02:00
event.status = 1
2023-11-08 23:10:45 +01:00
event.created_at = datetime.today()
event_repository.save(event)
content = {"message": "event is created"}
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content, status_code=status.HTTP_201_CREATED)
return response
2023-11-08 23:10:45 +01:00
@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:
2023-11-06 23:27:47 +01:00
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Body request is empty"
)
2023-11-12 21:18:49 +01:00
event_repository = events.EventRepository(database=database.database)
2024-12-21 23:05:24 +01:00
tags_repository = tags.TagsRepository(database=database)
2023-11-08 23:10:45 +01:00
event = event_repository.find_one_by({"id": {'$eq': ObjectId(item_id)}})
if event is None:
2023-11-06 23:27:47 +01:00
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
2023-11-08 23:10:45 +01:00
detail="Event not found"
2023-11-06 23:27:47 +01:00
)
2023-11-12 21:18:49 +01:00
event.name = eventSingle.name
event.place = eventSingle.place
2024-09-03 15:41:37 +02:00
event.description = eventSingle.description
2023-11-08 23:10:45 +01:00
event.start_date = eventSingle.start_date
event.end_date = eventSingle.end_date
2023-11-16 21:40:49 +01:00
event.organizers = eventSingle.organizers
2024-10-14 18:03:51 +02:00
event.tags = eventSingle.tags
2024-12-21 23:05:24 +01:00
for tag_name in eventSingle:
tag = tags_repository.find_one_by({"name": {'$eq': tag_name}})
if tag is None:
tag = Tags(name=tag_name)
tags_repository.save(tag)
2023-11-20 22:40:42 +01:00
event.latitude = eventSingle.latitude
event.longitude = eventSingle.longitude
2023-11-08 23:10:45 +01:00
event.updated_at = datetime.today()
2024-09-15 23:54:47 +02:00
event.imgUrl = eventSingle.imgUrl
2023-11-08 23:10:45 +01:00
event_repository.save(event)
content = {"message": "event is updated"}
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response
2023-11-08 23:10:45 +01:00
@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:
2023-11-06 23:27:47 +01:00
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
2023-11-08 23:10:45 +01:00
detail="eventids should be greater than 0"
2023-11-06 23:27:47 +01:00
)
2023-11-12 18:42:49 +01:00
event_repository = events.EventRepository(database=database.database)
2023-11-08 23:10:45 +01:00
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)
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response
2023-11-12 21:18:49 +01:00
@router.patch("/events/{item_id}", tags=["events"])
2023-11-08 23:10:45 +01:00
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"}
2023-11-06 23:27:47 +01:00
response = JSONResponse(content=content)
return response