Esempio n. 1
0
def run():
    subject = Subject.objects.get(uuid="26da580a-fc75-4f1a-92b2-be54e2865ceb")
    sp = SavedProcedure.objects.get(guid="5bcf6e9d-73a3-48db-9359-e1f110d3019f")
    encounter, observations =  v2compatlib.sp_to_encounter(sp,subject)
    print encounter
    for obs in observations:
        print obs
Esempio n. 2
0
def run():
    subject = Subject.objects.get(uuid="26da580a-fc75-4f1a-92b2-be54e2865ceb")
    sp = SavedProcedure.objects.get(
        guid="5bcf6e9d-73a3-48db-9359-e1f110d3019f")
    encounter, observations = v2compatlib.sp_to_encounter(sp, subject)
    print encounter
    for obs in observations:
        print obs
Esempio n. 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'
    
    # Begin upload to the emr
    #omrs = openmrslib.OpenMRS16(saved_procedure.upload_username,
    #                      saved_procedure.upload_password,
    #                      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)
    #omrs.create_patient(patient_id,
    #                    patient_first,
    #                    patient_last,
    #                    patient_gender,
    #                    patient_birthdate)
        
    # 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)
    '''
    #edata = {}
    #device = Device.objects.get(
    #observer = Observer.objects.get(username=client_id)
    #procedure = Procedure.objects.get(title=procedure_title)
    # mark encounter and binaries as uploaded
    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, obsDict =  v2compatlib.sp_to_encounter(saved_procedure,subject)
    encounter.save()
    observations = v2compatlib.responses_to_observations(encounter, observations, sort=True)
    for obs in observations:
	obs.save()
        if obs.concept.is_complex:
    	    b = BinaryResource.objects.get(sp=saved_procedure, id=obs.node)
    	    smtplib.sender.send_review_notification(obs)
     
    return result, message