Esempio n. 1
0
 def setUp(self):
     #create 2 users
     test_user1 = User.objects.create(username='******', password='******')
     test_user2 = User.objects.create(username='******', password='******')
     
     test_user1.save()
     test_user2.save()
     
     #create a book
     test_author = Author.objects.create(first_name='John', last_name='Smith')
     test_genre = Genre.objects.create(name='Fantasy')
     test_book = Book.objects.create(
             title='Good By!',
             author=test_author,
             summary='Abracadabra',
             genre=test_genre)
         
     #create genre as a post-step
     genre_objects_for_book = Genre.objects.all
     test_book.genre.set(genre_objects_for_book)
     test_book.save()
         
     # create 30 Status objects
     
     number_of_book_copies = 30
     for book_copy in number_of_book_copies:
         allowed_time = timezone.today()+datetime.timedelta(days=book_copy%5)
         the_wisher = test_user1 if book_copy%2 else test_user2
         status = 'wished'
         Status.objects.create(
                 book = book_copy,
                 due_back = allowed_time,
                 wisher = the_wisher,
                 status = status )
Esempio n. 2
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache['ip'] != request.user_ip:
            return None
        if not cachebuster.is_valid(VERSION_KEY, ban_cache['version']):
            return None
        if ban_cache.get('expires_on'):
            if ban_cache['expires_on'] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 3
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache["ip"] != request.user_ip:
            return None
        if ban_cache["version"] != request.cache_versions[BANS_CACHE]:
            return None
        if ban_cache.get("expires_on"):
            if ban_cache["expires_on"] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 4
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache['ip'] != request.user_ip:
            return None
        if not cachebuster.is_valid(VERSION_KEY, ban_cache['version']):
            return None
        if ban_cache.get('expires_on'):
            if ban_cache['expires_on'] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 5
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache["ip"] != request.user_ip:
            return None
        if ban_cache["version"] != request.cache_versions[BANS_CACHE]:
            return None
        if ban_cache.get("expires_on"):
            if ban_cache["expires_on"] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 6
0
 def test_date_validation(self):
     p = Patient.objects.create(name='Joe')
     p.eav.dob = 'bad'
     self.assertRaises(ValidationError, p.save)
     p.eav.dob = 15
     self.assertRaises(ValidationError, p.save)
     now = timezone.now()
     now = timezone.datetime(year=now.year, month=now.month, day=now.day,
                             hour=now.hour, minute=now.minute, second=now.second)
     p.eav.dob = now
     p.save()
     self.assertEqual(Patient.objects.get(pk=p.pk).eav.dob, now)
     today = timezone.today()
     p.eav.dob = today
     p.save()
     self.assertEqual(Patient.objects.get(pk=p.pk).eav.dob.date(), today)
Esempio n. 7
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[BAN_CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache['ip'] != request._misago_real_ip:
            return None
        if not cachebuster.is_valid(BAN_VERSION_KEY, ban_cache['version']):
            return None
        if ban_cache.get('expires_on'):
            """
            Hydrate ban date
            """
            if ban_cache['expires_on'] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 8
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[BAN_CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache['ip'] != request._misago_real_ip:
            return None
        if not cachebuster.is_valid(BAN_VERSION_KEY, ban_cache['version']):
            return None
        if ban_cache.get('expires_on'):
            """
            Hydrate ban date
            """
            if ban_cache['expires_on'] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 9
0
 def test_date_validation(self):
     p = Patient.objects.create(name="Joe")
     p.eav.dob = "bad"
     self.assertRaises(ValidationError, p.save)
     p.eav.dob = 15
     self.assertRaises(ValidationError, p.save)
     now = timezone.now()
     now = timezone.datetime(
         year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second
     )
     p.eav.dob = now
     p.save()
     self.assertEqual(Patient.objects.get(pk=p.pk).eav.dob, now)
     today = timezone.today()
     p.eav.dob = today
     p.save()
     self.assertEqual(Patient.objects.get(pk=p.pk).eav.dob.date(), today)
Esempio n. 10
0
def _get_session_bancache(request):
    try:
        ban_cache = request.session[BAN_CACHE_SESSION_KEY]
        ban_cache = _hydrate_session_cache(ban_cache)
        if ban_cache["ip"] != request.user_ip:
            return None
        if not cachebuster.is_valid(BAN_VERSION_KEY, ban_cache["version"]):
            return None
        if ban_cache.get("expires_on"):
            """
            Hydrate ban date
            """
            if ban_cache["expires_on"] < timezone.today():
                return None
        return ban_cache
    except KeyError:
        return None
Esempio n. 11
0
def validate_no_future_date(date):
    if date > today().date():
        raise ValidationError(**ERROR_MESSAGES.get('future_date_error'))
Esempio n. 12
0
 def age(self):
     TODAY = timezone.today()
     return (TODAY.year - self.birth_date.year)
Esempio n. 13
0
 def today(self):
     return datetime.today()
Esempio n. 14
0
 def age(self):
     TODAY = timezone.today()
     return TODAY.year - self.birth_date.year
Esempio n. 15
0
def user_respond(request, link_address):
    try:
        survey = get_object_or_404(Survey, pk=link_address)
    except:
        return HttpResponse('Invalid link address')
    if request.method == "POST":
        email = request.user.email
        user = get_object_or_404(MyUser, email=email)

        user.response_timer  # Retrieves or Creates user response timer instance
        utime = user.responsetimer

        if survey.survey_option == 'P':  # Check whether survey has the 'PAID' option.
            # Check whether user can respond to the survey based on the response timer
            if utime.end_time and (utime.end_time > timezone.now()):
                return redirect('surveys:survey_options')

        # Check whether survey was created by the user.
        if survey.user == user:
            return HttpResponse("Unable to process your Response!!")

        # Check whether user has responded to survey before.
        responded = Response.objects.filter(user=user).filter(
            survey=survey).exists()
        if responded:
            return HttpResponse("You can't answer this survey again")

        if survey.completed:  # Check whether survey is completed(Has received required responses)
            return HttpResponse(
                "Survey completed. Additional Responses denied")

        # Retrieve the link address of the survey recently responded to.
        # If no recent survey, make this one the recent one.
        recent_survey = request.session.get('recent_survey', str(link_address))

        #Calculate the minimum time required to complete the survey.
        survey_timer = timezone.now() + timedelta(
            minutes=survey.surveyproperties.survey_timer)

        # If the recently responded to survey is not the same as the current one.
        if False:  #New Test (not recent_survey == str(link_address):)
            # If the current survey is not the previous survey, set new 'survey timer'.
            request.session['survey_timer'] = str(survey_timer)

        # Get session 'survey timer' string and convert to datetime object type.
        timer = pd.to_datetime(
            request.session.get('survey_timer',
                                str(survey_timer))).to_pydatetime()

        # Make timer object timezone aware.
        localized_time = tz.utc.localize(timer)
        # If 'survey timer' is not completed; prevent 'Respondent' from submitting response.
        if timezone.now() <= localized_time:
            note = "Survey timer not completed, Please read through survey."
            messages.error(request, note)

            formatted_timer = localized_time.strftime('%Y/%m/%d %H:%M:%S')

            context = {
                'survey': survey,
                'server_timer': formatted_timer,
            }
            return render(request, "surveys/survey_view.html", context)

        # Set the 'current survey' as the 'recent survey' session.
        request.session['recent_survey'] = str(link_address)

        # Create 'Response' object for this user response and save it to the database.
        user_response = Response(user=user,
                                 survey=survey,
                                 resp_date=timezone.now(),
                                 survey_title=survey.title,
                                 survey_description=survey.description,
                                 survey_field=survey.field,
                                 survey_option=survey.survey_option,
                                 verified=user.is_active)
        user_response.save()

        # Update the waiting time(30 minutes) for the user's next 'PAID Survey' response.
        utime.end_time = timezone.now() + timedelta(minutes=30)
        utime.save()

        for question in survey.surveyquestion_set.all():
            response_question = ResponseQuestion(
                response=user_response,
                survey_question=question,
                question_text=question.question_text,
                html_name=question.html_name)
            response_question.save()

            if question.html_name[-2] == 'r':
                try:
                    selected_choice = question.surveychoice_set.get(
                        pk=request.POST['choice{}'.format(question.id)])
                except (KeyError, SurveyChoice.DoesNotExist):
                    error_message = "Incomplete form, fill empty spaces"
                    messages.error(request, error_message)

                    return render(request, 'surveys/survey_view.html',
                                  {'survey': survey})
                else:
                    response_choice = ResponseChoice(
                        response_question=response_question,
                        choice_text=selected_choice.choice_text,
                        html_name=selected_choice.html_name)
                    response_choice.save()
                    selected_choice.votes = F('votes') + 1
                    selected_choice.save()

            elif question.html_name[-2] == 't':
                response_choice = ResponseChoice(
                    response_question=response_question,
                    choice_text=request.POST['choice{}'.format(question.id)],
                    html_name='p_{}_t1'.format(question.html_name[2]))
                response_choice.save()

            else:
                selected_choices = request.POST.getlist('choice{}'.format(
                    question.id))
                for selected_choice_str in selected_choices:  #All question's (checkbox) choices that were selected
                    selected_choice = question.surveychoice_set.get(
                        pk=selected_choice_str)
                    response_choice = ResponseChoice(
                        response_question=response_question,
                        choice_text=selected_choice.choice_text,
                        html_name=selected_choice.html_name)
                    response_choice.save()
                    selected_choice.votes = F('votes') + 1
                    selected_choice.save()

        survey.total_responses = F('total_responses') + 1
        survey.verified_responses = F('verified_responses') + 1
        survey.save()
        survey.refresh_from_db()

        if survey.verified_responses >= int(survey.sample_size):
            survey.completed = True

        survey.percent_completed = \
         (survey.verified_responses/survey.sample_size) * 100

        survey.save()

        if survey.survey_option == 'P':
            reward_prices = {5: 2, 12: 8, 20: 15}

            if user.survey_offer and user.surveyoffer.on_offer:
                offer_info = user.surveyoffer
                offer_info.progress_count = F('progress_count') + 1
                offer_info.save()
                offer_info.refresh_from_db()

                if offer_info.progress_count >= offer_info.offer_threshold:
                    survey_offer_record = SurveyOfferRecords(
                        user=user,
                        offer_name=offer_info.offer_name,
                        offer_threshold=offer_info.offer_threshold,
                        completed=True,
                        date_started=offer_info.date_started,
                        date_ended=timezone.now(),
                    )
                    reward = Reward(
                        user=user,
                        reward_name=offer_info.offer_name,
                        reward_date=timezone.now(),
                        expire_date=timezone.today(),
                        reward_price=reward_prices[offer_info.offer_threshold])
                    offer_info.offer_name = None
                    offer_info.progress_count = 0
                    offer_info.on_offer = False
                    offer_info.offer_threshold = None
                    offer_info.date_started = None
                    offer_info.expire_date = None

                    survey_offer_record.save()
                    reward.save()
                    offer_info.save()

        del request.session['recent_survey']
        del request.session['survey_timer']

        success_message = "Your 'Response' was recorded successfully."
        messages.success(request, success_message)

        return redirect('surveys:response', user_response.id)

    return redirect('surveys:view_page', link_address)