Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pydantic = "*"
pytest = "*"
coverage = "*"
pytest-cov = "*"
moto = {extras = ["dynamodb"], version = "4.2.13"}
moto = {extras = ["dynamodb"], version = "==4.2.13"}
pyjwt = "*"
google-api-python-client = "*"
google-auth-httplib2 = "*"
Expand All @@ -21,6 +21,7 @@ thefuzz = "*"
sentry-sdk = {extras = ["chalice"], version = "*"}
pre-commit = "*"
ruff = "*"
mongomock = "*"

[dev-packages]

Expand Down
165 changes: 84 additions & 81 deletions Pipfile.lock

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions chalicelib/api/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,12 @@ def create_rush_event():
def modify_rush_event():
data = events_api.current_request.json_body
return event_service.modify_rush_event(data)

@events_api.route("/events/rush/settings", methods=["PATCH"], cors=True)
@auth(events_api, roles=["admin"])
def modify_rush_settings():
data = events_api.current_request.json_body
return event_service.modify_rush_settings(data)


@events_api.route("/events/rush/checkin/{event_id}", methods=["POST"], cors=True)
Expand Down
57 changes: 56 additions & 1 deletion chalicelib/modules/mongo.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
from pymongo.mongo_client import MongoClient
from bson import ObjectId
import mongomock
import boto3
import os


class MongoModule:
"""Manages connections to MongoDB."""

def __init__(self):
def __init__(self, use_mock=False):
"""Establishes connection to MongoDB server"""
self.use_mock = use_mock
if use_mock:
self.mongo_client = mongomock.MongoClient()
return

self.is_prod = os.environ.get("ENV") == "prod"
self.ssm_client = boto3.client("ssm")
self.user = self.ssm_client.get_parameter(
Expand Down Expand Up @@ -205,6 +211,55 @@ def update_document(self, collection, document_id, query, array_filters=None):
)
return False

@add_env_suffix
def update_many_documents(self, collection: str, filter_query: dict, update_query: dict, array_filters=None) -> dict:
"""
Updates multiple documents in the specified collection that match the given filter query.

Args:
collection (str): The name of the collection to update the documents in.
filter_query (dict): A dictionary containing the filter criteria for selecting documents to update.
update_query (dict): A dictionary containing the update operators.
array_filters (list, optional): A list of filters to apply when updating
elements in an array field of the document.
Each filter in the list is a dictionary
specifying the criteria for selecting
array elements to be updated. Default is None.

Returns:
dict: A dictionary containing the count of matched and modified documents.
"""
try:
update_options = {}
if array_filters:
# ensure array_filters is a list
if not isinstance(array_filters, list):
raise ValueError("array_filters must be a list.")
# ensure each item contains a dictionary
for f in array_filters:
if not isinstance(f, dict):
raise ValueError("Each item in array_filters must be a dictionary.")
update_options["array_filters"] = array_filters

result = self.mongo_client.vault[collection].update_many(
filter_query, update_query, **update_options
)

if result.matched_count > 0:
print(f"{result.matched_count} documents matched the filter query.")
print(f"{result.modified_count} documents were updated.")
return {
"matched_count": result.matched_count,
"modified_count": result.modified_count,
}
else:
print("No documents matched the filter query.")
return {"matched_count": 0, "modified_count": 0}
except Exception as e:
print(f"An error occurred while updating documents: {e}")
return {"matched_count": 0, "modified_count": 0}


@add_env_suffix
def get_document_by_id(self, collection, document_id):
"""
Expand Down
42 changes: 42 additions & 0 deletions chalicelib/services/EventService.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import datetime
from chalicelib.modules.google_sheets import GoogleSheetsModule
from chalicelib.modules.ses import ses, SesDestination
from typing import Optional


class EventService:
Expand Down Expand Up @@ -331,6 +332,47 @@ def modify_rush_event(self, data: dict):
print("error is ", e)
raise BadRequestError(e)

def modify_rush_settings(self, data: dict):
"""
Updates defaultRushCategory from the rush collection

Parameters
----------
data: dict
contains default_rush_category_id ID of the rush category to be default

Raises
------
BadRequestError
If default_rush_category_id is not in the rush collection
"""
default_rush_category_id = data["defaultRushCategoryId"]

collection = f"{self.collection_prefix}rush"

# Set all defaultRushCategory fields to false
mongo_module.update_many_documents(
collection,
{},
{"$set": {"defaultRushCategory": False}}
)

# if default_rush_category_id is "" --> reset defaultRushCategory
if not default_rush_category_id:
return

# Update the specified document to set its defaultRushCategory to true
result = mongo_module.update_document_by_id(
collection,
default_rush_category_id,
{"defaultRushCategory": True}
)

if not result:
raise ValueError(f"Document with ID {default_rush_category_id} was not found or could not be updated.")

return

def get_rush_event(self, event_id: str, hide_attendees: bool = True):
event = mongo_module.get_document_by_id(
f"{self.collection_prefix}rush-event", event_id
Expand Down
3 changes: 1 addition & 2 deletions tests/api/test_applicants.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from chalice.app import Request
from chalice.test import Client
from unittest.mock import MagicMock, patch
from unittest.mock import patch


from app import app
Expand Down
Loading