Beispiel #1
0
def maybe_upload_procedure(saved_procedure):
    """Validates whether an encounter is ready to upload to the emr backend.
    Requires all associated BinaryResources be complete.
    
    Parameters: 
        saved_procedure
            The SavedProcedure object which may be uploaded.
    """
    result = True
    message = ""
    logging.debug("Should I upload %s to the MRS?" % saved_procedure.guid)
    binaries = saved_procedure.binaryresource_set.all()
    
    ready = True
    waiting = []
    ready_list = []
    # checking all associated binaries
    for binary in binaries:
        if binary.ready_to_upload():
            message = ("Encounter: %s Binary: %s/%s COMPLETE" % (
                        saved_procedure.guid, binary.guid, len(binaries)))
            ready = ready and True
            ready_list.append(binary.guid)
        else:
            logging.debug("BinaryResource: %s completed: %s/%s" % 
                         (binary.pk, binary.upload_progress, binary.total_size))
            waiting.append(binary.guid)
            message = ("Encounter: %s is WAITING on  %s" 
                       % (saved_procedure.guid, waiting))
            ready = ready and False
    logging.debug("Encounter: %s has %s READY and %s WAITING" 
                  % (saved_procedure.guid,ready_list,waiting))
    # We need to bail here if not ready
    if not ready:
        return result, message
    
    # if uploaded flag already true we don't want to try again
    if saved_procedure.uploaded:
        message = "Encounter -> %s, Already uploaded." %  saved_procedure.guid
        logging.info(message)
        return result, message
 
    # do the upload
    binaries_to_upload = [binary for binary in binaries if not binary.uploaded]
    logging.debug('Uploading Encounter -> %s, Binaries to upload = %s' 
                  % (saved_procedure.guid, binaries_to_upload))
    files = defaultdict(list)
    
    # Set file for upload 
    for binary in binaries_to_upload:
        files[str(binary.element_id)].append(str(binary.data.path))

    # prep text data for upload
    client_name = saved_procedure.client.name
    savedprocedure_guid = saved_procedure.guid

    # decodes and cleans up responses-OpenMRS specific
    responses = cjson.decode(saved_procedure.responses,True)
    cleaned_responses = []
    patient_id = ""
    patient_first = ""
    patient_last = ""
    patient_gender = ""
    patient_birthdate = ""
    patient_month = ""
    patient_day = ""
    patient_year = ""

    enrolled = 'Yes'
    enrolledtemp = responses.get('patientEnrolled', None)
    if enrolledtemp:
        enrolled = enrolledtemp.get('answer', 'Yes')
        del responses['patientEnrolled']

    procedure_title = ''
    procedure_title_element = responses.get('procedureTitle', None)
    if procedure_title_element:
        del responses['procedureTitle']
        procedure_title = procedure_title_element.get('answer', '')
    
    for eid,attr in responses.items():
        if enrolled == "Yes":
            if (eid == "patientId"):
                patient_id = attr.get('answer')
            elif (eid == "patientGender"):
                patient_gender = attr.get('answer')
            elif (eid == 'patientFirstName'):
                patient_first = attr.get('answer')
            elif (eid == 'patientLastName'):
                patient_last = attr.get('answer')
            elif (eid == 'patientBirthdateDay'):
                patient_day = attr.get('answer')
            elif (eid == 'patientBirthdateMonth'):
                patient_month = attr.get('answer')
            elif (eid == 'patientBirthdateYear') and (patient_year==""):
                patient_year = attr.get('answer')
            else:
                attr['id'] = eid
                cleaned_responses.append(attr)
        else:
            if (eid == "patientIdNew"):
                patient_id = attr.get('answer')
            elif (eid == "patientGenderNew"):
                patient_gender = attr.get('answer')
            elif (eid == 'patientFirstNameNew'):
                patient_first = attr.get('answer')
            elif (eid == 'patientLastNameNew'):
                patient_last = attr.get('answer')
            elif (eid == 'patientBirthdateDayNew'):
                patient_day = attr.get('answer')
            elif (eid == 'patientBirthdateMonthNew'):
                patient_month = attr.get('answer')
            elif (eid == 'patientBirthdateYearNew'):
                patient_year = attr.get('answer')
            else:
                attr['id'] = eid
                cleaned_responses.append(attr)
    #patient_birthdate = '%s/%s/%s' % (months_dict[patient_month], patient_day, 
    #                                  patient_year)
    
    if patient_id is None:
        patient_id = DEFAULT_PATIENT_ID
    
    if patient_gender in ['Male', 'male', 'M', 'm']:
        patient_gender = 'M'
    elif patient_gender in ['Female', 'female', 'F', 'f']:
        patient_gender = 'F'
    
    # Begin upload to the emr
    #if openmrslib.OPENMRS_VERSION < 1.8:
    #    omrs = openmrs.OpenMRS(saved_procedure.upload_username,
    #                      saved_procedure.upload_password,
    #                      settings.OPENMRS_SERVER_URL)
    #else:
    #        omrs = openmrslib.build_opener(host=settings.OPENMRS_SERVER_URL)
      
    # creates the patient upstream if it does not exist
    new_patient = True if enrolled == "No" else False
    logging.debug("patient enrolled: %s" % new_patient)
    if new_patient:
        logging.debug("Creating new patient: patient_id -> %s" % patient_id)
    '''
    if openmrslib.OPENMRS_VERSION < 1.8:
	pass
        omrs.create_patient(patient_id,
                        patient_first,
                        patient_last,
                        patient_gender,
                        patient_birthdate)
    else:
        auth = {"username": saved_procedure.username,
                "password": saved_procedure.password}
        omrs.create_patient(patient_id,
                        patient_first,
                        patient_last,
                        patient_gender,
                        patient_birthdate,
                        auth = auth)
    '''
        
    # execute upload
    #logging.debug("Uploading to OpenMRS: %s %s %s %s %s "
    #              % (patient_id, client_name,
    #                 savedprocedure_guid, files, cleaned_responses))
    '''
    result, msg, _ = omrs.upload_procedure(patient_id,
                                            client_name,
                                            procedure_title,
                                            savedprocedure_guid,
                                            cleaned_responses,
                                            files)
    '''
    #message = 'sp.pk -> %s, %s ' % (saved_procedure.pk, msg)
    # mark encounter and binaries as uploaded
    result = True
    logging.debug("API: RESULT = %s" % result )
    
    
    if result:
        saved_procedure.uploaded = True
        saved_procedure.save()
        for binary in binaries_to_upload:
            binary.uploaded = True
            binary.save()
            logging.debug("Uploaded = True %s" % binaries_to_upload)
        flush(saved_procedure) 
    
    encounter = v2.Encounter.objects.get(uuid=saved_procedure.guid)
    observations = v2compatlib.responses_to_observations(encounter, responses, sort=True)
    for obs in observations:
        obs.save()
        if obs.concept.is_complex:
            notification_sent = sender.send_review_notification(encounter)
            logging.info("Sent notification for Observation: %s" % obs.uuid)
    return result, message
Beispiel #2
0
            saved_procedure.save()
            for binary in binaries_to_upload:
                binary.uploaded = True
                binary.save()
                logging.debug("Uploaded = True %s" % binaries_to_upload)
            flush(saved_procedure)

    # Default is to create the observations locally
    else:
        encounter = v2.Encounter.objects.get(uuid=saved_procedure.guid)
        observations = v2compatlib.responses_to_observations(encounter, responses, sort=True)
        for obs in observations:
            obs.save()
        if result:
            #if obs.concept.is_complex:
            notification_sent = sender.send_review_notification(encounter)
            logging.info("Sent notification for Observation: %s" % encounter.uuid)
    return result, message

def register_binary(procedure_guid, element_id, data):
    """Creates the BinaryResource object associated with an encounter.

    Parameters:
        procedure_guid
            The encounter id
        element_id
            The element within the encounter for which the binary was recorded
        data
            The request file field (data, name)
    """
    try:
Beispiel #3
0
def maybe_upload_procedure(saved_procedure):
    """Validates whether an encounter is ready to upload to the emr backend.
    Requires all associated BinaryResources be complete.

    Parameters:
        saved_procedure
            The SavedProcedure object which may be uploaded.
    """
    result = True
    message = ""
    logging.debug("Should I upload %s to the MRS?" % saved_procedure.guid)
    binaries = saved_procedure.binaryresource_set.all()

    ready = True
    waiting = []
    ready_list = []
    # checking all associated binaries
    for binary in binaries:
        if binary.ready_to_upload():
            message = ("Encounter: %s Binary: %s/%s COMPLETE" % (
                        saved_procedure.guid, binary.guid, len(binaries)))
            ready = ready and True
            ready_list.append(binary.guid)
        else:
            logging.debug("BinaryResource: %s completed: %s/%s" %
                         (binary.pk, binary.upload_progress, binary.total_size))
            waiting.append(binary.guid)
            message = ("Encounter: %s is WAITING on  %s"
                       % (saved_procedure.guid, waiting))
            ready = ready and False
    logging.debug("Encounter: %s has %s READY and %s WAITING"
                  % (saved_procedure.guid,ready_list,waiting))
    # We need to bail here if not ready
    if not ready:
        return result, message

    # if uploaded flag already true we don't want to try again
    if saved_procedure.uploaded:
        message = "Encounter -> %s, Already uploaded." %  saved_procedure.guid
        logging.info(message)
        return result, message

    # do the upload
    binaries_to_upload = [binary for binary in binaries if not binary.uploaded]
    logging.debug('Uploading Encounter -> %s, Binaries to upload = %s'
                  % (saved_procedure.guid, binaries_to_upload))
    files = defaultdict(list)

    # Set file for upload
    for binary in binaries_to_upload:
        files[str(binary.element_id)].append(str(binary.data.path))

    # prep text data for upload
    client_name = saved_procedure.client.name
    savedprocedure_guid = saved_procedure.guid

    # decodes and cleans up responses-OpenMRS specific
    responses = cjson.decode(saved_procedure.responses,True)
    cleaned_responses = []
    patient_id = ""
    patient_first = ""
    patient_last = ""
    patient_gender = ""
    patient_birthdate = ""
    patient_month = ""
    patient_day = ""
    patient_year = ""

    enrolled = 'Yes'
    enrolledtemp = responses.get('patientEnrolled', None)
    if enrolledtemp:
        enrolled = enrolledtemp.get('answer', 'Yes')
        del responses['patientEnrolled']

    procedure_title = ''
    procedure_title_element = responses.get('procedureTitle', None)
    if procedure_title_element:
        del responses['procedureTitle']
        procedure_title = procedure_title_element.get('answer', '')

    for eid,attr in responses.items():
        if enrolled == "Yes":
            if (eid == "patientId"):
                patient_id = attr.get('answer')
            elif (eid == "patientGender"):
                patient_gender = attr.get('answer')
            elif (eid == 'patientFirstName'):
                patient_first = attr.get('answer')
            elif (eid == 'patientLastName'):
                patient_last = attr.get('answer')
            elif (eid == 'patientBirthdateDay'):
                patient_day = attr.get('answer')
            elif (eid == 'patientBirthdateMonth'):
                patient_month = attr.get('answer')
            elif (eid == 'patientBirthdateYear') and (patient_year==""):
                patient_year = attr.get('answer')
            else:
                attr['id'] = eid
                cleaned_responses.append(attr)
        else:
            if (eid == "patientIdNew"):
                patient_id = attr.get('answer')
            elif (eid == "patientGenderNew"):
                patient_gender = attr.get('answer')
            elif (eid == 'patientFirstNameNew'):
                patient_first = attr.get('answer')
            elif (eid == 'patientLastNameNew'):
                patient_last = attr.get('answer')
            elif (eid == 'patientBirthdateDayNew'):
                patient_day = attr.get('answer')
            elif (eid == 'patientBirthdateMonthNew'):
                patient_month = attr.get('answer')
            elif (eid == 'patientBirthdateYearNew'):
                patient_year = attr.get('answer')
            else:
                attr['id'] = eid
                cleaned_responses.append(attr)
    patient_birthdate = '%s/%s/%s' % (months_dict[patient_month], patient_day,
                                      patient_year)

    if patient_id is None:
        patient_id = DEFAULT_PATIENT_ID

    if patient_gender in ['Male', 'male', 'M', 'm']:
        patient_gender = 'M'
    elif patient_gender in ['Female', 'female', 'F', 'f']:
        patient_gender = 'F'

    # Save to self or upstream

    if settings.TARGET == targets.OPENMRS:
        # Begin upload to the emr
        if openmrslib.OPENMRS_VERSION < 1.8:
            omrs = openmrs.OpenMRS(saved_procedure.upload_username,
                              saved_procedure.upload_password,
                              settings.OPENMRS_SERVER_URL)
        else:
                omrs = openmrslib.build_opener(host=settings.OPENMRS_SERVER_URL)

        # creates the patient upstream if it does not exist
        new_patient = True if enrolled == "No" else False
        logging.debug("patient enrolled: %s" % new_patient)
        if new_patient:
            logging.debug("Creating new patient: patient_id -> %s" % patient_id)
        if openmrslib.OPENMRS_VERSION < 1.8:
            omrs.create_patient(patient_id,
                            patient_first,
                            patient_last,
                            patient_gender,
                            patient_birthdate)
        else:
            auth = {"username": saved_procedure.username,
                    "password": saved_procedure.password}
            omrs.create_patient(patient_id,
                            patient_first,
                            patient_last,
                            patient_gender,
                            patient_birthdate,
                            auth = auth)


        # execute upload
        logging.debug("Uploading to OpenMRS: %s %s %s %s %s "
                      % (patient_id, client_name,
                         savedprocedure_guid, files, cleaned_responses))
        result, msg, _ = omrs.upload_procedure(patient_id,
                                                client_name,
                                                procedure_title,
                                                savedprocedure_guid,
                                                cleaned_responses,
                                                files)
        message = 'sp.pk -> %s, %s ' % (saved_procedure.pk, msg)
        # mark encounter and binaries as uploaded
        result = True
        logging.debug("API: RESULT = %s" % result )
        if result:
            saved_procedure.uploaded = True
            saved_procedure.save()
            for binary in binaries_to_upload:
                binary.uploaded = True
                binary.save()
                logging.debug("Uploaded = True %s" % binaries_to_upload)
            flush(saved_procedure)

    # Default is to create the observations locally
    else:
        encounter = v2.Encounter.objects.get(uuid=saved_procedure.guid)
        observations = v2compatlib.responses_to_observations(encounter, responses, sort=True)
        for obs in observations:
            obs.save()
        if result:
            #if obs.concept.is_complex:
            notification_sent = sender.send_review_notification(encounter)
            logging.info("Sent notification for Observation: %s" % encounter.uuid)
    return result, message
Beispiel #4
0
                binary.uploaded = True
                binary.save()
                logging.debug("Uploaded = True %s" % binaries_to_upload)
            flush(saved_procedure)

    # Default is to create the observations locally
    else:
        encounter = v2.Encounter.objects.get(uuid=saved_procedure.guid)
        observations = v2compatlib.responses_to_observations(encounter,
                                                             responses,
                                                             sort=True)
        for obs in observations:
            obs.save()
        if result:
            #if obs.concept.is_complex:
            notification_sent = sender.send_review_notification(encounter)
            logging.info("Sent notification for Observation: %s" %
                         encounter.uuid)
    return result, message


def register_binary(procedure_guid, element_id, data):
    """Creates the BinaryResource object associated with an encounter.

    Parameters:
        procedure_guid
            The encounter id
        element_id
            The element within the encounter for which the binary was recorded
        data
            The request file field (data, name)