def get_patient_by_uuid(requests, uuid): if not uuid: return None if not re.match(r'^[a-fA-F0-9\-]{36}$', uuid): logger.debug('Person UUID "{}" failed validation'.format(uuid)) return None return requests.get('/ws/rest/v1/patient/' + uuid, {'v': 'full'}).json()
def post_with_raise(self, uri, *args, **kwargs): response = self.post(uri, *args, **kwargs) try: response.raise_for_status() except HTTPError: logger.debug('Request: ', self.get_url(uri), kwargs) logger.debug('Response: ', response.json()) raise return response
def send_openmrs_data(requests, form_json, openmrs_config, case_trigger_infos, form_question_values): """ Updates an OpenMRS patient and creates visits :return: A response-like object that can be used by Repeater.handle_response """ response = None logger.debug('Fetching OpenMRS patient UUIDs with ', case_trigger_infos) for info in case_trigger_infos: assert isinstance(info, CaseTriggerInfo) response = sync_openmrs_patient(requests, info, form_json, form_question_values, openmrs_config) return response or OpenmrsResponse(404, 'Not Found')
def send_openmrs_data(requests, form_json, openmrs_config, case_trigger_infos, form_question_values): provider_uuid = getattr(openmrs_config, 'openmrs_provider', None) problem_log = [] person_uuids = [] logger.debug('Fetching OpenMRS patient UUIDs with ', case_trigger_infos) for info in case_trigger_infos: assert isinstance(info, CaseTriggerInfo) # todo: create patient if it doesn't exist? person_uuid = sync_openmrs_patient(requests, info, openmrs_config, problem_log) person_uuids.append(person_uuid) logger.debug('OpenMRS patient(s) found: ', person_uuids) # todo: find a better way to correlate to the correct or "main" patient if len(person_uuids) == 1 and all(person_uuid for person_uuid in person_uuids): person_uuid, = person_uuids info, = case_trigger_infos info.form_question_values.update(form_question_values) for form_config in openmrs_config.form_configs: logger.debug('Send visit for form?', form_config, form_json) if form_config.xmlns == form_json['form']['@xmlns']: logger.debug('Yes') send_openmrs_visit(requests, info, form_config, person_uuid, provider_uuid, visit_datetime=string_to_utc_datetime( form_json['form']['meta']['timeEnd']))
def send_openmrs_data(requests, form_json, case_trigger_infos, openmrs_config): problem_log = [] person_uuids = [] logger.debug(case_trigger_infos) for info in case_trigger_infos: assert isinstance(info, CaseTriggerInfo) # todo: create patient if it doesn't exist? person_uuid = sync_openmrs_patient(requests, info, openmrs_config, problem_log) person_uuids.append(person_uuid) logger.debug(person_uuids) # todo: find a better way to correlate to the correct or "main" patient if len(person_uuids) == 1 and all(person_uuid for person_uuid in person_uuids): person_uuid, = person_uuids info, = case_trigger_infos for form_config in openmrs_config.form_configs: logger.debug('send_openmrs_visit?', form_config, form_json) if form_config.xmlns == form_json['form']['@xmlns']: logger.debug('yes') send_openmrs_visit(requests, info, form_config, person_uuid, visit_datetime=string_to_utc_datetime( form_json['form']['meta']['timeEnd']))
def get_openmrs_patients(requests, importer, location=None): """ Send request to OpenMRS Reporting API and return results """ endpoint = '/ws/rest/v1/reportingrest/reportdata/' + importer.report_uuid params = parse_params(importer.report_params, location) response = requests.get(endpoint, params=params) try: response.raise_for_status() except HTTPError: logger.debug(response.json()) raise data = response.json() return data['dataSets'][0]['rows'] # e.g. ...
def set_person_properties(requests, person_uuid, properties): allowed_properties = ( 'gender', 'birthdate', 'birthdateEstimated', 'dead', 'deathDate', 'causeOfDeath') for p in properties: assert p in allowed_properties response = requests.post('/ws/rest/v1/person/{person_uuid}'.format( person_uuid=person_uuid), json=properties ) try: response.raise_for_status() except HTTPError: logger.debug(response.json()) raise return response.json()
def create_visits(requests, info, form_json, form_question_values, openmrs_config, person_uuid): provider_uuid = getattr(openmrs_config, 'openmrs_provider', None) info.form_question_values.update(form_question_values) for form_config in openmrs_config.form_configs: logger.debug('Send visit for form?', form_config, form_json) if form_config.xmlns == form_json['form']['@xmlns']: logger.debug('Yes') create_visit( requests, person_uuid=person_uuid, provider_uuid=provider_uuid, visit_datetime=string_to_utc_datetime(form_json['form']['meta']['timeEnd']), values_for_concept={obs.concept: [obs.value.get_value(info)] for obs in form_config.openmrs_observations if obs.value.get_value(info)}, encounter_type=form_config.openmrs_encounter_type, openmrs_form=form_config.openmrs_form, visit_type=form_config.openmrs_visit_type, # location_uuid=, # location of case owner (CHW) > location[meta][openmrs_uuid] )
def sync_openmrs_patient(requests, info, form_json, form_question_values, openmrs_config): patient = get_patient(requests, info, openmrs_config) if patient is None: raise ValueError('CommCare patient was not found in OpenMRS') person_uuid = patient['person']['uuid'] logger.debug('OpenMRS patient found: ', person_uuid) update_person_properties(requests, info, openmrs_config, person_uuid) name_uuid = patient['person']['preferredName']['uuid'] update_person_name(requests, info, openmrs_config, person_uuid, name_uuid) address_uuid = patient['person']['preferredAddress']['uuid'] if patient['person']['preferredAddress'] else None if address_uuid: update_person_address(requests, info, openmrs_config, person_uuid, address_uuid) else: create_person_address(requests, info, openmrs_config, person_uuid) sync_person_attributes(requests, info, openmrs_config, person_uuid, patient['person']['attributes']) create_visits(requests, info, form_json, form_question_values, openmrs_config, person_uuid) return OpenmrsResponse(200, 'OK')
def create_visit(requests, person_uuid, provider_uuid, visit_datetime, values_for_concept, encounter_type, openmrs_form, visit_type, location_uuid=None, patient_uuid=None): patient_uuid = patient_uuid or person_uuid start_datetime = server_datetime_to_openmrs_timestamp(visit_datetime) stop_datetime = server_datetime_to_openmrs_timestamp(visit_datetime + timedelta(days=1) - timedelta(seconds=1)) visit = { 'patient': patient_uuid, 'visitType': visit_type, 'startDatetime': start_datetime, 'stopDatetime': stop_datetime, } if location_uuid: visit['location'] = location_uuid response = requests.post_with_raise('/ws/rest/v1/visit', json=visit) visit_uuid = response.json()['uuid'] encounter = { 'encounterDatetime': start_datetime, 'patient': patient_uuid, 'form': openmrs_form, 'encounterType': encounter_type, 'visit': visit_uuid, } if location_uuid: encounter['location'] = location_uuid response = requests.post_with_raise('/ws/rest/v1/encounter', json=encounter) encounter_uuid = response.json()['uuid'] if provider_uuid: encounter_provider = {'provider': provider_uuid} uri = '/ws/rest/v1/encounter/{uuid}/encounterprovider'.format( uuid=encounter_uuid) requests.post_with_raise(uri, json=encounter_provider) observation_uuids = [] for concept_uuid, values in values_for_concept.items(): for value in values: observation = { 'concept': concept_uuid, 'person': person_uuid, 'obsDatetime': start_datetime, 'encounter': encounter_uuid, 'value': value, } if location_uuid: observation['location'] = location_uuid response = requests.post_with_raise('/ws/rest/v1/obs', json=observation) observation_uuids.append(response.json()['uuid']) logger.debug('Observations created: ', observation_uuids)
def create_visit(requests, person_uuid, visit_datetime, values_for_concept, encounter_type, openmrs_form, visit_type, patient_uuid=None): timestamp = server_datetime_to_openmrs_timestamp(visit_datetime) patient_uuid = patient_uuid or person_uuid observations = [ { "concept": concept_uuid, "value": value, "person": person_uuid, "obsDatetime": timestamp, } for concept_uuid, values in values_for_concept.items() for value in values ] observation_uuids = [] for observation in observations: response = requests.post('/ws/rest/v1/obs', json=observation) try: response.raise_for_status() except HTTPError: logger.debug(response.json()) raise observation_uuids.append(response.json()['uuid']) logger.debug('observations', observation_uuids) encounters = [ { "encounterType": encounter_type, "form": openmrs_form, "obs": observation_uuids, "patient": patient_uuid, } ] encounter_uuids = [] for encounter in encounters: response = requests.post('/ws/rest/v1/encounter', json=encounter) try: response.raise_for_status() except HTTPError: logger.debug(response.json()) raise encounter_uuids.append(response.json()['uuid']) logger.debug('encounters', encounter_uuids) visit = { "encounters": encounter_uuids, "patient": patient_uuid, "visitType": visit_type, } response = requests.post('/ws/rest/v1/visit', json=visit) try: response.raise_for_status() except HTTPError: logger.debug(response.json()) raise logger.debug(response.json()['uuid'])