def organisations_index(organisation_code=None):
    
    aggregation_type=integerise(request.args.get('aggregation_type', 2))

    template_args = {}
    org_packages = dqorganisations.organisationPackages(organisation_code)

    organisation = dqorganisations.organisations(organisation_code)
    packagegroups = dqorganisations.organisationPackageGroups(organisation_code)

    irs = [ir for ir in get_info_results(org_packages, organisation)]
    coverage = get_coverage(organisation, irs)

    organisation_survey = dqsurveys.getSurvey(organisation_code)

    surveydata = dqsurveys.getSurveyDataAllWorkflows(organisation_code)

    surveydata, _ = dqsurveys.get_survey_data_and_workflow(
        organisation_survey, surveydata)

    summary_data = get_summary_data(organisation, aggregation_type)

    allowed_to_view_survey = usermanagement.check_perms(
        "survey",
        "view")
    allowed_to_edit_survey_researcher = usermanagement.check_perms(
        "survey_researcher",
        "edit",
        {"organisation_code": organisation_code})

    show_researcher_button = (
        allowed_to_edit_survey_researcher and
         (
          (organisation_survey and
           organisation_survey.Workflow.name == 'researcher')
           or
          (not organisation_survey)
         )
        )

    template_args = dict(organisation=organisation,
                         summary_data=summary_data,
                         packagegroups=packagegroups,
                         coverage=coverage,
                         surveydata=surveydata,
                         admin=usermanagement.check_perms('admin'),
                         loggedinuser=current_user,
                         allowed_to_view_survey=allowed_to_view_survey,
                         show_researcher_button=show_researcher_button)

    return render_template("organisation_index.html", **template_args)
Example #2
0
def organisation_survey(organisation_code=None):
    organisation = dqorganisations.organisations(organisation_code)
    # make sure survey exists
    dqsurveys.getOrCreateSurvey({'organisation_id':organisation.id})

    survey = dqsurveys.getSurvey(organisation_code)
    surveydata = dqsurveys.getSurveyDataAllWorkflows(organisation_code)
    workflows = dqsurveys.workflowsAll()
    pct_complete = completion_percentage(survey)
    users = dqusers.surveyPermissions(organisation_code)
    admin = usermanagement.check_perms('admin')
    loggedinuser = current_user
    checksurveyOK = dqsurveys.checkSurveyData(organisation_code)

    return render_template("surveys/survey.html", 
                           **locals())
def organisation_publication_complete(organisation_code, aggregation_type):
    aggregation_type=integerise(request.args.get('aggregation_type', 2))
    all_aggregation_types = dqaggregationtypes.aggregationTypes()

    organisation = Organisation.query.filter_by(
        organisation_code=organisation_code).first_or_404()

    aggregate_results = dqorganisations._organisation_indicators_complete_split(
        organisation, aggregation_type)
        
    organisation_survey = dqsurveys.getSurvey(organisation_code)
    surveydata = dqsurveys.getSurveyDataAllWorkflows(organisation_code)

    surveydata, surveydata_workflow = get_survey_data_and_workflow(
        organisation_survey, surveydata)

    published_status_by_id = dict(map(id_tuple, dqsurveys.publishedStatus()))
    publishedformats = dict(map(id_tuple, dqsurveys.publishedFormatsAll()))

    published_status_by_id[None] = {
        'name': 'Unknown',
        'publishedstatus_class': 'label-inverse'
        }

    publishedformats[None] = {
        'name': 'Unknown',
        'format_class': 'label-inverse'
        }

    latest_runtime=1

    years = dict(get_ordinal_values_years())

    return render_template("organisation_index_complete.html",
                           organisation=organisation,
                           results=aggregate_results,
                           runtime=latest_runtime,
                           all_aggregation_types=all_aggregation_types,
                           aggregation_type=aggregation_type,
                           surveydata=surveydata,
                           published_status=published_status_by_id,
                           published_format=publishedformats,
                           surveydata_workflow=surveydata_workflow,
                           admin=usermanagement.check_perms('admin'),
                           loggedinuser=current_user,
                           years=years)
def organisation_publication_authorised(organisation_code, aggregation_type):
    aggregation_type=integerise(request.args.get('aggregation_type', 2))
    all_aggregation_types = dqaggregationtypes.allAggregationTypes()

    organisation = Organisation.query.filter_by(
        organisation_code=organisation_code).first_or_404()

    aggregate_results = dqorganisations._organisation_indicators_split(
        organisation, aggregation_type)

    aggregate_results['zero'] = util.resort_dict_indicator(
                                aggregate_results['zero'])
    aggregate_results['non_zero'] = util.resort_dict_indicator(
                                    aggregate_results['non_zero'])
        
    organisation_survey = dqsurveys.getSurvey(organisation_code)
    surveydata = dqsurveys.getSurveyDataAllWorkflows(organisation_code)
    
    surveydata, surveydata_workflow = dqsurveys.get_survey_data_and_workflow(
        organisation_survey, surveydata)

    published_status_by_id = dict(map(id_tuple, dqsurveys.publishedStatus()))
    publishedformats = dict(map(id_tuple, dqsurveys.publishedFormatsAll()))

    published_status_by_id[None] = {
        'title': 'Unknown',
        'title': 'unknown',
        'publishedstatus_class': 'label-inverse'
        }

    publishedformats[None] = {
        'title': 'Unknown',
        'name': 'unknown',
        'format_class': 'label-inverse'
        }

    latest_runtime=1

    years = dict(get_ordinal_values_years())

    test_level_description = {
        3: ("on", "organisation files", ""),
        2: ("on", "each package of data", ""),
        1: ("for", "each activity", "in your data"),
        0: ("for", "each transaction", "in your data")
        }

    links = {
        "organisation_page": url_for(
            'organisations', 
            organisation_code=organisation.organisation_code),
        "organisation_detail": url_for(
            'organisation_publication_detail', 
            organisation_code=organisation.organisation_code),
        "organisation_feedback": url_for(
            'organisations_feedback', 
            organisation_code=organisation.organisation_code)
        }
    if surveydata:
        links.update({
                "organisation_survey_edit": url_for(
                    'organisation_survey_edit', 
                    organisation_code=organisation.organisation_code, 
                    workflow_name=surveydata_workflow)
                })

    def agg_detail(agt):
        tmp = agt.as_dict()
        tmp["selected"] = agt.id == aggregation_type
        return tmp

    agg_type = [ agg_detail(agt) for agt in all_aggregation_types ]

    frequencies = { 
        "less than quarterly": (0.5,
                                """It looks like you publish less often than
          quarterly, so the maximum you can score for IATI data is
          75 points. The total points for the relevant indicators have been
          adjusted accordingly"""),
        "quarterly": (0.9,
                      """It looks like you publish quarterly and not monthly,
          so the maximum you can score for IATI data is 95 points. The total 
          points for the relevant indicators have been adjusted 
          accordingly.""")
        }

    freq_score = frequencies.get(organisation.frequency, (1.0, ))
    if organisation.frequency in frequencies:
        freq_alert = { "text": frequencies.get(organisation.frequency)[1] }
    else:
        freq_alert = None

    def annotate(res, zero):
        def annotate_test(t):
            tmp2 = dict(t)
            tmp2["results_pct_rounded"] = round(tmp2["results_pct"], 2)
            tmp2["results_num_rounded"] = round(tmp2["results_num"], 2)

            if "test_level" not in tmp2["test"]: # hopeless
                return tmp2

            test_level = tmp2["test"]["test_level"]
            level = test_level_description[test_level]
            preposition, description, coda = level
            tmp2["level_preposition"] = preposition
            tmp2["level_description"] = description
            tmp2["level_coda"] = coda

            return tmp2

        tmp = dict(res)

        tmp["is_activity"] = (
            tmp["indicator"]["indicator_category_name"] == "activity")

        multiplier = {True: freq_score[0], False: 1}[tmp["is_activity"]]

        def points():
            if not zero:
                return round((tmp["results_pct"] * multiplier / 2.0 + 50), 2)

            ind_id = res["indicator"]["id"]
            
            if surveydata:
                if (res["indicator"]["indicator_ordinal"] and surveydata[ind_id].PublishedFormat):
                    return round(
                        (surveydata[ind_id].OrganisationSurveyData.ordinal_value/3.0) * 
                        surveydata[ind_id].PublishedFormat.format_value * 50, 2)
                elif (surveydata[ind_id].PublishedStatus and surveydata[ind_id].PublishedFormat):
                    return (
                        surveydata[ind_id].PublishedStatus.publishedstatus_value * 
                        surveydata[ind_id].PublishedFormat.format_value * 50)
                else:
                    return 0
            else:
                return ""

        tmp["points"] = points()
        if not zero:
            tmp["points_minus_50"] = tmp["points"] - 50
            # it all fails if the other branch tries to use this value

        tmp["tests"] = map(annotate_test, res["tests"])

        if zero:
            if surveydata:
                osd = surveydata[tmp["indicator"]["id"]].OrganisationSurveyData.as_dict()

                def status_class_and_text():
                    if tmp["indicator"]["indicator_ordinal"]:
                        return (years[osd["ordinal_value"]]["class"], 
                                years[osd["ordinal_value"]]["text"])
                    else:
                        return (published_status_by_id[osd["published_status"]]["publishedstatus_class"], 
                                published_status_by_id[osd["published_status"]]["title"])
                def format_class_and_text():
                    if published_status_by_id[osd["published_status"]]["publishedstatus_class"] != 'important':
                        return (publishedformats[osd["published_format"]]["format_class"], 
                                publishedformats[osd["published_format"]]["title"])
                    else:
                        return ("", "")
                tmp["status_class"], tmp["status_text"] = status_class_and_text()
                tmp["format_class"], tmp["format_text"] = format_class_and_text()

        tmp["results_pct_rounded"] = round(tmp["results_pct"], 2)
        tmp["results_pct_halved_rounded"] = round(tmp["results_pct"]/2.0, 2)

        return tmp

    annotate_zero = lambda res : annotate(res, True)
    annotate_nonzero = lambda res : annotate(res, False)

    # testdata.results_pct|round(2)
    # testdata["results_num"]|round(2)
    # as far as line 296

    def get_sd(data):
        return {
            "OrganisationSurveyData": data[0].as_dict(),
            "Workflow": data[3].as_dict(),
        }

    def jsonsurvey(surveydata):
        return dict(map(lambda x: (x[0], get_sd(x[1])),
                             surveydata.items()))

    payload = {
        "organisation": organisation.as_dict(),
        "links": links,
        "agg_type": agg_type,
        "freq": freq_score,
        "freq_alert": freq_alert,
        "result": {
            "non_zero": map(annotate_nonzero, aggregate_results["non_zero"].values()),
            "zero":map(annotate_zero, aggregate_results["zero"].values())
            },
        "surveydata": jsonsurvey(surveydata)
        }
    json_data = json.dumps(payload, indent=2)

    return render_template("organisation_indicators.html",
                           organisation=organisation,
                           admin=usermanagement.check_perms('admin'),
                           loggedinuser=current_user,
                           json_data=json_data)