diff --git a/app/helpers.py b/app/helpers.py index 85c8716..f3b607c 100644 --- a/app/helpers.py +++ b/app/helpers.py @@ -6,9 +6,7 @@ def is_response_valid(response, error_message=""): - if response.status_code == 200: - return True - elif response.status_code == 201: + if response.status_code in [200, 201]: return True if error_message: logger.error(error_message) @@ -17,29 +15,28 @@ def is_response_valid(response, error_message=""): def is_response_empty(response_data, return_boolean, error_message=""): - if len(response_data) != 0: + if response_data: return response_data if return_boolean: if error_message: logger.error(error_message) raise HTTPException(status_code=404, detail=error_message) - else: - return False + return False return [] def validate_and_build_query_params(data, valid_query_params): - query_params = {} - for key in data.keys(): - if key not in valid_query_params: - logger.error("Query Parameter {key} is not allowed!") - raise HTTPException( - status_code=400, detail="Query Parameter {} is not allowed!".format(key) - ) - query_params[key] = data[key] - + query_params = {key: data[key] for key in data.keys() if key in valid_query_params} + invalid_params = [key for key in data.keys() if key not in valid_query_params] + if invalid_params: + raise HTTPException( + status_code=400, + detail="Query Parameter(s) {} is not allowed!".format( + ", ".join(invalid_params) + ), + ) return query_params def db_request_token(): - return {"Authorization": f"Bearer {settings.token}"} + return {"Authorization": f"Bearer {settings.TOKEN}"} diff --git a/app/id_generation.py b/app/id_generation.py deleted file mode 100644 index 1a904e7..0000000 --- a/app/id_generation.py +++ /dev/null @@ -1,42 +0,0 @@ -from fastapi import HTTPException -import requests -from settings import settings -import random - -school_db_url = settings.db_url + "/school" - - -class JNVIDGeneration: - def __init__(self, region, school, grade): - self.region = region - self.school = school - self.grade = grade - self.id = ( - self.get_class_code() - + self.get_jnv_code() - + self.generate_three_digit_code() - ) - - def get_id(self): - return self.id - - def get_class_code(self): - class_codes = {"9": "26", "10": "25", "11": "24", "12": "23"} - return class_codes[self.grade] - - def get_jnv_code(self): - response = requests.get( - school_db_url, params={"region": self.region, "name": self.school_name} - ) - if response.status_code == 200: - if len(response.json()) == 0: - return HTTPException( - status_code=404, detail="JNV or region does not exist!" - ) - return response.json() - return HTTPException(status_code=response.status_code, detail=response.errors) - - def generate_three_digit_code(code=""): - for _ in range(3): - code += random.randint(0, 9) - return code diff --git a/app/id_generation_classes.py b/app/id_generation_classes.py new file mode 100644 index 0000000..0c29c98 --- /dev/null +++ b/app/id_generation_classes.py @@ -0,0 +1,36 @@ +from settings import settings +import random +from router import school +import datetime +from dateutil.relativedelta import relativedelta +from request import build_request + + +class JNVIDGeneration: + def __init__(self, region, school, grade): + self.region = region + self.school = school + self.grade = grade + self.id = ( + self.get_class_code() + + self.get_jnv_code() + + self.generate_three_digit_code() + ) + + def get_class_code(self): + graduating_year = datetime.date.today() + relativedelta( + years=12 - int(self.grade) + ) + return str(graduating_year.year)[-2:] + + def get_jnv_code(self): + return school.get_school( + build_request( + query_params={"region": self.region, "name": self.school_name} + ) + ) + + def generate_three_digit_code(code=""): + for _ in range(3): + code += random.randint(0, 9) + return code diff --git a/app/main.py b/app/main.py index 4c82fc5..2affc0e 100644 --- a/app/main.py +++ b/app/main.py @@ -1,17 +1,19 @@ from router import ( + auth_group, auth, - session, + batch, + enrollment_record, + form, + group_session, + group_user, group, + school, + session_occurrence, + session, student, - session_group, + teacher, user_session, - session_occurrence, - batch, - program, - group_type, - form, user, - teacher, ) from fastapi.middleware.cors import CORSMiddleware from fastapi import FastAPI, Request @@ -55,8 +57,11 @@ async def log_requests(request: Request, call_next): origins = [ "http://localhost:8080", + "http://localhost:3000", "https://staging-auth.avantifellows.org", "https://auth.avantifellows.org", + "https://staging-gurukul.avantifellows.org", + "https://gurukul.avantifellows.org", ] app.add_middleware( @@ -73,19 +78,21 @@ def authjwt_exception_handler(request: Request, exc: AuthJWTException): return JSONResponse(status_code=exc.status_code, content={"detail": exc.message}) +app.include_router(auth_group.router) app.include_router(auth.router) -app.include_router(session.router) +app.include_router(batch.router) +app.include_router(enrollment_record.router) +app.include_router(form.router) +app.include_router(group_session.router) +app.include_router(group_user.router) app.include_router(group.router) +app.include_router(school.router) +app.include_router(session_occurrence.router) +app.include_router(session.router) app.include_router(student.router) -app.include_router(session_group.router) +app.include_router(teacher.router) app.include_router(user_session.router) -app.include_router(session_occurrence.router) -app.include_router(batch.router) -app.include_router(program.router) -app.include_router(group_type.router) -app.include_router(form.router) app.include_router(user.router) -app.include_router(teacher.router) @app.get("/") diff --git a/app/mapping.py b/app/mapping.py index 7ba8689..833142b 100644 --- a/app/mapping.py +++ b/app/mapping.py @@ -1,33 +1,85 @@ -FORM_GROUP_MAPPING = {"HaryanaStudents": "Haryana Student Profile"} +AUTH_GROUP_QUERY_PARAMS = ["id", "name", "locale"] + +BATCH_QUERY_PARAMS = [ + "id", + "name", + "contact_hours_per_week", + "batch_id", + "parent_id", + "program_id", + "auth_group_id", +] + +ENROLLMENT_RECORD_PARAMS = [ + "academic_year", + "is_current", + "start_date", + "end_date", + "group_id", + "group_type", + "user_id", + "subject_id", + "grade_id", +] + +FORM_SCHEMA_QUERY_PARAMS = ["id", "name", "attributes"] + +GROUP_QUERY_PARAMS = ["id", "type", "child_id"] + +GROUP_USER_QUERY_PARAMS = ["id", "group_id", "user_id"] + +SCHOOL_QUERY_PARAMS = ["id", "name", "school_name", "code", "board_medium"] + +SESSION_QUERY_PARAMS = ["id", "name", "session_id"] STUDENT_QUERY_PARAMS = [ "student_id", - "category", - "stream", - "physically_handicapped", - "annual_family_income", - "monthly_family_income", + "grade", + "grade_id", "father_name", "father_phone", - "father_profession", - "father_education_level", "mother_name", "mother_phone", + "category", + "stream", + "family_income", + "father_profession", + "father_education_level", "mother_profession", "mother_education_level", "time_of_device_availability", "has_internet_access", "primary_smartphone_owner", "primary_smartphone_owner_profession", - "group", + "guardian_name", + "guardian_relation", + "guardian_phone", + "guardian_education_level", + "guardian_profession", + "has_category_certificate", + "category_certificate", + "physically_handicapped", + "physically_handicapped_certificate", + "annual_family_income", + "monthly_family_income", + "number_of_smartphones", + "family_type", + "number_of_four_wheelers", + "number_of_two_wheelers", + "goes_for_tuition_or_other_coaching", + "know_about_avanti", + "percentage_in_grade_10_science", + "percentage_in_grade_10_math", + "percentage_in_grade_10_english", + "grade_10_marksheet", + "photo", ] -TEACHER_QUERY_PARAMS = ["grade", "designation"] +TEACHER_QUERY_PARAMS = ["teacher_id", "subject_id", "designation"] USER_QUERY_PARAMS = [ "id", "first_name", - "middle_name", "last_name", "email", "phone", @@ -43,18 +95,3 @@ "country", "consent_check", ] - -ENROLLMENT_RECORD_PARAMS = [ - "grade", - "academic_year", - "student_id", - "school_id", - "school_name", - "is_current", - "board_medium", - "date_of_enrollment", -] - -SCHOOL_QUERY_PARAMS = ["id", "name", "code"] -GROUP_TYPE_QUERY_PARAMS = ["id", "type", "child_id"] -GROUP_QUERY_PARAMS = ["name", "id", "locale"] diff --git a/app/models.py b/app/models.py index 82994bd..02a2f6e 100644 --- a/app/models.py +++ b/app/models.py @@ -2,6 +2,14 @@ from typing import Union, Dict, Optional +class AuthGroupResponse(BaseModel): + id: str + name: str + input_schema: Optional[Dict] = {} + locale: Optional[str] = "" + locale_data: Optional[Dict] = {} + + class AuthUser(BaseModel): id: str type: str @@ -10,6 +18,31 @@ class AuthUser(BaseModel): data: Union[Dict[str, str], None] +class BatchResponse(BaseModel): + id: str + name: str + contact_hours_per_week: Optional[int] = None + batch_id: str + parent_id: Optional[int] = None + start_date: Optional[str] = None + end_date: Optional[str] = None + program_id: Optional[int] = None + auth_group_id: Optional[int] = None + + +class EnrollmentRecordResponse(BaseModel): + id: str + academic_year: str + is_current: bool + start_date: str + end_date: Optional[str] = None + group_id: int + group_type: str + user_id: int + subject_id: int + grade_id: int + + class SessionResponse(BaseModel): id: Optional[str] = None session_id: Optional[str] = None @@ -24,24 +57,19 @@ class SessionResponse(BaseModel): is_session_open: bool type: Optional[str] = None auth_type: Optional[str] = None - activate_signup: Optional[str] = None + signup_form: Optional[str] = None id_generation: Optional[str] = None redirection: Optional[str] = None - pop_up_form: Optional[str] = None - form_schema_id: Optional[str] = None - number_of_fields_in_pop_form: Optional[str] = None - - -class GroupResponse(BaseModel): - id: str - name: str - input_schema: Optional[Dict] = {} - locale: Optional[str] = "" - locale_data: Optional[Dict] = {} + popup_form: Optional[str] = None + signup_form_id: Optional[str] = None + popup_form_id: Optional[str] = None + session_occurrence_id: Optional[str] = None class UserSession(BaseModel): user_id: str + session_id: str session_occurrence_id: int - is_user_valid: bool + user_activity_type: str + user_type: str data: Optional[Dict] = {} diff --git a/app/request.py b/app/request.py index b9a157b..093009b 100644 --- a/app/request.py +++ b/app/request.py @@ -7,7 +7,7 @@ def build_request( server: str = "http://127.0.0.1:8000/", path: str = "/", headers: dict = None, - body: str = None, + body: dict = None, query_params: dict = None, ) -> Request: if headers is None: diff --git a/app/router/auth.py b/app/router/auth.py index db32246..f9466f4 100644 --- a/app/router/auth.py +++ b/app/router/auth.py @@ -14,7 +14,6 @@ def index(): # if user is valid, generates both access token and refresh token. Otherwise, only an access token. @router.post("/create-access-token") def create_access_token(auth_user: AuthUser, Authorize: AuthJWT = Depends()): - print(auth_user) refresh_token = "" data = auth_user.data diff --git a/app/router/auth_group.py b/app/router/auth_group.py new file mode 100644 index 0000000..1b6a522 --- /dev/null +++ b/app/router/auth_group.py @@ -0,0 +1,27 @@ +from fastapi import APIRouter, Request +import requests +from models import AuthGroupResponse +from routes import auth_group_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import AUTH_GROUP_QUERY_PARAMS + +router = APIRouter(prefix="/auth-group", tags=["Auth-Group"]) + + +@router.get("/", response_model=AuthGroupResponse) +def get_auth_group(request: Request): + query_params = validate_and_build_query_params( + request.query_params, AUTH_GROUP_QUERY_PARAMS + ) + response = requests.get( + auth_group_db_url, params=query_params, headers=db_request_token() + ) + if is_response_valid(response, "Auth Group API could not fetch the data!"): + return is_response_empty( + response.json()[0], True, "Auth Group record does not exist!" + ) diff --git a/app/router/batch.py b/app/router/batch.py index ae96706..f4b460f 100644 --- a/app/router/batch.py +++ b/app/router/batch.py @@ -1,134 +1,25 @@ from fastapi import APIRouter, Request import requests -from router import routes -import helpers -from helpers import db_request_token +from routes import batch_db_url +from models import BatchResponse +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import BATCH_QUERY_PARAMS router = APIRouter(prefix="/batch", tags=["Batch"]) -@router.get("/") +@router.get("/", response_model=BatchResponse) def get_batch(request: Request): - """ - This API retrieves batch data based on the provided query parameters. - - Parameters: - request (Request): The request object containing the query parameters. - - Returns: - list: Returns the batch data that matches the provided query parameters. If no batch matches the parameters, an error message is returned. - - Example: - - GET $BASE_URL/get_batch?id=1234&name=math&contact_hours_per_week=3 - Response: - { - "status_code": 200, - "detail": "Batch data retrieved successfully!", - "batch_data": [{matching_batch_data}], - "headers": null - } - - GET $BASE_URL/get_batch?id=5678 - Response: - { - "status_code": 404, - "detail": "Batch does not exist!", - "headers": null - } - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, ["id", "name", "contact_hours_per_week"] + query_params = validate_and_build_query_params( + request.query_params, BATCH_QUERY_PARAMS ) response = requests.get( - routes.batch_db_url, params=query_params, headers=db_request_token() - ) - if helpers.is_response_valid(response, "Batch API could not fetch the data!"): - return helpers.is_response_empty( - response.json(), False, "Batch does not exist!" - ) - - -@router.post("/") -async def create_batch(request: Request): - """ - This API creates a new batch in the database. - - Parameters: - request (Request): The request object containing the batch data to be created. - - Returns: - list: Returns the created batch record if the creation is successful. If the creation fails, an error message is returned. - - Example: - - POST $BASE_URL/create_batch - Request body: {batch_data} - Response: - { - "status_code": 200, - "detail": "Batch created successfully!", - "batch_record": {created_batch_data}, - "headers": null - } - - POST $BASE_URL/create_batch - Request body: {invalid_batch_data} - Response: - { - "status_code": 500, - "detail": "Batch API could not post the data!", - "headers": null - } - """ - - data = await request.body() - response = requests.post(routes.batch_db_url, data=data, headers=db_request_token()) - if helpers.is_response_valid(response, "Batch API could not post the data!"): - return helpers.is_response_empty( - response.json(), "Batch API could not fetch the created record!" - ) - - -@router.patch("/") -async def update_batch(request: Request): - """ - This API updates an existing batch record in the database. - - Parameters: - request (Request): The request object containing the updated batch data. - - Returns: - list: Returns the updated batch record if the update is successful. If the update fails, an error message is returned. - - Example: - - PATCH $BASE_URL/update_batch - Request body: {updated_batch_data} - Response: - { - "status_code": 200, - "detail": "Batch updated successfully!", - "batch_record": {updated_batch_data}, - "headers": null - } - - PATCH $BASE_URL/update_batch - Request body: {invalid_batch_data} - Response: - { - "status_code": 500, - "detail": "Batch API could not patch the data!", - "headers": null - } - """ - data = await request.body() - response = requests.patch( - routes.batch_db_url + "/" + str(data["id"]), - data=data, - headers=db_request_token(), + batch_db_url, params=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "Batch API could not patch the data!"): - return helpers.is_response_empty( - response.json(), "Batch API could not fetch the patched record!" - ) + if is_response_valid(response, "Batch API could not fetch the data!"): + return is_response_empty(response.json()[0], True, "Batch does not exist!") diff --git a/app/router/enrollment_record.py b/app/router/enrollment_record.py index 68f2dc9..c86bf53 100644 --- a/app/router/enrollment_record.py +++ b/app/router/enrollment_record.py @@ -1,159 +1,40 @@ from fastapi import APIRouter, Request import requests -from router import routes -import helpers -import mapping -from helpers import db_request_token +from routes import enrollment_record_db_url +from models import EnrollmentRecordResponse +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import ENROLLMENT_RECORD_PARAMS router = APIRouter(prefix="/enrollment-record", tags=["Enrollment Record"]) -@router.get("/") +@router.get("/", response_model=EnrollmentRecordResponse) def get_enrollment_record(request: Request): - """ - This API retrieves enrollment record data based on the provided query parameters. - - Parameters: - request (Request): The request object containing the query parameters. - - Returns: - list: Returns the enrollment record data that matches the provided query parameters. If no enrollment record matches the parameters, an error message is returned. - - Example: - - GET $BASE_URL/get_enrollment_record?id=1234&student_id=5678 - Response: - { - "status_code": 200, - "detail": "Enrollment record data retrieved successfully!", - "enrollment_data": [{matching_enrollment_data}], - "headers": null - } - - GET $BASE_URL/get_enrollment_record?student_id=5678 - Response: - { - "status_code": 404, - "detail": "Enrollment record does not exist", - "headers": null - } - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.ENROLLMENT_RECORD_PARAMS + query_params = validate_and_build_query_params( + request.query_params, ENROLLMENT_RECORD_PARAMS ) response = requests.get( - routes.enrollment_record_db_url, params=query_params, headers=db_request_token() + enrollment_record_db_url, params=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "Enrollment API could not fetch the data!"): - return helpers.is_response_empty( - response.json(), False, "Enrollment record does not exist!" + if is_response_valid(response, "Enrollment API could not fetch the data!"): + return is_response_empty( + response.json(), True, "Enrollment record does not exist!" ) @router.post("/") async def create_enrollment_record(request: Request): - """ - This API creates a new enrollment record based on the provided request data. - - Parameters: - request (Request): The request object containing the enrollment record data. - - Returns: - dict: Returns the created enrollment record data if the creation is successful. If the creation fails, an error message is returned. - - Example: - - POST $BASE_URL/create_enrollment_record - Request Body: - { - "student_id": 1234, - "batch_id": 5678, - "enrollment_date": "2023-06-22", - ... - } - Response: - { - "status_code": 200, - "detail": "Enrollment record created successfully!", - "enrollment_record": {created_enrollment_data}, - "headers": null - } - - POST $BASE_URL/create_enrollment_record - Request Body: - { - "student_id": 1234, - "batch_id": 5678, - "enrollment_date": "2023-06-22", - ... - } - Response: - { - "status_code": 500, - "detail": "Enrollment API could not fetch the created record!", - "headers": null - } - """ data = await request.body() response = requests.post( - routes.enrollment_record_db_url, data=data, headers=db_request_token() + enrollment_record_db_url, data=data, headers=db_request_token() ) - if helpers.is_response_valid(response, "Enrollment API could not post the data!"): - return helpers.is_response_empty( + if is_response_valid(response, "Enrollment API could not post the data!"): + return is_response_empty( response.json(), "Enrollment API could not fetch the created record!" ) - - -@router.patch("/") -async def update_enrollment_record(request: Request): - """ - This API updates an existing enrollment record based on the provided request data. - - Parameters: - request (Request): The request object containing the updated enrollment record data. - - Returns: - dict: Returns the updated enrollment record data if the update is successful. If the update fails, an error message is returned. - - Example: - - PATCH $BASE_URL/update_enrollment_record - Request Body: - { - "id": 1234, - "enrollment_date": "2023-06-23", - ... - } - Response: - { - "status_code": 200, - "detail": "Enrollment record updated successfully!", - "enrollment_record": {updated_enrollment_data}, - "headers": null - } - - PATCH $BASE_URL/update_enrollment_record - Request Body: - { - "id": 1234, - "enrollment_date": "2023-06-23", - ... - } - Response: - { - "status_code": 500, - "detail": "Enrollment API could not fetch the patched record!", - "headers": null - } - """ - data = await request.body() - response = requests.patch( - routes.enrollment_record_db_url + "/" + str(data["id"]), - data=data, - headers=db_request_token(), - ) - if helpers.is_response_valid(response, "Enrollment API could not patch the data!"): - return helpers.is_response_empty( - response.json(), "Enrollment API could not fetch the patched record!" - ) diff --git a/app/router/form.py b/app/router/form.py index a80c5fb..9441e2d 100644 --- a/app/router/form.py +++ b/app/router/form.py @@ -1,26 +1,70 @@ -from fastapi import APIRouter, HTTPException, Request +from fastapi import APIRouter, Request import requests +from routes import form_db_url from settings import settings -from router import student, routes, enrollment_record +from router import student, enrollment_record from request import build_request -import helpers -import mapping -from helpers import db_request_token +from mapping import FORM_SCHEMA_QUERY_PARAMS, USER_QUERY_PARAMS, STUDENT_QUERY_PARAMS +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +import json router = APIRouter(prefix="/form-schema", tags=["Form"]) -def is_user_attribute_empty(form_attributes, priority, student_data): - return ( - form_attributes[str(priority)]["key"] in mapping.USER_QUERY_PARAMS - and student_data["user"][form_attributes[str(priority)]["key"]] is None +def is_user_attribute_empty(field, student_data): + return field["key"] in USER_QUERY_PARAMS and ( + student_data["user"][field["key"]] is None + or student_data["user"][field["key"]] == "" ) -def is_student_attribute_empty(form_attributes, priority, student_data): - return ( - form_attributes[str(priority)]["key"] in mapping.STUDENT_QUERY_PARAMS - and student_data[form_attributes[str(priority)]["key"]] is None +def is_student_attribute_empty(field, student_data): + key = field["key"] + # Special handling for primary_contact attribute with sub-fields for guardians and parents + guardian_keys = [ + "guardian_name", + "guardian_relation", + "guardian_phone", + "guardian_education_level", + "guardian_profession", + ] + parent_keys = [ + "father_name", + "father_phone", + "father_profession", + "father_education_level", + "mother_name", + "mother_phone", + "mother_profession", + "mother_education_level", + ] + + if key == "primary_contact" or key in guardian_keys or key in parent_keys: + return any( + key not in student_data + or student_data[key] == "" + or student_data[key] is None + for key in guardian_keys + ) and any( + key not in student_data + or student_data[key] == "" + or student_data[key] is None + for key in parent_keys + ) + + if key == "grade": + return ( + "grade_id" not in student_data + or student_data["grade_id"] is None + or student_data["grade_id"] == "" + ) + return key in STUDENT_QUERY_PARAMS and ( + key not in student_data or student_data[key] is None or student_data[key] == "" ) @@ -78,199 +122,122 @@ def school_name_in_returned_form_schema_data( return (returned_form_schema, number_of_fields_left) +def is_field_already_in_schema(field, schema): + return field["key"] in [value["key"] for value in list(schema.values())] + + def build_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - priority, + returned_form_schema, field, number_of_fields_in_form_schema ): - returned_form_schema[ - total_number_of_fields - number_of_fields_left - ] = form_attributes[str(priority)] - number_of_fields_left -= 1 - return (returned_form_schema, number_of_fields_left) + if not is_field_already_in_schema(field, returned_form_schema): + returned_form_schema[number_of_fields_in_form_schema] = field + number_of_fields_in_form_schema += 1 + return (returned_form_schema, number_of_fields_in_form_schema) -@router.get("/") -def get_form_schema(request: Request): - """ - This API returns a form schema when an ID is given +def is_user_or_student_attribute_empty_then_build_schema( + form_schema, number_of_fields_in_form_schema, field, data +): + return ( + build_returned_form_schema_data( + form_schema, field, number_of_fields_in_form_schema + ) + if is_user_attribute_empty(field, data) + or is_student_attribute_empty(field, data) + else (form_schema, number_of_fields_in_form_schema) + ) + - Returns: - list: form schema data if ID is a match, otherwise 404 +def find_dependant_parent(fields, priority, dependent_hierarchy, data): + parent_field_priority = [ + key + for key, value in list(fields.items()) + if value["key"] == fields[str(priority)]["dependantField"] + ] - Example: - > $BASE_URL/form_schema/?form_schema_id=1234 - returns [{form_schema_data_of_id_1234}] + if len(parent_field_priority) == 1: + dependent_hierarchy.append(int(parent_field_priority[0])) + find_dependant_parent( + fields, parent_field_priority[0], dependent_hierarchy, data + ) - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, ["id", "name"] - ) + return dependent_hierarchy + +def find_children_fields(fields, parent_field): + children_fields = [] + for field in fields: + if fields[field]["dependantField"] == parent_field["key"] or ( + len(fields[field]["showBasedOn"]) > 0 + and fields[field]["showBasedOn"].split("==")[0] == parent_field["key"] + ): + children_fields.append(int(field)) + + return children_fields + + +@router.get("/") +def get_form_schema(request: Request): + query_params = validate_and_build_query_params( + request.query_params, FORM_SCHEMA_QUERY_PARAMS + ) response = requests.get( - routes.form_db_url, params=query_params, headers=db_request_token() + form_db_url, params=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "Form API could not fetch the data!"): - return helpers.is_response_empty(response.json(), "Form does not exist!") + if is_response_valid(response, "Form API could not fetch the data!"): + return is_response_empty(response.json()[0], "True", "Form does not exist!") @router.get("/student") async def get_student_fields(request: Request): - query_params = helpers.validate_and_build_query_params( - request.query_params, ["number_of_fields_in_pop_form", "group", "student_id"] + query_params = validate_and_build_query_params( + request.query_params, + ["number_of_fields_in_popup_form", "form_id", "student_id"], ) - # get the field ordering for a particular group - form = get_form_schema( - build_request( - query_params={"name": mapping.FORM_GROUP_MAPPING[query_params["group"]]} - ) - ) - form = form[0] + form = get_form_schema(build_request(query_params={"id": query_params["form_id"]})) - # get student and user data for the student ID that is requesting for profile completion - # ASSUMPTION : student_id is valid and exists because only valid students will reach profile completion student_data = student.get_students( build_request(query_params={"student_id": query_params["student_id"]}) - ) + )[0] - if student_data: - student_data = student_data[0] + # get the priorities for all fields and sort them + priority_order = sorted([eval(i) for i in form["attributes"].keys()]) - # get enrollment data for the student - enrollment_record_data = enrollment_record.get_enrollment_record( - build_request(query_params={"student_id": student_data["id"]}) - ) + fields = form["attributes"] - # get the priorities for all fields and sort them - priority_order = sorted([eval(i) for i in form["attributes"].keys()]) + total_number_of_fields = int(query_params["number_of_fields_in_popup_form"]) - # get the form attributes - form_attributes = form["attributes"] + number_of_fields_in_form_schema = 0 - # number of fields to sent back to the student - total_number_of_fields = number_of_fields_left = int( - query_params["number_of_fields_in_pop_form"] - ) + returned_form_schema = {} + + for priority in priority_order: + if number_of_fields_in_form_schema <= total_number_of_fields: + children_fields = find_children_fields(fields, fields[str(priority)]) + children_fields.append(priority) + + for child_field in sorted(children_fields): + ( + returned_form_schema, + number_of_fields_in_form_schema, + ) = is_user_or_student_attribute_empty_then_build_schema( + returned_form_schema, + number_of_fields_in_form_schema, + fields[str(child_field)], + student_data, + ) + + # else: + + # ( + # returned_form_schema, + # number_of_fields_in_form_schema, + # ) = is_user_or_student_attribute_empty_then_build_schema( + # returned_form_schema, + # number_of_fields_in_form_schema, + # fields[str(priority)], + # student_data, + # ) - returned_form_schema = {} - - for priority in priority_order: - if number_of_fields_left > 0: - if is_user_attribute_empty( - form_attributes, priority, student_data - ) or is_student_attribute_empty( - form_attributes, priority, student_data - ): - ( - returned_form_schema, - number_of_fields_left, - ) = build_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - priority, - ) - - elif ( - form_attributes[str(priority)]["key"] - in mapping.ENROLLMENT_RECORD_PARAMS - and form_attributes[str(priority)]["key"] != "student_id" - ): - if form_attributes[str(priority)]["key"] != "school_name": - if enrollment_record_data == [] or ( - enrollment_record_data != [] - and enrollment_record_data[ - form_attributes[str(priority)]["key"] - ] - is None - ): - ( - returned_form_schema, - number_of_fields_left, - ) = build_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - priority, - ) - else: - if enrollment_record_data == []: - if student_data["user"]["state"]: - if student_data["user"]["district"]: - ( - returned_form_schema, - number_of_fields_left, - ) = school_name_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - student_data, - ) - - else: - ( - returned_form_schema, - number_of_fields_left, - ) = district_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - student_data, - ) - else: - ( - returned_form_schema, - number_of_fields_left, - ) = state_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - ) - else: - enrollment_record_data = enrollment_record_data[0] - if enrollment_record_data["school_id"] is None: - if student_data["user"]["district"] is None: - if student_data["user"]["state"] is None: - ( - returned_form_schema, - number_of_fields_left, - ) = state_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - ) - else: - ( - returned_form_schema, - number_of_fields_left, - ) = district_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - student_data, - ) - else: - ( - returned_form_schema, - number_of_fields_left, - ) = school_name_in_returned_form_schema_data( - returned_form_schema, - total_number_of_fields, - number_of_fields_left, - form_attributes, - student_data, - ) - - return returned_form_schema - - raise HTTPException(status_code=404, detail="Student does not exist!") + return returned_form_schema diff --git a/app/router/grade.py b/app/router/grade.py new file mode 100644 index 0000000..b370915 --- /dev/null +++ b/app/router/grade.py @@ -0,0 +1,25 @@ +from fastapi import APIRouter, Request +import requests +from routes import grade_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) + +router = APIRouter(prefix="/grade", tags=["Grade"]) + + +@router.get("/") +def get_grade(request: Request): + query_params = validate_and_build_query_params( + request.query_params, ["id", "number"] + ) + response = requests.get( + grade_db_url, params=query_params, headers=db_request_token() + ) + if is_response_valid(response, "Grade API could not fetch the data!"): + return is_response_empty( + response.json()[0], True, "Grade record does not exist!" + ) diff --git a/app/router/group.py b/app/router/group.py index 5fd711f..b36dfc7 100644 --- a/app/router/group.py +++ b/app/router/group.py @@ -1,114 +1,24 @@ from fastapi import APIRouter, Request import requests -from models import GroupResponse -from router import routes -import helpers -import mapping -from helpers import db_request_token +from routes import group_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import GROUP_QUERY_PARAMS router = APIRouter(prefix="/group", tags=["Group"]) -@router.get("/", response_model=GroupResponse) -def get_group_data(request: Request): - """ - This API returns group details corresponding to the provided group ID, if the ID exists in the database - - Parameters: - group_id (str): The ID against which details need to be retrieved - - Returns: - list: Returns group details if the group ID exists in the database, 404 otherwise - - Example: - > $BASE_URL/group/1234 - returns [{group_data}] - - > $BASE_URL/group/{invalid_id} - returns { - "status_code": 404, - "detail": "Group ID does not exist!", - "headers": null - } - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.GROUP_QUERY_PARAMS +@router.get("/") +def get_group(request: Request): + query_params = validate_and_build_query_params( + request.query_params, GROUP_QUERY_PARAMS ) response = requests.get( - routes.group_db_url, params=query_params, headers=db_request_token() - ) - if helpers.is_response_valid(response, "Group API could not fetch the data!"): - return helpers.is_response_empty( - response.json()[0], False, "Group record does not exist!" - ) - - -@router.post("/") -async def create_group(request: Request): - """ - This API creates a new group based on the provided data. - - Parameters: - request (Request): The request object containing the data for creating the group. - - Returns: - dict: Returns the created group record if the creation is successful. If the creation fails, an error message is returned. - - Example: - - POST $BASE_URL/create_group - Request Body: - { - "name": "ABC", - "locale": "en" - } - Response: - { - "id": 12, - "name": "ABC", - "locale": "en" - } - """ - data = await request.body() - response = requests.post(routes.group_db_url, data=data, headers=db_request_token()) - if helpers.is_response_valid(response, "Group API could not post the data!"): - return helpers.is_response_empty( - response.json(), "Group API could not fetch the created record!" - ) - - -@router.patch("/") -async def update_group(request: Request): - """ - This API updates an existing group based on the provided data. - - Parameters: - request (Request): The request object containing the data for updating the group. - - Returns: - dict: Returns the updated group record if the update is successful. If the update fails, an error message is returned. - - Example: - PATCH $BASE_URL/update_group - Request Body: - { - "id": 12, - "locale": "hi", - } - Response: - { - "id": 12, - "name": "ABC", - "locale": "hi" - } - """ - data = await request.body() - response = requests.patch( - routes.group_db_url + "/" + str(data["id"]), - data=data, - headers=db_request_token(), + group_db_url, params=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "Group API could not patch the data!"): - return helpers.is_response_empty( - response.json(), "Group API could not fetch the patched record!" - ) + if is_response_valid(response, "Group API could not fetch the data!"): + return is_response_empty(response.json(), True, "Group record does not exist!") diff --git a/app/router/group_session.py b/app/router/group_session.py new file mode 100644 index 0000000..d2eaf39 --- /dev/null +++ b/app/router/group_session.py @@ -0,0 +1,48 @@ +from fastapi import APIRouter, HTTPException +import requests +from settings import settings +from routes import group_session_db_url, group_db_url, auth_group_db_url +from helpers import db_request_token, is_response_valid, is_response_empty + + +router = APIRouter(prefix="/session-group", tags=["Session-Group"]) + + +def get_auth_group_details(auth_group_id): + auth_group_response = requests.get( + auth_group_db_url, params={"id": auth_group_id}, headers=db_request_token() + ) + if is_response_valid( + auth_group_response, "Auth group API could not fetch the data!" + ): + auth_group_data = is_response_empty( + auth_group_response.json()[0], True, "Auth group record does not exist!" + ) + return auth_group_data + + +def get_batch_from_group(group_id): + response = requests.get( + group_db_url, params={"id": group_id}, headers=db_request_token() + ) + if is_response_valid(response, "Group API could not fetch the data!"): + batch_data = is_response_empty( + response.json()[0], True, "Group record does not exist!" + ) + if batch_data: + return get_auth_group_details(batch_data["child_id"]["auth_group_id"]) + + +@router.get("/{session_id}") +def get_group_for_session(session_id: str): + response = requests.get( + group_session_db_url, + params={"session_id": session_id}, + headers=db_request_token(), + ) + if is_response_valid(response, "Group Session API could not fetch the data!"): + group_session_data = is_response_empty( + response.json()[0], True, "Group Session record does not exist!" + ) + if group_session_data: + return get_batch_from_group(group_session_data["group_id"]) diff --git a/app/router/group_type.py b/app/router/group_type.py deleted file mode 100644 index 47751fa..0000000 --- a/app/router/group_type.py +++ /dev/null @@ -1,118 +0,0 @@ -from fastapi import APIRouter, Request -import requests -from router import routes -import helpers -import mapping -from helpers import db_request_token - -router = APIRouter(prefix="/group-type", tags=["GroupType"]) - - -@router.get("/") -def get_group_type(request: Request): - """ - This API returns details of a group-type based on the provided ID, if it exists in the database. The group-type is identified by a combination of type and child_id, where the child_id corresponds to the ID of either the program, group, or batch table, depending on the type of the group. - - Parameters: - id (int): The ID against which details need to be retrieved - type (str): The type of the group-type being retrieved. Must be one of "group", "program", or "batch" - child_id (int): The ID of the corresponding table depending on the type of group-type being retrieved. - - Returns: - list: Returns group-type details if the ID exists in the database, 404 otherwise. - - Example: - > $BASE_URL/group-type?type=program&child_id=5678 - returns [{group_type_data}] - - > $BASE_URL/group-type?type=program&child_id=invalid_id - returns { - "status_code": 404, - "detail": "GroupType ID does not exist!", - "headers": null - } - """ - query_params = helpers.validate_and_build_query_params( - request, mapping.GROUP_TYPE_QUERY_PARAMS - ) - response = requests.get( - routes.group_type_db_url, params=query_params, headers=db_request_token() - ) - if helpers.is_response_valid(response, "Group-type API could not fetch the data!"): - return helpers.is_response_empty( - response.json(), False, "Group-type record does not exist!" - ) - - -@router.post("/") -async def create_group_type(request: Request): - """ - This API creates a new group type based on the provided data. - - Parameters: - request (Request): The request object containing the data for creating the group type. - - Returns: - dict: Returns the created group type record if the creation is successful. If the creation fails, an error message is returned. - - Example: - - POST $BASE_URL/create_group_type - Request Body: - { - "id": "123", - "type": "group", - "child_id": 1 - } - Response: - { - "id": "123", - "type": "group", - "child_id": 1 - } - """ - data = await request.body() - response = requests.post( - routes.group_type_db_url, data=data, headers=db_request_token() - ) - if helpers.is_response_valid(response, "Group-type API could not post the data!"): - return helpers.is_response_empty( - response.json(), "Group-type API could not fetch the created record!" - ) - - -@router.patch("/") -async def update_group_type(request: Request): - """ - This API updates an existing group type based on the provided data. - - Parameters: - request (Request): The request object containing the data for updating the group type. - - Returns: - dict: Returns the updated group type record if the update is successful. If the update fails, an error message is returned. - - Example: - PATCH $BASE_URL/update_group_type - Request Body: - { - "id": 123, - "type": "program", - } - Response: - { - "id": 123, - "type": "program", - "child_id": 1 - } - """ - data = await request.body() - response = requests.patch( - routes.group_type_db_url + "/" + str(data["id"]), - data=data, - headers=db_request_token(), - ) - if helpers.is_response_valid(response, "Group-type API could not patch the data!"): - return helpers.is_response_empty( - response.json(), "Group-type API could not fetch the patched record!" - ) diff --git a/app/router/group_user.py b/app/router/group_user.py new file mode 100644 index 0000000..62790e8 --- /dev/null +++ b/app/router/group_user.py @@ -0,0 +1,41 @@ +from fastapi import APIRouter, Request +import requests +from routes import group_user_db_url +from router import enrollment_record +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import GROUP_USER_QUERY_PARAMS + +router = APIRouter(prefix="/group-user", tags=["Group-User"]) + + +def create_auth_group_enrollment_record(data): + enrollment_record.create_enrollment_record() + + +@router.get("/") +def get_group_user(request: Request): + query_params = validate_and_build_query_params( + request.query_params, GROUP_USER_QUERY_PARAMS + ) + response = requests.get( + group_user_db_url, params=query_params, headers=db_request_token() + ) + if is_response_valid(response, "Group-User API could not fetch the data!"): + return is_response_empty( + response.json(), True, "Group-User record does not exist!" + ) + + +@router.post("/") +async def create_group_user(request: Request): + data = await request.body() + response = requests.post(group_user_db_url, data=data, headers=db_request_token()) + if is_response_valid(response, "Group-User API could not post the data!"): + return is_response_empty( + response.json(), True, "Group-User API could not fetch the created record!" + ) diff --git a/app/router/program.py b/app/router/program.py deleted file mode 100644 index 705e4c9..0000000 --- a/app/router/program.py +++ /dev/null @@ -1,62 +0,0 @@ -from fastapi import APIRouter, HTTPException, Request -import requests -from settings import settings -from helpers import db_request_token - -router = APIRouter(prefix="/program", tags=["Program"]) -program_db_url = settings.db_url + "/program/" - -QUERY_PARAMS = [ - "id", - "name", - "type", - "sub_type", - "mode", - "start_date", - "target_outreach", - "product_used", - "donor", - "state", - "model", - "group_id", -] - - -@router.get("/") -def get_program_data(request: Request): - """ - This API returns details of a program corresponding to the provided program ID, if the ID exists in the database. - - Parameters: - id (int): The ID against which details need to be retrieved. - - Returns: - list: Returns program details if the program ID exists in the database. If the ID does not exist, a 404 status code is returned with a message indicating that the program ID does not exist. - - Example: - > $BASE_URL/program/1234 - Returns: [{program_data}] - - > $BASE_URL/program/{invalid_id} - Returns: { - "status_code": 404, - "detail": "Program ID does not exist!", - "headers": null - } - """ - query_params = {} - for key in request.query_params.keys(): - if key not in QUERY_PARAMS: - raise HTTPException( - status_code=400, detail="Query Parameter {} is not allowed!".format(key) - ) - query_params[key] = request.query_params[key] - - response = requests.get( - program_db_url, params=query_params, headers=db_request_token() - ) - if response.status_code == 200: - if len(response.json()) != 0: - return response.json() - raise HTTPException(status_code=404, detail="Program does not exist!") - raise HTTPException(status_code=404, detail="Program does not exist!") diff --git a/app/router/school.py b/app/router/school.py index 681acc3..12fd340 100644 --- a/app/router/school.py +++ b/app/router/school.py @@ -1,23 +1,24 @@ from fastapi import APIRouter, Request import requests -from router import routes -import helpers -import mapping -from helpers import db_request_token +from routes import school_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import SCHOOL_QUERY_PARAMS router = APIRouter(prefix="/school", tags=["School"]) @router.get("/") def get_school(request: Request): - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.SCHOOL_QUERY_PARAMS + query_params = validate_and_build_query_params( + request.query_params, SCHOOL_QUERY_PARAMS ) response = requests.get( - routes.school_db_url, params=query_params, headers=db_request_token() + school_db_url, params=query_params, headers=db_request_token() ) - - if helpers.is_response_valid(response, "School API could not fetch the data!"): - return helpers.is_response_empty( - response.json(), False, "School does not exist" - ) + if is_response_valid(response, "School API could not fetch the data!"): + return is_response_empty(response.json()[0], True, "School does not exist") diff --git a/app/router/session.py b/app/router/session.py index 7cdae64..0238dbc 100644 --- a/app/router/session.py +++ b/app/router/session.py @@ -1,56 +1,26 @@ from fastapi import APIRouter, HTTPException, Request import requests from settings import settings +from routes import session_db_url from models import SessionResponse -from helpers import db_request_token -from logger_config import get_logger +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import SESSION_QUERY_PARAMS router = APIRouter(prefix="/session", tags=["Session"]) -session_db_url = settings.db_url + "/session/" -logger = get_logger() @router.get("/", response_model=SessionResponse) -async def get_session_data(request: Request): - """ - This API returns session details corresponding to the provided session ID, if the ID exists in the database - - Parameters: - session_id (str): The ID against which details need to be retrieved - - Returns: - list: Returns session details if the session ID exists in the database. If the ID does not exist, 404 is returned - - Example: - > $BASE_URL/session/1234 - returns [{session_data}] - - > $BASE_URL/session/{invalid_id} - returns { - "status_code": 404, - "detail": "Session ID does not exist!", - "headers": null - } - """ - query_params = {} - for key in request.query_params.keys(): - if key not in ["name", "session_id"]: - raise HTTPException( - status_code=400, detail="Query Parameter {} is not allowed!".format(key) - ) - query_params[key] = request.query_params[key] - - if "session_id" in query_params: - logger.info("Searching for session {} ...".format(query_params["session_id"])) - else: - logger.info("Searching for session {} ...".format(query_params["name"])) - +async def get_session(request: Request): + query_params = validate_and_build_query_params( + request.query_params, SESSION_QUERY_PARAMS + ) response = requests.get( session_db_url, params=query_params, headers=db_request_token() ) - - if response.status_code == 200: - if len(response.json()) != 0: - return response.json()[0] - raise HTTPException(status_code=404, detail="Session ID does not exist!") - raise HTTPException(status_code=404, detail="Session ID does not exist!") + if is_response_valid(response, "Session API could not fetch the data!"): + return is_response_empty(response.json(), "Session does not exist!") diff --git a/app/router/session_group.py b/app/router/session_group.py deleted file mode 100644 index 4106fad..0000000 --- a/app/router/session_group.py +++ /dev/null @@ -1,52 +0,0 @@ -from fastapi import APIRouter, HTTPException -import requests -from settings import settings -from helpers import db_request_token - -router = APIRouter(prefix="/session-group", tags=["Session-Group"]) -session_group_db_url = settings.db_url + "/group-session/" -group_type_db_url = settings.db_url + "/group-type/" - - -@router.get("/{session_id}") -def get_group_for_session(session_id: str): - """ - This API returns group ID corresponding to the provided session ID, if the ID exists in the database - - Parameters: - session_id (str): The ID against which group ID needs to be retrieved - - Returns: - list: Returns group ID if the session ID exists in the database. If the ID does not exist, 404 is returned - - Example: - > $BASE_URL/session/1234 - returns [{group_id: 123}] - - > $BASE_URL/session/{invalid_id} - returns { - "status_code": 404, - "detail": "Session ID does not exist!", - "headers": null - } - """ - response = requests.get( - session_group_db_url, - params={"session_id": session_id}, - headers=db_request_token(), - ) - if response.status_code == 200: - if len(response.json()) != 0: - data = response.json() - print(data) - group_type_response = requests.get( - group_type_db_url, - params={"id": data[0]["group_type_id"]}, - headers=db_request_token(), - ) - if group_type_response.status_code == 200: - if len(group_type_response.json()) != 0: - group_data = group_type_response.json() - return group_data[0]["child_id"] - raise HTTPException(status_code=404, detail="Session ID does not exist!") - raise HTTPException(status_code=404, detail="Session ID does not exist!") diff --git a/app/router/session_occurrence.py b/app/router/session_occurrence.py index f28b321..54abc5c 100644 --- a/app/router/session_occurrence.py +++ b/app/router/session_occurrence.py @@ -108,18 +108,17 @@ async def get_session_occurrence_data(request: Request): if has_session_started(session_occurrence["start_time"]) and has_session_ended(session_occurrence["end_time"]) ] - if len(matched_session_occurrences) > 0: response = requests.get( session_db_url, params=query_params, headers=db_request_token() ) - if response.status_code == 200: session_data = response.json()[0] - if session_data["is_active"]: session_data["is_session_open"] = True - + session_data[ + "session_occurrence_id" + ] = matched_session_occurrences[0]["id"] return session_data return {"is_session_open": False} raise HTTPException( diff --git a/app/router/student.py b/app/router/student.py index b2732c8..0de50aa 100644 --- a/app/router/student.py +++ b/app/router/student.py @@ -1,329 +1,304 @@ from fastapi import APIRouter, HTTPException, Request import requests from settings import settings -import helpers -import mapping -from router import routes, school, enrollment_record, user -from id_generation import JNVIDGeneration +from router import group, auth_group, group_user, user, school, grade, enrollment_record +from id_generation_classes import JNVIDGeneration from request import build_request -from logger_config import get_logger -from helpers import db_request_token +from routes import student_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from dateutil.relativedelta import relativedelta +from datetime import datetime +from mapping import ( + USER_QUERY_PARAMS, + STUDENT_QUERY_PARAMS, + ENROLLMENT_RECORD_PARAMS, + SCHOOL_QUERY_PARAMS, +) router = APIRouter(prefix="/student", tags=["Student"]) logger = get_logger() -def build_enrollment_data(data): - enrollment_data = {} - for key in data.keys(): - if key in mapping.ENROLLMENT_RECORD_PARAMS and key != "student_id": - enrollment_data[key] = data[key] - return enrollment_data - - -def build_student_data(data): - student_data = {} - for key in data.keys(): - if key in mapping.STUDENT_QUERY_PARAMS: - student_data[key] = data[key] - return student_data - - -def build_user_data(data): - user_data = {} - for key in data.keys(): - if key in mapping.USER_QUERY_PARAMS: - user_data[key] = data[key] - return user_data - - -def id_generation(data): - if data["group"] == "JNVStudents": - counter = settings.JNV_counter - if counter > 0: - JNV_Id = JNVIDGeneration( - data["region"], data["school_name"], data["grade"] - ).get_id - counter -= 1 - return JNV_Id - raise HTTPException( - status_code=400, detail="Student ID could not be generated. Max loops hit!" - ) - +def build_student_and_user_data(student_data): + data = {} + for key in student_data.keys(): + if key in STUDENT_QUERY_PARAMS + USER_QUERY_PARAMS: + if key == "physically_handicapped": + data["physically_handicapped"] = ( + "true" + if student_data["physically_handicapped"] == "Yes" + else "false" + ) + elif key == "has_category_certificate": + data["has_category_certificate"] = ( + "true" + if student_data["has_category_certificate"] == "Yes" + else "false" + ) + else: + data[key] = student_data[key] + return data -@router.get("/") -def get_students(request: Request): - """ - This API returns a student or a list of students who match the criteria(s) given in the request. - Optional Parameters: - student_id (str), birth_date (str), category (str), stream (str). - For extensive list of optional parameters, refer to the DB schema note on Notion. +def generate_JNV_student_id(data): + counter = settings.JNV_COUNTER_FOR_ID_GENERATION - Returns: - list: student data if student(s) whose details match, otherwise 404 + if counter > 0: + JNV_Id = JNVIDGeneration( + data["region"], data["school_name"], data["grade"] + ).get_id + counter -= 1 + return JNV_Id - Example: - > $BASE_URL/student/ - returns [data_of_all_students] + raise HTTPException( + status_code=400, detail="JNV Student ID could not be generated. Max loops hit!" + ) - > $BASE_URL/student/?student_id=1234 - returns [{student_data}] - > $BASE_URL/student/?stream=PCB - returns [data_of_all_students_with_stream_PCB] +async def create_school_user_record(data, school_name): + school_data = school.get_school(build_request(query_params={"name": school_name})) + group_data = group.get_group( + build_request(query_params={"child_id": school_data["id"], "type": "school"}) + ) - > $BASE_URL/student/?student_id=student_id_with_stream_PCM&stream=PCB + await group_user.create_group_user( + build_request( + method="POST", + body={ + "group_id": group_data[0]["id"], + "user_id": data["user"]["id"], + "academic_year": str(datetime.now().year) + + "-" + + str((datetime.now() + relativedelta(years=1)).year), + "start_date": datetime.now().strftime("%Y-%m-%d"), + "grade_id": data["grade_id"], + }, + ) + ) - returns { - "status_code": 404, - "detail": "No student found!", - "headers": null - } - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.STUDENT_QUERY_PARAMS + mapping.USER_QUERY_PARAMS +async def create_auth_group_user_record(data, auth_group_name): + auth_group_data = auth_group.get_auth_group( + build_request(query_params={"name": auth_group_name}) ) - - response = requests.get( - routes.student_db_url, params=query_params, headers=db_request_token() + group_data = group.get_group( + build_request( + query_params={"child_id": auth_group_data["id"], "type": "auth_group"} + ) ) - if helpers.is_response_valid(response, "Student API could not fetch the student!"): - return helpers.is_response_empty( - response.json(), True, "Student does not exist" + await group_user.create_group_user( + build_request( + method="POST", + body={ + "group_id": group_data[0]["id"], + "user_id": data["user"]["id"], + "academic_year": str(datetime.now().year) + + "-" + + str((datetime.now() + relativedelta(years=1)).year), + "start_date": datetime.now().strftime("%Y-%m-%d"), + "grade_id": data["grade_id"], + }, ) + ) -@router.get("/verify") -async def verify_student(request: Request, student_id: str): - """ - This API checks if the provided student ID and the additional details match in the database. +def create_new_student_record(data): + response = requests.post(student_db_url, data=data, headers=db_request_token()) + if is_response_valid(response, "Student API could not post the data!"): + created_student_data = is_response_empty( + response.json(), "Student API could fetch the created student" + ) - Parameters: - student_id (str): The student ID to be checked. + return created_student_data - Other parameters: - Example: birth_date (str), category (str), stream (str). - For extensive list of optional parameters, refer to the DB schema note on Notion. - Returns: - bool: True if the details match against the student ID, otherwise False +def check_if_email_or_phone_is_part_of_request(query_params): + if ( + "email" not in query_params + or query_params["email"] == "" + or query_params["email"] is None + ) and ( + "phone" not in query_params + or query_params["phone"] == "" + or query_params["phone"] is None + ): + raise HTTPException( + status_code=400, detail="Email/Phone is not part of the request data" + ) + return - Example: - > $BASE_URL/student/verify/?student_id=1234 - returns True - > $BASE_URL/student/verify/?student_id=1234&stream=PCB - returns True +def check_if_student_id_is_part_of_request(query_params): + if ( + "student_id" not in query_params + or query_params["student_id"] == "" + or query_params["student_id"] is None + ): + raise HTTPException( + status_code=400, detail="Student ID is not part of the request data" + ) + return - > $BASE_URL/student/verify/?student_id={invalid_id} - returns { - "status_code": 404, - "detail": "Student ID does not exist!", - "headers": null - } - > $BASE_URL/student/1234/?student_id=1234&stream=PCM - returns { - "status_code": 404, - "detail": "Student ID does not exist!", - "headers": null - } +@router.get("/") +def get_students(request: Request): + query_params = validate_and_build_query_params( + request.query_params, + STUDENT_QUERY_PARAMS + USER_QUERY_PARAMS + ENROLLMENT_RECORD_PARAMS, + ) + response = requests.get( + student_db_url, params=query_params, headers=db_request_token() + ) + if is_response_valid(response, "Student API could not fetch the student!"): + return is_response_empty(response.json(), True, "Student does not exist") - """ - query_params = helpers.validate_and_build_query_params( +@router.get("/verify") +async def verify_student(request: Request, student_id: str): + query_params = validate_and_build_query_params( request.query_params, - mapping.STUDENT_QUERY_PARAMS + mapping.USER_QUERY_PARAMS + ["group_id"], + STUDENT_QUERY_PARAMS + USER_QUERY_PARAMS + ["auth_group_id"], ) logger.info(f"Verifying student: {student_id}") response = requests.get( - routes.student_db_url, + student_db_url, params={"student_id": student_id}, headers=db_request_token(), ) - - if helpers.is_response_valid(response): - student_data = helpers.is_response_empty(response.json(), False) + if is_response_valid(response): + student_data = is_response_empty(response.json(), False) if student_data: student_data = student_data[0] - if len(query_params) != 0: - for key in query_params.keys(): - if key in mapping.USER_QUERY_PARAMS: - if student_data["user"][key] != "": - if student_data["user"][key] != query_params[key]: - return False - - if key in mapping.STUDENT_QUERY_PARAMS: - if student_data[key] != "": - if student_data[key] != query_params[key]: - return False - # check if the user belongs to the group that sent the validation request - if key == "group_id": - # get the group-type ID based on the group ID - response = requests.get( - routes.group_type_db_url, - params={ - "child_id": query_params["group_id"], - "type": "group", - }, - headers=db_request_token(), + for key, value in query_params.items(): + if key in USER_QUERY_PARAMS and student_data["user"].get(key) != value: + return False + if key in STUDENT_QUERY_PARAMS and student_data.get(key) != value: + return False + + # check if the user belongs to the auth-group that sent the validation request + if key == "auth_group_id": + response = group.get_group( + build_request( + query_params={ + "child_id": query_params["auth_group_id"], + "type": "auth_group", + } ) + ) - if helpers.is_response_valid(response): - data = helpers.is_response_empty(response.json(), False) - data = data[0] - - # check if the group-type ID and user ID mapping exists - response = requests.get( - routes.group_user_db_url, - params={ - "group_type_id": data["id"], + if response: + response = response[0] + group_user_response = group_user.get_group_user( + build_request( + query_params={ + "group_id": response["id"], "user_id": student_data["user"]["id"], - }, - headers=db_request_token(), + } ) - if helpers.is_response_valid(response): - return len(response.json()) != 0 - return False - - raise HTTPException( - status_code=400, - detail="Group Type ID could not be retrieved", ) + if not group_user_response or group_user_response == []: + return False return True - return False + return False @router.post("/") async def create_student(request: Request): data = await request.body() - print("student:", data) - query_params = helpers.validate_and_build_query_params( + query_params = validate_and_build_query_params( data["form_data"], - mapping.STUDENT_QUERY_PARAMS - + mapping.USER_QUERY_PARAMS - + mapping.ENROLLMENT_RECORD_PARAMS + STUDENT_QUERY_PARAMS + + USER_QUERY_PARAMS + + ENROLLMENT_RECORD_PARAMS + + SCHOOL_QUERY_PARAMS + ["id_generation"], ) - if data["id_generation"] == "False": - if ( - "student_id" not in query_params - or query_params["student_id"] == "" - or query_params["student_id"] is None - ): - raise HTTPException( - status_code=400, detail="Student ID is not part of the request data" - ) + if not data["id_generation"]: + student_id = query_params["student_id"] + check_if_student_id_is_part_of_request(query_params) - # check if student is already part of the ID. If yes, just return the student ID does_student_already_exist = await verify_student( build_request(), query_params["student_id"] ) + if does_student_already_exist: return query_params["student_id"] - else: - # if student ID is not part of the database, create a new student record - response = requests.post( - routes.student_db_url + "/register", - data=data["form_data"], - headers=db_request_token(), + else: + check_if_email_or_phone_is_part_of_request(query_params) + + user_already_exists = user.get_users( + build_request( + query_params={ + "email": query_params["email"] if "email" in query_params else None, + "phone": query_params["phone"] if "phone" in query_params else None, + } + ) + ) + if user_already_exists: + response = get_students( + build_request(query_params={"user_id": user_already_exists["user_id"]}) ) + return response["student_id"] - if helpers.is_response_valid( - response, "Student API could not post the data!" + else: + if data["auth_group"] == "JNVStudents": + student_id = generate_JNV_student_id(data) + + if ( + data["auth_group"] == "FeedingIndiaStudents" + or data["auth_group"] == "UttarakhandStudents" ): - created_student_data = helpers.is_response_empty( - response.json(), "Student API could fetch the created student" - ) + student_id = query_params["phone"] + query_params["student_id"] = student_id - # based on the school name, retrieve the school ID - school_id_response = school.get_school( - build_request(query_params={"name": data["form_data"]["school_name"]}) - ) - data["form_data"]["school_id"] = school_id_response[0]["id"] - print("here") - # create a new enrollment record for the student, based on the student ID and school ID - enrollment_data = build_enrollment_data(data["form_data"]) - enrollment_data["student_id"] = created_student_data["id"] - print(enrollment_data) - await enrollment_record.create_enrollment_record( - build_request(body=enrollment_data) + student_id_already_exists = await verify_student( + build_request(), student_id=student_id ) - return query_params["student_id"] + if student_id_already_exists: + return student_id - else: - if ( - "email" not in query_params - or query_params["email"] == "" - or query_params["email"] is None - ) or ( - "phone" not in query_params - or query_params["phone"] == "" - or query_params["phone"] is None - ): - raise HTTPException( - status_code=400, detail="Email/Phone is not part of the request data" - ) + if "grade" in query_params: + student_grade_id = grade.get_grade( + build_request(query_params={"number": int(query_params["grade"])}) + ) + query_params["grade_id"] = student_grade_id["id"] - does_user_already_exist = user.get_users( - build_request( - query_params={ - "email": query_params["email"], - "phone": query_params["phone"], - } - ) + if "physically_handicapped" in query_params: + query_params["physically_handicapped"] = ( + "true" if query_params["physically_handicapped"] == "Yes" else "false" ) - if not does_user_already_exist: - while True: - id = id_generation(data) - does_student_already_exist = verify_student( - build_request(), student_id=id - ) - if not does_student_already_exist: - response = requests.post( - routes.user_db_url, - params=query_params, - headers=db_request_token(), - ) - if response.status_code == 201: - return query_params["student_id"] - raise HTTPException(status_code=500, detail="User not created!") + new_student_data = create_new_student_record(query_params) - else: - response = get_students( - build_request( - query_params={"user_id": does_user_already_exist["user_id"]} - ) - ) - if response.status_code == 200: - return response["student_id"] - raise HTTPException( - status_code=404, detail="User and student details do not match!" - ) + await create_auth_group_user_record(new_student_data, data["auth_group"]) + + if "school_name" in query_params: + await create_school_user_record(new_student_data, query_params["school_name"]) + + return student_id @router.patch("/") async def update_student(request: Request): data = await request.body() - response = requests.patch( - routes.student_db_url + "/" + str(data["id"]), - data=data, - headers=db_request_token(), - ) - if helpers.is_response_valid(response, "Student API could not post the data!"): - return helpers.is_response_empty( - response.json(), "Student API could fetch the created student" + + response = requests.post(student_db_url, data=data, headers=db_request_token()) + if is_response_valid(response, "Student API could not patch the data!"): + return is_response_empty( + response.json(), "Student API could not fetch the patched student" ) @@ -331,59 +306,11 @@ async def update_student(request: Request): async def complete_profile_details(request: Request): data = await request.json() - helpers.validate_and_build_query_params( - data, - mapping.STUDENT_QUERY_PARAMS - + mapping.USER_QUERY_PARAMS - + mapping.ENROLLMENT_RECORD_PARAMS, - ) - - user_data, student_data, enrollment_data = ( - build_user_data(data), - build_student_data(data), - build_enrollment_data(data), - ) + student_data = build_student_and_user_data(data) - # get the PK of the student whose profile is being completed student_response = get_students( build_request(query_params={"student_id": data["student_id"]}) ) student_data["id"] = student_response[0]["id"] - - # update the student with the entered details await update_student(build_request(body=student_data)) - - user_data["id"] = student_response[0]["user"]["id"] - - if len(user_data) > 0: - # update the student with the entered user details - await user.update_user(build_request(body=user_data)) - - # get the enrollment record of the student - enrollment_record_response = enrollment_record.get_enrollment_record( - build_request(query_params={"student_id": student_response[0]["id"]}) - ) - - # if school name was entered by the student, get the school ID from the school table - if "school_name" in data: - school_response = school.get_school( - build_request(query_params={"name": data["school_name"]}) - ) - enrollment_data["school_id"] = school_response[0]["id"] - - # if enrollment record already exists, update with new details - if enrollment_record_response != []: - enrollment_data["id"] = enrollment_record_response[0]["id"] - - enrollment_record_response = await enrollment_record.update_enrollment_record( - build_request(body=enrollment_data) - ) - - # else, create a new enrollment record for the student - else: - enrollment_data["student_id"] = student_response[0]["id"] - - enrollment_record_response = await enrollment_record.create_enrollment_record( - build_request(body=enrollment_data) - ) diff --git a/app/router/teacher.py b/app/router/teacher.py index aef8a01..84d99c4 100644 --- a/app/router/teacher.py +++ b/app/router/teacher.py @@ -1,92 +1,53 @@ -from fastapi import APIRouter, HTTPException, Request +from fastapi import APIRouter, Request import requests from settings import settings -import helpers -import mapping -from router import routes -from helpers import db_request_token +from routes import teacher_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import USER_QUERY_PARAMS, TEACHER_QUERY_PARAMS, ENROLLMENT_RECORD_PARAMS router = APIRouter(prefix="/teacher", tags=["Teacher"]) @router.get("/") def get_teachers(request: Request): - """ - This API returns a teacher or a list of teachers who match the criteria(s) given in the request. - - Optional Parameters: - uuid (str), birth_date (str) - For extensive list of optional parameters, refer to the DB schema note on Notion. - - Returns: - list: teacher data if teacher(s) whose details match, otherwise 404 - - Example: - > $BASE_URL/teacher/ - returns [data_of_all_teachers] - - > $BASE_URL/teacher/?uuid=1234 - returns [{teacher_data}] - - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.TEACHER_QUERY_PARAMS + mapping.USER_QUERY_PARAMS + query_params = validate_and_build_query_params( + request.query_params, + TEACHER_QUERY_PARAMS + USER_QUERY_PARAMS + ENROLLMENT_RECORD_PARAMS, ) - response = requests.get( - routes.teacher_db_url, params=query_params, headers=db_request_token() + teacher_db_url, params=query_params, headers=db_request_token() ) - - if helpers.is_response_valid(response, "Teacher API could not fetch the teacher!"): - return helpers.is_response_empty( - response.json(), True, "Teacher does not exist" - ) + if is_response_valid(response, "Teacher API could not fetch the teacher!"): + return is_response_empty(response.json(), True, "Teacher does not exist") @router.get("/verify") async def verify_teacher(request: Request, teacher_id: str): - """ - This API checks if the provided teacher ID and the additional details match in the database. - - Parameters: - uuid (str): The teacher ID to be checked. - - Other parameters: - Example: birth_date (str) - For extensive list of optional parameters, refer to the DB schema note on Notion. - - Returns: - bool: True if the details match against the teacher ID, otherwise False - - """ - - query_params = helpers.validate_and_build_query_params( - request.query_params, - mapping.TEACHER_QUERY_PARAMS + mapping.USER_QUERY_PARAMS + ["teacher_id"], + query_params = validate_and_build_query_params( + request.query_params, TEACHER_QUERY_PARAMS + USER_QUERY_PARAMS ) response = requests.get( - routes.teacher_db_url, - params={"uuid": teacher_id}, + teacher_db_url, + params={"teacher_id": teacher_id}, headers=db_request_token(), ) - if helpers.is_response_valid(response): - data = helpers.is_response_empty(response.json(), False) + if is_response_valid(response): + data = is_response_empty(response.json(), False) if data: data = data[0] - if len(query_params) != 0: - for key in query_params.keys(): - if key in mapping.USER_QUERY_PARAMS: - if data["user"][key] != "": - if data["user"][key] != query_params[key]: - return False - - if key in mapping.TEACHER_QUERY_PARAMS: - if data[key] != "": - if data[key] != query_params[key]: - return False + for key, value in query_params.items(): + if key in USER_QUERY_PARAMS and data["user"].get(key) != value: + return False + if key in TEACHER_QUERY_PARAMS and data.get(key) != value: + return False return True - return False + return False diff --git a/app/router/user.py b/app/router/user.py index de14508..8b769f0 100644 --- a/app/router/user.py +++ b/app/router/user.py @@ -1,87 +1,45 @@ from fastapi import APIRouter, Request import requests -from router import student, routes +from router import student from request import build_request -import mapping -import helpers -from helpers import db_request_token +from routes import user_db_url +from helpers import ( + db_request_token, + validate_and_build_query_params, + is_response_valid, + is_response_empty, +) +from mapping import ( + USER_QUERY_PARAMS, + STUDENT_QUERY_PARAMS, + ENROLLMENT_RECORD_PARAMS, + SCHOOL_QUERY_PARAMS, +) router = APIRouter(prefix="/user", tags=["User"]) @router.get("/") def get_users(request: Request): - """ - This API returns a user or a list of users who match the criteria(s) given in the request. - - Optional Parameters: - phone (str), date_of_birth (str), email (str). - For extensive list of optional parameters, refer to the DB schema note on Notion. - - Returns: - list: user data if user(s) whose details match, otherwise 404 - - Example: - > GET $BASE_URL/user/ - returns [data_of_all_users] - - > GET $BASE_URL/user/?user_id=1234 - returns [{user_data}] - - > GET $BASE_URL/user/?region=Hyderabad - returns [data_of_all_users_with_region_hyderabad] - - > GET $BASE_URL/user/?user_id=user_id_with_stream_PCM&stream=PCB - returns { - "status_code": 404, - "detail": "No student found!", - "headers": null - } - - """ - query_params = helpers.validate_and_build_query_params( - request.query_params, mapping.USER_QUERY_PARAMS + query_params = validate_and_build_query_params( + request.query_params, USER_QUERY_PARAMS ) response = requests.get( - routes.user_db_url, params=query_params, headers=db_request_token() + user_db_url, params=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "User API could not fetch the data!"): - return helpers.is_response_empty(response.json(), "User does not exist!") + if is_response_valid(response, "User API could not fetch the data!"): + return is_response_empty(response.json(), "User does not exist!") @router.post("/") async def create_user(request: Request): - """ - This API creates a new user based on the provided data. - - Parameters: - request (Request): The request object containing the data for creating the user. - - Returns: - dict: Returns the created user record if the creation is successful. If the creation fails, an error message is returned. - - Example: - - POST $BASE_URL/user/1234 - Request Body: - { - "id": 1234, - "name": "Updated User A", - "email": "updated_user_a@example.com" - } - Response: - { - "id": 1234, - "name": "Updated User A", - "email": "updated_user_a@example.com" - } - """ data = await request.json() - helpers.validate_and_build_query_params( + validate_and_build_query_params( data["form_data"], - mapping.STUDENT_QUERY_PARAMS - + mapping.USER_QUERY_PARAMS - + mapping.ENROLLMENT_RECORD_PARAMS + STUDENT_QUERY_PARAMS + + USER_QUERY_PARAMS + + ENROLLMENT_RECORD_PARAMS + + SCHOOL_QUERY_PARAMS + ["id_generation"] + ["user_type"], ) @@ -92,51 +50,8 @@ async def create_user(request: Request): body={ "form_data": data["form_data"], "id_generation": data["id_generation"], - "group": data["group"], + "auth_group": data["auth_group"], } ) ) return create_student_response - - -@router.patch("/") -async def update_user(request: Request): - """ - This API updates an existing user record based on the provided data. - - Parameters: - request (Request): The request object containing the data for updating the user. - - Returns: - dict: Returns the updated user record if the update is successful. If the update fails, an error message is returned. - - Example: - - PATCH $BASE_URL/user/1234 - Request Body: - { - "id": 1234, - "name": "Updated User A", - "email": "updated_user_a@example.com" - } - Response: - { - "id": 1234, - "name": "Updated User A", - "email": "updated_user_a@example.com" - } - """ - data = await request.body() - query_params = helpers.validate_and_build_query_params( - data, mapping.USER_QUERY_PARAMS - ) - - response = requests.patch( - routes.user_db_url + "/" + str(query_params["id"]), - data=query_params, - headers=db_request_token(), - ) - if helpers.is_response_valid(response, "User API could not patch the data!"): - return helpers.is_response_empty( - response.json(), "User API could fetch the patched user!" - ) diff --git a/app/router/user_session.py b/app/router/user_session.py index ff09b11..d007e10 100644 --- a/app/router/user_session.py +++ b/app/router/user_session.py @@ -2,45 +2,35 @@ import requests from models import UserSession from datetime import datetime -from router import routes -import helpers -from helpers import db_request_token +from routes import user_session_db_url +from helpers import db_request_token, is_response_valid, is_response_empty +from router import student, session, user +from request import build_request router = APIRouter(prefix="/user-session", tags=["User-Session"]) @router.post("/") -def user_session_data(user_session: UserSession): - """ - This function creates a new user session and stores it in the database. +async def user_session(user_session: UserSession): + query_params = user_session.dict() + query_params["timestamp"] = datetime.now().isoformat() - Parameters: - user_session (UserSession): The user session object containing the session data. + if query_params["user_type"] == "student": + user_id_response = student.get_students( + build_request(query_params={"student_id": query_params["user_id"]}) + ) - Returns: - dict: Returns the created user session record if the creation is successful. If the creation fails, an error message is returned. + query_params["user_id"] = user_id_response[0]["user"]["id"] + + session_pk_id_response = await session.get_session( + build_request(query_params={"session_id": query_params["session_id"]}) + ) + query_params["session_id"] = session_pk_id_response[0]["id"] - Example: - POST $BASE_URL/user_session_data - Request Body: - { - "user_id": 1234, - "session_id": "abcd1234", - "start_time": "2023-07-04T12:30:00" - } - Response: - { - "user_id": 1234, - "session_id": "abcd1234", - "start_time": "2023-07-04T12:30:00" - } - """ - query_params = user_session.dict() - query_params["start_time"] = datetime.now().isoformat() response = requests.post( - routes.user_session_db_url, json=query_params, headers=db_request_token() + user_session_db_url, json=query_params, headers=db_request_token() ) - if helpers.is_response_valid(response, "User-session API could not post the data!"): - helpers.is_response_empty( + if is_response_valid(response, "User-session API could not post the data!"): + is_response_empty( response.json(), "User-session API could not fetch the created record!" ) diff --git a/app/router/routes.py b/app/routes.py similarity index 57% rename from app/router/routes.py rename to app/routes.py index b68ebbc..9ac94a1 100644 --- a/app/router/routes.py +++ b/app/routes.py @@ -1,13 +1,18 @@ from settings import settings -student_db_url = settings.db_url + "/student" -group_db_url = settings.db_url + "/group" -group_type_db_url = settings.db_url + "/group-type/" +auth_group_db_url = settings.db_url + "/auth-group" +batch_db_url = settings.db_url + "/batch/" enrollment_record_db_url = settings.db_url + "/enrollment-record" form_db_url = settings.db_url + "/form-schema" -user_db_url = settings.db_url + "/user" +grade_db_url = settings.db_url + "/grade" +group_user_db_url = settings.db_url + "/group-user" +group_db_url = settings.db_url + "/group/" +program_db_url = settings.db_url + "/program" school_db_url = settings.db_url + "/school" -batch_db_url = settings.db_url + "/batch/" -user_session_db_url = settings.db_url + "/user-session/" +group_session_db_url = settings.db_url + "/group-session" +session_occurrence_db_url = settings.db_url + "/session-occurrence" +session_db_url = settings.db_url + "/session" +student_db_url = settings.db_url + "/student" teacher_db_url = settings.db_url + "/teacher" -group_user_db_url = settings.db_url + "/group-user" +user_session_db_url = settings.db_url + "/user-session/" +user_db_url = settings.db_url + "/user" diff --git a/app/settings.py b/app/settings.py index 564d314..b937fde 100644 --- a/app/settings.py +++ b/app/settings.py @@ -20,7 +20,8 @@ class Settings(BaseModel): authjwt_cookie_samesite: str = "lax" # DB service base URL db_url: str = os.environ.get("DB_SERVICE_URL") - token: str = os.environ.get("DB_SERVICE_TOKEN") + TOKEN: str = os.environ.get("DB_SERVICE_TOKEN") + JNV_COUNTER_FOR_ID_GENERATION: int = os.environ.get("JNV_COUNTER_FOR_ID_GENERATION") # callback to get the configuration