def handle(self, *args, **options):
        for element in DataElement.objects.all():
            print element.name
            data_elements = dhis2_request('dataElements/%s.json' % element.identifier)

            category_combo = data_elements['categoryCombo']['id']
            category_combos = dhis2_request('categoryCombos/%s.json' % category_combo)
            category_option_combos = category_combos['categoryOptionCombos']

            for category_option_combo in category_option_combos:
                result = dhis2_request('categoryOptionCombos/%s.json' % category_option_combo['id'])

                print '    %s' % result['name']
                selection = raw_input('    Under 5 years(1) 5 years and above (2) others(0): ')

                try:
                    coc = CategoryOptionCombo()
                    coc.data_element = element
                    coc.name = result['name']
                    coc.age_group = int(selection)
                    coc.identifier = category_option_combo['id']
                    # Should be run once
                    coc.save()
                except Exception, e:
                    print e.message
    def handle(self, *args, **options):
        data_set_id = options['data_set_id'][0]
        result = dhis2_request('dataSets/%s.json' % data_set_id)

        for index, de in enumerate(result['dataElements']):
            result = dhis2_request('dataElements/%s.json' % de['id'])
            print "%s. %s" % (index+1, result['name'])
    def handle(self, *args, **options):
        data_element_name = options['data_element_name'][0]

        result = dhis2_request('dataElements.json?pageSize=50000')
        data_elements = result['dataElements']

        for de in data_elements:
            if de['displayName'].startswith(data_element_name):
                print "%s (%s)" % (de['displayName'], de['id'])

                result = dhis2_request('dataElements/%s.json' % de['id'])
                data_sets = result['dataSets']

                for index, ds in enumerate(data_sets):
                    result = dhis2_request('dataSets/%s.json' % ds['id'])

                    print "  %s. %s (%s) *%s" % (index+1, result['name'], ds['id'], result['periodType'])
    def handle(self, *args, **options):
        root_org_unit = 'akV6429SUqu'  # MOH - Uganda
        unit = options['unit'][0]

        if unit == 'region':
            root_org_unit = dhis2_request('organisationUnits/%s.json' % root_org_unit)
            store_children(root_org_unit, Region)

        elif unit == 'district':
            regions = Region.objects.all()
            for region in regions:
                region_org_unit = dhis2_request('organisationUnits/%s.json' % region.identifier)
                store_children(region_org_unit, District)

        elif unit == 'subcounty':
            districts = District.objects.all()
            for district in districts:
                district_org_unit = dhis2_request('organisationUnits/%s.json' % district.identifier)
                store_children(district_org_unit, SubCounty)

        else:
            self.stdout.write(self.style.NOTICE('Unknown unit [%s]' % options['unit']))
def store_children(parent_org_unit, child_model):
    for child_org_unit in parent_org_unit['children']:

        try:
            # Throws error when unit already exists
            child_model.objects.get(identifier=child_org_unit['id'])

        except ObjectDoesNotExist:
            result = dhis2_request('organisationUnits/%s.json' % child_org_unit['id'])

            child_model_instance = child_model()
            child_model_instance.identifier = child_org_unit['id']
            child_model_instance.name = result['name']
            child_model_instance.save()
    def handle(self, *args, **options):
        regions = [region.identifier for region in Region.objects.all()]
        districts = [district.identifier for district in District.objects.all()]
        sub_counties = [sub_county.identifier for sub_county in SubCounty.objects.all()]

        combined = regions + districts + sub_counties

        facilities = []
        result = dhis2_request('organisationUnits.json?pageSize=7600')
        self.stdout.write('Returned [%s] organisation units' % len(result['organisationUnits']))

        for org_unit in result['organisationUnits']:
            if org_unit['id'] not in combined:
                facilities.append(org_unit['id'])

                f = Facility()
                f.identifier = org_unit['id']
                f.name = org_unit['displayName']
                f.save()

        self.stdout.write('Collected [%s] facilities' % len(facilities))
    def handle(self, *args, **options):
        data_set = "Cm5cTKifbLA"
        period = "201603"

        dhis2_total = 0

        print ">>>> Fetching Data Set Report from DHIS2"
        report = dhis2_request('dataSetReport.json?ds=%s&pe=%s&ou=akV6429SUqu' % (data_set, period), False)
        soup = BeautifulSoup(report, 'html.parser')

        dhis2_inpatient_malaria_deaths = self.get_total("malaria total", soup, [3, 4, 7, 8])
        dhis2_malaria_admissions = self.get_total("malaria total", soup, [1, 2, 5, 6])
        dhis2_total_inpatient_deaths = self.get_total("(D) Deaths", soup, [19])

        print ">>>> Fetching Dashboard Data"

        url = "path?from_date=201603&to_date=201604&group=period&region=0&district=0"
        request = RequestFactory().get(url)
        view = JsonDataView()
        result = json.loads(view.get(request).getvalue())

        dashboard_inpatient_malaria_deaths = float(result[period]['inpatient_malaria_deaths'])
        dashboard_malaria_admissions = float(result[period]['malaria_admissions'])
        dashboard_total_inpatient_deaths = float(result[period]['total_inpatient_deaths'])


        print "Inpatient Malaria deaths: DHIS2 (%s), Dashboard (%s)" % (dhis2_inpatient_malaria_deaths,
                                                                dashboard_inpatient_malaria_deaths)

        print "Malaria Admissions: DHIS2 (%s), Dashboard (%s)" % (dhis2_malaria_admissions,
                                                                dashboard_malaria_admissions)

        print "Total Inpatient Deaths: DHIS2 (%s), Dashboard (%s)" % (dhis2_total_inpatient_deaths,
                                                                      dashboard_total_inpatient_deaths)

        assert dhis2_inpatient_malaria_deaths == dashboard_inpatient_malaria_deaths
        assert dhis2_malaria_admissions == dashboard_malaria_admissions
        assert dhis2_total_inpatient_deaths == dashboard_total_inpatient_deaths
    def handle(self, *args, **options):
        unit = options['unit'][0]

        if unit == 'district':
            regions = Region.objects.all()
            for region in regions:
                result = dhis2_request('organisationUnits/%s.json' % region.identifier)
                for child in result['children']:
                    try:
                        child_district = District.objects.get(identifier=child['id'])
                        child_district.region = region
                        child_district.save()
                    except ObjectDoesNotExist:
                        pass

        elif unit == 'sub_county':
            districts = District.objects.all()
            total_districts = len(districts)

            for district_idx, district in enumerate(districts):
                result = dhis2_request('organisationUnits/%s.json?pageSize=10000' % district.identifier)

                total_children = len(result['children'])
                for child_idx, child in enumerate(result['children']):
                    try:
                        child_sub_county = SubCounty.objects.get(identifier=child['id'])
                        child_sub_county.district = district
                        child_sub_county.save()
                    except ObjectDoesNotExist:
                        pass

                    self.show_status(district_idx, total_districts, child_idx, total_children)

        elif unit == 'facility':
            sub_counties = SubCounty.objects.all()
            total_sub_counties = len(sub_counties)
            # last_county = 'pnxCSdB9Msk'
            # start = False

            for sub_county_idx, sub_county in enumerate(sub_counties):
                # if start is False:
                #     if sub_county.identifier == last_county:
                #         start = True
                #     else:
                #         continue

                result = dhis2_request('organisationUnits/%s.json?pageSize=10000' % sub_county.identifier)

                total_children = len(result['children'])
                for child_idx, child in enumerate(result['children']):
                    try:
                        child_facility = Facility.objects.get(identifier=child['id'])
                        child_facility.sub_county = sub_county
                        child_facility.save()
                    except ObjectDoesNotExist:
                        pass

                    self.show_status(sub_county_idx, total_sub_counties, child_idx, total_children)

        else:
            pass