Example #1
0
def calc_multi_iteration_average(team_name, survey, num_iterations=2):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    iteration_index = 0
    if num_iterations > 0:
        iteration_index = num_iterations - 1
    else:
        return None

    archive_dates = survey.temperatureresponse_set.filter(
        archive_date__isnull=False).values('archive_date').distinct().order_by(
            '-archive_date')

    if archive_dates.count() < num_iterations and archive_dates.count() > 0:
        iteration_index = archive_dates.count(
        ) - 1  #oldest archive date if less than target iteration count

    if archive_dates.count() > iteration_index:
        response_dates = survey.temperatureresponse_set.filter(
            archive_date=archive_dates[iteration_index]
            ['archive_date']).values('response_date').order_by('response_date')

        if team_name != '':
            accumulated_stats = survey.accumulated_team_stats(
                team_name, timezone.now(), response_dates[0]['response_date'])
        else:
            accumulated_stats = survey.accumulated_stats(
                timezone.now(), response_dates[0]['response_date'])

        return accumulated_stats

    return None
Example #2
0
def member_edit(request, id=None):
    if id:
        member=get_object_or_404(Members,pk=id)
    else:
        member=Members()
    if request.POST:
        form=MemberForm(request, request.POST,instance=member)
        if  form.is_valid():
            print "MemberForm is valid"
            post = form.save(commit=False)
            post.studio = request.user.studiouser.studio_id
            post.created_by = request.user
            post.modified_by = request.user
            from django.utils import timezone
            if id:
                post.modified_date = timezone.now()   
            else:
                post.created_date = timezone.now()
            post.save()
            post.categories = form.cleaned_data['categories']
            post.save()
            return HttpResponseRedirect("/sway/members")
        else:
            print "MemberForm is invalid", form.errors, form.non_field_errors
    else:
        print "member_edit GET request"
        #form=MemberForm({"instance":member,"studio":request.user.studiouser.studio_id})
        form=MemberForm(request, instance=member)
        #form.studio = request.user.studiouser.studio_id                        
    return render(request, 'sway/add_members.html', {'form': form, 'id':member.id}, context_instance=RequestContext(request))
Example #3
0
def home(request, survey_type = 'TEAMTEMP'):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    if request.method == 'POST':
        form = CreateSurveyForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            csf = form.cleaned_data
            form_id = utils.random_string(8)
            userid = responses.get_or_create_userid(request)
            user, created = User.objects.get_or_create(id=userid)
            # TODO check that id is unique!
            team_name = csf['team_name'].replace(" ", "_")
            survey = TeamTemperature(creation_date = timezone.now(),
                                     password = make_password(csf['password']),
                                     creator = user,
                                     survey_type = survey_type,
                                     archive_date = timezone.now(),
                                     id = form_id)
            survey.save()
            team_details = Teams(request = survey,
                                team_name = team_name)
            team_details.save()
            return HttpResponseRedirect('/admin/%s/%s' % (form_id, team_name))
    else:
        form = CreateSurveyForm()
    return render(request, 'index.html', {'form': form})
Example #4
0
def home(request, survey_type = 'TEAMTEMP'):
    timezone.activate(pytz.timezone('UTC'))
    if request.method == 'POST':
        form = CreateSurveyForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            csf = form.cleaned_data
            form_id = utils.random_string(8)
            userid = responses.get_or_create_userid(request)
            user, created = User.objects.get_or_create(id=userid)
            # TODO check that id is unique!
            dept_names = csf['dept_names']
            region_names = csf['region_names']
            site_names = csf['site_names']
            survey = TeamTemperature(creation_date = timezone.now(),
                                     password = make_password(csf['password']),
                                     creator = user,
                                     survey_type = survey_type,
                                     archive_date = timezone.now(),
                                     id = form_id,
                                     dept_names = dept_names,
                                     region_names = region_names,
                                     site_names = site_names,
                                     archive_schedule = 7,
                                     default_tz = 'UTC'
                                     )
            survey.save()
            return HttpResponseRedirect('/team/%s' % (form_id))
    else:
        form = CreateSurveyForm()
    return render(request, 'index.html', {'form': form, 'survey_type': survey_type})
Example #5
0
def reset(request, survey_id):
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    timezone.activate(pytz.timezone(survey.default_tz or 'UTC'))
    # if valid session token or valid password render results page

    if not authenticated_user(request, survey_id):
        return HttpResponseRedirect('/admin/%s' % survey_id)

    teamtemp = TeamTemperature.objects.get(pk=survey_id)

    #Save Survey Summary for all survey teams
    arch_date = timezone.now()
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(archived = False).values('team_name').distinct()

    for team in teams:
        Summary = None
        team_stats = None
        summary_word_list = ""
        team_stats = teamtemp.team_stats([team['team_name']])
        for word in team_stats['words'] :
            summary_word_list = summary_word_list + word['word'] + " "
        Summary = TeamResponseHistory(request = survey,
            average_score = team_stats['average']['score__avg'],
            word_list = summary_word_list,
            responder_count = team_stats['count'],
            team_name = team['team_name'],
            archive_date = arch_date)
        Summary.save()

        TemperatureResponse.objects.filter(request = survey_id, team_name = team['team_name'], archived = False).update(**data)

    print >>sys.stderr,"Archiving: " + " " + teamtemp.id + " at " + str(nowstamp)

    return HttpResponseRedirect('/admin/%s' % survey_id)
Example #6
0
def scheduled_archive(request, survey_id):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)

    teamtemp = TeamTemperature.objects.get(pk=survey_id)

    #Save Survey Summary for all survey teams
    arch_date = timezone.now()
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(
        archived=False).values('team_name').distinct()
    average_total = 0
    average_count = 0
    average_responder_total = 0

    for team in teams:
        Summary = None
        team_stats = None
        summary_word_list = ""
        team_stats = teamtemp.team_stats(team['team_name'])
        for word in team_stats['words']:
            summary_word_list = summary_word_list + word['word'] + " "
        Summary = TeamResponseHistory(
            request=survey,
            average_score=team_stats['average']['score__avg'],
            word_list=summary_word_list,
            responder_count=team_stats['count'],
            team_name=team['team_name'],
            archive_date=arch_date)
        Summary.save()
        average_total = average_total + team_stats['average']['score__avg']
        average_count = average_count + 1
        average_responder_total = average_responder_total + team_stats['count']

        TemperatureResponse.objects.filter(request=survey_id,
                                           team_name=team['team_name'],
                                           archived=False).update(**data)

    #Save Survey Summary as AGREGATE AVERAGE for all teams
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(
        archived=False).values('team_name').distinct()
    Summary = None
    team_stats = None
    summary_word_list = ""
    team_stats = teamtemp.stats()

    if average_count > 0:
        Summary = TeamResponseHistory(request=survey,
                                      average_score=average_total /
                                      float(average_count),
                                      word_list=summary_word_list,
                                      responder_count=average_responder_total,
                                      team_name='Average',
                                      archive_date=arch_date)

    if Summary:
        Summary.save()

    return
Example #7
0
 def test_current_showtimes_for_movie_check_movie(self):
     cinema = mommy.make('Cinema')
     movie = mommy.make('Movie')
     showtimes = mommy.make('Showtime', cinema=cinema, showing_at=(timezone.now()), _quantity = 5)
     self.assertEqual(0, len(cinema.current_showtimes_for_movie(movie.name)))
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now()))
     self.assertIn(showtime, cinema.current_showtimes_for_movie(movie.name))
Example #8
0
 def test_current_showtimes_for_movie_check_time(self):
     cinema = mommy.make('Cinema')
     movie = mommy.make('Movie')
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now()))
     self.assertIn(showtime, cinema.current_showtimes_for_movie(movie.name))
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now()+ datetime.timedelta(days=60)))
     self.assertNotIn(showtime, cinema.current_showtimes_for_movie(movie.name))
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now() - datetime.timedelta(days=2)))
     self.assertNotIn(showtime, cinema.current_showtimes_for_movie(movie.name))
Example #9
0
 def test_available_cinemas_for_movie_cinema_check_time(self):
     city = mommy.make('City')
     cinema = mommy.make('Cinema', city=city)
     movie = mommy.make('Movie')
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now() + datetime.timedelta(days=60)))
     self.assertNotIn(cinema, city.available_cinemas_for_movie(movie.name))
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now() - datetime.timedelta(days=2)))
     self.assertNotIn(cinema, city.available_cinemas_for_movie(movie.name))
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now()))
     self.assertIn(cinema, city.available_cinemas_for_movie(movie.name))
Example #10
0
def scheduled_archive(request, survey_id):
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    timezone.activate(pytz.timezone(survey.default_tz or 'UTC'))
    
    teamtemp = TeamTemperature.objects.get(pk=survey_id)
    
    #Save Survey Summary for all survey teams
    arch_date = timezone.now()
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(archived = False).values('team_name').distinct()
    average_total = 0
    average_count = 0
    average_responder_total = 0
    
    for team in teams:
        Summary = None
        team_stats = None
        summary_word_list = ""
        team_stats = teamtemp.team_stats([team['team_name']])
        for word in team_stats['words'] :
            summary_word_list = summary_word_list + word['word'] + " "
        Summary = TeamResponseHistory(request = survey,
                                      average_score = team_stats['average']['score__avg'],
                                      word_list = summary_word_list,
                                      responder_count = team_stats['count'],
                                      team_name = team['team_name'],
                                      archive_date = arch_date)
        Summary.save()
        average_total = average_total + team_stats['average']['score__avg']
        average_count = average_count + 1
        average_responder_total = average_responder_total + team_stats['count']
    
        TemperatureResponse.objects.filter(request = survey_id, team_name = team['team_name'], archived = False).update(**data)

    #Save Survey Summary as AGREGATE AVERAGE for all teams
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(archived = False).values('team_name').distinct()
    Summary = None
    team_stats = None
    summary_word_list = ""
    team_stats = teamtemp.stats()

    if average_count > 0:
        Summary = TeamResponseHistory(request = survey,
                                  average_score = average_total/float(average_count),
                                  word_list = summary_word_list,
                                  responder_count = average_responder_total,
                                  team_name = 'Average',
                                  archive_date = arch_date)

    if Summary:
        Summary.save()

    return
Example #11
0
def admin(request, survey_id, team_name=''):
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    timezone.activate(pytz.timezone(survey.default_tz or 'UTC'))
    # if valid session token or valid password render results page
    password = None
    user = None
    survey_teams=[]
    next_archive_date = timezone.now()
    
    if request.method == 'POST':
        form = ResultsPasswordForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            rpf = form.cleaned_data
            password = rpf['password'].encode('utf-8')
    else: 
        try: 
            userid = request.session.get('userid', '__nothing__')
            user = User.objects.get(id=userid)
        except User.DoesNotExist:
            return render(request, 'password.html', {'form': ResultsPasswordForm()})
    if user and survey.creator.id == user.id or check_password(password, survey.password):
        request.session['userid'] = survey.creator.id
        teamtemp = TeamTemperature.objects.get(pk=survey_id)
        survey_type = teamtemp.survey_type
        if team_name != '':
            team_found = teamtemp.teams_set.filter(team_name = team_name).count()
            if team_found == 0 and survey_type != 'DEPT-REGION-SITE':
                TeamDetails = Teams(request = survey,team_name = team_name)
                TeamDetails.save()
            results = teamtemp.temperatureresponse_set.filter(team_name = team_name, archived = False)
        else:
            results = teamtemp.temperatureresponse_set.filter(archived = False)

        survey_teams = teamtemp.teams_set.all()

        if team_name != '':
            stats = survey.team_stats(team_name=team_name)
        else:
            stats = survey.stats()

        if survey.archive_schedule > 0:
            next_archive_date = timezone.localtime(survey.archive_date) + timedelta(days=(survey.archive_schedule))
            if next_archive_date < timezone.localtime(timezone.now()):
                next_archive_date = timezone.localtime(timezone.now() + timedelta(days=1))

        return render(request, 'results.html',
                { 'id': survey_id, 'stats': stats,
                  'results': results, 'team_name':team_name,
                      'pretty_team_name':team_name.replace("_", " "),'survey_teams':survey_teams,
                      'archive_schedule' : survey.archive_schedule, 'next_archive_date' : next_archive_date.strftime("%A %d %B %Y")
                    } )
    else:
        return render(request, 'password.html', {'form': ResultsPasswordForm()})
Example #12
0
def generate_wordcloud(word_list):

    mashape_key = os.environ.get('XMASHAPEKEY')
    if mashape_key != None:
        Unirest.timeout(20)
        print >>sys.stderr, str(timezone.now()) + " Start Word Cloud Generation: " + word_list
        response = Unirest.post("https://gatheringpoint-word-cloud-maker.p.mashape.com/index.php",
                                headers={"X-Mashape-Key": mashape_key},
                                params={"config": "n/a", "height": 500, "textblock": word_list, "width": 800}
                                )
        print >>sys.stderr, str(timezone.now()) + " Finish Word Cloud Generation: " + word_list
        if response.code == 200:
            return save_url(response.body['url'], 'media/wordcloud_images')
    return None
Example #13
0
    def returned_wrapper(request, *args, **kwargs):
        try:
            start = request.GET.get('start', None)
            end=request.GET.get('end',None)
            kind= request.GET.get('kind','now')
            # utcnow=datetime.now()
            utcnow=timezone.now()
            # targetdate = targetdate if kind=='history' else datetime.now()
            start = start if kind == 'history' else utcnow
            if kind=='now' or end==None:
                end=start+timedelta(days=1)
                # now str转成 yyyy-mm-dd HH:mm
                # targetdate.strftime('%Y-%m-%d %H:%M')
                pass
            elif kind=='history':
                # history str时转成 yyyy-mm-dd
                # TODO
                start=datetime.strptime(start,'%Y-%m-%d').replace(tzinfo=utc)
                end=datetime.strptime(end,'%Y-%m-%d').replace(tzinfo=utc)
                # targetdate=targetdate+timedelta(hours=-8)
                # tzname = timezone.get_current_timezone_name()
                # targetdate=pytz.timezone(tzname).localize(targetdate)

            # 转换为世界时
            # targetdate=DateCommon.local2Utc(targetdate)
            # isNow=request.GET.get('isNow',True)
            request.GET=request.GET.copy()
            request.GET['start']=start
            request.GET['end']=end
            return func(request, *args, **kwargs)
        except ObjectDoesNotExist:
            raise Http404()
Example #14
0
def db_update_daily_session_by_cp(request):
    now = timezone.now()
    zeroToday = now - timedelta(hours=now.hour,
                                minutes=now.minute,
                                seconds=now.second,
                                microseconds=now.microsecond)
    zeroYesterday = zeroToday - timedelta(hours=24, minutes=0, seconds=0)

    # When dev, you might call this function by accident, so it helps check daily ingestion to avoid duplicate
    isExist = db_ui_session.objects.filter(timestamp__gte=zeroToday)
    if len(isExist) > 0:
        print(len(isExist))
        print("checked duplicate")
        return render(request, 'home.html')

    retvals = cp.read_daily_sessions(zeroYesterday)
    for retval in retvals:
        session = db_ui_session()
        session.session_id = retval['sessionID']
        session.group_name = retval['groupName']
        session.start_time = retval['startTime']
        session.end_time = retval['endTime']
        session.timestamp = retval['timestamp']
        session.energy = retval['energy']
        session.user_id = retval['userID']
        session.save()

    return render(request, 'home.html')
Example #15
0
def get_one_week_range_v2(cur_date, t_default=None, action=None):
    # d = cur_date.astimezone(pytz.timezone('UTC'))
    # if not d:
    #     if not t_default:
    #         d_default = date.today()
    #     else:
    #         d_default = t_default.date()
    #     d = d_default.strftime('%Y-%m-%d')
    users_tz = timezone.get_current_timezone()
    if not cur_date:
        cur_date = get_localized_datetime(timezone.now())
    else:
        cur_date = timezone.make_aware(datetime.strptime(
            cur_date, "%Y-%m-%d %H:%M:%S"),
                                       timezone=users_tz)

    t_datetime = get_localized_datetime(cur_date)

    if action:
        if action == 'previous':
            t_datetime = t_datetime - timedelta(days=7)
        elif action == 'next':
            t_datetime = t_datetime + timedelta(days=7)

    d = t_datetime.strftime('%Y-%m-%d %H:%M:%S')

    t_monday = get_monday_of_the_week(t_datetime)
    t_next_monday = get_next_monday_of_the_week(t_datetime)

    logger.debug(
        'current_date is: {}, and parsed as {}; and monday is {}, and next monday is {}'
        .format(d, t_datetime, t_monday, t_next_monday))
    return d, t_monday, t_next_monday
def viewDoctor(request, doctor_id):
    """ View Doctor.

    Returns a selected doctor details upon GET request

    :param incoming request
        doctor_id
    :return: viewDoctor.html

    """
    doctors = get_object_or_404(Doctor, pk=doctor_id)
    doctorEmail = doctors.user.email
    doctorAppointments = []
    doctorAppointments = Appointment.objects.filter(doctor__id=doctor_id)
    reviews = []
    for app in doctorAppointments:
        if app.review != "None":
            reviews.append(app.review)
    timeslots = []
    for timeslot in doctors.time_slots:
        if ((timeslot - timezone.now()).total_seconds() > 0):
            timeslots.append(timeslot)
    doctors.time_slots = timeslots
    doctors.save()
    context = {'doctors': doctors, 'reviews': reviews}
    return render(request, 'seApp/viewDoctor.html', context)
Example #17
0
def cached_word_cloud(word_list):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    words = ""
    word_cloudurl = ""
    word_count = 0

    for word in word_list:
        for i in range(0, word['id__count']):
            words = words + word['word'] + " "
            word_count += 1

    #TODO Write a better lookup and model to replace this hack
    word_cloud_index = WordCloudImage.objects.filter(word_list=words)

    if word_cloud_index:
        if os.path.isfile(
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             word_cloud_index[0].image_url)):
            word_cloudurl = word_cloud_index[0].image_url
        else:
            #Files have been deleted remove from db and then regenerate
            WordCloudImage.objects.filter(word_list=words).delete()

    if word_cloudurl == "" and words != "":
        word_cloudurl = generate_wordcloud(words)
        if word_cloudurl:
            word_cloud = WordCloudImage(creation_date=timezone.now(),
                                        word_list=words,
                                        image_url=word_cloudurl)
            word_cloud.save()
    return word_cloudurl
Example #18
0
def cached_word_cloud(word_list):
    words = ""
    word_cloudurl = ""
    word_count = 0

    for word in word_list:
        for i in range(0,word['id__count']):
            words = words + word['word'] + " "
            word_count += 1
    
    #TODO Write a better lookup and model to replace this hack
    word_cloud_index = WordCloudImage.objects.filter(word_list = words)
    
    if word_cloud_index:
        if os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), word_cloud_index[0].image_url)):
            word_cloudurl =  word_cloud_index[0].image_url
        else:
            #Files have been deleted remove from db and then regenerate
            WordCloudImage.objects.filter(word_list = words).delete()
    
    if word_cloudurl == "" and words != "":
        word_cloudurl = generate_wordcloud(words)
        if word_cloudurl:
            word_cloud = WordCloudImage(creation_date = timezone.now(),
                                        word_list = words, image_url = word_cloudurl)
            word_cloud.save()
    return word_cloudurl
Example #19
0
def set(request, survey_id):
    thanks = ""
    rows_changed = 0
    survey_teams=[]

    if not authenticated_user(request, survey_id):
        return HttpResponseRedirect('/admin/%s' % survey_id)

    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    survey_teams = survey.teams_set.all()

    if request.method == 'POST':
        form = SurveySettingsForm(request.POST, error_class=ErrorBox)
        survey_settings_id = request.POST.get('id', None)
        if form.is_valid():
            srf = form.cleaned_data
            pw = survey.password
            if srf['password'] != '':
                pw = make_password(srf['password'])
                thanks = "Password Updated. "
            if srf['archive_schedule'] != survey.archive_schedule:
                if survey.archive_date == None:
                    survey.archive_date = timezone.now()
                thanks = thanks + "Schedule Updated. "
            if srf['survey_type'] != survey.survey_type:
                thanks = thanks + "Survey Type Updated. "
            if srf['current_team_name'] != '':
                rows_changed = change_team_name(srf['current_team_name'].replace(" ", "_"), srf['new_team_name'].replace(" ", "_"), survey.id)
                print >>sys.stderr,"Team Name Updated: " + " " + str(rows_changed) + " From: " + srf['current_team_name'] + " To: " +srf['new_team_name']

            survey_settings = TeamTemperature(id = survey.id,
                                              creation_date = survey.creation_date,
                                              creator = survey.creator,
                                              password = pw,
                                              archive_date = survey.archive_date,
                                              archive_schedule = srf['archive_schedule'],
                                              survey_type = srf['survey_type'])
            survey_settings.save()
            survey_settings_id = survey_settings.id
            form = SurveySettingsForm(instance=survey_settings)
            if srf['current_team_name'] != ''and srf['new_team_name'] != '':
                thanks = thanks + "Team Name Change Processed: " + str(rows_changed) + " rows updated. "
            if srf['current_team_name'] != '' and srf['new_team_name'] == '':
                thanks = thanks + "Team Name Change Processed: " + str(rows_changed) + " rows deleted. "

    else:
        try:
            previous = TeamTemperature.objects.get(id = survey_id)
            survey_settings_id = previous.id
        except TeamTemperature.DoesNotExist:
            previous = None
            survey_settings_id = None
        
        form = SurveySettingsForm(instance=previous)
    return render(request, 'set.html', {'form': form, 'thanks': thanks,
                  'survey_settings_id': survey_settings_id,
                  'survey_teams' : survey_teams})
Example #20
0
def submit_(request, survey_id, team_name=''):
    userid = responses.get_or_create_userid(request)
    user, created = User.objects.get_or_create(id=userid)
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    thanks = ""
    
    if request.method == 'POST':
        form = SurveyResponseForm(request.POST, error_class=ErrorBox)
        response_id = request.POST.get('id', None)
        if form.is_valid():
            srf = form.cleaned_data
            # TODO check that id is unique!
            response = TemperatureResponse(id = response_id,
                                           request = survey,
                                           score = srf['score'],
                                           word = srf['word'],
                                           responder = user,
                                           team_name = team_name,
                                           response_date = timezone.now())
            response.save()
            response_id = response.id
            form = SurveyResponseForm(instance=response)
            thanks = "Thank you for submitting your answers. You can " \
                     "amend them now or later using this browser only if you need to."

        else:
            raise Exception('Form Is Not Valid:',form)
            print >>sys.stderr, "else"
    else:
        try: 
            previous = TemperatureResponse.objects.get(request = survey_id, 
                                                       responder = user,
                                                       team_name = team_name,
                                                       archived = False) 
            response_id = previous.id
        except TemperatureResponse.DoesNotExist:
            previous = None
            response_id = None

        form = SurveyResponseForm(instance=previous)

    survey_type_title = 'Team Temperature'
    temp_question_title = 'Temperature (1-10) (1 is very negative, 6 is OK, 10 is very positive):'
    word_question_title = 'One word to describe how you are feeling:'
    if survey.max_word_count > 1:
        word_question_title = str(survey.max_word_count) + ' words to describe how you are feeling:'
    if survey.survey_type == 'CUSTOMERFEEDBACK':
        survey_type_title = 'Customer Feedback'
        temp_question_title = 'Please give feedback on our team performance (1 - 10) (1 is very poor - 10 is very positive):'
        word_question_title = 'Please suggest one word to describe how you are feeling about the team and service:'

    return render(request, 'form.html', {'form': form, 'thanks': thanks,
                                         'response_id': response_id, 'survey_type_title' : survey_type_title,
                                         'temp_question_title' : temp_question_title,
                                         'word_question_title' : word_question_title,
                                         'team_name': team_name,'pretty_team_name': team_name.replace("_", " "),
                                         'id': survey_id})
Example #21
0
def submit(request, survey_id, team_name=''):
    userid = responses.get_or_create_userid(request)
    user, created = User.objects.get_or_create(id=userid)
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    thanks = ""
    if request.method == 'POST':
        form = SurveyResponseForm(request.POST, error_class=ErrorBox)
        response_id = request.POST.get('id', None)
        if form.is_valid():
            srf = form.cleaned_data
            # TODO check that id is unique!
            response = TemperatureResponse(id=response_id,
                                           request=survey,
                                           score=srf['score'],
                                           word=srf['word'],
                                           responder=user,
                                           team_name=team_name,
                                           response_date=timezone.now())
            response.save()
            response_id = response.id
            form = SurveyResponseForm(instance=response)
            thanks = "Thank you for submitting your answers. You can " \
                     "amend them now or later if you need to"
    else:
        try:
            previous = TemperatureResponse.objects.get(request=survey_id,
                                                       responder=user,
                                                       team_name=team_name,
                                                       archived=False)
            response_id = previous.id
        except TemperatureResponse.DoesNotExist:
            previous = None
            response_id = None

        form = SurveyResponseForm(instance=previous)

    survey_type_title = 'Team Temperature'
    temp_question_title = 'Temperature (1-10) (1 is very negative, 6 is OK, 10 is very positive):'
    word_question_title = 'One word to describe how you are feeling:'
    if survey.survey_type == 'CUSTOMERFEEDBACK':
        survey_type_title = 'Customer Feedback'
        temp_question_title = 'Please give feedback on our team performance (1 - 10) (1 is very poor - 10 is very positive):'
        word_question_title = 'Please suggest one word to describe how you are feeling about the team and service:'

    return render(
        request, 'form.html', {
            'form': form,
            'thanks': thanks,
            'response_id': response_id,
            'survey_type_title': survey_type_title,
            'temp_question_title': temp_question_title,
            'word_question_title': word_question_title,
            'team_name': team_name.replace("_", " ")
        })
Example #22
0
def auto_archive_surveys(request):
    timezone.activate(pytz.timezone('UTC'))
    print >>sys.stderr,"auto_archive_surveys: Start at " + str(timezone.localtime(timezone.now())) + " UTC"

    teamtemps = TeamTemperature.objects.filter(archive_schedule__gt=0)
    nowstamp = timezone.now()
    data = {'archive_date': nowstamp}

    for teamtemp in teamtemps:
        print >>sys.stderr,"auto_archive_surveys: Survey " + teamtemp.id
        print >>sys.stderr,"auto_archive_surveys: Comparing " + str(timezone.localtime(timezone.now()).date()) + " >= " + str(timezone.localtime( teamtemp.archive_date + timedelta(days=teamtemp.archive_schedule) ).date())
        print >>sys.stderr,"auto_archive_surveys: Comparing " + str(timezone.localtime(timezone.now())) + " >= " + str(timezone.localtime( teamtemp.archive_date + timedelta(days=teamtemp.archive_schedule) ))
        print >>sys.stderr,"auto_archive_surveys: Comparison returns: " + str( timezone.localtime(timezone.now()).date() >= timezone.localtime( teamtemp.archive_date + timedelta(days=teamtemp.archive_schedule) ).date() )

        if teamtemp.archive_date is None or (timezone.localtime( timezone.now() ).date() >= (timezone.localtime( teamtemp.archive_date + timedelta(days=teamtemp.archive_schedule) ).date() ) ):
            scheduled_archive(request, teamtemp.id)
            TeamTemperature.objects.filter(pk=teamtemp.id).update(**data)
            print >>sys.stderr,"Archiving: " + " " + teamtemp.id + " at " + str(nowstamp) + " UTC " + str(timezone.localtime(timezone.now())) + " UTC"

    print >>sys.stderr,"auto_archive_surveys: Stop at " + str(timezone.localtime(timezone.now())) + " UTC"
Example #23
0
def generate_wordcloud(word_list):

    mashape_key = os.environ.get('XMASHAPEKEY')
    if mashape_key != None:
        Unirest.timeout(20)
        print >> sys.stderr, str(
            timezone.now()) + " Start Word Cloud Generation: " + word_list
        response = Unirest.post(
            "https://gatheringpoint-word-cloud-maker.p.mashape.com/index.php",
            headers={"X-Mashape-Key": mashape_key},
            params={
                "config": "n/a",
                "height": 500,
                "textblock": word_list,
                "width": 800
            })
        print >> sys.stderr, str(
            timezone.now()) + " Finish Word Cloud Generation: " + word_list
        if response.code == 200:
            return save_url(response.body['url'], 'media/wordcloud_images')
    return None
Example #24
0
def generate_wordcloud(word_list):

    word_cloud_key = os.environ.get('XMASHAPEKEY')
    if word_cloud_key != None:
        timeout = 25
        Unirest.timeout(timeout)
        word_list = word_list.lower()
        fixed_asp = "FALSE"
        rotate = "FALSE"
        word_count = len(word_list.split())
        if word_count < 20:
            fixed_asp = "TRUE"
            rotate = "TRUE"
        print >>sys.stderr, str(timezone.now()) + " Start Word Cloud Generation: " + word_list
        response = Unirest.post("https://www.teamtempapp.com/wordcloud/api/v1.0/generate_wc",
                                headers={"Content-Type" : "application/json", "Word-Cloud-Key" : word_cloud_key},
                                params=json.dumps({"textblock" : word_list, "height" : 500, "width" : 800, "s_fit" : "TRUE",
                                                    "fixed_asp" : fixed_asp, "rotate" : rotate })
                                )
        print >>sys.stderr, str(timezone.now()) + " Finish Word Cloud Generation: " + word_list
        if response.code == 200:
            return save_url(response.body['url'], 'wordcloud_images')
    return None
Example #25
0
def home(request, survey_type='TEAMTEMP'):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    if request.method == 'POST':
        form = CreateSurveyForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            csf = form.cleaned_data
            form_id = utils.random_string(8)
            userid = responses.get_or_create_userid(request)
            user, created = User.objects.get_or_create(id=userid)
            # TODO check that id is unique!
            team_name = csf['team_name'].replace(" ", "_")
            survey = TeamTemperature(creation_date=timezone.now(),
                                     password=make_password(csf['password']),
                                     creator=user,
                                     survey_type=survey_type,
                                     archive_date=timezone.now(),
                                     id=form_id)
            survey.save()
            team_details = Teams(request=survey, team_name=team_name)
            team_details.save()
            return HttpResponseRedirect('/admin/%s/%s' % (form_id, team_name))
    else:
        form = CreateSurveyForm()
    return render(request, 'index.html', {'form': form})
Example #26
0
def calc_multi_iteration_average(team_name, survey, num_iterations=2,tz='UTC'):
    timezone.activate(pytz.timezone(tz))
    iteration_index = 0
    if num_iterations > 0:
        iteration_index = num_iterations - 1
    else:
        return None
    
    archive_dates = survey.temperatureresponse_set.filter(archive_date__isnull=False).values('archive_date').distinct().order_by('-archive_date')
    
    if archive_dates.count() < num_iterations and archive_dates.count() > 0:
        iteration_index = archive_dates.count() - 1 #oldest archive date if less than target iteration count
    
    if archive_dates.count() > iteration_index:
        response_dates = survey.temperatureresponse_set.filter(archive_date = archive_dates[iteration_index]['archive_date']).values('response_date').order_by('response_date')
        
        if team_name != '':
            accumulated_stats = survey.accumulated_team_stats(team_name,timezone.now(),response_dates[0]['response_date'])
        else:
            accumulated_stats = survey.accumulated_stats(timezone.now(),response_dates[0]['response_date'])
        
        return accumulated_stats
    
    return None
def get_last_five_days(from_date="now", tz=None):
    """
    Get last days returned to you as datetime objects in array
    @params:
        from_date: (date to return consecutive days ongoing from) (optional)
    """
    days = []

    now = datetime.now()
    if not from_date == "now":
        now = timezone.now()

    if not from_date == "now":
        now = from_date

    delta = now - timedelta(5)
    for day in xrange(1,6):
        days.append(delta)
        delta = delta + timedelta(1)
    return days
Example #28
0
def get_last_five_days(from_date="now", tz=None):
    """
    Get last days returned to you as datetime objects in array
    @params:
        from_date: (date to return consecutive days ongoing from) (optional)
    """
    days = []

    now = datetime.now()
    if not from_date == "now":
        now = timezone.now()

    if not from_date == "now":
        now = from_date

    delta = now - timedelta(5)
    for day in xrange(1, 6):
        days.append(delta)
        delta = delta + timedelta(1)
    return days
Example #29
0
    def send_notification(self, notification_send_time, issue_type, client,
                          ticket):
        if ticket.date_added.date() == datetime.date.today():
            now = timezone.now()
            time_diff = now - ticket.date_added
            ticket_notification = self.check_notification_sent(ticket)
            if ticket_notification:

                if time_diff > datetime.timedelta(
                        minutes=notification_send_time
                ) and not ticket_notification.is_txt_sent and not ticket_notification.is_try:
                    ticket_answer = Answer.objects.filter(ticket_id=ticket)

                    if not len(ticket_answer):
                        try:
                            for issue in ISSUE_TYPE:
                                if issue[0] == issue_type:
                                    issue_type = issue[1]

                            for sms in SMS_NUMBERS:
                                message = client.messages.create(
                                    to=sms[1],
                                    from_="Your contact number",
                                    body=
                                    "Hello {0}, {1} from {2} has just opened a {3} on Gluu support:(https://support.gluu.org{4}). "
                                    "Please respond ASAP. "
                                    "Thanks! - Gluu Team".format(
                                        sms[0], ticket.created_by,
                                        ticket.company_association, issue_type,
                                        generate_ticket_link(ticket)))
                                if message.sid:
                                    log_message = 'SMS notification with ticket name:{} sent to staff member: {}'
                                    log_message = log_message.format(
                                        ticket.title, sms[0])
                                    ticket_notification.is_try = 1
                                    ticket_notification.save()
                                    print "sms sent"

                        except Exception as e:
                            pass
Example #30
0
def auto_archive_surveys(request):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    print >> sys.stderr, "auto_archive_surveys: Start at " + str(
        timezone.localtime(timezone.now())) + " EST"

    teamtemps = TeamTemperature.objects.filter(archive_schedule__gt=0)
    nowstamp = timezone.now()
    data = {'archive_date': nowstamp}

    for teamtemp in teamtemps:
        print >> sys.stderr, "auto_archive_surveys: Survey " + teamtemp.id
        print >> sys.stderr, "auto_archive_surveys: Comparing " + str(
            timezone.localtime(timezone.now()).date()) + " >= " + str(
                timezone.localtime(teamtemp.archive_date + timedelta(
                    days=teamtemp.archive_schedule)).date())
        print >> sys.stderr, "auto_archive_surveys: Comparing " + str(
            timezone.localtime(timezone.now())) + " >= " + str(
                timezone.localtime(teamtemp.archive_date +
                                   timedelta(days=teamtemp.archive_schedule)))
        print >> sys.stderr, "auto_archive_surveys: Comparison returns: " + str(
            timezone.localtime(timezone.now()).date() >= timezone.localtime(
                teamtemp.archive_date +
                timedelta(days=teamtemp.archive_schedule)).date())

        if teamtemp.archive_date is None or (
                timezone.localtime(timezone.now()).date() >=
            (timezone.localtime(teamtemp.archive_date + timedelta(
                days=teamtemp.archive_schedule)).date())):
            scheduled_archive(request, teamtemp.id)
            TeamTemperature.objects.filter(pk=teamtemp.id).update(**data)
            print >> sys.stderr, "Archiving: " + " " + teamtemp.id + " at " + str(
                nowstamp) + " UTC " + str(timezone.localtime(
                    timezone.now())) + " EST"

    print >> sys.stderr, "auto_archive_surveys: Stop at " + str(
        timezone.localtime(timezone.now())) + " EST"
Example #31
0
def bvc(request,
        survey_id,
        team_name='',
        archive_id='',
        weeks_to_trend='12',
        num_iterations='0'):
    #Check if *any* scheduled archive surveys are overdue for archiving
    #auto_archive_surveys(request)

    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)

    password = None
    user = None
    num_rows = 0
    json_history_chart_table = None
    historical_options = {}
    stats_date = ''
    survey_teams = []
    ignore_bvc_auth = False

    if settings.IGNORE_BVC_AUTH:
        ignore_bvc_auth = settings.IGNORE_BVC_AUTH

    #Process POST return results from Password Form Submit:
    if request.method == 'POST':
        form = ResultsPasswordForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            rpf = form.cleaned_data
            password = rpf['password'].encode('utf-8')
            if check_password(password, survey.password):
                request.session['userid'] = survey.creator.id

    #Retrieve User Token - if user does not exist present password entry form
    try:
        userid = request.session.get('userid', '__nothing__')
        user = User.objects.get(id=userid)
    except User.DoesNotExist:
        if not ignore_bvc_auth:
            return render(request, 'password.html',
                          {'form': ResultsPasswordForm()})

    #If authenticated via user token or ignoring auth for bvc rendering
    if ignore_bvc_auth or (user and survey.creator.id == user.id):
        survey_type_title = 'Team Temperature'
        if survey.survey_type == 'CUSTOMERFEEDBACK':
            survey_type_title = 'Customer Feedback'

        if not ignore_bvc_auth:
            request.session['userid'] = survey.creator.id
        teamtemp = TeamTemperature.objects.get(pk=survey_id)
        if team_name != '':
            if archive_id == '':
                results = teamtemp.temperatureresponse_set.filter(
                    team_name=team_name, archived=False)
            else:
                past_date = teamtemp.temperatureresponse_set.filter(
                    id=archive_id).values('archive_date')[0]
                results = teamtemp.temperatureresponse_set.filter(
                    team_name=team_name,
                    archived=True,
                    archive_date=past_date['archive_date'])
                stats_date = past_date['archive_date']
            team_history = teamtemp.teamresponsehistory_set.filter(
                team_name=team_name).order_by('archive_date')
            num_rows = teamtemp.teamresponsehistory_set.filter(
                team_name=team_name).count()
            teams = teamtemp.teamresponsehistory_set.filter(
                team_name=team_name).values('team_name').distinct()
            archived_dates = teamtemp.temperatureresponse_set.filter(
                team_name=team_name,
                archived=True).values('archive_date',
                                      'id').distinct('archive_date')
        else:
            if archive_id == '':
                results = teamtemp.temperatureresponse_set.filter(
                    archived=False)
            else:
                past_date = teamtemp.temperatureresponse_set.filter(
                    id=archive_id).values('archive_date')[0]
                results = teamtemp.temperatureresponse_set.filter(
                    archive_date=past_date['archive_date'])
                stats_date = past_date['archive_date']
            team_history = teamtemp.teamresponsehistory_set.all().order_by(
                'archive_date')
            num_rows = teamtemp.teamresponsehistory_set.all().count()
            teams = teamtemp.teamresponsehistory_set.all().values(
                'team_name').distinct()
            archived_dates = teamtemp.temperatureresponse_set.filter(
                archived=True).values('archive_date',
                                      'id').distinct('archive_date')

        trend_period = timedelta(weeks=int(float(weeks_to_trend)))
        buffer_max = timedelta(days=3)
        max_date = timezone.now() + buffer_max
        min_date = max_date - trend_period - buffer_max

        team_index = 0
        if num_rows > 0:
            history_chart_schema = {
                "archive_date": ("datetime", "Archive_Date")
            }
            history_chart_columns = ('archive_date', )
            average_index = None
            for team in teams:
                history_chart_schema.update({
                    team['team_name']:
                    ("number", team['team_name'].replace("_", " "))
                })
                history_chart_columns = history_chart_columns + (
                    team['team_name'], )
                if team['team_name'] == 'Average':
                    average_index = team_index
                team_index += 1

            history_chart_data = []
            row = None
            for survey_summary in team_history:
                if row == None:
                    row = {}
                    row['archive_date'] = timezone.localtime(
                        survey_summary.archive_date)
                elif row['archive_date'] != timezone.localtime(
                        survey_summary.archive_date):
                    history_chart_data.append(row)
                    row = {}
                    row['archive_date'] = timezone.localtime(
                        survey_summary.archive_date)
                row[survey_summary.team_name] = (
                    float(survey_summary.average_score),
                    str(float(survey_summary.average_score)) + " (" +
                    str(survey_summary.responder_count) + " Responses)")

            history_chart_data.append(row)

            # Loading it into gviz_api.DataTable
            history_chart_table = gviz_api.DataTable(history_chart_schema)
            history_chart_table.LoadData(history_chart_data)

            # Creating a JSon string
            json_history_chart_table = history_chart_table.ToJSon(
                columns_order=(history_chart_columns))

            historical_options = {
                'legendPosition': 'newRow',
                'title': survey_type_title + ' by Team',
                'vAxis': {
                    'title': survey_type_title
                },
                'hAxis': {
                    'title': "Month"
                },
                'seriesType': "bars",
                'vAxis': {
                    'ticks': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
                },
                'max': 12,
                'min': 0,
                'focusTarget': 'category',
                'tooltip': {
                    'trigger': 'selection',
                    'isHtml': 'true'
                },
            }
            if average_index != None:
                historical_options.update(
                    {'series': {
                        average_index: {
                            'type': "line"
                        }
                    }})

        if team_name != '' and stats_date == '':
            stats = survey.team_stats(team_name=team_name)
        elif team_name == '' and stats_date != '':
            stats = survey.archive_stats(archive_date=stats_date)
        elif team_name != '' and stats_date != '':
            stats = survey.archive_team_stats(team_name=team_name,
                                              archive_date=stats_date)
        else:
            stats = survey.stats()

        survey_teams = teamtemp.teams_set.all()

        if int(float(num_iterations)) > 0:
            multi_stats = calc_multi_iteration_average(
                team_name, survey, int(float(num_iterations)))
            if multi_stats:
                stats = multi_stats

        #generate word cloud
        words = ""
        word_cloudurl = ""
        word_count = 0
        for word in stats['words']:
            for i in range(0, word['id__count']):
                words = words + word['word'] + " "
                word_count += 1

        #TODO Write a better lookup and model to replace this hack
        word_cloud_index = WordCloudImage.objects.filter(word_list=words)

        if word_cloud_index:
            if os.path.isfile(
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 word_cloud_index[0].image_url)):
                word_cloudurl = word_cloud_index[0].image_url
            else:
                #Files have been deleted remove from db and then regenerate
                WordCloudImage.objects.filter(word_list=words).delete()

        if word_cloudurl == "" and words != "":
            word_cloudurl = generate_wordcloud(words)
            if word_cloudurl:
                word_cloud = WordCloudImage(creation_date=timezone.now(),
                                            word_list=words,
                                            image_url=word_cloudurl)
                word_cloud.save()

        return render(
            request, 'bvc.html', {
                'id': survey_id,
                'stats': stats,
                'results': results,
                'team_name': team_name,
                'archive_date': stats_date,
                'pretty_team_name': team_name.replace("_", " "),
                'team_history': team_history,
                'json_historical_data': json_history_chart_table,
                'min_date': min_date,
                'max_date': max_date,
                'historical_options': historical_options,
                'archived_dates': archived_dates,
                'survey_teams': survey_teams,
                'word_cloudurl': word_cloudurl,
                'num_iterations': num_iterations,
                'team_count': team_index,
                'survey_type_title': survey_type_title
            })
    else:
        return render(request, 'password.html',
                      {'form': ResultsPasswordForm()})
Example #32
0
def reset(request, survey_id):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    # if valid session token or valid password render results page

    if not authenticated_user(request, survey_id):
        return HttpResponseRedirect('/admin/%s' % survey_id)

    teamtemp = TeamTemperature.objects.get(pk=survey_id)

    #Save Survey Summary for all survey teams
    arch_date = timezone.now()
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(
        archived=False).values('team_name').distinct()
    average_total = 0
    average_count = 0
    average_responder_total = 0
    for team in teams:
        Summary = None
        team_stats = None
        summary_word_list = ""
        team_stats = teamtemp.team_stats(team['team_name'])
        for word in team_stats['words']:
            summary_word_list = summary_word_list + word['word'] + " "
        Summary = TeamResponseHistory(
            request=survey,
            average_score=team_stats['average']['score__avg'],
            word_list=summary_word_list,
            responder_count=team_stats['count'],
            team_name=team['team_name'],
            archive_date=arch_date)
        Summary.save()
        average_total = average_total + team_stats['average']['score__avg']
        average_count = average_count + 1
        average_responder_total = average_responder_total + team_stats['count']

        TemperatureResponse.objects.filter(request=survey_id,
                                           team_name=team['team_name'],
                                           archived=False).update(**data)

    #Save Survey Summary as AGREGATE AVERAGE for all teams
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(
        archived=False).values('team_name').distinct()
    Summary = None
    team_stats = None
    summary_word_list = ""
    team_stats = teamtemp.stats()

    if average_count > 0:
        Summary = TeamResponseHistory(request=survey,
                                      average_score=average_total /
                                      float(average_count),
                                      word_list=summary_word_list,
                                      responder_count=average_responder_total,
                                      team_name='Average',
                                      archive_date=arch_date)

    if Summary:
        Summary.save()
        nowstamp = timezone.now()
        data = {'archive_date': nowstamp}
        TeamTemperature.objects.filter(pk=teamtemp.id).update(**data)
        print >> sys.stderr, "Archiving: " + " " + teamtemp.id + " at " + str(
            nowstamp)

    return HttpResponseRedirect('/admin/%s' % survey_id)
Example #33
0
 def was_published_recently(self):
   return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
Example #34
0
def set(request, survey_id):
    thanks = ""
    rows_changed = 0
    survey_teams = []

    if not authenticated_user(request, survey_id):
        return HttpResponseRedirect('/admin/%s' % survey_id)

    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    survey_teams = survey.teams_set.all()

    if request.method == 'POST':
        form = SurveySettingsForm(request.POST, error_class=ErrorBox)
        survey_settings_id = request.POST.get('id', None)
        if form.is_valid():
            srf = form.cleaned_data
            pw = survey.password
            if srf['password'] != '':
                pw = make_password(srf['password'])
                thanks = "Password Updated. "
            if srf['archive_schedule'] != survey.archive_schedule:
                if survey.archive_date == None:
                    survey.archive_date = timezone.now()
                thanks = thanks + "Schedule Updated. "
            if srf['survey_type'] != survey.survey_type:
                thanks = thanks + "Survey Type Updated. "
            if srf['current_team_name'] != '':
                rows_changed = change_team_name(
                    srf['current_team_name'].replace(" ", "_"),
                    srf['new_team_name'].replace(" ", "_"), survey.id)
                print >> sys.stderr, "Team Name Updated: " + " " + str(
                    rows_changed) + " From: " + srf[
                        'current_team_name'] + " To: " + srf['new_team_name']

            survey_settings = TeamTemperature(
                id=survey.id,
                creation_date=survey.creation_date,
                creator=survey.creator,
                password=pw,
                archive_date=survey.archive_date,
                archive_schedule=srf['archive_schedule'],
                survey_type=srf['survey_type'])
            survey_settings.save()
            survey_settings_id = survey_settings.id
            form = SurveySettingsForm(instance=survey_settings)
            if srf['current_team_name'] != '' and srf['new_team_name'] != '':
                thanks = thanks + "Team Name Change Processed: " + str(
                    rows_changed) + " rows updated. "
            if srf['current_team_name'] != '' and srf['new_team_name'] == '':
                thanks = thanks + "Team Name Change Processed: " + str(
                    rows_changed) + " rows deleted. "

    else:
        try:
            previous = TeamTemperature.objects.get(id=survey_id)
            survey_settings_id = previous.id
        except TeamTemperature.DoesNotExist:
            previous = None
            survey_settings_id = None

        form = SurveySettingsForm(instance=previous)
    return render(
        request, 'set.html', {
            'form': form,
            'thanks': thanks,
            'survey_settings_id': survey_settings_id,
            'survey_teams': survey_teams
        })
Example #35
0
def admin(request, survey_id, team_name=''):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    # if valid session token or valid password render results page
    password = None
    user = None
    survey_teams = []
    next_archive_date = timezone.now()

    if request.method == 'POST':
        form = ResultsPasswordForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            rpf = form.cleaned_data
            password = rpf['password'].encode('utf-8')
    else:
        try:
            userid = request.session.get('userid', '__nothing__')
            user = User.objects.get(id=userid)
        except User.DoesNotExist:
            return render(request, 'password.html',
                          {'form': ResultsPasswordForm()})
    if user and survey.creator.id == user.id or check_password(
            password, survey.password):
        request.session['userid'] = survey.creator.id
        teamtemp = TeamTemperature.objects.get(pk=survey_id)
        if team_name != '':
            team_found = teamtemp.teams_set.filter(team_name=team_name).count()
            if team_found == 0:
                TeamDetails = Teams(request=survey, team_name=team_name)
                TeamDetails.save()
            results = teamtemp.temperatureresponse_set.filter(
                team_name=team_name, archived=False)
        else:
            results = teamtemp.temperatureresponse_set.filter(archived=False)

        survey_teams = teamtemp.teams_set.all()

        if team_name != '':
            stats = survey.team_stats(team_name=team_name)
        else:
            stats = survey.stats()

        if survey.archive_schedule > 0:
            next_archive_date = timezone.localtime(
                survey.archive_date) + timedelta(
                    days=(survey.archive_schedule))
            if next_archive_date < timezone.localtime(timezone.now()):
                next_archive_date = timezone.localtime(timezone.now() +
                                                       timedelta(days=1))

        return render(
            request, 'results.html', {
                'id': survey_id,
                'stats': stats,
                'results': results,
                'team_name': team_name,
                'pretty_team_name': team_name.replace("_", " "),
                'survey_teams': survey_teams,
                'archive_schedule': survey.archive_schedule,
                'next_archive_date': next_archive_date.strftime("%A %d %B %Y")
            })
    else:
        return render(request, 'password.html',
                      {'form': ResultsPasswordForm()})
Example #36
0
 def test_movie_future_showtimes(self):
     movie = mommy.make('Movie')
     future_showtimes = mommy.make('Showtime',movie=movie, showing_at=(timezone.now() + datetime.timedelta(days=60)), _quantity=2)
     self.assertNotIn(future_showtimes[0], movie.current_showtimes())
     self.assertNotIn(future_showtimes[1], movie.current_showtimes())
Example #37
0
def transient_detail(request, slug):

    transient = Transient.objects.filter(slug=slug)
    logs = Log.objects.filter(transient=transient[0].id)

    obs = None
    if len(transient) == 1:
        from django.utils import timezone

        transient_obj = transient.first(
        )  # This should throw an exception if more than one or none are returned
        transient_id = transient[0].id

        alt_names = AlternateTransientNames.objects.filter(
            transient__pk=transient_id)

        transient_followup_form = TransientFollowupForm()
        transient_followup_form.fields["classical_resource"].queryset = \
          view_utils.get_authorized_classical_resources(request.user).filter(end_date_valid__gt = timezone.now()-timedelta(days=1)).order_by('telescope__name')
        transient_followup_form.fields[
            "too_resource"].queryset = view_utils.get_authorized_too_resources(
                request.user).filter(
                    end_date_valid__gt=timezone.now() -
                    timedelta(days=1)).order_by('telescope__name')
        transient_followup_form.fields[
            "queued_resource"].queryset = view_utils.get_authorized_queued_resources(
                request.user).filter(
                    end_date_valid__gt=timezone.now() -
                    timedelta(days=1)).order_by('telescope__name')

        transient_observation_task_form = TransientObservationTaskForm()

        # Status update properties
        all_transient_statuses = TransientStatus.objects.all()
        transient_status_follow = TransientStatus.objects.get(name="Following")
        transient_status_watch = TransientStatus.objects.get(name="Watch")
        transient_status_ignore = TransientStatus.objects.get(name="Ignore")
        transient_comment_form = TransientCommentForm()

        # Transient tag
        all_colors = WebAppColor.objects.all()
        all_transient_tags = TransientTag.objects.all()
        assigned_transient_tags = transient_obj.tags.all()

        # GW Candidate?
        gwcand, gwimages = None, None
        for att in assigned_transient_tags:
            if att.name == 'GW Candidate':
                gwcand = GWCandidate.objects.filter(name=transient_obj.name)[0]
                gwimages = GWCandidateImage.objects.filter(
                    gw_candidate__name=gwcand.name)

        # Get associated Observations
        followups = TransientFollowup.objects.filter(
            transient__pk=transient_id)
        if followups:
            for i in range(len(followups)):
                followups[
                    i].observation_set = TransientObservationTask.objects.filter(
                        followup=followups[i].id)

                if followups[i].classical_resource:
                    followups[i].resource = followups[i].classical_resource
                elif followups[i].too_resource:
                    followups[i].resource = followups[i].too_resource
                elif followups[i].queued_resource:
                    followups[i].resource = followups[i].queued_resource
        else:
            followups = None

        hostdata = Host.objects.filter(pk=transient_obj.host_id)
        if hostdata:
            hostphotdata = view_utils.get_recent_phot_for_host(
                request.user, host_id=hostdata[0].id)
            transient_obj.hostdata = hostdata[0]
        else:
            hostphotdata = None

        if hostphotdata: transient_obj.hostphotdata = hostphotdata

        lastphotdata = view_utils.get_recent_phot_for_transient(
            request.user, transient_id=transient_id)
        firstphotdata = view_utils.get_disc_mag_for_transient(
            request.user, transient_id=transient_id)

        # obsnights,tellist = view_utils.getObsNights(transient[0])
        # too_resources = ToOResource.objects.all()
        #
        # for i in range(len(too_resources)):
        #	telescope = too_resources[i].telescope
        #	too_resources[i].telescope_id = telescope.id
        #	observatory = Observatory.objects.get(pk=telescope.observatory_id)
        #	too_resources[i].deltahours = too_resources[i].awarded_too_hours - too_resources[i].used_too_hours
        obsnights = view_utils.get_obs_nights_happening_soon(request.user)
        too_resources = view_utils.get_too_resources(request.user)

        date = datetime.datetime.now(tz=pytz.utc)
        date_format = '%m/%d/%Y %H:%M:%S'

        spectra = SpectraService.GetAuthorizedTransientSpectrum_ByUser_ByTransient(
            request.user, transient_id)

        context = {
            'transient': transient_obj,
            'followups': followups,
            # 'telescope_list': tellist,
            'observing_nights': obsnights,
            'too_resource_list': too_resources,
            'nowtime': date.strftime(date_format),
            'transient_followup_form': transient_followup_form,
            'transient_observation_task_form': transient_observation_task_form,
            'transient_comment_form': transient_comment_form,
            'alt_names': alt_names,
            'all_transient_statuses': all_transient_statuses,
            'transient_status_follow': transient_status_follow,
            'transient_status_watch': transient_status_watch,
            'transient_status_ignore': transient_status_ignore,
            'logs': logs,
            'all_transient_tags': all_transient_tags,
            'assigned_transient_tags': assigned_transient_tags,
            'all_colors': all_colors,
            'all_transient_spectra': spectra,
            'gw_candidate': gwcand,
            'gw_images': gwimages
        }

        if lastphotdata and firstphotdata:
            context['recent_mag'] = lastphotdata.mag
            context['recent_filter'] = lastphotdata.band
            context['recent_magdate'] = lastphotdata.obs_date
            context['first_mag'] = firstphotdata.mag
            context['first_filter'] = firstphotdata.band
            context['first_magdate'] = firstphotdata.obs_date

        return render(request, 'YSE_App/transient_detail.html', context)

    else:
        return Http404('Transient not found')
Example #38
0
 def test_available_movies_in_city(self):
     city = mommy.make('City')
     cinema = mommy.make('Cinema', city=city)
     movie = mommy.make('Movie')
     showtime = mommy.make('Showtime', movie=movie, cinema=cinema, showing_at=(timezone.now()))
     self.assertIn(movie, city.available_movies())
def appointmentView(request, app_id):
    """ Patient Appointment Actions.

    Handles appointment status changing(Booking, Cancellation, Edit, Payment) and validation

    :param incoming request
    :return: seApp:appointmentDone
    :return: seApp:appointmentCancel
    :return: seApp:appointmentEdit
    """
    appointment = get_object_or_404(Appointment, pk=app_id)

    form = ReviewForm()
    app = get_object_or_404(Appointment, pk=app_id)
    form = ReviewForm(instance=app)

    context = {'appointment': appointment, 'app': app, 'form': form}
    if appointment.status == 'Paid':
        if request.method == 'POST':
            doctor = appointment.doctor.user.email
            if 'cancel' in request.POST:
                appointment.status = "Cancelled"
                appointment.save()
                timeslots = appointment.time_slot
                appointment.doctor.time_slots.append(timeslots)
                appointment.doctor.save()
                sendEmail('Appointment Cancelled', doctor, 'appointmentCancel')
                return render(request, 'seApp/appointmentcancelled.html',
                              context)

            if 'edit' in request.POST:
                timeslots = []
                for timeslot in appointment.doctor.time_slots:
                    if ((timeslot - timezone.now()).total_seconds() > 0):
                        timeslots.append(timeslot)
                appointment.doctor.time_slots = timeslots
                appointment.doctor.save()
                appointment.status = "Cancelled"
                appointment.save()
                timeslotadd = appointment.time_slot
                appointment.doctor.time_slots.append(timeslotadd)
                timeslotnew = request.POST['appointment']
                timeslotParsed = parse_datetime(timeslotnew)
                appointment.doctor.time_slots.remove(timeslotParsed)
                appointment.doctor.save()
                appointmentnew = Appointment(patient=appointment.patient,
                                             doctor=appointment.doctor,
                                             status='Pending',
                                             time_slot=timeslotnew,
                                             review='None',
                                             prescription=[])
                appointmentnew.save()
                sendEmail('Appointment Modified', doctor, 'appointmentEdit')
                return render(request, 'seApp/appointmentcancelled.html',
                              context)

        return render(request, 'seApp/appointmentpaid.html', context)

    if appointment.status == 'Pending':

        if request.method == 'POST':
            # body = json.loads(request.body)
            doctor = appointment.doctor.user.email
            if 'cancel' in request.POST:
                appointment.status = "Cancelled"
                appointment.save()
                timeslots = appointment.time_slot
                appointment.doctor.time_slots.append(timeslots)
                appointment.doctor.save()
                sendEmail('Appointment Cancelled', doctor, 'appointmentCancel')
                return render(request, 'seApp/appointmentcancelled.html',
                              context)

            if body['status'] == 'completed':
                appointment.status = 'Paid'
                appointment.save()
                sendEmail('Appointment Modified', doctor, 'appointmentEdit')
                return render(request, 'seApp/appointmentcancelled.html',
                              context)

        return render(request, 'seApp/appointmentcancelled.html', context)

    if (appointment.status == 'Done'):

        if request.method == 'POST':
            if 'submit' in request.POST:
                form = ReviewForm(request.POST, instance=app)
                tempRating = int(request.POST['rate'])
                if app.doctor.rating is None:
                    app.doctor.rating = 5
                if tempRating == 5:
                    rating = app.doctor.rating + 0.2
                elif tempRating == 4:
                    rating = app.doctor.rating + 0.1
                elif tempRating == 2:
                    rating = app.doctor.rating - 0.1
                elif tempRating == 1:
                    rating = app.doctor.rating - 0.2
                else:
                    rating = app.doctor.rating
                app.doctor.rating = 5 if rating > 5 else rating
                app.doctor.save()
                #clinic rating
                totalRating = 0
                noDoctors = 0
                doctors = Doctor.objects.all()
                clinic = app.doctor.clinic
                for doctor in doctors:
                    if doctor.clinic == clinic:
                        totalRating = totalRating + doctor.rating
                        noDoctors += 1
                clinic.rating = (totalRating / noDoctors)
                clinic.save()

                if form.is_valid():
                    form.save()
        return render(request, 'seApp/appointmentdone.html', context)

    else:
        return render(request, 'seApp/appointmentcancelled.html', context)
Example #40
0
def reset(request, survey_id):
    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)
    # if valid session token or valid password render results page

    if not authenticated_user(request, survey_id):
        return HttpResponseRedirect('/admin/%s' % survey_id)

    teamtemp = TeamTemperature.objects.get(pk=survey_id)

    #Save Survey Summary for all survey teams
    arch_date = timezone.now()
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(archived = False).values('team_name').distinct()
    average_total = 0
    average_count = 0
    average_responder_total = 0
    for team in teams:
        Summary = None
        team_stats = None
        summary_word_list = ""
        team_stats = teamtemp.team_stats(team['team_name'])
        for word in team_stats['words'] :
            summary_word_list = summary_word_list + word['word'] + " "
        Summary = TeamResponseHistory(request = survey,
            average_score = team_stats['average']['score__avg'],
            word_list = summary_word_list,
            responder_count = team_stats['count'],
            team_name = team['team_name'],
            archive_date = arch_date)
        Summary.save()
        average_total = average_total + team_stats['average']['score__avg']
        average_count = average_count + 1
        average_responder_total = average_responder_total + team_stats['count']

        TemperatureResponse.objects.filter(request = survey_id, team_name = team['team_name'], archived = False).update(**data)

    #Save Survey Summary as AGREGATE AVERAGE for all teams
    data = {'archived': True, 'archive_date': timezone.now()}
    teams = teamtemp.temperatureresponse_set.filter(archived = False).values('team_name').distinct()
    Summary = None
    team_stats = None
    summary_word_list = ""
    team_stats = teamtemp.stats()
        
    if average_count > 0:
        Summary = TeamResponseHistory(request = survey,
            average_score = average_total/float(average_count),
            word_list = summary_word_list,
            responder_count = average_responder_total,
            team_name = 'Average',
            archive_date = arch_date)

    if Summary:
        Summary.save()
        nowstamp = timezone.now()
        data = {'archive_date': nowstamp}
        TeamTemperature.objects.filter(pk=teamtemp.id).update(**data)
        print >>sys.stderr,"Archiving: " + " " + teamtemp.id + " at " + str(nowstamp)

    return HttpResponseRedirect('/admin/%s' % survey_id)
Example #41
0
def bvc(request, survey_id, team_name='', archive_id= '', weeks_to_trend='12', num_iterations='0'):
    #Check if *any* scheduled archive surveys are overdue for archiving
    #auto_archive_surveys(request)

    timezone.activate(pytz.timezone('Australia/Queensland'))
    survey = get_object_or_404(TeamTemperature, pk=survey_id)

    password = None
    user = None
    num_rows = 0
    json_history_chart_table = None
    historical_options = {}
    stats_date = ''
    survey_teams=[]
    ignore_bvc_auth = False
    
    if settings.IGNORE_BVC_AUTH:
        ignore_bvc_auth = settings.IGNORE_BVC_AUTH

    #Process POST return results from Password Form Submit:
    if request.method == 'POST':
        form = ResultsPasswordForm(request.POST, error_class=ErrorBox)
        if form.is_valid():
            rpf = form.cleaned_data
            password = rpf['password'].encode('utf-8')
            if check_password(password, survey.password):
                request.session['userid'] = survey.creator.id

    #Retrieve User Token - if user does not exist present password entry form
    try:
        userid = request.session.get('userid', '__nothing__')
        user = User.objects.get(id=userid)
    except User.DoesNotExist:
        if not ignore_bvc_auth:
            return render(request, 'password.html', {'form': ResultsPasswordForm()})

    #If authenticated via user token or ignoring auth for bvc rendering
    if ignore_bvc_auth or (user and survey.creator.id == user.id):
        survey_type_title = 'Team Temperature'
        if survey.survey_type == 'CUSTOMERFEEDBACK':
            survey_type_title = 'Customer Feedback'

        if not ignore_bvc_auth:
            request.session['userid'] = survey.creator.id
        teamtemp = TeamTemperature.objects.get(pk=survey_id)
        if team_name != '':
            if archive_id == '':
                results = teamtemp.temperatureresponse_set.filter(team_name = team_name, archived = False)
            else:
                past_date = teamtemp.temperatureresponse_set.filter(id=archive_id).values('archive_date')[0]
                results = teamtemp.temperatureresponse_set.filter(team_name = team_name, archived = True,archive_date=past_date['archive_date'])
                stats_date = past_date['archive_date']
            team_history = teamtemp.teamresponsehistory_set.filter(team_name = team_name).order_by('archive_date')
            num_rows = teamtemp.teamresponsehistory_set.filter(team_name = team_name).count()
            teams = teamtemp.teamresponsehistory_set.filter(team_name = team_name).values('team_name').distinct()
            archived_dates = teamtemp.temperatureresponse_set.filter(team_name = team_name, archived = True).values('archive_date','id').distinct('archive_date')
        else:
            if archive_id == '':
                results = teamtemp.temperatureresponse_set.filter(archived = False)
            else:
                past_date = teamtemp.temperatureresponse_set.filter(id=archive_id).values('archive_date')[0]
                results = teamtemp.temperatureresponse_set.filter( archive_date=past_date['archive_date'] )
                stats_date = past_date['archive_date']
            team_history = teamtemp.teamresponsehistory_set.all().order_by('archive_date')
            num_rows = teamtemp.teamresponsehistory_set.all().count()
            teams = teamtemp.teamresponsehistory_set.all().values('team_name').distinct()
            archived_dates = teamtemp.temperatureresponse_set.filter(archived = True).values('archive_date','id').distinct('archive_date')

        trend_period = timedelta(weeks=int(float(weeks_to_trend)))
        buffer_max = timedelta(days=3)
        max_date = timezone.now() + buffer_max
        min_date = max_date - trend_period - buffer_max

        team_index = 0
        if num_rows > 0:
            history_chart_schema = {"archive_date": ("datetime", "Archive_Date")}
            history_chart_columns = ('archive_date',)
            average_index = None
            for team in teams:
                history_chart_schema.update({team['team_name'] :  ("number",team['team_name'].replace("_", " "))})
                history_chart_columns = history_chart_columns + (team['team_name'],)
                if team['team_name'] == 'Average':
                    average_index = team_index
                team_index += 1
            
            history_chart_data = []
            row = None
            for survey_summary in team_history:
                if row == None:
                    row = {}
                    row['archive_date'] = timezone.localtime(survey_summary.archive_date)
                elif row['archive_date'] != timezone.localtime(survey_summary.archive_date):
                    history_chart_data.append(row)
                    row = {}
                    row['archive_date'] = timezone.localtime(survey_summary.archive_date)
                row[survey_summary.team_name] = (float(survey_summary.average_score), str(float(survey_summary.average_score)) + " (" + str(survey_summary.responder_count) + " Responses)")
    
            history_chart_data.append(row)
    
            # Loading it into gviz_api.DataTable
            history_chart_table = gviz_api.DataTable(history_chart_schema)
            history_chart_table.LoadData(history_chart_data)
            
            # Creating a JSon string
            json_history_chart_table = history_chart_table.ToJSon(columns_order=(history_chart_columns))

            historical_options = {
                'legendPosition': 'newRow',
                'title' : survey_type_title + ' by Team',
                'vAxis': {'title': survey_type_title},
                'hAxis': {'title': "Month"},
                'seriesType': "bars",
                'vAxis': { 'ticks': [1,2,3,4,5,6,7,8,9,10] },
                'max': 12,
                'min': 0,
                'focusTarget': 'category',
                'tooltip': { 'trigger': 'selection', 'isHtml': 'true' },
            }
            if average_index != None:
                historical_options.update({'series': {average_index: {'type': "line"}}})



        if team_name != '' and stats_date == '':
            stats = survey.team_stats(team_name=team_name)
        elif team_name == '' and stats_date != '':
            stats = survey.archive_stats(archive_date=stats_date)
        elif team_name != '' and stats_date != '':
            stats = survey.archive_team_stats(team_name=team_name,archive_date=stats_date)
        else:
            stats = survey.stats()

        survey_teams = teamtemp.teams_set.all()

        if int(float(num_iterations)) > 0:
            multi_stats = calc_multi_iteration_average(team_name, survey, int(float(num_iterations)))
            if multi_stats:
                stats = multi_stats

        #generate word cloud
        words = ""
        word_cloudurl = ""
        word_count = 0
        for word in stats['words']:
            for i in range(0,word['id__count']):
                words = words + word['word'] + " "
                word_count += 1

        #TODO Write a better lookup and model to replace this hack
        word_cloud_index = WordCloudImage.objects.filter(word_list = words)

        if word_cloud_index:
            if os.path.isfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), word_cloud_index[0].image_url)):
                word_cloudurl =  word_cloud_index[0].image_url
            else:
                #Files have been deleted remove from db and then regenerate
                WordCloudImage.objects.filter(word_list = words).delete()

        if word_cloudurl == "" and words != "":
            word_cloudurl = generate_wordcloud(words)
            if word_cloudurl:
                word_cloud = WordCloudImage(creation_date = timezone.now(),
                                            word_list = words, image_url = word_cloudurl)
                word_cloud.save()

        return render(request, 'bvc.html',
                { 'id': survey_id, 'stats': stats, 
                  'results': results, 'team_name':team_name, 'archive_date':stats_date,
                  'pretty_team_name':team_name.replace("_", " "),
                  'team_history' : team_history ,
                  'json_historical_data' : json_history_chart_table, 'min_date' : min_date, 'max_date' : max_date,
                  'historical_options' : historical_options, 'archived_dates': archived_dates,
                  'survey_teams': survey_teams, 'word_cloudurl':word_cloudurl, 'num_iterations':num_iterations,
                  'team_count' : team_index, 'survey_type_title' : survey_type_title
                } )
    else:
        return render(request, 'password.html', {'form': ResultsPasswordForm()})
Example #42
0
class TwitterAPIService:
    """
    Get some tweets from the twitter API.
    Set up tweepy authorization on every instance.
    """
    with open('/home/alan/Code/misc/django-ember/secrets.json') as f:
        keys = json.load(f)
    __CONSUMER_KEY = keys[1]['consumer_key']
    __CONSUMER_SECRET = keys[2]['consumer_secret']
    __ACCESS_TOKEN = keys[3]['access_token']
    __ACCESS_TOKEN_SECRET = keys[4]['access_token_secret']

    __auth = tweepy.OAuthHandler(consumer_key=__CONSUMER_KEY,
                                 consumer_secret=__CONSUMER_SECRET)
    __auth.set_access_token(__ACCESS_TOKEN, __ACCESS_TOKEN_SECRET)
    __api = tweepy.API(__auth)
    __week = timezone.now() - timedelta(days=6)
    __tweets = []

    def get_tweets(self):
        return self.__tweets

    def set_tweets(self):
        """
        Extract and store the tweets.
        If database is not empty, use oldest_tweet to get older tweets.
        If oldest_tweet.date is a week old, get younger tweets.
        """
        query = Tweet.objects.all()
        if list(query):
            oldest_tweet_id = query.aggregate(Min('tweet_id'))['tweet_id__min']
            oldest_tweet = Tweet.objects.get(tweet_id=oldest_tweet_id)
            youngest_tweet_id = query.aggregate(
                Max('tweet_id'))['tweet_id__max']
            if oldest_tweet.tweet_date <= self.__week:
                self.__tweets = self.__api.search(q='#python',
                                                  since_id=youngest_tweet_id,
                                                  count=100)
            else:
                self.__tweets = self.__api.search(q='#python',
                                                  max_id=int(oldest_tweet_id) -
                                                  1,
                                                  count=100)
        else:
            self.__tweets = self.__api.search(q='#python', count=100)
        if self.__tweets:
            self.store_tweets()

    def store_tweets(self):
        if Tweet.objects.all():
            Tweet.objects.filter(tweet_date__lte=self.__week).delete()
        for tweet in self.__tweets:
            try:
                new_tweet = Tweet(tweet_id=tweet.id,
                                  tweet_date=tweet.created_at,
                                  tweet_source=tweet.source,
                                  tweet_favorite_cnt=tweet.favorite_count,
                                  tweet_retweet_cnt=tweet.retweet_count,
                                  tweet_text=tweet.text,
                                  tweet_user=tweet.user)
                new_tweet.save()
            except IntegrityError:
                pass
Example #43
0
def db_update_by_cp():
    except_flag, retval_all_groups, retval_act_sessions = cp.read_all_groups()
    if except_flag == False:
        resp_code = retval_all_groups
        resp_text = retval_act_sessions
        alert = db_alert()
        alert.alert_time = timezone.now()
        alert.alert_type = 'ChargePoint API'
        alert.alert_desc = resp_text
        alert.alert_status = 'Open'
        alert.save()

        # TODO: @Zixiong Wait for dicussion to finish handling exception
        # db_opt_session.objects.all().delete()
        # stations = db_station.objects.all()
        # for station in stations:
        #     station
        return

    print('*' * 100)
    start = time.time()
    for retval_one_group in retval_all_groups:
        for retval_one_station in retval_one_group:
            for retval in retval_one_station['Port']:
                # update properties for station
                station = db_station()
                try:
                    station = db_station.objects.get(
                        station_id=retval_one_station['station_id'],
                        port_number=retval['port_number'])
                except:
                    # print("new station")
                    station.station_id = retval_one_station['station_id']
                    station.port_number = retval['port_number']
                station.group_name = retval_one_station['group_name']
                station.station_load = retval_one_station['station_load']

                # update properties for ports
                station.port_status = retval['port_status']
                station.shed_state = retval['shed_state']
                station.port_load = retval['port_load']
                station.allowed_load = retval['allowed_load']
                station.port_power = retval['port_power']
                station.recent_user = None
                station.port_timestamp = retval['port_timestamp']

                if retval['port_status'] == "INUSE" and retval[
                        'user_id'] is not None:
                    # update user
                    user = db_user()
                    try:
                        user = db_user.objects.get(user_id=retval['user_id'])
                    except:
                        print("new user")
                        user.user_id = retval['user_id']

                    # update recent use for ports
                    user.recent_station_id = retval_one_station['station_id']
                    user.session_id = str(retval['session_id'])
                    user.recent_port_number = retval['port_number']
                    user.timestamp = retval['port_timestamp']
                    user.save()

                    #add foreign user key
                    station.recent_user = user

                station.save()

    db_opt_session.objects.all().delete()
    for retval in retval_act_sessions:
        session = db_opt_session()
        session.session_id = retval['sessionID']
        session.group_name = retval['groupName']
        session.start_time = retval['startTime']
        session.timestamp = retval['timestamp']
        session.energy = retval['energy']
        session.user_id = retval['userID']
        session.save()

    print('Total View Time: ', time.time() - start)