Exemple #1
0
    def post(self):
        validations = [{
            'language': {
                'key': 'language',
                'validator': value_exists,
                'response': Error,
                'error': 'Language selection cannot be blank.',
            },
            'about_text': {
                'key': 'aboutText',
                'validator': value_exists,
                'response': Error,
                'error': 'Survey about text cannot be blank.',
            },
            'terms_of_service': {
                'key': 'termsOfService',
                'validator': value_exists,
                'response': Error,
                'error': 'Survey terms of service name cannot be blank.',
            }
        }]
        validated = validate_json(validations, self.headers,
                                  self.resource_type)
        survey = database.survey.get(current_identity.survey_id)
        database.survey.update(survey,
                               settings=validated,
                               questions=request.json['questions'])

        return Success(status_code=201,
                       headers=self.headers,
                       resource_type=self.resource_type,
                       body=request.json)
Exemple #2
0
def patch_a_party(party_id):
    user_input = request.get_json()
    data = validate_json(request.get_json())
    name = validate_empty_string(user_input.get("name"))
    valid_keys = [data, name]
    for key in valid_keys:
        if not key:
            response = custom_response(
                400, f"Invalid Input! check on data you are trying to submit")
            return response
    party_patched = Party.patch_a_party(party_id, user_input.get("name"))
    if party_patched is not False:
        return jsonify({
            "status":
            200,
            "data": [{
                "id": party_patched["id"],
                "name": party_patched["name"]
            }]
        })
    return jsonify({
        "status": 404,
        "data": [{
            "message": "Party does not exists"
        }]
    }), 404
    def post(self):
        validations = [{
            'admin_email': {
                'key': 'email',
                'validator': value_exists,
                'response': Error,
                'error': 'Email cannot be blank.',
            },
            'admin_password': {
                'key': 'password',
                'validator': value_exists,
                'response': Error,
                'error': 'Password cannot be blank.',
            },
            'survey_name': {
                'key': 'surveyName',
                'validator': value_exists,
                'response': Error,
                'error': 'Survey name cannot be blank.',
            },
            'signup_code': {
                'key': 'signupCode',
                'validator': database.survey.register.use_token,
                'response': Error,
                'error': 'Survey sign-up token is invalid.',
            }
        }]

        validated = validate_json(validations, self.headers,
                                  self.resource_type)

        errors = []
        survey = database.survey.register.create(
            survey_name=validated['survey_name'])
        if survey:
            admin_role = database.web_user.create_admin(
                survey=survey,
                email=validated['admin_email'],
                password=validated['admin_password'])
            reseacher_token = database.web_user.create_invite_researcher_token(
                survey)
        else:
            errors.append('Survey already exists.')

        if not errors:
            if not admin_role:
                errors.append('Admin user could not be created.')
            if not reseacher_token:
                errors.append(
                    'Initial invite reseacher token could not be created.')

        if errors:
            return Error(status_code=400,
                         headers=self.headers,
                         resource_type=self.resource_type,
                         errors=errors)
        return Success(status_code=201,
                       headers=self.headers,
                       resource_type=self.resource_type,
                       body=make_keys_camelcase(validated))
Exemple #4
0
def create_party():
    user_input = request.get_json()
    data = validate_json(request.get_json())
    _id = validate_id(user_input.get("id"))
    name = validate_empty_string(user_input.get("name"))
    hqAddress = validate_empty_string(user_input.get("hqAddress"))
    logoUrl = validate_empty_string(user_input.get("logoUrl"))
    exists = Party.party_does_not_exists(user_input.get("id"))
    valid_keys = [data, _id, name, logoUrl, hqAddress, exists]
    for key in valid_keys:
        if not key:
            response = custom_response(
                400, f"Invalid Input! check on data you are trying to submit")
            return response
    new_party = Party.save_party(user_input.get("id"), user_input.get("name"),
                                 user_input.get("hqAddress"),
                                 user_input.get("logoUrl"))
    return jsonify({
        "status": 201,
        "data": [{
            "id": new_party["id"],
            "name": new_party["name"]
        }]
    })
Exemple #5
0
def create_office():
    user_input = request.get_json()
    data = validate_json(request.get_json())
    _id = validate_id(user_input.get("id"))
    name = validate_empty_string(user_input.get("name"))
    _type = validate_empty_string(user_input.get("type"))
    exists = Office.office_does_not_exists(user_input.get("id"))
    valid_keys = [data, _id, name, _type, exists]
    for key in valid_keys:
        if not key:
            response = custom_response(
                400, f"Invalid Input! check on data you are trying to submit")
            return response
    new_office = Office.save_office(user_input.get("id"),
                                    user_input.get("name"),
                                    user_input.get("type"))
    return jsonify({
        "status":
        201,
        "data": [{
            "id": new_office["id"],
            "name": new_office["name"]
        }]
    })
Exemple #6
0
    def post(self):
        validations = [{
            'about_text': {
                'key': 'aboutText',
                'validator': None,
            },
            'terms_of_service': {
                'key': 'termsOfService',
                'validator': None
            },
            'contact_email': {
                'key': 'contactEmail',
                'validator': value_exists,
                'response': Error,
                'error': 'A contact email address must be specified.'
            },
            'survey_max_days': {
                'key': 'surveyMaxDays',
                'validator': value_exists,
                'response': Error,
                'error':
                'A maximum number of survey prompt days must be entered.',
            },
            'survey_max_prompts': {
                'key': 'surveyMaxPrompts',
                'validator': value_exists,
                'response': Error,
                'error': 'A maximum number of survey prompts must be entered.',
            },
            'gps_accuracy_meters': {
                'key':
                'gpsAccuracyThresholdMeters',
                'validator':
                value_exists,
                'response':
                Error,
                'error':
                'A minimum GPS accuracy threshold must be specified. (Higher threshold is lower accuracy)'
            },
            'tripbreaker_interval_seconds': {
                'key': 'tripbreakerIntervalSeconds',
                'validator': value_exists,
                'response': Error,
                'error': 'Trip breaking interval must be provided.'
            },
            'tripbreaker_cold_start_meters': {
                'key': 'tripbreakerColdStartDistanceMeters',
                'validator': value_exists,
                'response': Error,
                'error': 'Trip breaking cold start distance must be provided.'
            },
            'tripbreaker_subway_buffer_meters': {
                'key': 'tripbreakerSubwayBufferMeters',
                'validator': value_exists,
                'response': Error,
                'error': 'Trip breaking subway buffer must be provided.'
            }
        }]
        validated = validate_json(validations, self.headers,
                                  self.resource_type)
        survey = database.survey.get(current_identity.survey_id)
        survey.about_text = validated['about_text']
        survey.terms_of_service = validated['terms_of_service']
        survey.contact_email = validated['contact_email']
        survey.max_survey_days = validated['survey_max_days']
        survey.max_prompts = validated['survey_max_prompts']
        survey.gps_accuracy_threshold = validated['gps_accuracy_meters']
        survey.trip_break_interval = validated['tripbreaker_interval_seconds']
        survey.trip_break_cold_start_distance = validated[
            'tripbreaker_cold_start_meters']
        survey.trip_subway_buffer = validated[
            'tripbreaker_subway_buffer_meters']
        db.session.commit()

        return Success(status_code=201,
                       headers=self.headers,
                       resource_type=self.resource_type,
                       body=make_keys_camelcase(validated))
Exemple #7
0
    def post(self):
        validations = [{
            'uuid': {
                'key': 'uuid',
                'validator': value_exists,
                'response': Error,
                'error': 'UUID must be supplied. No action taken.'
            },
            'survey_answers': {
                'key': 'survey',
                'validator': None
            },
            'coordinates': {
                'key': 'coordinates',
                'validator': None
            },
            'prompts_answers': {
                'key': 'prompts',
                'validator': None
            },
            'cancelled_prompts': {
                'key': 'cancelledPrompts',
                'validator': None
            }
        }]
        validated = validate_json(validations, self.headers,
                                  self.resource_type)
        user = database.user.find_by_uuid(validated['uuid'])

        if user:
            survey_answers, coordinates, prompts_answers, cancelled_prompts = None, None, None, None
            response = {
                'survey': 'No new survey data supplied.',
                'coordinates': 'No new coordinates data supplied.',
                'prompts': 'No new prompt answers supplied.',
                'cancelledPrompts': 'No cancelled prompts supplied.'
            }
            if validated['survey_answers']:
                survey_answers = database.survey.upsert(
                    user=user, answers=validated['survey_answers'])
                if survey_answers:
                    response[
                        'survey'] = 'Survey answer for {} upserted.'.format(
                            user.uuid)
            if validated['coordinates']:
                coordinates = rename_json_keys(validated['coordinates'],
                                               camelcase_to_underscore)
                coordinates = database.coordinates.insert(
                    user=user, coordinates=coordinates)
                if coordinates:
                    response['coordinates'] = (
                        'New coordinates for {} inserted.'.format(user.uuid))

            # upsert prompts answers and remove any existing conflicting cancelled prompt responses
            if validated['prompts_answers']:
                formatted_prompts = rename_json_keys(
                    validated['prompts_answers'], camelcase_to_underscore)
                error = self._fail_on_deprecated_prompts(formatted_prompts)
                if error:
                    return error
                prompts_answers = database.prompts.upsert(
                    user=user, prompts=formatted_prompts)
                prompts_uuids = {p.prompt_uuid for p in prompts_answers}
                database.cancelled_prompts.delete(prompts_uuids)

                if prompts_answers:
                    response['prompts'] = (
                        'New prompt answers for {} inserted.'.format(
                            user.uuid))

            # filter cancelled prompts which conflict with a provided response by uuid and insert cancelled prompts
            if validated['cancelled_prompts']:
                formatted_cancelled_prompts = rename_json_keys(
                    validated['cancelled_prompts'], camelcase_to_underscore)

                # fail gracefully on older version of mobile app that do not provide a prompt uuid
                error = self._fail_on_deprecated_prompts(
                    formatted_cancelled_prompts)
                if error:
                    return error

                if validated['prompts_answers']:
                    answers_uuids = {
                        p['uuid']
                        for p in validated['prompts_answers']
                    }
                    filtered_cancelled_prompts = []
                    for c in formatted_cancelled_prompts:
                        if c['uuid'] not in answers_uuids:
                            filtered_cancelled_prompts.append(c)
                else:
                    filtered_cancelled_prompts = formatted_cancelled_prompts
                cancelled_prompts = database.cancelled_prompts.insert(
                    user=user, cancelled_prompts=filtered_cancelled_prompts)
                if cancelled_prompts:
                    response['cancelledPrompts'] = (
                        'New cancelled prompts for {} inserted.'.format(
                            user.uuid))

            status = None
            if any([
                    survey_answers, coordinates, prompts_answers,
                    cancelled_prompts
            ]):
                database.commit()
                status = 201
            else:
                status = 200

            # add in deprecation warning for v1 api
            return Success(
                status_code=status,
                headers=self.headers,
                resource_type=self.resource_type,
                status=
                'Warning (deprecated): API v1 will soon be phased out. Please refer to documentation for v2 calls.',
                body=response)

        return Error(
            status_code=410,
            headers=self.headers,
            resource_type=self.resource_type,
            errors=['Could not find survey for {}.'.format(validated['uuid'])])
    def post(self):
        validations = [{
            'email': {
                'key': 'email',
                'validator': value_exists,
                'response': Error,
                'error': 'Email cannot be blank.',
            },
            'password': {
                'key': 'password',
                'validator': value_exists,
                'response': Error,
                'error': 'Password cannot be blank.',
            },
            'survey_name': {
                'key': 'surveyName',
                'validator': value_exists,
                'response': Error,
                'error': 'Survey name cannot be blank.',
            }
        }]
        validated = validate_json(validations, self.headers,
                                  self.resource_type)
        survey = database.survey.find_by_name(validated['survey_name'])

        # create a researcher user if a signup token is provided
        researcherToken = request.json.get('registrationToken', '').strip()
        if researcherToken:
            user = database.web_user.create_researcher(
                survey=survey,
                email=validated['email'],
                password=validated['password'],
                token=researcherToken)

            if user is False:
                return Error(status_code=400,
                             headers=self.headers,
                             resource_type=self.resource_type,
                             errors=['Web user already exists for email.'])
            elif user is None:
                return Error(status_code=403,
                             headers=self.headers,
                             resource_type=self.resource_type,
                             errors=['Researcher user could not be created.'])

        else:
            mobile_user = database.mobile_user.find_by_email(
                email=validated['email'])
            if not mobile_user:
                return Error(
                    status_code=404,
                    headers=self.headers,
                    resource_type=self.resource_type,
                    errors=[
                        'Participant email not found in any survey response.'
                    ])
            else:
                user = database.web_user.create_participant(
                    survey,
                    email=validated['email'],
                    password=validated['password'],
                    uuid=mobile_user.uuid)
                if user is False:
                    return Error(
                        status_code=400,
                        headers=self.headers,
                        resource_type=self.resource_type,
                        errors=['Participant user could not be created.'])
        return Success(status_code=201,
                       headers=self.headers,
                       resource_type=self.resource_type,
                       body=make_keys_camelcase(validated))
Exemple #9
0
    def post(self):
        validations = [{
            'uuid': {
                'key': 'uuid',
                'validator': value_exists,
                'response': Error,
                'error': 'UUID must be supplied. No action taken.'
            },
            'survey_answers': {
                'key': 'survey',
                'validator': None
            },
            'coordinates': {
                'key': 'coordinates',
                'validator': None
            },
            'prompts_answers': {
                'key': 'prompts',
                'validator': None
            },
            'cancelled_prompts': {
                'key': 'cancelledPrompts',
                'validator': None
            }
        }]
        validated = validate_json(validations, self.headers, self.resource_type)
        user = database.user.find_by_uuid(validated['uuid'])

        if user:
            survey_answers, coordinates, prompts_answers, cancelled_prompts = None, None, None, None
            response = {
                'survey': 'No new survey data supplied.',
                'coordinates': 'No new coordinates data supplied.',
                'prompts': 'No new prompt answers supplied.',
                'cancelledPrompts': 'No cancelled prompts supplied.'
            }
            if validated['survey_answers']:
                survey_answers = database.survey.upsert(user=user,
                                                        answers=validated['survey_answers'])
                if survey_answers:
                    response['survey'] = 'Survey answer for {} upserted.'.format(user.uuid)
            if validated['coordinates']:
                coordinates = database.coordinates.insert(user=user,
                                                          coordinates=validated['coordinates'])
                if coordinates:
                    response['coordinates'] = (
                        'New coordinates for {} inserted.'.format(user.uuid))
            
            # upsert prompts answers and remove any existing conflicting cancelled prompt responses
            if validated['prompts_answers']:
                prompts_answers = database.prompts.upsert(user=user,
                                                          prompts=validated['prompts_answers'])
                prompts_uuids = [p.prompt_uuid for p in prompts_answers]
                database.cancelled_prompts.delete(prompts_uuids)

                if prompts_answers:
                    response['prompts'] = (
                        'New prompt answers for {} inserted.'.format(user.uuid))

            # filter cancelled prompts which conflict with a provided response by uuid and insert cancelled prompts
            if validated['cancelled_prompts']:
                if validated['prompts_answers']:
                    answers_uuids = {p['uuid'] for p in validated['prompts_answers']}
                    filtered_cancelled_prompts = []
                    for c in validated['cancelled_prompts']:
                        if c['uuid'] not in answers_uuids:
                            filtered_cancelled_prompts.append(c)
                else:
                    filtered_cancelled_prompts = validated['cancelled_prompts']
                cancelled_prompts = database.cancelled_prompts.insert(user=user,
                                                                      cancelled_prompts=filtered_cancelled_prompts)
                if cancelled_prompts:
                    response['cancelledPrompts'] = (
                        'New cancelled prompts for {} inserted.'.format(user.uuid))

            status = None
            if any([survey_answers, coordinates, prompts_answers, cancelled_prompts]):
                database.commit()
                status = 201
            else:
                status = 200

            return Success(status_code=status,
                           headers=self.headers,
                           resource_type=self.resource_type,
                           body=response)

        return Error(status_code=400,
                     headers=self.headers,
                     resource_type=self.resource_type,
                     errors=['Could not find survey for {}.'.format(validated['uuid'])])