示例#1
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetLCScoreboard, self).get_context_data(**kwargs)
     try:
         office_name = self.kwargs['office_name']
     except KeyError:
         office_name = 'ANDES'
     context['office_name'] = office_name
     office = Office.objects.select_related(
         'superoffice',
         'superoffice__superoffice').get(name=office_name.replace('_', ' '))
     officeID = office.expaID
     context['officeID'] = officeID
     products = []
     for product in Program.objects.all():
         products.append(product.name)
     context['products'] = products
     #Prepara la información respecto a los logros del LC a partir de la información dentro de la base de datos
     achieved = {}
     total = 0
     for logro in LogrosPrograma.objects.filter(office=officeID):
         program = logro.program_id
         achieved[program] = logro
         total += achieved[program].realized
     achieved['total'] = {'realized': total}
     context['achieved'] = achieved
     #Carga de la base de datos los logros planeados
     planned = {}
     total_meta = 0
     for meta in MonthlyGoal.objects.filter(
             office_id=officeID).values('program').annotate(
                 realized=Sum('realized'), approved=Sum('approved')):
         program = meta['program']
         planned[program] = meta
         meta = planned[program]['realized']
         if meta is None:
             meta = 0
         total_meta += meta
     planned['total'] = {'realized': total_meta}
     context['planned'] = planned
     #Agrega los rankings
     rankings = {
         'rankings': {
             'approved': tools.getLCRankings('Total', 'approved',
                                             lc=office),
             'realized': tools.getLCRankings('Total', 'realized', lc=office)
         }
     }
     context.update(rankings)
     return context
示例#2
0
    def get_context_data(self, **kwargs):
        context = super(GetAreaScoreboard, self).get_context_data(**kwargs)
        api = ExpaApi()
        office_name = self.kwargs['office_name']
        context['office_name'] = office_name
        office = Office.objects.select_related('superoffice', 'superoffice__superoffice').get(name=office_name.replace('_', ' '))
        officeID = office.expaID
        program = self.kwargs['programa']
        context['officeID'] = officeID
        context['program'] = program
        #Prepara la información respecto a los logros del LC a partir de la información dentro de la base de datos
        achieved = {}
        for logro in LogrosPrograma.objects.filter(office=officeID, program_id=program):
            achieved = logro
        context['achieved'] = achieved 
        #Carga de la base de datos los logros planeados
        planned = {}
        for meta in MonthlyGoal.objects.filter(office_id=officeID, program_id=program).values('program').annotate(realized=Sum('realized'), approved=Sum('approved')):
            planned = meta
        context['planned'] = planned
        #context['performance'] = api.getProgramWeeklyPerformance(programa)
        #columns = zip(context['performance']['weekly']['MA'], context['performance']['weekly']['RE'])
        #Creates the JSON data to be used by Google Charts
        #chartList = [['Semana', 'Matches', 'Realizaciones']]
        #for index, week in enumerate(columns):
        #    chartList.append(['Semana %i' % index, columns[index][0], columns[index][1]])
        #context['weeklyJSON'] = json.dumps(chartList)
        
        #Finds the top for LATAM and inside own country
        rankings = {
            'rankings': {
                'approved':tools.getLCRankings(program, 'approved', lc=office),
                'realized':tools.getLCRankings(program, 'realized', lc=office),
                }
            }
        context.update(rankings)
        #These analytics are related to the fulfillment of the current monthly goal
        context['planned_monthly'] = MonthlyGoal.objects.filter(office=officeID, program=program.upper()).order_by('year', 'month')
        context['achieved_monthly'] = MonthlyAchievement.objects.filter(office=officeID, program=program.upper()).order_by('month')
        #context['monthly_achievements'] = api.getProgramMonthlyPerformance(programa, 1395)

        if program[0].lower() == 'o': #Specific analytics for OGX
            #Context data for total uncontacted EPs
            try:
                context['uncontacted'] = api.getUncontactedEPs(officeID)['total']
            except ValueError as e:
                print e #TODO: Logging?
                context['uncontacted'] = "EXPA Error"
            #Context data for Weekly registered/contacted and contacted/interviewed analytics
            try:
                weekRegisteredEPs = api.getWeekRegistered(officeID)
                weekRegisteredContacted = 0.0
                for ep in weekRegisteredEPs['eps']:
                    if ep['contacted_at']:
                        weekRegisteredContacted += 1
                try:
                    contacted_rate = weekRegisteredContacted/weekRegisteredEPs['total']
                except ZeroDivisionError:
                    contacted_rate = 0
                context['weekRegisteredAnalytics'] = {
                    'total':weekRegisteredEPs['total'],
                    'nContacted':weekRegisteredContacted,
                    'rate':contacted_rate*100,
                    'gap':weekRegisteredContacted - weekRegisteredEPs['total']
                }
            except ValueError as e:
                context['weekRegisteredAnalytics'] = {
                    'total':'EXPA Error',
                    'nContacted':'EXPA Error',
                    'rate':'EXPA Error',
                    'gap':'EXPA Error',
                }
 
            try:
                weekContactedEPs = api.getWeekContacted(officeID)
                weekContactedInterviewed = 0.0
                for ep in weekContactedEPs['eps']:
                    if ep['interviewed']:
                        weekContactedInterviewed += 1
                try:
                    interviewed_rate = weekContactedInterviewed/weekContactedEPs['total']
                except ZeroDivisionError:
                    interviewed_rate = 0
                context['weekContactedAnalytics'] = {
                    'total':weekContactedEPs['total'],
                    'nContacted':weekContactedInterviewed,
                    'rate':interviewed_rate*100,
                    'gap':weekContactedInterviewed - weekContactedEPs['total']
                }
            except ValueError as e:#TODO: Mover a la EXPA API
                context['weekContactedAnalytics'] = {
                    'total':'EXPA Error',
                    'nContacted':'EXPA Error',
                    'rate':'EXPA Error',
                    'gap':'EXPA Error',
                }

        else:
            print program[0]
        return context
示例#3
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetColombianEBs, self).get_context_data(**kwargs)
     context['lcs'] = api.getColombiaContactList()
     return context
示例#4
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetLCWeeklyGoals, self).get_context_data(**kwargs)
     context['performance'] = api.getLCWeeklyPerformance()
     return context
示例#5
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetAndesYearlyPerformance, self).get_context_data(**kwargs)
     context['programs'] = api.getLCYearlyPerformance(2015)
     return context
示例#6
0
    def get_context_data(self, **kwargs):
        context = super(GetBangladeshScoreboard, self).get_context_data(**kwargs)
        api = ExpaApi('*****@*****.**')
        office_id = 2010
        context['office_id'] = office_id
        office = Office.objects.select_related('superoffice').get(expaID=office_id)
        office_name = office.name
        program = 'ogv'
        context['office_name'] = office_name
        context['program'] = program
        #Prepara la información respecto a los logros del LC a partir de la información dentro de la base de datos
        achieved = {}
        
        #TODO: En esta parte voy a crear el diccionario para el scoreboard del MC de una manera super folclórica, pero con el objetivo de mejorar más tade obviamente
        year_metrics = [] #Here I will save all metrics in a format understandable by the scoreboard
        measurements = ['applicants', 'accepted', 'realized', 'completed']
        logros = api.getCurrentMCYearStats('ogv', office_id)
        planned = {
            'applicants': 785, 
            'accepted': 314,
            'approved': 157,
            'realized': 125,
            'completed': 100,

        }
        for measurement in measurements:
            measurement_data = {
                'planned': planned[measurement],
                'executed': logros[measurement],
                'gap': planned[measurement] - logros[measurement],
                'name': measurement,
            }
            year_metrics.append(measurement_data)
        context['year_metrics'] = year_metrics
        wig_measure = 'approved'
        wig = {
            'planned': planned[wig_measure],
            'executed': logros[wig_measure],
            'gap': planned[wig_measure] - logros[wig_measure],
            'name': wig_measure,
        }
        context['wig'] = wig
        context['finance'] = {
            'planned':500000,
            'executed':300000,
        }


        quarter_achievements = api.get_stats(office_id, program, '2018-04-01', datetime.now().strftime('%Y-%m-%d'))
        context['quarter_execution'] = quarter_achievements
        context['month_execution'] = quarter_achievements
        #context['achieved_last_week'] = api.get_past_stats(7, program, office_id)
        context['countdown'] = (datetime.strptime('2018-08-01', '%Y-%m-%d') - datetime.now()).days
        
        #TM scoreboard: See how many members are on each stage of performance
        vd_api = PodioApi(19600457)
        individual_performance = {}
        approvals = vd_api.get_filtered_items({
            157141796:{'from':'2018-04-01'}
        })
        for customer in approvals:
            ep_manager = customer['values'][157144216]['value']['name']            
            if ep_manager in individual_performance:
                individual_performance[ep_manager] += 1
            else:
                individual_performance[ep_manager] = 1

        aggregation = {
            '1':0,
            '2':0,
            '3':0,
            '4':0,
        }
        for manager, approvals in individual_performance.items():
            if approvals == 1:
                aggregation['1'] += 1
            elif approvals == 2:
                aggregation['2'] += 2
            elif approvals == 3:
                aggregation['3'] += 3
            elif approvals >= 4:
                aggregation['4'] += 4

        context['tm_performance'] = aggregation



        return context
示例#7
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetIndex, self).get_context_data(**kwargs)
     context['lcs'] = Office.objects.filter(superoffice_id=1551).order_by('name')
     return context
示例#8
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetLCWeeklyGoals, self).get_context_data(**kwargs)
     context['performance'] = api.getLCWeeklyPerformance()
     return context
示例#9
0
    def get_context_data(self, **kwargs):
        context = super(GetTeamsScoreboard, self).get_context_data(**kwargs)
        api = ExpaApi('*****@*****.**')
        office_id = 2010
        context['office_id'] = office_id
        office = Office.objects.select_related('superoffice').get(expaID=office_id)
        office_name = office.name
        program = 'ogv'
        context['office_name'] = office_name
        context['program'] = program
        #Prepara la información respecto a los logros del LC a partir de la información dentro de la base de datos
        achieved = {}
        
        #TODO: En esta parte voy a crear el diccionario para el scoreboard del MC de una manera super folclórica, pero con el objetivo de mejorar más tade obviamente
        year_metrics = [] #Here I will save all metrics in a format understandable by the scoreboard
        year_metrics_dict={}
        measurements = ['applicants', 'accepted', 'realized', 'completed']
        logros = api.get_stats(office_id, 'ogv', '2018-04-01')
        planned = {
            'applicants': 500, 
            'accepted': 200,
            'approved': 100,
            'realized': 90,
            'completed': 82,

        }
        team_planned = {
            'applicants': 125, 
            'accepted': 50,
            'approved': 25,
            'realized': 23,
            'completed': 21,

        }
        for measurement in measurements:
            measurement_data = {
                'planned': planned[measurement],
                'executed': logros[measurement],
                'gap': planned[measurement] - logros[measurement],
                'name': measurement,
            }
            year_metrics.append(measurement_data)
            year_metrics_dict[measurement] = measurement_data
        context['year_metrics'] = year_metrics
        wig_measure = 'approved'
        wig = {
            'planned': planned[wig_measure],
            'executed': logros[wig_measure],
            'gap': planned[wig_measure] - logros[wig_measure],
            'name': wig_measure,
        }
        context['wig'] = wig
        all_metrics = {'all': year_metrics_dict}
        all_metrics['all'][wig_measure] = wig


        quarter_achievements = api.get_stats(office_id, program, '2018-04-01', datetime.now().strftime('%Y-%m-%d'))
        context['quarter_execution'] = quarter_achievements
        context['month_execution'] = quarter_achievements
        #context['achieved_last_week'] = api.get_past_stats(7, program, office_id)
        context['countdown'] = (datetime.strptime('2018-08-01', '%Y-%m-%d') - datetime.now()).days

        cons_api = PodioApi(19156174)
        vd_api = PodioApi(19156174)
        team_leaders = Member.objects.filter(is_active=True).order_by('-extra_points')
        context['teams'] = team_leaders
        performance = {}
        for team_leader in team_leaders:
            performance[team_leader.podio_id] = {
                'applicants': 0,
                'accepted': 0,
                'approved': 0,
                'realized': 0,
                'completed': 0,
            }
            
        recent_items = cons_api.get_items_by_view(37897730)
        start_date = '2018-04-01'
        for item in recent_items:
            if 151795765 not in item['values']:
                continue
            tl_id = item['values'][151795765]['value']['user_id']
            if tl_id in performance:
                if 151950042 in item['values']:
                    registration_date =  item['values'][151950042]['value']['start_date']
                status = item['values'][151795769]['value']
                status_number = status.split(' - ')[0]
                if status_number != 0: #if uncontacted, ignores everything
                    if 159724899 in item['values']:
                        contacted_date = item['values'][159724899]['value']['start_date']
                        if contacted_date >= start_date:
                            pass
                    #        performance[tl_id]['contacted'] += 1
                    if 158519539 in item['values']:
                        application_date = item['values'][158519539]['value']['start_date']
                        if application_date >= start_date:
                            performance[tl_id]['applicants'] += 1
                    if 169759824 in item['values']:
                        acceptance_date = item['values'][169759824]['value']['start_date']
                        if acceptance_date >= start_date:
                            performance[tl_id]['accepted'] += 1
                    if 159728809 in item['values']:
                        approval_date = item['values'][159728809]['value']['start_date']
                        if approval_date >= start_date:
                            performance[tl_id]['approved'] += 1
        team_performance = {}
        measurements.append(wig_measure)
        for tl in team_leaders:
            data = {}
            for measurement in measurements:
                measurement_data = {
                    'planned': team_planned[measurement],
                    'executed': performance[tl.podio_id][measurement],
                    'gap': team_planned[measurement] - performance[tl.podio_id][measurement]
                }
                data[measurement] = measurement_data
            team_performance[tl.podio_id] = data

        all_metrics.update(team_performance)
        context['metrics_json'] = json.dumps(all_metrics)
            
        return context
示例#10
0
    def get_context_data(self, **kwargs):
        context = super(GetAreaScoreboard, self).get_context_data(**kwargs)
        api = ExpaApi(account='*****@*****.**')
        office_name = self.kwargs['office_name']
        context['office_name'] = office_name
        office = Office.objects.select_related(
            'superoffice',
            'superoffice__superoffice').get(name=office_name.replace('_', ' '))
        officeID = office.expaID
        program = self.kwargs['programa']
        context['officeID'] = officeID
        context['program'] = program
        #Prepara la información respecto a los logros del LC a partir de la información dentro de la base de datos
        achieved = {}
        for logro in LogrosPrograma.objects.filter(office=officeID,
                                                   program_id=program):
            achieved = logro
        context['achieved'] = achieved
        #Carga de la base de datos los logros planeados
        planned = {}
        for meta in MonthlyGoal.objects.filter(
                office_id=officeID,
                program_id=program).values('program').annotate(
                    realized=Sum('realized'), approved=Sum('approved')):
            planned = meta
        context['planned'] = planned
        #context['performance'] = api.getProgramWeeklyPerformance(programa)
        #columns = zip(context['performance']['weekly']['MA'], context['performance']['weekly']['RE'])
        #Creates the JSON data to be used by Google Charts
        #chartList = [['Semana', 'Matches', 'Realizaciones']]
        #for index, week in enumerate(columns):
        #    chartList.append(['Semana %i' % index, columns[index][0], columns[index][1]])
        #context['weeklyJSON'] = json.dumps(chartList)

        #Finds the top for LATAM and inside own country
        rankings = {
            'rankings': {
                'approved': tools.getLCRankings(program, 'approved',
                                                lc=office),
                'realized': tools.getLCRankings(program, 'realized',
                                                lc=office),
            }
        }
        context.update(rankings)
        #These analytics are related to the fulfillment of the current monthly goal
        context['planned_monthly'] = MonthlyGoal.objects.filter(
            office=officeID,
            program=program.upper()).order_by('year', 'month')
        context['achieved_monthly'] = MonthlyAchievement.objects.filter(
            office=officeID, program=program.upper()).order_by('month')
        #This data is related to the planned and achieved goals during the current month
        current_month = {}
        current_month_number, current_year_number = map(
            int,
            datetime.now().strftime("%m,%Y").split(','))
        try:
            current_month['planned'] = MonthlyGoal.objects.get(
                office=officeID,
                program=program.upper(),
                month=current_month_number)
        except MonthlyGoal.DoesNotExist:
            current_month['planned'] = "Falta llenar metas en PODIO"
        current_month['achieved'] = api.getMonthStats(current_month_number,
                                                      current_year_number,
                                                      program.upper(),
                                                      officeID)
        context['current_month'] = current_month
        #context['monthly_achievements'] = api.getProgramMonthlyPerformance(programa, 1395)
        #These analytics are related to the achievements durint a past period of time
        context['achieved_past_week'] = api.get_past_stats(
            7, program, officeID)

        if program[0].lower() == 'o':  #Specific analytics for OGX
            #Context data for total uncontacted EPs
            try:
                context['uncontacted'] = api.getUncontactedEPs(
                    officeID)['total']
            except APIUnavailableException as e:
                print e  #TODO: Logging?
                context['uncontacted'] = "EXPA Error"
            #Context data for Weekly registered/contacted and contacted/interviewed analytics
            try:
                weekRegisteredEPs = api.getWeekRegistered(officeID)
                weekRegisteredContacted = 0.0
                for ep in weekRegisteredEPs['eps']:
                    if ep['contacted_at']:
                        weekRegisteredContacted += 1
                try:
                    contacted_rate = weekRegisteredContacted / weekRegisteredEPs[
                        'total']
                except ZeroDivisionError:
                    contacted_rate = 0
                context['weekRegisteredAnalytics'] = {
                    'total': weekRegisteredEPs['total'],
                    'nContacted': weekRegisteredContacted,
                    'rate': contacted_rate * 100,
                    'gap': weekRegisteredContacted - weekRegisteredEPs['total']
                }
            except APIUnavailableException as e:
                context['weekRegisteredAnalytics'] = {
                    'total': 'EXPA Error',
                    'nContacted': 'EXPA Error',
                    'rate': 'EXPA Error',
                    'gap': 'EXPA Error',
                }

            try:
                weekContactedEPs = api.getWeekContacted(officeID)
                weekContactedInterviewed = 0.0
                for ep in weekContactedEPs['eps']:
                    if ep['interviewed']:
                        weekContactedInterviewed += 1
                try:
                    interviewed_rate = weekContactedInterviewed / weekContactedEPs[
                        'total']
                except ZeroDivisionError:
                    interviewed_rate = 0
                context['weekContactedAnalytics'] = {
                    'total': weekContactedEPs['total'],
                    'nContacted': weekContactedInterviewed,
                    'rate': interviewed_rate * 100,
                    'gap': weekContactedInterviewed - weekContactedEPs['total']
                }
            except APIUnavailableException as e:  #TODO: Mover a la EXPA API
                context['weekContactedAnalytics'] = {
                    'total': 'EXPA Error',
                    'nContacted': 'EXPA Error',
                    'rate': 'EXPA Error',
                    'gap': 'EXPA Error',
                }

        else:
            print program[0]
        return context
示例#11
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetColombianEBs, self).get_context_data(**kwargs)
     context['lcs'] = api.getColombiaContactList()
     return context
示例#12
0
 def get_context_data(self, **kwargs):
     api = ExpaApi()
     context = super(GetAndesYearlyPerformance,
                     self).get_context_data(**kwargs)
     context['programs'] = api.getLCYearlyPerformance(2015)
     return context