Beispiel #1
0
def listPrograms(request):
    try:
        token = request.headers.get('accessToken')
        user = getUserByAccessToken(token)
        programs = getPrograms(user)
        return successResponse(message="programs fetched successfully",
                               body=transformProgramList(programs))
    except Exception as ex:
        return internalServerErrorResponse(
            errorCode=ErrorCodes.GET_PROGRAM_LIST_FAILED,
            message="failed to fetch list of programs",
            data={})
Beispiel #2
0
def totalbudgetandbeneficary(request):
    token = request.headers.get('accessToken')
    user = getUserByAccessToken(token)
    if user is None:
        return unAuthenticatedResponse(
            ErrorCodes.UNAUTHENTICATED_REQUEST,
            message=getUnauthenticatedErrorPacket(userId=0))
    userId = user.id
    totalbudget, totalbeneficaries = totalamount(userId)
    if totalamount and totalbeneficaries is None:
        return resourceNotFoundResponse(
            ErrorCodes.PROGRAM_DOES_NOT_EXIST,
            message=getFormDoesNotExistErrorPacket(userId=user.id))
    return successResponse(message="Total budget and beneficaries",
                           body=transformtotalbudgetandbeneficary(
                               totalbudget, totalbeneficaries))
Beispiel #3
0
def deleteProgram(request, programId):
    token = request.headers.get('accessToken')
    user = getUserByAccessToken(token)
    if user is None:
        return unAuthenticatedResponse(
            ErrorCodes.UNAUTHENTICATED_REQUEST,
            message=getUnauthenticatedErrorPacket(userId=0))
    # Getting the program to be deleted
    programToDelete = getProgramById(programId)
    # deleting program from the database
    if programToDelete != None:
        status, deletedform = deleteprogram(programToDelete)
        if status is False:
            return internalServerErrorResponse(
                ErrorCodes.FORM_DELETION_FAILED,
                message="Something Went Wrong, Couldn't Delete Program")
        # return success
        return successResponse(message="Successfully deleted Form", body={})
    return resourceNotFoundResponse(
        ErrorCodes.PROGRAM_DOES_NOT_EXIST,
        message=getFormDoesNotExistErrorPacket(userId=user.id))
Beispiel #4
0
def createProgram(request):
    try:
        body = request.POST
        image = request.FILES['image'] if 'image' in request.FILES else False
        token = request.headers.get('accessToken')
        user = getUserByAccessToken(token)
        if image == False:
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=f"please provide a valid image file")
        # check if all required fields are present in request payload
        missingKeys = validateKeys(payload=body,
                                   requiredKeys=[
                                       'name', 'description', 'code',
                                       "locations", "sdgs", "budget",
                                       "totalNumberOfBeneficiaries",
                                       "activeMarker"
                                   ])
        if missingKeys:
            return badRequestResponse(
                errorCode=ErrorCodes.MISSING_FIELDS,
                message=
                f"The following key(s) are missing in the request payload: {missingKeys}"
            )

        if not validateThatListIsEmpty(body['locations']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=f"Program must contain a list of locations")

        if not validateThatListIsEmpty(body['sdgs']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=f"Program must contain a list of sdgs and indicators")
        is_program_exist = getProgramByDetail(body['name'],
                                              body['description'],
                                              body['code'], user)
        if is_program_exist.exists():
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=f"Program already exists")
        # validation for sdg
        for sdg in json.loads(body['sdgs']):
            missingSdgkey = validateKeys(payload=sdg,
                                         requiredKeys=['id', 'indicators'])
            if missingSdgkey:
                return badRequestResponse(
                    ErrorCodes.MISSING_FIELDS,
                    message=
                    f"The following key(s) are missing in the request locations array payload: {missingSdgkey}"
                )
            # check that sdg exist
            sdg_id = sdg['id']
            sdg_exist = getSdgById(sdg_id)
            if sdg_exist is None:
                return badRequestResponse(
                    ErrorCodes.GENERIC_INVALID_PARAMETERS,
                    message=f"sgd {sdg_id} does not exist")
            # check that indicator exist
            sdg_indicators = sdg['indicators']
            for sdg_indicator in sdg_indicators:
                sdg_inidcator_exist = getIndicator(sdg_indicator)
                if sdg_inidcator_exist is None:
                    return badRequestResponse(
                        ErrorCodes.GENERIC_INVALID_PARAMETERS,
                        message=
                        f"selected sdg indicator {sdg_indicator} does not exist"
                    )

        token = request.headers.get('accessToken')
        user = getUserByAccessToken(token)
        if user is None:
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=f"User does not exist")

        if not validateThatStringIsEmptyAndClean(body['name']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=
                f"Program name can neither contain special characters nor be empty"
            )
        if not validateThatStringIsEmpty(body['description']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=
                f"Program description can neither contain special characters nor be empty",
                body={})
        if not validateThatStringIsEmptyAndClean(body['code']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=
                f"Program code can neither contain special characters nor be empty"
            )
        if not validateThatStringIsEmptyAndClean(body['budget']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=
                f"budget can neither contain special characters nor be empty")
        if not validateThatStringIsEmptyAndClean(
                body['totalNumberOfBeneficiaries']):
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=
                f"Beneficiaries can neither contain special characters nor be empty"
            )

        # load the fields from Json
        name = body['name']
        description = body['description']
        code = body['code']
        locations = json.loads(body['locations'])
        sdgs = json.loads(body['sdgs'])
        budget = body['budget']
        totalNumberOfBeneficiaries = body['totalNumberOfBeneficiaries']
        activeMarker = json.loads(body['activeMarker'])
        validate_image = validateImage(image.name)
        if validate_image is not None:
            return badRequestResponse(
                errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
                message=validate_image)

        image_link = upload_file(image, image.name)

        program = CreateProgramRecord(name, image_link, description, code,
                                      locations, sdgs, user, budget,
                                      totalNumberOfBeneficiaries, activeMarker)
        programFormList = None

        if program is None:
            return internalServerErrorResponse(
                errorCode=ErrorCodes.PROGRAM_CREATION_FAILED,
                message=f"Program failed to create")
        else:
            return successResponse(message="successfully created program",
                                   body=transformProgram(
                                       program, program.location_set.all(),
                                       program.program_sdg_set.all(),
                                       programFormList))

    except AttributeError as ex:
        return internalServerErrorResponse(errorCode=ErrorCodes.MISSING_FIELDS,
                                           message=f"missing attributes")
    except Exception as ex:
        # Log Exception
        return internalServerErrorResponse(
            errorCode=ErrorCodes.PROGRAM_CREATION_FAILED,
            message=f"program failed to create")
Beispiel #5
0
def updateProgram(request, programId):
    token = request.headers.get('accessToken')
    user = getUserByAccessToken(token)
    if user is None:
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=f"User does not exist")
    programToUpdate = getProgramById(programId)
    if programToUpdate is None:
        return resourceNotFoundResponse(ErrorCodes.GENERIC_INVALID_PARAMETERS,
                                        message="Program does not exist ")
    body = request.POST
    image = request.FILES['image'] if 'image' in request.FILES else False
    if image == False:
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=f"please provide a valid image file")

    # check if all required fields are present in request payload
    missingKeys = validateKeys(payload=body,
                               requiredKeys=[
                                   'name', 'description', 'code', "locations",
                                   "sdgs", "budget",
                                   "totalNumberOfBeneficiaries", "activeMarker"
                               ])
    if missingKeys:
        return badRequestResponse(
            errorCode=ErrorCodes.MISSING_FIELDS,
            message=
            f"The following key(s) are missing in the request payload: {missingKeys}"
        )

    if not validateThatListIsEmpty(body['locations']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=f"Program must contain a list of locations")
    if not validateThatListIsEmpty(body['sdgs']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=f"Program must contain a list of sdgs and indicators")
    # validation for sdg
    for sdg in json.loads(body['sdgs']):
        missingSdgkey = validateKeys(payload=sdg,
                                     requiredKeys=['id', 'indicators'])
        if missingSdgkey:
            return badRequestResponse(
                ErrorCodes.MISSING_FIELDS,
                message=
                f"The following key(s) are missing in the request locations array payload: {missingSdgkey}"
            )

        # check that sdg exist
        sdg_id = sdg['id']
        sdg_exist = getSdgById(sdg_id)
        if sdg_exist is None:
            return badRequestResponse(ErrorCodes.GENERIC_INVALID_PARAMETERS,
                                      message=f"sgd {sdg_id} does not exist")
        # check that sdg indicator exist
        sdg_indicators = sdg['indicators']
        for sdg_indicator in sdg_indicators:
            sdg_inidcator_exist = getIndicator(sdg_indicator)
            if sdg_inidcator_exist is None:
                return badRequestResponse(
                    ErrorCodes.GENERIC_INVALID_PARAMETERS,
                    message=
                    f"selected sdg indicator {sdg_indicator} does not exist")
    if not validateThatStringIsEmptyAndClean(body['name']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=
            f"Program name can neither contain special characters nor be empty"
        )
    if not validateThatStringIsEmpty(body['description']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=
            f"Program description can neither contain special characters nor be empty",
            body={})
    if not validateThatStringIsEmptyAndClean(body['code']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=
            f"Program code can neither contain special characters nor be empty"
        )
    if not validateThatStringIsEmptyAndClean(body['budget']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=
            f"budget can neither contain special characters nor be empty")
    if not validateThatStringIsEmptyAndClean(
            body['totalNumberOfBeneficiaries']):
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=
            f"Beneficiaries can neither contain special characters nor be empty"
        )

    name = body['name']
    description = body['description']
    code = body['code']
    locations = json.loads(body['locations'])
    sdgs = json.loads(body['sdgs'])
    budget = body['budget']
    totalNumberOfBeneficiaries = body['totalNumberOfBeneficiaries']
    activeMarker = json.loads(body['activeMarker'])
    validate_image = validateImage(image.name)
    if validate_image is not None:
        return badRequestResponse(
            errorCode=ErrorCodes.GENERIC_INVALID_PARAMETERS,
            message=validate_image)
    image_link = upload_file(image, image.name)
    updatedProgram = updatedProgramRecord(programToUpdate, name, description,
                                          image_link, code, locations, sdgs,
                                          user, budget,
                                          totalNumberOfBeneficiaries,
                                          activeMarker)
    if updatedProgram.form_program_set.all() is not None:
        updatedFormlist = updatedProgram.form_program_set.all()
    else:
        updatedFormlist = None
    # raise an error response if update wasn't successful
    if updatedProgram == None:
        return internalServerErrorResponse(
            ErrorCodes.PROGRAM_UPDATE_FAILED,
            message="Program update was unsuccessful")

    return successResponse(message="successfully updated program",
                           body=transformProgram(
                               updatedProgram,
                               updatedProgram.location_set.all(),
                               updatedProgram.program_sdg_set.all(),
                               updatedFormlist))