diff --git a/.gitignore b/.gitignore index ad89cb0..09fb7bb 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,4 @@ __pycache__ .vercel tempCodeRunnerFile.py -.pytest_cache +.pytest_cache \ No newline at end of file diff --git a/API/fwapp.py b/API/fwapp.py index 2c21d54..1c2aa4c 100644 --- a/API/fwapp.py +++ b/API/fwapp.py @@ -4,7 +4,7 @@ from API.services.db import * from API.services.auth import * from API.services.auth.utils import JWTBearer -from API.utils import scopes +from API.utils import scopes, role_manager from API.core.ExceptionHandlers import * from API.core.Exceptions import * from API.models import (UserAuth, UserOut, UseRefreshToken, @@ -83,18 +83,18 @@ def api_get_data(village_name: str, user_credentials: str = Depends(JWTBearer()) } user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=["admin", "GOVTOff"], village_name=village_name, + @scopes.init_checks(authorized_roles=[role_manager.admin, role_manager.GOVTOff], village_name=village_name, response_result=response_result) def scoped_checks(user_creds: UserOut): - if user_creds.role == 'admin': - response_data = fetch_from_db(response_result, user_creds.village_name) + if user_creds.role == role_manager.admin: + village_data = fetch_from_db(response_result, user_creds.village_name) else: - response_data = fetch_from_db(response_result, village_name) - return response_data['data'] + village_data = fetch_from_db(response_result, village_name) + return village_data - response_data = scoped_checks(user_creds) + village_data = scoped_checks(user_creds) - response_result['data'] = response_data + response_result['data'] = village_data response_result['status'] = 'success' response_result['message'] = ['authorized'] @@ -112,7 +112,7 @@ def api_get_familydata(respondents_id: str, user_credentials: str = Depends(JWTB user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['admin', 'GOVTOff'], wrong_endpoint_roles=['GOVTOff'], + @scopes.init_checks(authorized_roles=[role_manager.admin, role_manager.GOVTOff], wrong_endpoint_roles=[role_manager.GOVTOff], village_name=user_creds.village_name, response_result=response_result) def scoped_checks(user_creds: UserOut): pass @@ -121,7 +121,7 @@ def scoped_checks(user_creds: UserOut): familydata = fetch_familydata(response_result, user_creds.village_name, respondents_id) - response_result['data'] = familydata["data"] + response_result['data'] = familydata response_result['status'] = 'success' response_result['message'] = ['Authenticated'] return response_result @@ -138,7 +138,7 @@ def api_get_individual_data(respondents_id: str, user_credentials: str = Depends user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['admin', 'GOVTOff'], wrong_endpoint_roles=['GOVTOff'], + @scopes.init_checks(authorized_roles=[role_manager.admin, role_manager.GOVTOff], wrong_endpoint_roles=[role_manager.GOVTOff], village_name=user_creds.village_name, response_result=response_result) def scoped_checks(user_creds: UserOut): pass @@ -164,17 +164,17 @@ async def auth_signup(data: Union[UserAuth, BulkSignup], user_credentials: str = user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['admin', 'GOVTOff'], + @scopes.init_checks(authorized_roles=[role_manager.admin, role_manager.GOVTOff], village_name=data.village_name, response_result=response_result) def scoped_checks(user_creds: UserOut): if isinstance(data, UserAuth): - if data.role not in ['admin', 'user']: + if data.role not in [role_manager.admin, role_manager.user]: raise AuthorizationFailedException(response_result, "not authorized") - if data.role == 'admin' and user_creds.role == 'admin': + if data.role == role_manager.admin and user_creds.role == role_manager.admin: raise AuthorizationFailedException(response_result, "not authorized") - if user_creds.role == "admin" and data.village_name != user_creds.village_name: + if user_creds.role == role_manager.admin and data.village_name != user_creds.village_name: raise AuthorizationFailedException(response_result, "not authorized") scoped_checks(user_creds) @@ -202,23 +202,15 @@ async def auth_use_refresh_token(existing_tokens: UseRefreshToken): return handle_refresh_token_access(existing_tokens.refresh_access_token) -@app.get("/ops/get_village_list", summary="Get the list of village names", response_model=FrontendResponseModel, - tags=["Sensitive ops"], dependencies=[Depends(JWTBearer())]) -async def get_village_list(user_credentials: str = Depends(JWTBearer())): +@app.get("/api/get_village_list", summary="Get the list of village names", response_model=FrontendResponseModel, + tags=["Resource Server"]) +async def get_village_list(): response_result = { "status": "not_allowed", "message": ["Not authenticated"], "data": {}, } - user_creds = get_current_user_credentials(user_credentials) - - @scopes.init_checks(authorized_roles=['GOVTOff'], response_result=response_result) - def scoped_checks(user_creds: UserOut): - pass - - scoped_checks(user_creds) - village_list = get_available_villages(response_result) response_result['data']["village_names"] = village_list return response_result @@ -236,7 +228,7 @@ async def ops_delete_database(dbname: str, user_credentials: str = Depends(JWTBe user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['GOVTOff'], response_result=response_result, village_name=dbname) + @scopes.init_checks(authorized_roles=[role_manager.GOVTOff], response_result=response_result, village_name=dbname) def scoped_checks(user_creds): pass @@ -257,7 +249,7 @@ async def ops_update_village_list(dbname: str, user_credentials: str = Depends(J user_creds = get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['GOVTOff'], response_result=response_result) + @scopes.init_checks(authorized_roles=[role_manager.GOVTOff], response_result=response_result) def scoped_checks(user_creds): pass @@ -266,7 +258,7 @@ def scoped_checks(user_creds): create_new_village(dbname, user_creds, response_result) return response_result -@app.get('/api/get_respid_list', summary="Get the list of users", dependencies=[Depends(JWTBearer())], tags=["Resource Server"]) +@app.get('/api/get_respdata_list', summary="Get the list of users", dependencies=[Depends(JWTBearer())], tags=["Resource Server"]) async def get_respid_list(date:str, village_name:str=None, user_credentials:str=Depends(JWTBearer())): response_result={ "status":"not_allowed", @@ -276,17 +268,17 @@ async def get_respid_list(date:str, village_name:str=None, user_credentials:str= user_creds=get_current_user_credentials(user_credentials) - @scopes.init_checks(authorized_roles=['admin','GOVTOff'],response_result=response_result,village_name=village_name) + @scopes.init_checks(authorized_roles=[role_manager.admin,role_manager.GOVTOff],response_result=response_result,village_name=village_name) def scoped_checks(user_creds:UserOut): - if user_creds.role == 'admin': - response_data = get_resp_id_on_date(user_creds.village_name,'meta',date,response_result) + if user_creds.role == role_manager.admin: + response_data = get_resp_data_on_date(user_creds.village_name, date,response_result) else: - response_data = get_resp_id_on_date(village_name,'meta',date,response_result) + response_data = get_resp_data_on_date(village_name, date,response_result) return response_data response_data = scoped_checks(user_creds) - response_result['data']['user_ids'] = response_data + response_result['data'] = response_data response_result['status'] = 'success' response_result['message'] = ['authorized'] diff --git a/API/services/auth/AuthServices.py b/API/services/auth/AuthServices.py index f29d72f..9048fb0 100644 --- a/API/services/auth/AuthServices.py +++ b/API/services/auth/AuthServices.py @@ -11,6 +11,7 @@ from API.core.Exceptions import * from API.models import UserOut, UserAuth, TokenPayload, BulkSignup from API.services.db.utils import DBQueries +from API.utils import role_manager from .utils import Auth @@ -48,7 +49,7 @@ def signup(response_result: FrontendResponseModel, data: Union[UserAuth,BulkSign passwords=[Auth.get_password_hash(passwd) for passwd in data.passwords] village_name=data.village_name - users=DBQueries.filtered_db_search("Auth","user",["_id","password","village_name"],AADHAR={"$in":AADHAR_NOS}) + users=DBQueries.filtered_db_search("Auth", role_manager.user, ["_id","password","village_name"], search_idxs={"AADHAR":{"$in":AADHAR_NOS}}) users=[user["AADHAR"] for user in users] invalid_users=[] @@ -68,7 +69,7 @@ def signup(response_result: FrontendResponseModel, data: Union[UserAuth,BulkSign valid_users.append(userinfo) if len(valid_users)!=0: - DBQueries.insert_to_database("Auth", "user", valid_users) # saving user to database + DBQueries.insert_to_database("Auth", role_manager.user, valid_users) # saving user to database response_result['status'] = f'success' response_result['message'] = [f'Users created successfully'] else: diff --git a/API/services/db/DBManipulation.py b/API/services/db/DBManipulation.py index 8316b21..0f78672 100644 --- a/API/services/db/DBManipulation.py +++ b/API/services/db/DBManipulation.py @@ -15,36 +15,11 @@ from API.utils.DBConnection import DBConnection from API.core.Exceptions import * -from .utils import DBQueries +from .utils import DBQueries, field_manager collection_names = { - "sv": "static_vars", - # respondent's profile - "rpf": "respondent_prof", - # gen household info - "ghi": "gen_ho_info", - # family info - "fi": "fam_info", - # migration status - "ms": "mig_status", - # govt schemes - "gs": "govt_schemes", - # water source - "ws": "water_source", - # source of energy - "soe": "source_of_energy", - # land holding info - "lhi": "land_holding_info", - # agricultural inputs - "ai": "agri_inputs", - # agricultural products - "ap": "agri_products", - # livestock numbers - "ln": "livestock_nos", - # major problems - "mp": "major_problems", - # meta - "meta": "meta" + # family data + "fam_data":"family_data", } def json_encoder(custom_encodings: dict): @@ -74,82 +49,15 @@ def commit_to_db(response_result: dict, form_data: FormData, user_AADHAR: str)-> pymongo.results.InsertManyResult which returns the result of the commit operation. """ db = form_data.static_vars.village_name - cursor = DBQueries.filtered_db_search(db, collection_names['meta'], [], resp_id=form_data.respondent_prof.id_no) + cursor = DBQueries.filtered_db_search(db, collection_names['fam_data'], [], search_idxs={"respondent_prof.id_no":form_data.respondent_prof.id_no}) if db in DBConnection.get_client().list_database_names() and len(list(cursor)) != 0: raise DuplicateEntryException(response_result) - - DBQueries.insert_to_database(form_data.static_vars.village_name, - collection_names['meta'], dict({'resp_id': form_data.respondent_prof.id_no, - 'volunteer_id': user_AADHAR, - 'timestamp': datetime.now()}) - ) - fid = DBQueries.fetch_last(db, collection_names['meta'])['_id'] - - # respondent's profile - data = form_data.respondent_prof.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['rpf'], data) - - # gen_ho_data - data = form_data.gen_ho_info.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['ghi'], data) - - # fam_info - data = form_data.fam_info - data = [fam_mem_info.model_dump() for fam_mem_info in data] - [indiv_info.update({"__id": fid}) for indiv_info in data] - DBQueries.insert_to_database(db, collection_names['fi'], data) - - # migration info - data = form_data.mig_status.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['ms'], data) - - # gov schemes - data = form_data.govt_schemes.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['gs'], data) - - # water source - data = form_data.water_source.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['ws'], data) - - # soucre of E - data = form_data.source_of_energy.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['soe'], data) - - # Land holding info - data = form_data.land_holding_info.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['lhi'], data) - - # agri inputs - data = form_data.agri_inputs.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['ai'], data) - - # agri products - data = form_data.agri_products - data = [agri_prods.model_dump() for agri_prods in data] - [indiv_crop.update({"__id": fid}) for indiv_crop in data] - DBQueries.insert_to_database(db, collection_names['ap'], data) - - # data['__id'] = fid - # DBQueries.insert_to_database(db, collection_names['ap'], data) - - # livestock nums - data = form_data.livestock_nos.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['ln'], data) - - # major probs - data = form_data.major_problems.model_dump() - data['__id'] = fid - DBQueries.insert_to_database(db, collection_names['mp'], data) + + data=form_data.model_dump() + data.update({"volunteer_id": user_AADHAR, "timestamp": datetime.now()}) + data.pop("static_vars") + DBQueries.insert_to_database(db, collection_names['fam_data'], data) response_result['status'] = 'success' response_result['message'][0] = 'authenticated' @@ -166,11 +74,11 @@ def fetch_from_db(response_result: dict, resp_data: str)->dict: A dictionary containing the data fetched from the database. """ db = resp_data - result = DBQueries.retrieve_documents(db) + result = DBQueries.retrieve_documents(db,collection_names["fam_data"]) return result @json_encoder({ObjectId: str}) -def fetch_familydata(response_result: dict, resp_data: str, respondent_id: str)->dict: +def fetch_familydata(response_result: dict, village_name: str, respondent_id: str)->dict: """Wrapper function to fetch family data from the database. Args: response_result (dict): response result to be returned in case of error. @@ -179,23 +87,33 @@ def fetch_familydata(response_result: dict, resp_data: str, respondent_id: str)- Returns: A dictionary containing the data of the family fetched from the database. """ - db = resp_data - result = DBQueries.retrieve_documents_by_id(db, respondent_id, response_result) - return result + db = village_name + doc = [docs for docs in DBQueries.filtered_db_search(db,collection_names["fam_data"],[],search_idxs={"respondent_prof.id_no":respondent_id})] -@json_encoder({ObjectId: str}) -def fetch_individualdata(response_result: dict, db_name: str, respondent_id: str)->Cursor[_DocumentType]: + if len(doc) == 0: + raise InfoNotFoundException(response_result,"family with this respondent id does not exist in the database") + return doc[0] + +def fetch_individualdata(response_result: dict, db_name: str, AADHAR_No: str)->Cursor[_DocumentType]: """Wrapper function to fetch individual data from the database. Args: response_result (dict): response result to be returned in case of error. db_name (str): name of the database. - respondent_id (str): id of the respondent. + AADHAR_No (str): id of the respondent. Returns: Cursor[_DocumentType]: A cursor containing the data of the individual - fetched from the database.""" - result = DBQueries.fetch_indiv_document(db_name, respondent_id, response_result) - return result + fetched from the database. + """ + exclude_fields = field_manager.get_form_fields(FormData, exclude=["fam_info"]) + exclude_fields += ["_id","timestamp","volunteer_id"] + indivdata = [docs for docs in DBQueries.filtered_db_search(db_name,collection_names["fam_data"],exclude_fields,search_idxs={"fam_info.AADHAR_No":AADHAR_No})] + if len(indivdata) == 0: + raise InfoNotFoundException(response_result, "person with this id does not exist in the database") + + fam_members = [doc for doc in indivdata[0]["fam_info"] if doc["AADHAR_No"] == AADHAR_No] + + return fam_members[0] def get_db_conn_flag()->DBConnection: @@ -225,11 +143,10 @@ def get_available_villages(response_result:FrontendResponseModel)->list: list: A list containing the names of the villages in the database. """ response_result['status'] = 'success' - response_result['message'] = ['Authenticated'] return DBQueries.list_database_names() -def create_new_village(dbname,user_creds,response_result:FrontendResponseModel)->None: +def create_new_village(dbname, user_creds, response_result:FrontendResponseModel)->None: """Wrapper function to create a new village in the database. """ village_list=get_available_villages(response_result) @@ -240,15 +157,17 @@ def create_new_village(dbname,user_creds,response_result:FrontendResponseModel)- response_result['message'] = ['Authenticated','Village name added'] response_result["data"]={} -def get_resp_id_on_date(dbname,coll_name,date,response_result:FrontendResponseModel)->list: - """Wrapper function to get the list of users who have filled the form on a given date. +@json_encoder({ObjectId: str}) +def get_resp_data_on_date(dbname, date, response_result:FrontendResponseModel)->list: + """Wrapper function to get the data of users who have filled the form on a given date. """ - start_date=datetime.strptime(f"{date} 00:00:00","%d-%m-%Y %H:%M:%S") - end_date=datetime.strptime(f"{date} 23:59:59","%d-%m-%Y %H:%M:%S") + start_date=datetime.strptime(f"{date} 00:00:00","%Y-%m-%d %H:%M:%S") + end_date=datetime.strptime(f"{date} 23:59:59","%Y-%m-%d %H:%M:%S") + + cursor=DBQueries.filtered_db_search(dbname,collection_names["fam_data"],[], + search_idx={"timestamp":{"$gte":start_date,"$lte":end_date}}) - cursor=DBQueries.filtered_db_search(dbname,coll_name,['_id','__id','timestamp','volunteer_id'], - timestamp={"$gte":start_date,"$lte":end_date}) - resp_data=[docs["resp_id"] for docs in cursor if docs["resp_id"]] + resp_data=[doc for doc in cursor] response_result['status'] = 'success' response_result['message'] = ['Authenticated'] diff --git a/API/services/db/utils/DBFieldManager.py b/API/services/db/utils/DBFieldManager.py new file mode 100644 index 0000000..2150145 --- /dev/null +++ b/API/services/db/utils/DBFieldManager.py @@ -0,0 +1,34 @@ +from API.models import * + +from typing import Any + +class DBFieldManager: + """ + This class is used to manage the fields of the forms. + """ + forms = [FormData] + def __init__(self): + self.form_fields = {cls.__name__:cls.__annotations__.keys() for cls in self.forms} + + def get_form_fields(self, form_name: Any, exclude: list = None, include: list = None): + """ + Get the fields of the form. + + Args: + form_name (Any): name of the form + exclude (list, optional): fields to exclude. Defaults to None. + include (list, optional): fields to include. Defaults to None. + """ + form_name = form_name.__name__ if isinstance(form_name, type) else form_name + if exclude is not None and include is not None: + raise AttributeError("Cannot use both exclude and include together.") + + if exclude is not None: + return [field for field in self.form_fields[form_name] if field not in exclude] + + if include is not None: + return [field for field in self.form_fields[form_name] if field in include] + + return self.form_fields[form_name] + +field_manager = DBFieldManager() \ No newline at end of file diff --git a/API/services/db/utils/DBQueries.py b/API/services/db/utils/DBQueries.py index d977e7a..3ef6245 100644 --- a/API/services/db/utils/DBQueries.py +++ b/API/services/db/utils/DBQueries.py @@ -1,7 +1,7 @@ """ Queries script for the API. It is used to create the queries that are used to interact with the database. """ -from typing import Union, Tuple +from typing import Union, Tuple, List from datetime import datetime import pymongo.cursor @@ -52,27 +52,10 @@ def count_all_documents(cls, db_name:str, coll_name:str)->int: mydb = con[db_name] mycol = mydb[coll_name] return mycol.count_documents({}) + @classmethod - def fetch_last(cls, db_name:str, coll_name:str)->Cursor[_DocumentType]: - """Fetch the last document in the collection. - - Args: - db_name (str): name of the database - coll_name (str): name of the collection - - Returns: - Cursor[_DocumentType]: cursor to the last document in the collection - """ - con = DBConnection.get_client() - - mydb = con[db_name] - mycol = mydb[coll_name] - - return mycol.find().sort('_id', -1)[0] - - @classmethod - def retrieve_documents(cls, db_name:str)->dict: + def retrieve_documents(cls, db_name:str, coll_name:str)->dict: """Retrieve all documents in the collection. Args: db_name (str): name of the database @@ -82,67 +65,10 @@ def retrieve_documents(cls, db_name:str)->dict: """ con = DBConnection.get_client() mydb = con[db_name] - response_data = {} - response_data["data"] = {} - - for cols in mydb.list_collection_names(): - mycol = mydb[cols] - li = [docs for docs in mycol.find({})] - response_data["data"].update({mycol.full_name.split('.')[-1]: li}) - return response_data - - @classmethod - def retrieve__id(cls, db_name:str, respondent_id:str, response_result:dict)->Tuple: - """Retrieve the __id of via respondents_id - Args: - db_name (str): name of the database - respondent_id (str): respondents_id of the family - - Returns: - str: __id of the respondent""" - con = DBConnection.get_client() - mydb = con[db_name] - metacol = mydb['meta'] - respcol=mydb['respondent_prof'] - li = [docs for docs in metacol.find({"resp_id": respondent_id})] - if len(li) == 0: - raise InfoNotFoundException(response_result, - "family with this respondent id does not exist in the database") - - #get respondent_id from the meta collection - resp_id=li[0]['resp_id'] - respli=[docs for docs in respcol.find({"id_no": resp_id})] - #get __id from the respondent_prof collection - try: - return respli[0]['__id'], li[0]['volunteer_id'], li[0]['timestamp'] - except KeyError as e: - return respli[0]['__id'], None, None - - @classmethod - def retrieve_documents_by_id(cls, db_name:str,respondent_id:str, response_result:dict)->dict: - """"Retrieve all documents in the collection by respondent_id. - Args: - db_name (str): name of the database - respondent_id (str): respondent_id of the family - response_result (dict): response result to be returned in case of error. - - Returns: - dict: all documents in the collection by respondent_id - """ - con = DBConnection.get_client() - mydb = con[db_name] - response_data = {} - response_data["data"] = {} - __id, volunteer_id, timestamp = cls.retrieve__id(db_name,respondent_id, response_result) - for cols in mydb.list_collection_names(): - if cols=="meta": - continue - mycol = mydb[cols] - li = [docs for docs in cls.filtered_db_search(db_name,cols,['__id','_id'],__id=__id)] - response_data["data"].update({mycol.full_name.split('.')[-1]: li}) - response_data["data"].update({"filled_by": volunteer_id, "filled_time": timestamp}) - return response_data + mycol = mydb[coll_name] + return {"data":[docs for docs in mycol.find({})]} + @classmethod def filtered_db_search(cls, db_name:str, coll_name:str,fields_to_drop:list ,**kwargs) -> pymongo.cursor.Cursor: @@ -161,25 +87,19 @@ def filtered_db_search(cls, db_name:str, coll_name:str,fields_to_drop:list ,**kw mydb = con[db_name] mycol = mydb[coll_name] - cursor = mycol.find(kwargs,{i:0 for i in fields_to_drop}) - return cursor - - @classmethod - def fetch_indiv_document(cls,db_name:str,respondent_id:str, response_result:dict)->Cursor[_DocumentType]: - """Fetch individual's documents in the collection. - Args: - db_name (str): name of the database - respondent_id (str): respondent_id of the individual + search_idxs = {} + for key, val in kwargs.items(): + if isinstance(val, dict): + search_idxs.update({nested_key:nested_val for nested_key, nested_val in val.items()}) + else: + search_idxs.update({key:val}) + + cursor = mycol.find(search_idxs ,{i:0 for i in fields_to_drop}) - Returns: - :class:Cursor[_DocumentType] individual's documents in the collection - """ - indivdata = [docs for docs in cls.filtered_db_search(db_name,'fam_info',['__id','_id'],AADHAR_No=respondent_id)] - if len(indivdata) == 0: - raise InfoNotFoundException(response_result, "person with this id does not exist in the database") - return indivdata[0] + return cursor + @classmethod def delete_database(cls,db_name:str)->None: """Delete the database. @@ -198,13 +118,13 @@ def list_database_names(cls)->list: list: list of all database names """ return [db_names for db_names in DBConnection.get_client().list_database_names() if - db_names not in ['Auth', 'string']] + db_names not in ['Auth']] @classmethod - def create_db(cls,db_name,user_creds)->None: + def create_db(cls, db_name:str, user_creds:str)->None: """Create a database. Args: dbname (str): name of the database """ - DBQueries.insert_to_database(db_name, coll_name="meta", data={'resp_id': user_creds.AADHAR,'volunteer_id': user_creds.AADHAR,'timestamp': datetime.now()}) + DBQueries.insert_to_database(db_name, coll_name="family_data", data={'resp_id': user_creds.AADHAR,'volunteer_id': user_creds.AADHAR,'timestamp': datetime.now()}) diff --git a/API/services/db/utils/__init__.py b/API/services/db/utils/__init__.py index 4417155..14afd83 100644 --- a/API/services/db/utils/__init__.py +++ b/API/services/db/utils/__init__.py @@ -1 +1,2 @@ -from .DBQueries import * \ No newline at end of file +from .DBQueries import * +from .DBFieldManager import field_manager \ No newline at end of file diff --git a/API/utils/RoleManager.py b/API/utils/RoleManager.py new file mode 100644 index 0000000..f3266c8 --- /dev/null +++ b/API/utils/RoleManager.py @@ -0,0 +1,9 @@ +class RoleManager: + available_roles = ['admin','user','GOVTOff'] + + def __init__(self): + for role in self.available_roles: + if getattr(self,role,None) is None: + self.__setattr__(role, role) + +role_manager = RoleManager() \ No newline at end of file diff --git a/API/utils/__init__.py b/API/utils/__init__.py index e69de29..80a9085 100644 --- a/API/utils/__init__.py +++ b/API/utils/__init__.py @@ -0,0 +1 @@ +from .RoleManager import role_manager \ No newline at end of file diff --git a/API/utils/scopes.py b/API/utils/scopes.py index e75ede3..32b6285 100644 --- a/API/utils/scopes.py +++ b/API/utils/scopes.py @@ -28,6 +28,7 @@ from API.models import UserOut from API.services.db import DBManipulation from API.core.Exceptions import * +from .RoleManager import role_manager def init_checks(**kwargs) -> Callable: @@ -37,7 +38,7 @@ def wrapper_checks(creds: UserOut): raise AuthorizationFailedException(kwargs['response_result'], "not authorized") if 'wrong_endpoint_roles' in kwargs.keys() and creds.role in kwargs['wrong_endpoint_roles']: raise AuthorizationFailedException(kwargs['response_result'], "wrong endpoint") - if creds.role == 'GOVTOff' and "village_name" in kwargs and kwargs['village_name'] \ + if creds.role == role_manager.GOVTOff and "village_name" in kwargs and kwargs['village_name'] \ not in DBManipulation.get_available_villages(kwargs["response_result"]): raise VillageNotFoundException(kwargs['response_result'], "village not found in the DB") return specs(creds) diff --git a/tests/intended_responses/fetch_fam_data.json b/tests/intended_responses/fetch_fam_data.json index 8380924..1cfd097 100644 --- a/tests/intended_responses/fetch_fam_data.json +++ b/tests/intended_responses/fetch_fam_data.json @@ -1,176 +1,31 @@ { "status": "success", - "message": [ - "Authenticated" - ], + "message": ["Authenticated"], "data": { - "gen_ho_info": [ - { - "ho_id": "A1", - "hoh_name": "Dada", - "hoh_gender": "Male", - "category": "OBC", - "pov_status": "BPL", - "own_house": true, - "house_type": "pucca", - "toilet": "Private", - "drainage_status": "open", - "waste_collection_sys": "doorstep", - "compost_pit": "Individual", - "biogas_plant": "Group", - "annual_income": 120000 - } - ], - "agri_inputs": [ - { - "is_chemical_fertilizer_used": [ - true, - 5 - ], - "is_chemical_insecticide_used": [ - false, - 0 - ], - "is_chemical_weedicide_used": [ - false, - 0 - ], - "is_chemical_organic_manures": [ - false, - 0 - ], - "irrigation": "Open", - "irrigation_sys": "Open" - } - ], - "source_of_energy": [ - { - "electricity_conn": true, - "elec_avail_perday_hour": 12, - "lighting": [ - "electricity" - ], - "cooking": [ - "LPG" - ], - "cook_chullah": "Smokeless", - "appliances": [ - { - "appliance_name": "fan", - "appliance_nos": 2, - "appliance_dur": 5 - }, - { - "appliance_name": "bulb", - "appliance_nos": 2, - "appliance_dur": 5 - } - ] - } - ], - "land_holding_info": [ - { - "total_land": 2, - "irrigated_area": 0.5, - "barren_or_wasteland": 0.1, - "cultivable_area": 0.4, - "unirrigated_area": 0.3, - "uncultivable_area": 0.2 - } - ], - "water_source": [ - { - "piped_water": [ - true, - 10 - ], - "hand_pump": [ - true, - 20 - ], - "comm_water": [ - false, - 0 - ], - "open_well": [ - true, - 40 - ], - "mode_of_water_storage": "individual", - "other_water_source": "None" - } - ], - "agri_products": [ - { - "crop_name": "rice", - "crop_area_prev_yr_acre": 0.2, - "productivity_in_quintals_per_acre": 3 - } - ], - "livestock_nos": [ - { - "cows": 2, - "buffalo": 2, - "goats_and_sheeps": 0, - "calves": 1, - "bullocks": 1, - "poultry_and_ducks": 0, - "livestock_shelter": [ - "open" - ], - "avg_daily_milk_prod_litres": 5, - "animal_waste_or_cow_dung_kgs": 1 - } - ], - "major_problems": [ - { - "problems": [ - "None" - ], - "Suggestions_by_villagers": [ - "None" - ] - } - ], - "govt_schemes": [ - { - "PM_jan_dhan_yojana": 2, - "PM_ujjawala_yojana": 3, - "PM_awas_yojana": 2, - "sukanya_samriddhi_yojana": 3, - "mudra_yojana": 0, - "PM_jivan_jyoti_yojana": 0, - "PM_suraksha_bima_yojana": 0, - "atal_pension_yojana": 0, - "fasal_bima_yojana": 0, - "kaushal_vikas_yojana": 0, - "krishi_sinchai_yojana": 0, - "jan_aushadhi_yojana": 0, - "SBM_toilet": 0, - "soil_health_card": 0, - "ladli_lakshmi_yojana": 0, - "janni_suraksha_yojana": 0, - "kisan_credit_card": 0 - } - ], - "respondent_prof": [ - { - "respondents_name": "Hemanth", - "respondents_age": 20, - "relation_w_hoh": "Son", - "respondents_contact": "8479239724", - "id_type": "AC", - "id_no": "test" - } - ], - "mig_status": [ - { - "are_migrants": false, - "num_migrants": 0, - "migration_period_months": 0, - "years_since_migration": 0 - } - ], + "_id": "64e37e96588d2c453b5694e4", + "respondent_prof": { + "respondents_name": "Hemanth", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "test" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, "fam_info": [ { "name": "Mayuresh", @@ -237,7 +92,97 @@ "occupations": "Student" } ], - "filled_by": "5734219582373335", - "filled_time": "2023-02-17T13:16:37.888000" + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T15:11:18.182000" } -} \ No newline at end of file +} diff --git a/tests/intended_responses/respdata.json b/tests/intended_responses/respdata.json new file mode 100644 index 0000000..ecc6b89 --- /dev/null +++ b/tests/intended_responses/respdata.json @@ -0,0 +1,1110 @@ +{ + "status": "success", + "message": ["authorized"], + "data": [ + { + "_id": "64e37e96588d2c453b5694e4", + "respondent_prof": { + "respondents_name": "Hemanth", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "test" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "test_sub", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T15:11:18.182000" + }, + { + "_id": "64e3939ece795f00bc33d41b", + "respondent_prof": { + "respondents_name": "Hemanth", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "8523705708935799" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "2345", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T22:11:02.181000" + }, + { + "_id": "64e3939fce795f00bc33d41c", + "respondent_prof": { + "respondents_name": "Hemanth", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "791228828148196" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "2345", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T22:11:03.209000" + }, + { + "_id": "64e393acce795f00bc33d41d", + "respondent_prof": { + "respondents_name": "Hemanth", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "801283712946576" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "2345", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T22:11:16.924000" + }, + { + "_id": "64e39669680494c663ce5d0e", + "respondent_prof": { + "respondents_name": "string", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "string2" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "2345", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T22:22:57.910000" + }, + { + "_id": "64e396ae680494c663ce5d0f", + "respondent_prof": { + "respondents_name": "string", + "respondents_age": 20, + "relation_w_hoh": "Son", + "respondents_contact": "8479239724", + "id_type": "AC", + "id_no": "string3" + }, + "gen_ho_info": { + "ho_id": "A1", + "hoh_name": "Dada", + "hoh_gender": "Male", + "category": "OBC", + "pov_status": "BPL", + "own_house": true, + "house_type": "pucca", + "toilet": "Private", + "drainage_status": "open", + "waste_collection_sys": "doorstep", + "compost_pit": "Individual", + "biogas_plant": "Group", + "annual_income": 120000 + }, + "fam_info": [ + { + "name": "Mayuresh", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "1234", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Anmol", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "2345", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Hemanth", + "age": 20, + "sex": "Male", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "3456", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + }, + { + "name": "Gargi", + "age": 20, + "sex": "Female", + "marital_status": "U", + "education": "College", + "schooling_status": "3 year", + "AADHAR_No": "4567", + "has_bank_acc": true, + "is_computer_literate": true, + "has_SSP": "no pension", + "health_prob": "None", + "has_MNREGA": true, + "SHG": true, + "occupations": "Student" + } + ], + "mig_status": { + "are_migrants": false, + "num_migrants": 0, + "migration_period_months": 0, + "years_since_migration": 0 + }, + "govt_schemes": { + "PM_jan_dhan_yojana": 2, + "PM_ujjawala_yojana": 3, + "PM_awas_yojana": 2, + "sukanya_samriddhi_yojana": 3, + "mudra_yojana": 0, + "PM_jivan_jyoti_yojana": 0, + "PM_suraksha_bima_yojana": 0, + "atal_pension_yojana": 0, + "fasal_bima_yojana": 0, + "kaushal_vikas_yojana": 0, + "krishi_sinchai_yojana": 0, + "jan_aushadhi_yojana": 0, + "SBM_toilet": 0, + "soil_health_card": 0, + "ladli_lakshmi_yojana": 0, + "janni_suraksha_yojana": 0, + "kisan_credit_card": 0 + }, + "water_source": { + "piped_water": [true, 10], + "hand_pump": [true, 20], + "comm_water": [false, 0], + "open_well": [true, 40], + "mode_of_water_storage": "individual", + "other_water_source": "None" + }, + "source_of_energy": { + "electricity_conn": true, + "elec_avail_perday_hour": 12, + "lighting": ["electricity"], + "cooking": ["LPG"], + "cook_chullah": "Smokeless", + "appliances": [ + { + "appliance_name": "fan", + "appliance_nos": 2, + "appliance_dur": 5 + }, + { + "appliance_name": "bulb", + "appliance_nos": 2, + "appliance_dur": 5 + } + ] + }, + "land_holding_info": { + "total_land": 2, + "irrigated_area": 0.5, + "barren_or_wasteland": 0.1, + "cultivable_area": 0.4, + "unirrigated_area": 0.3, + "uncultivable_area": 0.2 + }, + "agri_inputs": { + "is_chemical_fertilizer_used": [true, 5], + "is_chemical_insecticide_used": [false, 0], + "is_chemical_weedicide_used": [false, 0], + "is_chemical_organic_manures": [false, 0], + "irrigation": "Open", + "irrigation_sys": "Open" + }, + "agri_products": [ + { + "crop_name": "rice", + "crop_area_prev_yr_acre": 0.2, + "productivity_in_quintals_per_acre": 3 + } + ], + "livestock_nos": { + "cows": 2, + "buffalo": 2, + "goats_and_sheeps": 0, + "calves": 1, + "bullocks": 1, + "poultry_and_ducks": 0, + "livestock_shelter": ["open"], + "avg_daily_milk_prod_litres": 5, + "animal_waste_or_cow_dung_kgs": 1 + }, + "major_problems": { + "problems": ["None"], + "Suggestions_by_villagers": ["None"] + }, + "volunteer_id": "5734219582373335", + "timestamp": "2023-08-21T22:24:06.170000" + } + ] +} diff --git a/tests/intended_responses/respid_data.json b/tests/intended_responses/respid_data.json deleted file mode 100644 index 658648e..0000000 --- a/tests/intended_responses/respid_data.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "user_ids": [ - "123412341234", - "012345678999", - "121212121212", - "121212121212", - "123412341235", - "123456789101", - "VIV1234567", - "102192837465", - "ZAS12345", - "111111115", - "111111116", - "111111117", - "111111118", - "111111119", - "873912790318", - "448003990988988", - "516329145259208", - "327247887001101", - "645574464113240" - ] -} \ No newline at end of file diff --git a/tests/test_delete_database.py b/tests/test_delete_database.py index 6c4eff1..aeca320 100644 --- a/tests/test_delete_database.py +++ b/tests/test_delete_database.py @@ -15,7 +15,7 @@ class MyDeleteDatabaseTest(unittest.TestCase): params={"dbname":"test_db"} DEL_VILLAGE_NAME=BASE_URL+"/ops/delete_database" - GET_VILLAGE_LIST=BASE_URL+"/ops/get_village_list" + GET_VILLAGE_LIST=BASE_URL+"/api/get_village_list" PUT_URL=BASE_URL+'/ops/update_village_list' def test_delete_database_user(self): diff --git a/tests/test_get_resp_id.py b/tests/test_get_resp_id_data.py similarity index 80% rename from tests/test_get_resp_id.py rename to tests/test_get_resp_id_data.py index 06517f6..fcc947f 100644 --- a/tests/test_get_resp_id.py +++ b/tests/test_get_resp_id_data.py @@ -5,35 +5,35 @@ from login_utils import get_access_token, BASE_URL class MyGetRespIDTestCase(unittest.TestCase): - url=BASE_URL+"/api/get_respid_list" + url=BASE_URL+"/api/get_respdata_list" - with open("tests/intended_responses/respid_data.json","r") as f: + with open("tests/intended_responses/respdata.json","r") as f: data=json.load(f) - def test_get_respid_owner_valid_village(self): + def test_get_respdata_owner_valid_village(self): signincred = { "AADHAR_NO": f"{os.environ['ADMIN_ID']}", "password": f"{os.environ['ADMIN_PWD']}", "village_name": f"{os.environ['ADMIN_VILLAGE_NAME']}", "role": f"{os.environ['OWNER_ROLE']}" } - params={"date":"27-02-2023","village_name":"Sehore"} + params={"date":"2023-08-21","village_name":"Sehore"} headers={ "accept":"application/json", "Authorization": f"Bearer {get_access_token(signincred)}", "Content-Type": "application/json", } response=requests.get(url=self.url,params=params,headers=headers) - self.assertEqual(response.json()["data"],self.data) + self.assertEqual(response.json(),self.data) - def test_get_respid_owner_invalid_village(self): + def test_get_respdata_owner_invalid_village(self): signincred = { "AADHAR_NO": f"{os.environ['ADMIN_ID']}", "password": f"{os.environ['ADMIN_PWD']}", "village_name": f"{os.environ['ADMIN_VILLAGE_NAME']}", "role": f"{os.environ['OWNER_ROLE']}" } - params={"date":"27-02-2023","village_name":"villageDoesNotExist"} + params={"date":"2023-08-21","village_name":"villageDoesNotExist"} headers={ "accept":"application/json", "Authorization": f"Bearer {get_access_token(signincred)}", @@ -42,7 +42,7 @@ def test_get_respid_owner_invalid_village(self): response=requests.get(url=self.url,params=params,headers=headers) self.assertEqual(response.status_code,400) - def test_get_respid_admin(self): + def test_get_respdata_admin(self): signincred = { "AADHAR_NO": f"{os.environ['ADMIN_ID']}", "password": f"{os.environ['ADMIN_PWD']}", @@ -50,16 +50,16 @@ def test_get_respid_admin(self): "role": f"{os.environ['ADMIN_ROLE']}" } - params={"date":"27-02-2023","village_name":"None"} + params={"date":"2023-08-21","village_name":"None"} headers = { "accept": "application/json", "Authorization": f"Bearer {get_access_token(signincred)}", "Content-Type": "application/json", } response=requests.get(url=self.url,params=params,headers=headers) - self.assertEqual(response.json()["data"],self.data) + self.assertEqual(response.json(),self.data) - def test_get_respid_user(self): + def test_get_respdata_user(self): signincred = { "AADHAR_NO": f"{os.environ['ADMIN_ID']}", "password": f"{os.environ['ADMIN_PWD']}", diff --git a/tests/test_update_village_list.py b/tests/test_update_village_list.py index f15bfb2..b84b546 100644 --- a/tests/test_update_village_list.py +++ b/tests/test_update_village_list.py @@ -14,7 +14,7 @@ class MyUpdateVillageListTest(unittest.TestCase): params={"dbname":"test_db"} - GET_VILLAGE_LIST=BASE_URL+"/ops/get_village_list" + GET_VILLAGE_LIST=BASE_URL+"/api/get_village_list" DEL_VILLAGE_NAME=BASE_URL+"/ops/delete_database" PUT_URL=BASE_URL+'/ops/update_village_list'