def sync_org_units(): """ Synchronize DHIS2 Organization Units with local data. This data is used to fulfill the first requirement of `DHIS2 Integration`_: Allow mobile users in CommCareHQ to be associated with a particular DHIS2 Organisation Unit, so that when they create cases their new cases can be associated with that area or facility. .. _DHIS2 Integration: https://www.dropbox.com/s/8djk1vh797t6cmt/WV Sri Lanka Detailed Requirements.docx """ # Loop through all enabled domains for domain in Domain.get_all(): settings = Dhis2Settings.for_domain(domain.name) if settings is None or not settings.is_enabled(): continue dhis2_api = Dhis2Api(settings.dhis2.host, settings.dhis2.username, settings.dhis2.password, settings.dhis2.top_org_unit_name) # Is it a bad idea to read all org units into dictionaries and sync them ... their_org_units = {ou['id']: ou for ou in dhis2_api.gen_org_units_with_parents()} # ... or should we rather just drop all ours and import all theirs every time? org_unit_objects = FixtureManager(Dhis2OrgUnit, domain, ORG_UNIT_FIXTURES) our_org_units = {ou.id: ou for ou in org_unit_objects.all()} # Add new org units for id_, ou in their_org_units.iteritems(): if id_ not in our_org_units: org_unit = Dhis2OrgUnit(id=id_, name=ou['name'], parent_id=ou['parent_id']) org_unit.save() # Delete former org units for id_, ou in our_org_units.iteritems(): if id_ not in their_org_units: ou.delete()
def get_user_by_org_unit(domain, org_unit_id, top_org_unit_name): """ Look up user ID by a DHIS2 organisation unit ID """ result = (UserES() .domain(domain) .term('user_data.dhis_org_id', org_unit_id) .run()) if result.total: # Don't just assign all cases to the first user. Spread them fairly. i = random.randrange(result.total) return CommCareUser.wrap(result.hits[i]) # No user is assigned to this organisation unit (i.e. region or facility). # Try its parent org unit. org_unit_objects = FixtureManager(Dhis2OrgUnit, domain, ORG_UNIT_FIXTURES) org_units = {ou.id: ou for ou in org_unit_objects.all()} if ( org_unit_id in org_units and org_units[org_unit_id]['name'] != top_org_unit_name and org_units[org_unit_id]['parent_id'] ): return get_user_by_org_unit(domain, org_units[org_unit_id]['parent_id'], top_org_unit_name) # We don't know that org unit ID, or we're at the top for this project, or we're at the top of DHIS2 return None