Exemple #1
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = WorkflowLevel1.objects.all().filter(
            country__in=countries).distinct()
        getIndicators = Indicator.objects.all().filter(
            workflowlevel1__country__in=countries).exclude(
                collecteddata__isnull=True).order_by("-number")
        getIndicatorTypes = IndicatorType.objects.all()
        workflowlevel1 = self.kwargs['workflowlevel1']
        indicator = self.kwargs['indicator']
        type = self.kwargs['type']
        indicator_name = ""
        type_name = ""
        workflowlevel1_name = ""

        q = {'id__isnull': False}
        # if we have a workflowlevel1 filter active
        if int(workflowlevel1) != 0:
            q = {
                'id': workflowlevel1,
            }
            # redress the indicator list based on workflowlevel1
            getIndicators = Indicator.objects.select_related().filter(
                workflowlevel1=workflowlevel1)
            workflowlevel1_name = WorkflowLevel1.objects.get(id=workflowlevel1)
        # if we have an indicator type active
        if int(type) != 0:
            r = {
                'indicator__indicator_type__id': type,
            }
            q.update(r)
            # redress the indicator list based on type
            getIndicators = Indicator.objects.select_related().filter(
                indicator_type__id=type)
            type_name = IndicatorType.objects.get(id=type).indicator_type
        # if we have an indicator id append it to the query filter
        if int(indicator) != 0:
            s = {
                'indicator': indicator,
            }
            q.update(s)
            indicator_name = Indicator.objects.get(id=indicator)

        indicators = WorkflowLevel1.objects.all().filter(
            country__in=countries).filter(**q).order_by('name').annotate(
                indicator_count=Count('indicator'))
        return render(
            request, self.template_name, {
                'getPrograms': getPrograms,
                'getIndicators': getIndicators,
                'workflowlevel1_name': workflowlevel1_name,
                'indicator_name': indicator_name,
                'type_name': type_name,
                'workflowlevel1': workflowlevel1,
                'indicator': indicator,
                'type': type,
                'getProgramsIndicator': indicators,
                'getIndicatorTypes': getIndicatorTypes
            })
Exemple #2
0
def RRIMAPublicDashboard(request,id=0):

    ## retrieve program
    model = Program
    program_id = id
    getProgram = Program.objects.all().filter(id=program_id)


    ## retrieve the coutries the user has data access for
    countries = getCountry(request.user)

    #retrieve projects for a program
    getProjects = ProjectAgreement.objects.all()##.filter(program__id=1, program__country__in=1)

    pageText = {}
    pageText['pageTitle'] = "Refugee Response and Migration News"
    pageText['projectSummary'] = {}

    pageNews = JupyterNotebooks.objects.all().filter(very_custom_dashboard="RRIMA")

    pageMap = [{"latitude":39.9334, "longitude":32.8597, "location_name":"Ankara","site_contact":"Sonal Shinde, Migration Response Director, [email protected]", "site_description":"Migration Response Coordination","region_name":"Turkey"},
        {"latitude":38.4237, "longitude":27.1428, "location_name":"Izmir","site_contact":"Tracy Lucas, Emergency Program Manager, ECHO Aegean Response, [email protected]", "site_description":"Cash, Information Dissemination, Youth, Protection", "region_name":"Turkey"},
        {"latitude":37.0660, "longitude":37.3781, "location_name":"Gaziantep","site_contact":"Jihane Nami, Director of Programs Turkey, [email protected]", "site_description":"Cash, NFI, Shelter, Protection, Information Dissemination","region_name":"Turkey"},
        {"latitude":39.2645, "longitude":26.2777, "location_name":"Lesvos", "site_contact":"Chiara Bogoni, Island Emergency Program Manager, [email protected]", "site_description":"Cash, Youth Programs, Food","region_link":"Greece"},
        {"latitude":37.9838, "longitude":23.7275, "location_name":"Athens", "site_contact":"Josh Kreger, Team Leader - Greece, [email protected] and Kaja Wislinska, Team Leader - Athens and Mainland, [email protected]","site_description":"Cash, Youth Psychosocial Support, Legal Support","region_link":"Greece","region_link":"Greece"},
        {"latitude":44.7866, "longitude":20.4489, "location_name":"Belgrade","site_contact":"Radovan Jovanovic, Team Leader - Balkans, [email protected]","site_description":"SIM Card Distribution, Information Dissemination","region_name":"Balkans"}]
   # Borrowed data for bar graph
    colorPalettes = {
    'bright':['#82BC00','#C8C500','#10A400','#CF102E','#DB5E11','#A40D7A','#00AFA8','#1349BB','#FFD200 ','#FF7100','#FFFD00','#ABABAB','#7F7F7F','#7B5213','#C18A34'],
    'light':['#BAEE46','#FDFB4A','#4BCF3D','#F2637A','#FFA268','#C451A4','#4BC3BE','#5B7FCC','#9F54CC','#FFE464','#FFA964','#FFFE64','#D7D7D7','#7F7F7F','#D2A868','#FFD592']
    };

    return render(request, 'customdashboard/rrima_dashboard.html', 
        {'pageText': pageText, 'pageNews': pageNews, 'pageMap': pageMap, 'countries': countries }) 
Exemple #3
0
def indicator_report(request, program=0, indicator=0, type=0):
    """
    This is the indicator library report.  List of all indicators across a country or countries filtered by
    program.  Lives in the "Report" navigation.
    URL: indicators/report/0/
    :param request:
    :param program:
    :return:
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(
        funding_status="Funded", country__in=countries).distinct()

    getIndicators = []

    if program != 0:
        getIndicators = Indicator.objects.filter(program__id=program)

    getIndicatorTypes = IndicatorType.objects.all()

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(
        request, "indicators/report.html", {
            'program': program,
            'getPrograms': getPrograms,
            'form': FilterForm(),
            'helper': FilterForm.helper,
            'getIndicatorTypes': getIndicatorTypes,
            'getIndicators': getIndicators
        })
Exemple #4
0
    def get(self, request, program, type, id):
        q = {'program__id__isnull': False}
        # if we have a program filter active
        if int(program) != 0:
            q = {
                'program__id': program,
            }
        # if we have an indicator type active
        if int(type) != 0:
            r = {
                'indicator_type__id': type,
            }
            q.update(r)
        # if we have an indicator id append it to the query filter
        if int(id) != 0:
            s = {
                'id': id,
            }
            q.update(s)

        countries = getCountry(request.user)
        indicator = Indicator.objects.all().filter(
            program__country__in=countries).filter(**q).values(
                'id',
                'program__name',
                'baseline',
                'level__name',
                'lop_target',
                'program__id',
                'external_service_record__external_service__name',
                'key_performance_indicator',
                'name',
                'indicator_type__indicator_type',
                'sector__sector',
            )
        indicator_count = Indicator.objects.all().filter(
            program__country__in=countries).filter(**q).filter(
                collecteddata__isnull=True).count()
        indicator_data_count = Indicator.objects.all().filter(
            program__country__in=countries).filter(**q).filter(
                collecteddata__isnull=False).count()

        indicator_serialized = json.dumps(list(indicator))

        final_dict = {
            'indicator': indicator_serialized,
            'indicator_count': indicator_count,
            'data_count': indicator_data_count
        }

        if request.GET.get('export'):
            indicator_export = Indicator.objects.all().filter(**q)
            dataset = IndicatorResource().export(indicator_export)
            response = HttpResponse(dataset.csv,
                                    content_type='application/ms-excel')
            response[
                'Content-Disposition'] = 'attachment; filename=indicator_data.csv'
            return response

        return JsonResponse(final_dict, safe=False)
Exemple #5
0
def programIndicatorReport(request, program=0):
    """
    Show LIST of indicators with a filtered search view using django-tables2
    and django-filter
    """
    program = int(program)
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
    getIndicators = Indicator.objects.all().filter(program__id=program).select_related().order_by('level', 'number')
    getProgram = Program.objects.get(id=program)

    if request.method == "GET" and "search" in request.GET:
        #list1 = list()
        #for obj in filtered:
        #    list1.append(obj)
        """
         fields = (indicator_type, name, number, source, definition, disaggregation, baseline, lop_target, means_of_verification, data_collection_method, responsible_person,
                    method_of_analysis, information_use, reporting_frequency, comments, program, sector, approved_by, approval_submitted_by, create_date, edit_date)
        """
        getIndicators = Indicator.objects.all().filter(
                                           Q(indicator_type__icontains=request.GET["search"]) |
                                           Q(name__icontains=request.GET["search"]) |
                                           Q(number__icontains=request.GET["search"]) |
                                           Q(definition__startswith=request.GET["search"])
                                          ).filter(program__id=program).select_related().order_by('level','number')


    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(request, "indicators/grid_report.html", {'getIndicators': getIndicators, 'getPrograms': getPrograms, 'getProgram': getProgram, 'form': FilterForm(), 'helper': FilterForm.helper})
Exemple #6
0
 def get_queryset(self):
     user_countries = getCountry(self.request.user)
     queryset = TolaTable.objects.filter(country__in=user_countries)
     table_id = self.request.query_params.get('table_id', None)
     if table_id is not None:
         queryset = queryset.filter(table_id=table_id)
     return queryset
Exemple #7
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        countries = getCountry(request.user)
        if program_id == 0:
            getDistribution = Distribution.objects.all().filter(
                program__country__in=countries).values('id',
                                                       'distribution_name',
                                                       'create_date',
                                                       'program')
        elif program_id != 0 and project_id == 0:
            getDistribution = Distribution.objects.all().filter(
                program_id=program_id).values('id', 'distribution_name',
                                              'create_date', 'program')
        else:
            getDistribution = Distribution.objects.all().filter(
                program_id=program_id,
                initiation_id=project_id).values('id', 'distribution_name',
                                                 'create_date', 'program')

        getDistribution = json.dumps(list(getDistribution),
                                     cls=DjangoJSONEncoder)

        final_dict = {'getDistribution': getDistribution}

        return JsonResponse(final_dict, safe=False)
Exemple #8
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        countries = getCountry(request.user)

        if program_id == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(
                Q(training__program__country__in=countries)
                | Q(distribution__program__country__in=countries)).values(
                    'id', 'beneficiary_name', 'create_date')
        elif program_id != 0 and project_id == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(
                program__id=program_id).values('id', 'beneficiary_name',
                                               'create_date')
        else:
            getBeneficiaries = Beneficiary.objects.all().filter(
                program__id=program_id,
                training__project_agreement=project_id).values(
                    'id', 'beneficiary_name', 'create_date')

        getBeneficiaries = json.dumps(list(getBeneficiaries),
                                      cls=DjangoJSONEncoder)

        final_dict = {'getBeneficiaries': getBeneficiaries}

        return JsonResponse(final_dict, safe=False)
Exemple #9
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        print project_id
        countries = getCountry(request.user)
        if int(self.kwargs['program']) == 0:
            getTraining = TrainingAttendance.objects.all().filter(
                program__country__in=countries).values(
                    'id', 'create_date', 'training_name',
                    'project_agreement__project_name')
        elif program_id != 0 and project_id == 0:
            getTraining = TrainingAttendance.objects.all().filter(
                program=program_id).values('id', 'create_date',
                                           'training_name',
                                           'project_agreement__project_name')
        else:
            getTraining = TrainingAttendance.objects.all().filter(
                program_id=program_id, project_agreement_id=project_id).values(
                    'id', 'create_date', 'training_name',
                    'project_agreement__project_name')

        getTraining = json.dumps(list(getTraining), cls=DjangoJSONEncoder)

        final_dict = {'getTraining': getTraining}

        return JsonResponse(final_dict, safe=False)
Exemple #10
0
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.request = kwargs.pop('request')
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),

                'name', 'url', Field('description', rows="3", css_class='input-xlarge'),'file_field',
                'project','program',

            FormActions(
                Submit('submit', 'Save', css_class='btn-default'),
                Reset('reset', 'Reset', css_class='btn-warning')
            )
        )

        super(DocumentationForm, self).__init__(*args, **kwargs)

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['project'].queryset = ProjectAgreement.objects.filter(program__country__in=countries)
        self.fields['program'].queryset = Program.objects.filter(country__in=countries)
Exemple #11
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(
            funding_status="Funded", country__in=countries).distinct()
        getIndicators = Indicator.objects.all().filter(
            program__country__in=countries).exclude(collecteddata__isnull=True)
        getIndicatorTypes = IndicatorType.objects.all()
        program = self.kwargs['program']
        indicator = self.kwargs['indicator']
        type = self.kwargs['type']
        indicator_name = ""
        type_name = ""
        program_name = ""

        q = {'id__isnull': False}
        # if we have a program filter active
        if int(program) != 0:
            q = {
                'id': program,
            }
            # redress the indicator list based on program
            getIndicators = Indicator.objects.select_related().filter(
                program=program)
            program_name = Program.objects.get(id=program)
        # if we have an indicator type active
        if int(type) != 0:
            r = {
                'indicator__indicator_type__id': type,
            }
            q.update(r)
            # redress the indicator list based on type
            getIndicators = Indicator.objects.select_related().filter(
                indicator_type__id=type)
            type_name = IndicatorType.objects.get(id=type).indicator_type
        # if we have an indicator id append it to the query filter
        if int(indicator) != 0:
            s = {
                'indicator': indicator,
            }
            q.update(s)
            indicator_name = Indicator.objects.get(id=indicator)

        indicators = Program.objects.all().filter(
            funding_status="Funded",
            country__in=countries).filter(**q).order_by('name').annotate(
                indicator_count=Count('indicator'))
        return render(
            request, self.template_name, {
                'getPrograms': getPrograms,
                'getIndicators': getIndicators,
                'program_name': program_name,
                'indicator_name': indicator_name,
                'type_name': type_name,
                'program': program,
                'indicator': indicator,
                'type': type,
                'getProgramsIndicator': indicators,
                'getIndicatorTypes': getIndicatorTypes
            })
Exemple #12
0
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.request = kwargs.pop('request')
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.layout = Layout(

            HTML("""<br/>"""),

                'name', 'url', Field('description', rows="3", css_class='input-xlarge'),'file_field',
                'project','program',

            FormActions(
                Submit('submit', 'Save', css_class='btn-default'),
                Reset('reset', 'Reset', css_class='btn-warning')
            )
        )

        super(DocumentationForm, self).__init__(*args, **kwargs)

        #override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        self.fields['project'].queryset = ProjectAgreement.objects.filter(program__country__in=countries)
        self.fields['program'].queryset = Program.objects.filter(country__in=countries)
Exemple #13
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        program = kwargs['program']
        indicator = kwargs['indicator']
        type = kwargs['type']

        q = {'program__id__isnull': False}
        # if we have a program filter active
        if int(program) != 0:
            q = {
                'indicator__program__id': program,
            }
        # if we have an indicator type active
        if int(type) != 0:
            r = {
                'indicator__indicator_type__id': type,
            }
            q.update(r)
        # if we have an indicator id append it to the query filter
        if int(indicator) != 0:
            s = {
                'indicator__id': indicator,
            }
            q.update(s)

        getCollectedData = CollectedData.objects.all().prefetch_related(
            'evidence', 'indicator', 'program', 'indicator__objectives',
            'indicator__strategic_objectives'
        ).filter(program__country__in=countries).filter(**q).order_by(
            'indicator__program__name', 'indicator__number').values(
                'id', 'indicator__id', 'indicator__name',
                'indicator__program__name',
                'indicator__indicator_type__indicator_type',
                'indicator__level__name', 'indicator__sector__sector',
                'date_collected', 'indicator__baseline',
                'indicator__lop_target',
                'indicator__key_performance_indicator',
                'indicator__external_service_record__external_service__name',
                'evidence', 'tola_table', 'targeted', 'achieved')

        #getCollectedData = {x['id']:x for x in getCollectedData}.values()

        collected_sum = CollectedData.objects.filter(
            program__country__in=countries).filter(**q).aggregate(
                Sum('targeted'), Sum('achieved'))

        # datetime encoding breaks without using this
        from django.core.serializers.json import DjangoJSONEncoder
        collected_serialized = json.dumps(list(getCollectedData),
                                          cls=DjangoJSONEncoder)

        final_dict = {
            'collected': collected_serialized,
            'collected_sum': collected_sum
        }

        return JsonResponse(final_dict, safe=False)
Exemple #14
0
 def list(self, request):
     program_id = request.query_params.get('program', None)
     if program_id:
         queryset = Indicator.objects.filter(program__in=[program_id])
     else:
         user_countries = getCountry(request.user)
         queryset = Indicator.objects.filter(program__country__in=user_countries)
     serializer = self.get_serializer(queryset, many=True)
     return Response(serializer.data)
Exemple #15
0
 def queryset(self, request, queryset):
     """
     Returns the filtered queryset based on the value
     provided in the query string and retrievable via
     `self.value()`.
     """
     # Filter by logged in users allowable countries
     user_countries = getCountry(request.user)
     return queryset.filter(country__in=user_countries)
Exemple #16
0
def indicator_data_report(request, id=0, program=0):
    """
    This is the Indicator Visual report for each indicator and program.  Displays a list collected data entries
    and sums it at the bottom.  Lives in the "Reports" navigation.
    URL: indicators/data/[indicator_id]/[program_id]/
    :param request:
    :param id: Indicator ID
    :param program:
    :return:
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
    getIndicators = Indicator.objects.select_related().filter(country__in=countries)
    indicator_name = None
    program_name = None
    q = None

    #Build query based on filters and search
    if int(id) != 0:
        getSiteProfile = Indicator.objects.all().filter(id=id).select_related()
        q = {
            'indicator__id': id
        }
        indicator_name = Indicator.objects.get(id=id).name
    else:
        getSiteProfile = SiteProfile.objects.all().select_related()
        q = {
            'indicator__country__in': countries,
        }

    if int(program) != 0:
        getSiteProfile = SiteProfile.objects.all().filter(projectagreement__program__id=program).select_related()
        program_name = Program.objects.get(id=program).name
        q = {
            'program__id':program,
            'agreement__program__id': program,
        }
        #redress the indicator list based on program
        getIndicators = Indicator.objects.select_related().filter(program=program)

    if request.method == "GET" and "search" in request.GET:
        queryset = CollectedData.objects.filter(**q).filter(
                                           Q(agreement__project_name__contains=request.GET["search"]) |
                                           Q(description__icontains=request.GET["search"]) |
                                           Q(indicator__name__contains=request.GET["search"])
                                          ).select_related()
    else:
        queryset = CollectedData.objects.all().filter(**q).select_related()

    #pass query to table and configure
    table = IndicatorDataTable(queryset)
    table.paginate(page=request.GET.get('page', 1), per_page=20)

    RequestConfig(request).configure(table)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(request, "indicators/data_report.html", {'getQuantitativeData':queryset,'countries':countries, 'getSiteProfile':getSiteProfile, 'table': table,'getPrograms':getPrograms, 'getIndicators': getIndicators, 'form': FilterForm(), 'helper': FilterForm.helper, 'id': id,'program':program,'indicator_name':indicator_name, 'program_name': program_name})
Exemple #17
0
def DefaultCustomDashboard(request,id=0,status=0):
    """
    This is used as the workflow program dashboard
    # of agreements, approved, rejected, waiting, archived and total for dashboard
    http://127.0.0.1:8000/customdashboard/65/
    """
    program_id = id

    countries = getCountry(request.user)

    #transform to list if a submitted country
    selected_countries_list = Country.objects.all().filter(program__id=program_id)

    getQuantitativeDataSums = CollectedData.objects.filter(indicator__program__id=program_id,achieved__isnull=False, indicator__key_performance_indicator=True).exclude(achieved=None,targeted=None).order_by('indicator__number').values('indicator__number','indicator__name','indicator__id').annotate(targets=Sum('targeted'), actuals=Sum('achieved')).exclude(achieved=None,targeted=None)
    
    getFilteredName=Program.objects.get(id=program_id)
    
    getProjectsCount = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries).count()
    getBudgetEstimated = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries).annotate(estimated=Sum('total_estimated_budget'))
    getAwaitingApprovalCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='awaiting approval', program__country__in=countries).count()
    getApprovedCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='approved', program__country__in=countries).count()
    getRejectedCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='rejected', program__country__in=countries).count()
    getInProgressCount = ProjectAgreement.objects.all().filter(program__id=program_id).filter(Q(Q(approval='in progress') | Q(approval=None)), program__country__in=countries).count()
    nostatus_count = ProjectAgreement.objects.all().filter(program__id=program_id).filter(Q(Q(approval=None) | Q(approval=""))).count()
    print getInProgressCount


    getSiteProfile = SiteProfile.objects.all().filter(Q(projectagreement__program__id=program_id) | Q(collecteddata__program__id=program_id))
    getSiteProfileIndicator = SiteProfile.objects.all().filter(Q(collecteddata__program__id=program_id))

    if (status) =='Approved':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries, approval='approved').prefetch_related('projectcomplete')
    elif(status) =='Rejected':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries, approval='rejected').prefetch_related('projectcomplete')
    elif(status) =='In Progress':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries, approval='in progress').prefetch_related('projectcomplete')
    elif(status) =='Awaiting Approval':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries, approval='awaiting approval').prefetch_related('projectcomplete')
    else:
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries)

    get_project_completed = []
    getProjectsComplete = ProjectComplete.objects.all()
    for project in getProjects:
        for complete in getProjectsComplete:
            if complete.actual_budget != None:
                if project.id == complete.project_agreement_id:

                    get_project_completed.append(project)

    return render(request, "customdashboard/customdashboard/visual_dashboard.html", {'getSiteProfile':getSiteProfile, 'getBudgetEstimated': getBudgetEstimated, 'getQuantitativeDataSums': getQuantitativeDataSums,
                                                                     'country': countries, 'getAwaitingApprovalCount':getAwaitingApprovalCount,
                                                                     'getFilteredName': getFilteredName,'getProjects': getProjects, 'getApprovedCount': getApprovedCount,
                                                                     'getRejectedCount': getRejectedCount, 'getInProgressCount': getInProgressCount,'nostatus_count': nostatus_count,
                                                                     'getProjectsCount': getProjectsCount, 'selected_countries_list': selected_countries_list,
                                                                     'getSiteProfileIndicator': getSiteProfileIndicator, 'get_project_completed': get_project_completed})
Exemple #18
0
    def __init__(self, *args, **kwargs):
        # instance = kwargs.get('instance', None)
        self.request = kwargs.pop('request')
        self.program = kwargs.pop('program')
        self.indicator = kwargs.pop('indicator', None)
        self.tola_table = kwargs.pop('tola_table')
        super(CollectedDataForm, self).__init__(*args, **kwargs)

        # override the program queryset to use request.user for country
        self.fields['evidence'].queryset = Documentation.objects\
            .filter(program=self.program)

        # override the program queryset to use request.user for country
        self.fields['complete'].queryset = ProjectComplete.objects\
            .filter(program=self.program)
        self.fields['complete'].label = _("Project")

        # override the program queryset to use request.user for country
        countries = getCountry(self.request.user)
        # self.fields['program'].queryset = Program.objects\
        #   .filter(funding_status="Funded", country__in=countries).distinct()
        try:
            int(self.program)
            self.program = Program.objects.get(id=self.program)
        except TypeError:
            pass

        self.fields['periodic_target'].queryset = PeriodicTarget.objects\
            .filter(indicator=self.indicator)\
            .order_by('customsort', 'create_date', 'period')

        self.fields['program2'].initial = self.program
        self.fields['program2'].label = _("Program")

        try:
            int(self.indicator)
            self.indicator = Indicator.objects.get(id=self.indicator)
        except TypeError:
            pass

        self.fields['indicator2'].initial = self.indicator.name
        self.fields['indicator2'].label = _("Indicator")
        self.fields['program'].widget = forms.HiddenInput()
        self.fields['indicator'].widget = forms.HiddenInput()
        self.fields['target_frequency'].initial = self.indicator\
            .target_frequency
        self.fields['target_frequency'].widget = forms.HiddenInput()
        self.fields['site'].queryset = SiteProfile.objects\
            .filter(country__in=countries)
        self.fields['site'].label = _('Site')
        self.fields['tola_table'].queryset = TolaTable.objects\
            .filter(Q(owner=self.request.user) | Q(id=self.tola_table))
        self.fields['periodic_target'].label = _('Measure against target*')
        self.fields['achieved'].label = _('Actual value')
        self.fields['date_collected'].help_text = ' '
        self.fields['date_collected'].label = _('Date collected')
Exemple #19
0
def collecteddata_import(request):
    """
    Import collected data from Tola Tables
    :param request:
    :return:
    """
    owner = request.user
    # get the TolaTables URL and token from the sites object
    service = TolaSites.objects.get(site_id=1)

    # add filter to get just the users tables only
    user_filter_url = service.tola_tables_url + "&owner__username="******"&shared__username="******"POST":
        id = request.POST["service_table"]
        filter_url = service.tola_tables_url + "&id=" + id

        data = get_table(filter_url)

        # Get Data Info
        for item in data:
            name = item["name"]
            url = item["data"]
            remote_owner = item["owner"]["username"]

        # send table ID to count items in data
        count = getTableCount(url, id)

        # get the users country
        countries = getCountry(request.user)
        check_for_existence = TolaTable.objects.all().filter(name=name, owner=owner)
        if check_for_existence:
            result = "error"
        else:
            create_table = TolaTable.objects.create(
                name=name, owner=owner, remote_owner=remote_owner, table_id=id, url=url, unique_count=count
            )
            create_table.country.add(countries[0].id)
            create_table.save()
            result = "success"

        # send result back as json
        message = result
        return HttpResponse(json.dumps(message), content_type="application/json")

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(request, "indicators/collecteddata_import.html", {"getTables": data})
Exemple #20
0
 def get(self, request, *args, **kwargs):
     ## retrieve program
     model = Program
     ## retrieve the countries the user has data access for
     countries = getCountry(request.user)
     dashboard_id = int(self.kwargs['pk'])
     
     getDashboardListComponents = DashboardComponent.objects.all().filter(componentset=dashboard_id)
         
     return render(request, self.template_name, {'getDashboardListComponents': getDashboardListComponents})
Exemple #21
0
 def list(self, request):
     program_id = request.query_params.get('program', None)
     if program_id:
         program = Program.objects.get(pk=program_id)
         queryset = program.get_sites()
     else:
         user_countries = getCountry(request.user)
         queryset = SiteProfile.objects.all().filter(country__in=user_countries)
     serializer = self.get_serializer(queryset, many=True)
     return Response(serializer.data)
Exemple #22
0
 def queryset(self, request, queryset):
     """
     Returns the filtered queryset based on the value
     provided in the query string and retrievable via
     `self.value()`.
     """
     # Filter by logged in users allowable countries
     user_countries = getCountry(request.user)
     #if not request.user.user.is_superuser:
     return queryset.filter(country__in=user_countries)
Exemple #23
0
def indicator_data_report(request, id=0, program=0):
    """
    Show LIST of indicator based quantitative outputs with a filtered search view using django-tables2
    and django-filter
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
    getIndicators = Indicator.objects.select_related().filter(country__in=countries)
    indicator_name = None
    program_name = None
    q = None

    #Build query based on filters and search
    if int(id) != 0:
        getSiteProfile = Indicator.objects.all().filter(id=id).select_related()
        q = {
            'indicator__id': id
        }
        indicator_name = Indicator.objects.get(id=id).name
    else:
        getSiteProfile = SiteProfile.objects.all().select_related()
        q = {
            'indicator__country__in': countries,
        }

    if int(program) != 0:
        getSiteProfile = SiteProfile.objects.all().filter(projectagreement__program__id=program).select_related()
        program_name = Program.objects.get(id=program).name
        q = {
            'program__id':program,
            'agreement__program__id': program,
        }
        #redress the indicator list based on program
        getIndicators = Indicator.objects.select_related().filter(program=program)

    if request.method == "GET" and "search" in request.GET:
        """
         fields = ('targeted', 'achieved', 'description', 'indicator', 'agreement', 'complete')
        """
        queryset = CollectedData.objects.filter(**q).filter(
                                           Q(agreement__project_name__contains=request.GET["search"]) |
                                           Q(description__icontains=request.GET["search"]) |
                                           Q(indicator__name__contains=request.GET["search"])
                                          ).select_related()
    else:
        queryset = CollectedData.objects.all().filter(**q).select_related()

    #pass query to table and configure
    table = IndicatorDataTable(queryset)
    table.paginate(page=request.GET.get('page', 1), per_page=20)

    RequestConfig(request).configure(table)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(request, "indicators/data_report.html", {'getQuantitativeData':queryset,'countries':countries, 'getSiteProfile':getSiteProfile, 'table': table,'getPrograms':getPrograms, 'getIndicators': getIndicators, 'form': FilterForm(), 'helper': FilterForm.helper, 'id': id,'program':program,'indicator_name':indicator_name, 'program_name': program_name})
Exemple #24
0
    def get(self, request, *args, **kwargs):

        project_agreement_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()        
        if int(self.kwargs['pk']) == 0:
            getTraining = TrainingAttendance.objects.all().filter(program__country__in=countries)
        else:
            getTraining = TrainingAttendance.objects.all().filter(project_agreement_id=self.kwargs['pk'])

        return render(request, self.template_name, {'getTraining': getTraining, 'project_agreement_id': project_agreement_id, 'getPrograms': getPrograms})
Exemple #25
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(country__in=countries, funding_status="Funded").distinct()

        if int(self.kwargs['pk']) == 0:
            getProgramsIndicator = Program.objects.all().filter(funding_status="Funded", country__in=countries).order_by('name').annotate(indicator_count=Count('indicator'))
        else:
            getProgramsIndicator = Program.objects.all().filter(id=self.kwargs['pk']).order_by('name').annotate(indicator_count=Count('indicator'))

        return render(request, self.template_name, {'getPrograms': getPrograms, 'getProgramsIndicator': getProgramsIndicator})
Exemple #26
0
    def get(self, request, *args, **kwargs):

        project_agreement_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()        
        if int(self.kwargs['pk']) == 0:
            getTraining = TrainingAttendance.objects.all().filter(program__country__in=countries)
        else:
            getTraining = TrainingAttendance.objects.all().filter(project_agreement_id=self.kwargs['pk'])

        return render(request, self.template_name, {'getTraining': getTraining, 'project_agreement_id': project_agreement_id, 'getPrograms': getPrograms})
Exemple #27
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
        getIndicators = Indicator.objects.select_related().filter(country__in=countries).exclude(collecteddata__isnull=True)
        getCollectedData = None
        collected_sum = None

        #filter by program or inidcator or both
        if int(self.kwargs['indicator']) != 0:
            getCollectedData = CollectedData.objects.all().filter(indicator__id=self.kwargs['indicator'])
            collected_sum = CollectedData.objects.filter(indicator__id=self.kwargs['indicator']).aggregate(Sum('targeted'),Sum('achieved'))
        elif int(self.kwargs['indicator']) == 0 and int(self.kwargs['program']) != 0:
            getCollectedData = CollectedData.objects.all().filter(program=self.kwargs['program'])
            collected_sum = CollectedData.objects.filter(program=self.kwargs['program']).aggregate(Sum('targeted'),Sum('achieved'))
            #redress indicator query based on submitted program
            getIndicators = Indicator.objects.select_related().filter(program=self.kwargs['program']).exclude(collecteddata__isnull=True)
        elif int(self.kwargs['indicator']) != 0 and int(self.kwargs['program']) != 0:
            getCollectedData = CollectedData.objects.all().filter(program=self.kwargs['program'],indicator__id=self.kwargs['indicator'])
            collected_sum = CollectedData.objects.filter(program=self.kwargs['program'],indicator__id=self.kwargs['indicator']).aggregate(Sum('targeted'),Sum('achieved'))
            #redress indicator query based on submitted program
            getIndicators = Indicator.objects.select_related().filter(program=self.kwargs['program']).exclude(collecteddata__isnull=True)
        elif int(self.kwargs['indicator']) == 0 and int(self.kwargs['program']) == 0:
            getCollectedData = CollectedData.objects.all().filter(indicator__country__in=countries)
            collected_sum = CollectedData.objects.filter(indicator__country__in=countries).aggregate(Sum('targeted'),Sum('achieved'))


        #get details about the filtered indicator or program
        try:
            filter_indicator = Indicator.objects.get(id=self.kwargs['indicator'])
        except Indicator.DoesNotExist:
            filter_indicator = None

        try:
            filter_program = Program.objects.get(id=self.kwargs['program'])
        except Program.DoesNotExist:
            filter_program = None

        #TEMP CODE to migrate inidcators for Afghanistan that do not have programs but have Agreements
        if getCollectedData:
            for data in getCollectedData:
                set_program = None
                if data.program is None and data.agreement:
                    try:
                        program_from_agreement = ProjectAgreement.objects.get(id=data.agreement.id)
                        set_program = program_from_agreement.program
                    except ProjectAgreement.DoesNotExist:
                        set_program = None
                    if set_program:
                        update=CollectedData.objects.filter(id=data.pk).update(program=set_program)

        #END TEMP CODE

        return render(request, self.template_name, {'getCollectedData': getCollectedData, 'getPrograms': getPrograms, 'getIndicators':getIndicators,'filter_program':filter_program,'filter_indicator': filter_indicator, 'collected_sum': collected_sum})
Exemple #28
0
    def get_initial(self):
        countries = getCountry(self.request.user)
        default_country = None
        if countries:
            default_country = countries[0]
        initial = {
            'approved_by': self.request.user,
            'filled_by': self.request.user,
            'country': default_country
        }

        return initial
Exemple #29
0
    def get(self, request, *args, **kwargs):

        program_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()

        if int(self.kwargs['pk']) == 0:
            getDistribution = Distribution.objects.all().filter(program__country__in=countries)
        else:
            getDistribution = Distribution.objects.all().filter(program_id=self.kwargs['pk'])

        return render(request, self.template_name, {'getDistribution': getDistribution, 'program_id': program_id, 'getPrograms': getPrograms})
Exemple #30
0
    def get(self, request, *args, **kwargs):

        program_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()

        if int(self.kwargs['pk']) == 0:
            getDistribution = Distribution.objects.all().filter(program__country__in=countries)
        else:
            getDistribution = Distribution.objects.all().filter(program_id=self.kwargs['pk'])

        return render(request, self.template_name, {'getDistribution': getDistribution, 'program_id': program_id, 'getPrograms': getPrograms})
Exemple #31
0
    def get(self, request, *args, **kwargs):

        ## retrieve the coutries the user has data access for
        country = None
        countries = getCountry(request.user)
        country_list = Country.objects.all().filter(id__in=countries)
        if int(self.kwargs['pk']) == 0:
            getProgram = Program.objects.all().filter(country__in=countries)
        else:
            getProgram = Program.objects.all().filter(
                country__id=self.kwargs['pk'])
            country = Country.objects.get(id=self.kwargs['pk']).country

        program_list = []
        for program in getProgram:
            # get the percentage of indicators with data
            getInidcatorDataCount = Indicator.objects.filter(
                program__id=program.id).exclude(
                    collecteddata__targeted=None).count()
            getInidcatorCount = Indicator.objects.filter(
                program__id=program.id).count()
            if getInidcatorCount > 0 and getInidcatorDataCount > 0:
                getInidcatorDataPercent = 100 * float(
                    getInidcatorDataCount) / float(getInidcatorCount)
            else:
                getInidcatorDataPercent = 0

            program.indicator_data_percent = int(getInidcatorDataPercent)
            program.indicator_percent = int(100 - getInidcatorDataPercent)

            # get the percentage of projects with completes (tracking)
            getProjectAgreementCount = ProjectAgreement.objects.filter(
                program__id=program.id).count()
            getProjectCompleteCount = ProjectComplete.objects.filter(
                program__id=program.id).count()
            if getProjectAgreementCount > 0 and getProjectCompleteCount > 0:
                project_percent = 100 * float(getProjectCompleteCount) / float(
                    getProjectAgreementCount)
            else:
                project_percent = 0

            # append the rounded percentages to the program list
            program.project_percent = int(project_percent)
            program.project_agreement_percent = int(100 - project_percent)
            program_list.append(program)

        return render(
            request, self.template_name, {
                'getProgram': program_list,
                'getCountry': country_list,
                'country': country
            })
Exemple #32
0
def indicator_report(request, program=0, indicator=0, type=0):
    """
    This is the indicator library report.  List of all indicators across a country or countries filtered by
    program.  Lives in the "Report" navigation.
    URL: indicators/report/0/
    :param request:
    :param program:
    :return:
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()

    getIndicatorTypes = IndicatorType.objects.all()

    if int(program) != 0:
        getIndicators = Indicator.objects.all().filter(program__id=program).select_related()

    elif int(type) != 0:
        getIndicators = Indicator.objects.all().filter(indicator_type=type).select_related()

    else:
        getIndicators = Indicator.objects.all().select_related().filter(program__country__in=countries)

    table = IndicatorTable(getIndicators)
    table.paginate(page=request.GET.get("page", 1), per_page=20)

    if request.method == "GET" and "search" in request.GET:
        queryset = Indicator.objects.filter(
            Q(indicator_type__indicator_type__contains=request.GET["search"])
            | Q(name__contains=request.GET["search"])
            | Q(number__contains=request.GET["search"])
            | Q(number__contains=request.GET["search"])
            | Q(sector__sector__contains=request.GET["search"])
            | Q(definition__contains=request.GET["search"])
        )
        table = IndicatorTable(queryset)

    RequestConfig(request).configure(table)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(
        request,
        "indicators/report.html",
        {
            "program": program,
            "get_agreements": table,
            "getPrograms": getPrograms,
            "form": FilterForm(),
            "helper": FilterForm.helper,
            "getIndicatorTypes": getIndicatorTypes,
        },
    )
Exemple #33
0
    def get(self, request, *args, **kwargs):

        project_agreement_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
        

        if int(self.kwargs['pk']) == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(Q(training__program__country__in=countries) | Q(distribution__program__country__in=countries) )
        else:
            getBeneficiaries = Beneficiary.objects.all().filter(training__id=self.kwargs['pk'])

        return render(request, self.template_name, {'getBeneficiaries': getBeneficiaries, 'project_agreement_id': project_agreement_id, 'getPrograms': getPrograms})
Exemple #34
0
    def get(self, request, *args, **kwargs):
        ## retrieve program
        model = Program
        ## retrieve the countries the user has data access for
        countries = getCountry(request.user)
        dashboard_id = int(self.kwargs['pk'])

        getDashboardListComponents = DashboardComponent.objects.all().filter(
            componentset=dashboard_id)

        return render(
            request, self.template_name,
            {'getDashboardListComponents': getDashboardListComponents})
Exemple #35
0
    def get(self, request, *args, **kwargs):

        project_agreement_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
        

        if int(self.kwargs['pk']) == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(Q(training__program__country__in=countries) | Q(distribution__program__country__in=countries) )
        else:
            getBeneficiaries = Beneficiary.objects.all().filter(training__id=self.kwargs['pk'])

        return render(request, self.template_name, {'getBeneficiaries': getBeneficiaries, 'project_agreement_id': project_agreement_id, 'getPrograms': getPrograms})
Exemple #36
0
def indicator_report(request, program=0):
    """
    This is the indicator library report.  List of all indicators across a country or countries filtered by
    program.  Lives in the "Report" navigation.
    URL: indicators/report/0/
    :param request:
    :param program:
    :return:
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(
        funding_status="Funded", country__in=countries).distinct()

    if int(program) == 0:
        getIndicators = Indicator.objects.all().select_related().filter(
            country__in=countries)
    else:
        getIndicators = Indicator.objects.all().filter(
            program__id=program).select_related()

    table = IndicatorTable(getIndicators)
    table.paginate(page=request.GET.get('page', 1), per_page=20)

    if request.method == "GET" and "search" in request.GET:
        #list1 = list()
        #for obj in filtered:
        #    list1.append(obj)
        """
         fields = (indicator_type, name, number, source, definition, disaggregation, baseline, lop_target, means_of_verification, data_collection_method, responsible_person,
                    method_of_analysis, information_use, reporting_frequency, comments, program, sector, approved_by, approval_submitted_by, create_date, edit_date)
        """
        queryset = Indicator.objects.filter(
            Q(indicator_type__indicator_type__contains=request.GET["search"])
            | Q(name__contains=request.GET["search"])
            | Q(number__contains=request.GET["search"])
            | Q(number__contains=request.GET["search"])
            | Q(sector__sector__contains=request.GET["search"])
            | Q(definition__contains=request.GET["search"]))
        table = IndicatorTable(queryset)

    RequestConfig(request).configure(table)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(
        request, "indicators/report.html", {
            'program': program,
            'get_agreements': table,
            'getPrograms': getPrograms,
            'form': FilterForm(),
            'helper': FilterForm.helper
        })
Exemple #37
0
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.request = kwargs.pop('request')
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.layout = Layout(
            HTML("""<br/>"""),
            TabHolder(
                Tab(
                    'Personal Information',
                    Fieldset(
                        '',
                        'beneficiary_name',
                        'father_name',
                        'age',
                        'gender',
                        'site',
                        'remarks',
                    ),
                ),
                Tab(
                    'Benefits',
                    Fieldset(
                        '',
                        'workflowlevel1',
                        'training',
                        'distirbution',
                    ),
                ),
            ),
            HTML("""<br/>"""),
            FormActions(Submit('submit', 'Save', css_class='btn-default'),
                        Reset('reset', 'Reset', css_class='btn-warning')),
        )

        super(BeneficiaryForm, self).__init__(*args, **kwargs)

        countries = getCountry(self.request.user)
        self.fields['training'].queryset = TrainingAttendance.objects.filter(
            workflowlevel1__country__in=countries)
        self.fields['distribution'].queryset = Distribution.objects.filter(
            workflowlevel1__country__in=countries)
        self.fields['site'].queryset = SiteProfile.objects.filter(
            country__in=countries)
Exemple #38
0
def indicator_report(request, workflowlevel1=0, indicator=0, type=0):
    """
    This is the indicator library report.  List of all indicators across a country or countries filtered by
    workflowlevel1.  Lives in the "Report" navigation.
    URL: indicators/report/0/
    :param request:
    :param workflowlevel1:
    :return:
    """
    countries = getCountry(request.user)

    getPrograms = WorkflowLevel1.objects.all().filter(
        country__in=countries).distinct()
    getIndicatorTypes = IndicatorType.objects.all()

    filters = {}
    if int(workflowlevel1) != 0:
        filters['workflowlevel1__id'] = workflowlevel1
    if int(type) != 0:
        filters['indicator_type'] = type
    if int(indicator) != 0:
        filters['id'] = indicator
    if workflowlevel1 == 0 and type == 0:
        filters['workflowlevel1__country__in'] = countries

    indicator_data = Indicator.objects.filter(**filters)\
            .prefetch_related('sector')\
            .select_related('workflowlevel1', 'external_service_record','indicator_type',\
                'disaggregation', 'reporting_frequency')\
            .values('id','workflowlevel1__name','baseline','level__name','lop_target',\
                   'workflowlevel1__id','external_service_record__external_service__name',\
                   'key_performance_indicator','name','indicator_type__id', 'indicator_type__indicator_type',\
                   'sector__sector','disaggregation__disaggregation_type',\
                   'means_of_verification','data_collection_method',\
                   'reporting_frequency__frequency','create_date','edit_date',\
                   'source','method_of_analysis')

    data = json.dumps(list(indicator_data), cls=DjangoJSONEncoder)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form

    return render(
        request, "indicators/report.html", {
            'workflowlevel1': workflowlevel1,
            'getPrograms': getPrograms,
            'getIndicatorTypes': getIndicatorTypes,
            'getIndicators': indicator_data,
            'data': data
        })
Exemple #39
0
    def get(self, request, *args, **kwargs):
    ## retrieve program
        model = Program
        program_id = int(self.kwargs['pk'])
        getProgram = Program.objects.all().filter(id=program_id)

        ## retrieve the coutries the user has data access for
        countries = getCountry(request.user)

        #retrieve projects for a program
        # getProjects = ProjectAgreement.objects.all().filter(program__id=program__id, program__country__in=countries)

        #retrieve projects for a program
        getCustomDashboards = CustomDashboard.objects.all().filter(program=program_id)
            
        return render(request, self.template_name, {'pk': program_id, 'getCustomDashboards': getCustomDashboards, 'getProgram': getProgram})
Exemple #40
0
def RRIMAJupyterView1(request,id=0):
    """
    RRIMA custom dashboard TODO: Migrate this to the existing configurable dashboard
    :param request:
    :param id:
    :return:
    """
    model = Program
    program_id = 1#id ##USE TURKEY PROGRAM ID HERE
    # getProgram = Program.objects.all().filter(id=program_id)

    ## retrieve the coutries the user has data access for
    countries = getCountry(request.user)
    with open('static/rrima.html') as myfile: data = "\n".join(line for line in myfile) 
    
    return HttpResponse(data)
Exemple #41
0
def RRIMAJupyterView1(request,id=0):
    """
    RRIMA custom dashboard TODO: Migrate this to the existing configurable dashboard
    :param request:
    :param id:
    :return:
    """
    model = WorkflowLevel1
    workflowlevel1_id = 1#id ##USE TURKEY workflowlevel1 ID HERE
    # getworkflowlevel1 = workflowlevel1.objects.all().filter(id=workflowlevel1_id)

    ## retrieve the coutries the user has data access for
    countries = getCountry(request.user)
    with open('static/rrima.html') as myfile: data = "\n".join(line for line in myfile)

    return HttpResponse(data)
Exemple #42
0
def programIndicatorReport(request, program=0):
    """
    This is the GRID report or indicator plan for a program.  Shows a simple list of indicators sorted by level
    and number. Lives in the "Indicator" home page as a link.
    URL: indicators/program_report/[program_id]/
    :param request:
    :param program:
    :return:
    """
    program = int(program)
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
    getIndicators = Indicator.objects.all().filter(program__id=program).select_related().order_by("level", "number")
    getProgram = Program.objects.get(id=program)

    getIndicatorTypes = IndicatorType.objects.all()

    if request.method == "GET" and "search" in request.GET:
        # list1 = list()
        # for obj in filtered:
        #    list1.append(obj)
        getIndicators = (
            Indicator.objects.all()
            .filter(
                Q(indicator_type__icontains=request.GET["search"])
                | Q(name__icontains=request.GET["search"])
                | Q(number__icontains=request.GET["search"])
                | Q(definition__startswith=request.GET["search"])
            )
            .filter(program__id=program)
            .select_related()
            .order_by("level", "number")
        )

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(
        request,
        "indicators/grid_report.html",
        {
            "getIndicators": getIndicators,
            "getPrograms": getPrograms,
            "getProgram": getProgram,
            "form": FilterForm(),
            "helper": FilterForm.helper,
            "getIndicatorTypes": getIndicatorTypes,
        },
    )
Exemple #43
0
def DefaultCustomDashboard(request,id=0,sector=0,status=0):
    """
    # of agreements, approved, rejected, waiting, archived and total for dashboard
    """
    program_id = id

    countries = getCountry(request.user)

    #transform to list if a submitted country
    selected_countries_list = Country.objects.all().filter(program__id=program_id)

    getQuantitativeDataSums = CollectedData.objects.all().filter(indicator__program__id=program_id,achieved__isnull=False, indicator__key_performance_indicator=True).exclude(achieved=None,targeted=None).order_by('indicator__number').values('indicator__number','indicator__name','indicator__id').annotate(targets=Sum('targeted'), actuals=Sum('achieved'))
    getFilteredName=Program.objects.get(id=program_id)
    getProjectStatus = ProjectStatus.objects.all()

    getProjectsCount = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries).count()
    getBudgetEstimated = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries).annotate(estimated=Sum('total_estimated_budget'))
    getAwaitingApprovalCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='', program__country__in=countries).count()
    getApprovedCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='approved', program__country__in=countries).count()
    getRejectedCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='rejected', program__country__in=countries).count()
    getInProgressCount = ProjectAgreement.objects.all().filter(program__id=program_id, approval='in progress', program__country__in=countries).count()

    getSiteProfile = SiteProfile.objects.all().filter(Q(projectagreement__program__id=program_id) | Q(collecteddata__program__id=program_id))
    getSiteProfileIndicator = SiteProfile.objects.all().filter(Q(collecteddata__program__id=program_id))


    if (status) =='Approved':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries,approval='approved')
    elif(status) =='Rejected':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries,approval='rejected')
    elif(status) =='In Progress':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries,approval='in progress')
    elif(status) =='Awaiting Approval':
       getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries,approval='awaiting approval')
    else:
        getProjects = ProjectAgreement.objects.all().filter(program__id=program_id, program__country__in=countries)

    getCustomDashboard = CustomDashboard.objects.all()



    return render(request, "customdashboard/visual_dashboard.html", {'getSiteProfile':getSiteProfile, 'getBudgetEstimated': getBudgetEstimated, 'getQuantitativeDataSums': getQuantitativeDataSums,
                                                                     'country': countries, 'getProjectStatus': getProjectStatus, 'getAwaitingApprovalCount':getAwaitingApprovalCount,
                                                                     'getFilteredName': getFilteredName,'getProjects': getProjects, 'getApprovedCount': getApprovedCount,
                                                                     'getRejectedCount': getRejectedCount, 'getInProgressCount': getInProgressCount,
                                                                     'getCustomDashboard': getCustomDashboard, 'getProjectsCount': getProjectsCount, 'selected_countries_list': selected_countries_list,
                                                                     'getSiteProfileIndicator': getSiteProfileIndicator})
Exemple #44
0
    def get(self, request, *args, **kwargs):

        program_id = self.kwargs['program']
        countries = getCountry(request.user)
        if program_id != 0:
            getAgreements = ProjectAgreement.objects.all().filter(program = program_id).values('id', 'project_name')
        else:
            pass
        
        final_dict = {}
        if getAgreements:

            getAgreements = json.dumps(list(getAgreements), cls=DjangoJSONEncoder)

            final_dict = {'getAgreements': getAgreements}

        return JsonResponse(final_dict, safe=False)
Exemple #45
0
    def get(self, request, *args, **kwargs):

        program_id = self.kwargs['program']
        countries = getCountry(request.user)
        if program_id != 0:
            getAgreements = ProjectAgreement.objects.all().filter(program = program_id).values('id', 'project_name')
        else:
            pass
        
        final_dict = {}
        if getAgreements:

            getAgreements = json.dumps(list(getAgreements), cls=DjangoJSONEncoder)

            final_dict = {'getAgreements': getAgreements}

        return JsonResponse(final_dict, safe=False)
Exemple #46
0
 def __init__(self, *args, **kwargs):
     self.request = kwargs.pop('request')
     countries = getCountry(self.request.user)
     super(ReportFormCommon, self).__init__(*args, **kwargs)
     self.fields['program'].label = _("Program")
     self.fields['timeperiods'].label = _("Time periods")
     self.fields['numrecentperiods'].widget.attrs['placeholder'] = _(
         "enter a number")
     self.fields['targetperiods'].label = _("Target periods")
     self.fields['program'].queryset = Program.objects \
         .filter(country__in=countries,
                 funding_status="Funded",
                 reporting_period_start__isnull=False,
                 reporting_period_end__isnull=False,
                 indicator__target_frequency__isnull=False,) \
         .exclude(indicator__isnull=True) \
         .distinct()
Exemple #47
0
    def get(self, request, *args, **kwargs):

        if int(kwargs["id"]) == 0:
            del kwargs["id"]
        if int(kwargs["indicator_type"]) == 0:
            del kwargs["indicator_type"]
        if int(kwargs["program"]) == 0:
            del kwargs["program"]

        countries = getCountry(request.user)

        queryset = Indicator.objects.filter(**kwargs).filter(program__country__in=countries)

        indicator = IndicatorResource().export(queryset)
        response = HttpResponse(indicator.csv, content_type="application/ms-excel")
        response["Content-Disposition"] = "attachment; filename=indicator.csv"
        return response
Exemple #48
0
    def get(self, request, *args, **kwargs):

        project_agreement_id = self.kwargs['pk']
        countries = getCountry(request.user)
        getworkflowlevel1s = WorkflowLevel1.objects.all().filter(
            country__in=countries).distinct()
        if int(self.kwargs['pk']) == 0:
            getTraining = TrainingAttendance.objects.all().filter(
                workflowlevel1__country__in=countries)
        else:
            getTraining = TrainingAttendance.objects.all().filter(
                project_agreement_id=self.kwargs['pk'])

        return render(request, self.template_name, \
                      {'getTraining': getTraining, \
                      'project_agreement_id': project_agreement_id, \
                      'getworkflowlevel1s': getworkflowlevel1s})
Exemple #49
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(
            funding_status="Funded", country__in=countries).distinct()

        getIndicatorTypes = IndicatorType.objects.all()

        program = int(self.kwargs['program'])
        indicator = int(self.kwargs['indicator'])
        type = int(self.kwargs['type'])

        filters = {}
        if program != 0:
            filters['program__id'] = program
        if type != 0:
            filters['indicator_type'] = type
        if indicator != 0:
            filters['id'] = indicator
        if program == 0 and type == 0:
            filters['program__country__in'] = countries

        getIndicators = Indicator.objects.filter(**filters).select_related(\
            'program', 'external_service_record','indicator_type', 'sector', \
            'disaggregation', 'reporting_frequency').\
            values('id','program__name','baseline','level__name','lop_target',\
                   'program__id','external_service_record__external_service__name',\
                   'key_performance_indicator','name','indicator_type__indicator_type',\
                   'sector__sector','disaggregation__disaggregation_type',\
                   'means_of_verification','data_collection_method',\
                   'reporting_frequency__frequency','create_date','edit_date',\
                   'source','method_of_analysis')

        q = request.GET.get('search', None)
        if q:
            getIndicators = getIndicators.filter(
                Q(indicator_type__indicator_type__contains=q)
                | Q(name__contains=q) | Q(number__contains=q)
                | Q(number__contains=q) | Q(sector__sector__contains=q)
                | Q(definition__contains=q))

        from django.core.serializers.json import DjangoJSONEncoder

        get_indicators = json.dumps(list(getIndicators), cls=DjangoJSONEncoder)

        return JsonResponse(get_indicators, safe=False)
Exemple #50
0
 def get(self, *args, **kwargs ):
     #filter by program or indicator
     print int(self.kwargs['program'])
     print int(self.kwargs['indicator'])
     if int(self.kwargs['program']) != 0 and int(self.kwargs['indicator']) == 0:
         print "Program"
         queryset = CollectedData.objects.all().filter(indicator__program__id=self.kwargs['program'])
     elif int(self.kwargs['program']) == 0 and int(self.kwargs['indicator']) != 0:
         print "Indicator"
         queryset = CollectedData.objects.all().filter(indicator__id=self.kwargs['indicator'])
     else:
         countries = getCountry(self.request.user)
         queryset = CollectedData.objects.all().filter(indicator__country__in=countries)
     dataset = CollectedDataResource().export(queryset)
     response = HttpResponse(dataset, content_type='text/csv')
     response['Content-Disposition'] = 'attachment; filename=indicator_data.csv'
     return response
Exemple #51
0
 def __init__(self, *args, **kwargs):
     self.request = kwargs.pop('request')
     countries = getCountry(self.request.user)
     super(ReportFormCommon, self).__init__(*args, **kwargs)
     self.fields['program'].label = _("Program")
     self.fields['timeperiods'].label = _("Time periods")
     self.fields['timeperiods'].choices = ((k, v.capitalize()) for k, v in self.TIMEPERIODS_CHOICES)
     self.fields['numrecentperiods'].widget.attrs['placeholder'] = _("enter a number")
     self.fields['targetperiods'].label = _("Target periods")
     self.fields['program'].queryset = self.request.user.tola_user.available_programs \
         .filter(funding_status="Funded",
                 reporting_period_start__isnull=False,
                 reporting_period_end__isnull=False,
                 reporting_period_start__lte=timezone.localdate(),
                 indicator__target_frequency__isnull=False,) \
         .exclude(indicator__isnull=True) \
         .distinct()
Exemple #52
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()
        getIndicators = Indicator.objects.all().filter(country__in=countries).exclude(collecteddata__isnull=True)
        getCollectedData = None
        collected_sum = None

        #filter by program or inidcator or both
        if int(self.kwargs['indicator']) != 0:
            getCollectedData = CollectedData.objects.all().prefetch_related('evidence','indicator','program','indicator__objectives','indicator__strategic_objectives').filter(indicator__id=self.kwargs['indicator']).order_by('program','indicator__number')
            collected_sum = CollectedData.objects.filter(indicator__id=self.kwargs['indicator']).aggregate(Sum('targeted'),Sum('achieved'))
        elif int(self.kwargs['indicator']) == 0 and int(self.kwargs['program']) != 0:
            getCollectedData = CollectedData.objects.all().prefetch_related('evidence','indicator','program','indicator__objectives','indicator__strategic_objectives').filter(program=self.kwargs['program']).order_by('program','indicator__number')
            collected_sum = CollectedData.objects.filter(program=self.kwargs['program']).aggregate(Sum('targeted'),Sum('achieved'))
            #redress indicator query based on submitted program
            getIndicators = Indicator.objects.select_related().filter(program=self.kwargs['program']).exclude(collecteddata__isnull=True)
        elif int(self.kwargs['indicator']) != 0 and int(self.kwargs['program']) != 0:
            getCollectedData = CollectedData.objects.all().prefetch_related('evidence','indicator','program','indicator__objectives','indicator__strategic_objectives').filter(program=self.kwargs['program'],indicator__id=self.kwargs['indicator']).order_by('program','indicator__number')
            collected_sum = CollectedData.objects.filter(program=self.kwargs['program'],indicator__id=self.kwargs['indicator']).aggregate(Sum('targeted'),Sum('achieved'))
            #redress indicator query based on submitted program
            getIndicators = Indicator.objects.select_related().filter(program=self.kwargs['program']).exclude(collecteddata__isnull=True)
        elif int(self.kwargs['indicator']) == 0 and int(self.kwargs['program']) == 0:
            getCollectedData = CollectedData.objects.all().prefetch_related('evidence','indicator','program','indicator__objectives','indicator__strategic_objectives').filter(indicator__country__in=countries).order_by('program','indicator__number')
            collected_sum = CollectedData.objects.filter(indicator__country__in=countries).aggregate(Sum('targeted'),Sum('achieved'))


        #get details about the filtered indicator or program
        try:
            filter_indicator = Indicator.objects.get(id=self.kwargs['indicator'])
        except Indicator.DoesNotExist:
            filter_indicator = None

        try:
            filter_program = Program.objects.get(id=self.kwargs['program'])
        except Program.DoesNotExist:
            filter_program = None

        if self.request.GET.get('export'):
            dataset = CollectedDataResource().export(getCollectedData)
            response = HttpResponse(dataset.csv, content_type='application/ms-excel')
            response['Content-Disposition'] = 'attachment; filename=indicator_data.csv'
            return response

        return render(request, self.template_name, {'getCollectedData': getCollectedData, 'getPrograms': getPrograms, 'getIndicators':getIndicators,'filter_program':filter_program,'filter_indicator': filter_indicator, 'collected_sum': collected_sum})
Exemple #53
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        countries = getCountry(request.user)

        if program_id == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(Q(training__program__country__in=countries) | Q(distribution__program__country__in=countries) ).values('id', 'beneficiary_name', 'create_date')
        elif program_id !=0 and project_id == 0:
            getBeneficiaries = Beneficiary.objects.all().filter(program__id=program_id).values('id', 'beneficiary_name', 'create_date')
        else:
            getBeneficiaries = Beneficiary.objects.all().filter(program__id=program_id, training__project_agreement=project_id).values('id', 'beneficiary_name', 'create_date')

        getBeneficiaries = json.dumps(list(getBeneficiaries), cls=DjangoJSONEncoder)

        final_dict = {'getBeneficiaries': getBeneficiaries}

        return JsonResponse(final_dict, safe=False)
Exemple #54
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        countries = getCountry(request.user)
        if program_id == 0:
            getDistribution = Distribution.objects.all().filter(program__country__in=countries).values('id', 'distribution_name', 'create_date', 'program')
        elif program_id !=0 and project_id == 0:
            getDistribution = Distribution.objects.all().filter(program_id=program_id).values('id', 'distribution_name', 'create_date', 'program')
        else:
            getDistribution = Distribution.objects.all().filter(program_id=program_id, initiation_id=project_id).values('id', 'distribution_name', 'create_date', 'program')

        
        getDistribution = json.dumps(list(getDistribution), cls=DjangoJSONEncoder)

        final_dict = {'getDistribution': getDistribution}

        return JsonResponse(final_dict, safe=False)
Exemple #55
0
    def get(self, request, *args, **kwargs):

        program_id = int(self.kwargs['program'])
        project_id = int(self.kwargs['project'])
        print project_id
        countries = getCountry(request.user)
        if int(self.kwargs['program']) == 0:
            getTraining = TrainingAttendance.objects.all().filter(program__country__in=countries).values('id', 'create_date', 'training_name', 'project_agreement__project_name')
        elif program_id != 0 and project_id == 0:
            getTraining = TrainingAttendance.objects.all().filter(program=program_id).values('id','create_date', 'training_name', 'project_agreement__project_name')
        else:
            getTraining = TrainingAttendance.objects.all().filter(program_id=program_id, project_agreement_id=project_id).values('id','create_date', 'training_name', 'project_agreement__project_name')

        getTraining = json.dumps(list(getTraining), cls=DjangoJSONEncoder)

        final_dict = {'getTraining': getTraining}

        return JsonResponse(final_dict, safe=False)
Exemple #56
0
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.request = kwargs.pop('request')
        self.helper.form_method = 'post'
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-6'
        self.helper.form_error_title = 'Form Errors'
        self.helper.error_text_inline = True
        self.helper.help_text_inline = True
        self.helper.html5_required = True
        self.helper.add_input(Submit('submit', 'Save'))

        super(TrainingAttendanceForm, self).__init__(*args, **kwargs)

        countries = getCountry(self.request.user)
        self.fields['project_agreement'].queryset = ProjectAgreement.objects.filter(program__country__in=countries)
        self.fields['program'].queryset = Program.objects.filter(country__in=countries)
Exemple #57
0
    def get(self, request, *args, **kwargs):

        countries = getCountry(request.user)
        getPrograms = Program.objects.all().filter(country__in=countries, funding_status="Funded").distinct()
        getIndicatorTypes = IndicatorType.objects.all()

        if int(self.kwargs["program"]) != 0:
            getProgramsIndicator = (
                Program.objects.all()
                .filter(id=self.kwargs["program"])
                .order_by("name")
                .annotate(indicator_count=Count("indicator"))
            )
        elif int(self.kwargs["indicator"]) != 0:
            getProgramsIndicator = (
                Program.objects.all()
                .filter(indicator=self.kwargs["indicator"])
                .order_by("name")
                .annotate(indicator_count=Count("indicator"))
            )
        if int(self.kwargs["type"]) != 0:
            getProgramsIndicator = (
                Program.objects.all()
                .filter(indicator=self.kwargs["indicator"])
                .order_by("name")
                .annotate(indicator_count=Count("indicator"))
            )
        else:
            getProgramsIndicator = (
                Program.objects.all()
                .filter(funding_status="Funded", country__in=countries)
                .order_by("name")
                .annotate(indicator_count=Count("indicator"))
            )

        return render(
            request,
            self.template_name,
            {
                "getPrograms": getPrograms,
                "getProgramsIndicator": getProgramsIndicator,
                "getIndicatorTypes": getIndicatorTypes,
            },
        )
Exemple #58
0
    def get(self, request, *args, **kwargs):

        if int(kwargs["indicator"]) == 0:
            del kwargs["indicator"]
        if int(kwargs["program"]) == 0:
            del kwargs["program"]
        if int(kwargs["type"]) == 0:
            del kwargs["type"]
        else:
            kwargs["indicator__indicator_type__id"] = kwargs["type"]
            del kwargs["type"]

        countries = getCountry(request.user)

        queryset = CollectedData.objects.filter(**kwargs).filter(indicator__program__country__in=countries)
        dataset = CollectedDataResource().export(queryset)
        response = HttpResponse(dataset.csv, content_type="application/ms-excel")
        response["Content-Disposition"] = "attachment; filename=indicator_data.csv"
        return response
Exemple #59
0
def indicator_report(request, program=0):
    """
    This is the indicator library report.  List of all indicators across a country or countries filtered by
    program.  Lives in the "Report" navigation.
    URL: indicators/report/0/
    :param request:
    :param program:
    :return:
    """
    countries = getCountry(request.user)
    getPrograms = Program.objects.all().filter(funding_status="Funded", country__in=countries).distinct()

    if int(program) == 0:
        getIndicators = Indicator.objects.all().select_related().filter(country__in=countries)
    else:
        getIndicators = Indicator.objects.all().filter(program__id=program).select_related()

    table = IndicatorTable(getIndicators)
    table.paginate(page=request.GET.get('page', 1), per_page=20)

    if request.method == "GET" and "search" in request.GET:
        #list1 = list()
        #for obj in filtered:
        #    list1.append(obj)
        """
         fields = (indicator_type, name, number, source, definition, disaggregation, baseline, lop_target, means_of_verification, data_collection_method, responsible_person,
                    method_of_analysis, information_use, reporting_frequency, comments, program, sector, approved_by, approval_submitted_by, create_date, edit_date)
        """
        queryset = Indicator.objects.filter(
                                           Q(indicator_type__indicator_type__contains=request.GET["search"]) |
                                           Q(name__contains=request.GET["search"]) | Q(number__contains=request.GET["search"]) |
                                           Q(number__contains=request.GET["search"]) | Q(sector__sector__contains=request.GET["search"]) |
                                           Q(definition__contains=request.GET["search"])
                                          )
        table = IndicatorTable(queryset)

    RequestConfig(request).configure(table)

    # send the keys and vars from the json data to the template along with submitted feed info and silos for new form
    return render(request, "indicators/report.html", {'program': program, 'get_agreements': table, 'getPrograms': getPrograms, 'form': FilterForm(), 'helper': FilterForm.helper})