Esempio n. 1
0
def test_user_with_existing_email_is_not_inserted():
    SurveyResponse.create(name="Rosa",
                          email="*****@*****.**",
                          age=62,
                          about_me="I love birds")
    with pytest.raises(IntegrityError):
        SurveyResponse.create(name="Joan",
                              email="*****@*****.**",
                              age=63,
                              about_me="I love gardening, too!!!")
Esempio n. 2
0
def test_create_user_with_all_fields_successful():
    return SurveyResponse.create(name="James",
                                 email="*****@*****.**",
                                 age=35,
                                 about_me="developer",
                                 address="123 Big Street, Waunakee, WI, USA",
                                 gender="male",
                                 favorite_book="War & Peace",
                                 favorite_colors="red,blue,green")
Esempio n. 3
0
def get_response(id):
    """Fetches the SurveyResponse for the specified ID

    Args:
        id (int): Primary key of the SurveyResponse to be returned

    Returns:
        dict
    """

    resp = SurveyResponse.get(SurveyResponse.id == id)
    return _convert_response_to_dict(resp)
Esempio n. 4
0
def get_all_responses():
    """Fetches all SurveyResponses

    Returns:
        dict
    """

    responses = []

    for resp in SurveyResponse.select():
        responses.append(_convert_response_to_dict(resp))

    return responses
Esempio n. 5
0
def create_response(data):
    """Creates a new SurveyResponse

    Args:
        data (dict): Values to be inserted into new SurveyResponse instance

    Returns:
        int: Primary key (id) of the newly inserted SurveyResponse
    """

    name = data["name"]
    email = data["email"]

    resp = SurveyResponse.create(name=name, email=email)
    return resp.id
Esempio n. 6
0
def finish(id):
    """Mark a SurveyResponse as finished

    Args:
        id (int): primary key of the surveyresponse to be returned
    """

    resp = SurveyResponse.get(SurveyResponse.id == id)
    error_msg = "Response ID {0} is missing field {1}; can't mark as finished"

    # If we are missing any mandatory fields, we can't finish out the response
    for field_name in ("name", "email", "age", "about_me"):
        field = getattr(resp, field_name, None)
        if field is None:
            raise RuntimeError(error_msg.format(resp.id, field_name))

    resp.finished = True
    resp.save()
Esempio n. 7
0
def update_response(id, data):
    """Updates an existing SurveyResponse

    Args:
        id (int): Primary key of the SurveyResponse to be returned
        data (dict): Values to be inserted into new SurveyResponse instance
    """

    resp = SurveyResponse.get(SurveyResponse.id == id)

    for field in SurveyResponse._meta.sorted_field_names:
        if field in data and field != "finished":
            setattr(resp, field, data[field])

    resp.save()

    if "finished" in data:
        finish(id)
Esempio n. 8
0
def test_create_user_with_minimum_model_fields_successful():
    SurveyResponse.create(name="Pedro", email="*****@*****.**")
Esempio n. 9
0
def test_create_user_with_minimum_required_fields_successful():
    SurveyResponse.create(name="Nancy",
                          email="*****@*****.**",
                          age=62,
                          about_me="I love gardening!!!")
Esempio n. 10
0
def receive_sms(request):
    try:
        f = open("log.log", "a+")
        data_to_log = request.POST
        data_to_log['date_time'] = str(datetime.datetime.now())
        f.write("{}\n".format(json.dumps(data_to_log)))
        f.close()
    except Exception as e:
        f = open("log.log", "a+")
        f.write(str(e))
        f.close()

    sender = request.POST.get(
        'from')  # phone number from which the message originated from
    message = request.POST.get('text')  # Message from sender
    message = message.strip()
    date = request.POST.get('date')  # Date time when the message was sent
    msg_id = request.POST.get('id')  # Message ID from Africa's Talking

    aspirant = Client.objects.all()[0]

    sms_inbox = Inbox(africastalking_msg_id=msg_id,
                      phone_number=sender,
                      message=message,
                      date_created=datetime.datetime.now(),
                      date_received=date,
                      user=aspirant.user)

    subscriber_exist = Subscriber.objects.filter(phone_number=sender).exists()
    volunteer_exist = Volunteer.objects.filter(phone_number=sender).exists()

    try:
        message_arr = message.split(' ')
        first_word = message_arr[0].lower()
        first_word = first_word.strip()
        sms_util = SMS()

        if len(message_arr) == 1:
            if first_word == 'vote' and subscriber_exist is False:  # subscriber user
                sms_inbox.message_type = 'SUBSCRIBE'
                sms_inbox.save()
                subscriber = Subscriber(
                    phone_number=sms_util.format_phone_number(sender),
                    aspirant=aspirant,
                    is_active=True)
                subscriber.save()
                ret_msg = """You have successfully subscribe to {}. Send the word campaign to {} to view his campaign."""\
                    .format(aspirant.alias_name, settings.SMS_SHORT_CODE)
                sms_util.send_single_sms(sms_util.format_phone_number(sender),
                                         ret_msg)
                Outbox(phone_number=sms_util.format_phone_number(sender),
                       message=ret_msg,
                       message_type="ACK",
                       is_sent=True,
                       user=aspirant.user,
                       date_sent=datetime.datetime.now()).save()
                return

            elif first_word == 'volunteer':
                ret_msg = """To register as {}'s volunteer, send the word volunteer followed by your email address to {}.""" \
                    .format(aspirant.alias_name, settings.SMS_SHORT_CODE)
                sms_util.send_single_sms(sms_util.format_phone_number(sender),
                                         ret_msg)
                Outbox(phone_number=sms_util.format_phone_number(sender),
                       message=ret_msg,
                       message_type="ACK",
                       is_sent=True,
                       user=aspirant.user,
                       date_sent=datetime.datetime.now()).save()

            elif first_word.isdigit():  # SMS menu
                phone_number = sms_util.format_phone_number(sender)
                sms_menu_log = SMSMenuLog.objects.filter(
                    phone_number=phone_number).order_by('-date_created')[0]
                allowed_options = json.loads(sms_menu_log.allowed_options)
                extra_info = json.loads(sms_menu_log.extra_info)
                menu_type = sms_menu_log.menu_type
                menu_option = int(first_word)

                if menu_option not in allowed_options:
                    msg = extra_info['FALL_BACK_SMS']
                    sms_util.send_single_sms(phone_number, msg)
                    return

                if menu_type == 'MANIFESTO':  #Send campaign
                    sms_inbox.message_type = 'MANIFESTO'
                    sms_inbox.save()

                    manifesto_id = extra_info['MANIFESTO_ID']
                    options_mapping = extra_info['OPTIONS_MAPPING']
                    manifesto = Campaign.objects.get(id=manifesto_id)
                    manifesto_item_id = options_mapping[first_word]
                    manifesto_item = CampaignItems.objects.get(
                        campaign=manifesto, id=manifesto_item_id)
                    manifesto_msg = """{}\n{}""".format(
                        manifesto_item.title, manifesto_item.content)
                    sms_util.send_single_sms(phone_number, manifesto_msg)

                    manifesto_item_reception = CampaignItemsReception(
                        campaign_item=CampaignItems.objects.get(
                            id=manifesto_item_id),
                        date_read=datetime.datetime.now())

                    try:
                        manifesto_item_reception.subscriber = Subscriber.objects.get(
                            phone_number=phone_number)
                    except:
                        pass
                    manifesto_item_reception.save()

                elif menu_type == 'SURVEY':  #Send survey
                    sms_inbox.message_type = 'SURVEY'
                    sms_inbox.save()

                    survey_id = extra_info['SURVEY_ID']
                    was_question = extra_info['WAS_QUESTION']

                    if was_question == 1:  # Save survey response
                        options_mapping = extra_info['OPTIONS_MAPPING']
                        survey_response = SurveyResponse()
                        survey_response.survey_option = SurveyOptions.objects.get(
                            id=options_mapping[first_word])
                        try:
                            survey_response.subscriber = Subscriber.objects.get(
                                phone_number=sms_util.format_phone_number(
                                    phone_number))
                        except:
                            pass
                        survey_response.save()

                    next_question_number = extra_info['NEXT_QUESTION_NUMBER']
                    survey = Survey.objects.get(id=survey_id)

                    try:
                        survey_question = SurveyQuestion.objects.get(
                            survey=survey,
                            question_number=next_question_number)
                        question_options = SurveyOptions.objects.filter(
                            survey_question=survey_question)
                        msg = "{}\n".format(survey_question.question)
                        fall_back_sms = "Invalid option.\n"
                        allowed_options = []
                        options_mapping = {}

                        for i in range(0, len(question_options)):
                            msg += "{}. {}\n".format(
                                i + 1, question_options[i].option)
                            fall_back_sms += "{}. {}\n".format(
                                i + 1, question_options[i].option)
                            allowed_options.append(i + 1)
                            options_mapping[i + 1] = question_options[i].id

                        SMSMenuLog(date_created=datetime.datetime.now(),
                                   phone_number=phone_number,
                                   menu_type='SURVEY',
                                   allowed_options=json.dumps(allowed_options),
                                   extra_info=json.dumps({
                                       'WAS_QUESTION':
                                       1,
                                       'NEXT_QUESTION_NUMBER':
                                       next_question_number + 1,
                                       'SURVEY_ID':
                                       survey_id,
                                       'FALL_BACK_SMS':
                                       fall_back_sms,
                                       'OPTIONS_MAPPING':
                                       options_mapping
                                   })).save()
                        sms_util.send_single_sms(phone_number, msg)
                    except:
                        msg = "Thank you for participating in this survey."
                        sms_util.send_single_sms(phone_number, msg)

        elif first_word == 'volunteer' and volunteer_exist is False:  # Register volunteer
            sms_inbox.message_type = 'VOLUNTEER'
            sms_inbox.save()
            email_address = message_arr[1]

            try:
                validate_email(email_address)
                user = User(username=email_address, email=email_address)
                user.save()
                volunteer = Volunteer(
                    phone_number=sms_util.format_phone_number(sender),
                    aspirant=aspirant,
                    is_active=True,
                    user=user)
                volunteer.save()
                try:
                    recipient = [user]
                    email = SendEmail()
                    txt_template = 'email/email_template_volunteer_registration.txt'
                    html_template = 'email/email_template_volunteer_registration.html'
                    send_mail = email.tuma_mail(recipient, txt_template,
                                                html_template)
                    if send_mail:
                        ret_msg = """You have successfully been registered as {}'s volunteer. A verification link has been sent to {}.""" \
                            .format(aspirant.alias_name, email_address)
                    else:
                        ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \
                            .format(email_address)
                        volunteer.delete()
                        user.delete()
                except Exception, e:
                    ret_msg = """Unsuccessful registration.Unable to sent verification link to {}""" \
                        .format(email_address)
                    volunteer.delete()
                    user.delete()
                sms_util.send_single_sms(sms_util.format_phone_number(sender),
                                         ret_msg)
                Outbox(phone_number=sms_util.format_phone_number(sender),
                       message=ret_msg,
                       message_type="ACK",
                       is_sent=True,
                       user=aspirant.user,
                       date_sent=datetime.datetime.now()).save()
                return

            except:
                ret_msg = """Invalid email address.Please send the word volunteer followed by a valid email address to {}.""" \
                    .format(aspirant.alias_name, settings.SMS_SHORT_CODE)
                sms_util.send_single_sms(sms_util.format_phone_number(sender),
                                         ret_msg)
                Outbox(phone_number=sms_util.format_phone_number(sender),
                       user=aspirant.user,
                       message=ret_msg,
                       message_type="ACK",
                       is_sent=True,
                       date_sent=datetime.datetime.now()).save()