Example #1
0
def validate_credentials(request):
    """Validates user credentials with the backing data store.
    
    Request parameters:
        username
            a valid username
        password
            a valid password
    
    Parameters:
        request
            An authorization check request.
    """
    try:
        username = request.REQUEST.get("username", None)
        password = request.REQUEST.get("password", None)
        logging.info("username: "******"Credential check: SUCCESS")
            response = json_succeed("username and password validated!")
        else:
            logging.debug("Credential check: FAIL")
            response = json_fail(
                "username and password combination incorrect!")
    except Exception, e:
        msg = '%s validate_credentials' % MSG_MDS_ERROR
        logging.error('%s %s' % (msg, str(e)))
        response = json_fail(msg)
Example #2
0
def getPatient(uri, user, passwd, userid):
    """Executes get request to the data store for checking a patient id.
    
    Parameters:
        uri
            The server url.
        user
            A valid username.
        passwd
            A valid password.
    """
    # Create an OpenerDirector with support for Basic HTTP Authentication...
    omrs = openmrs.OpenMRS(user, passwd, settings.OPENMRS_SERVER_URL)
    if omrs.validate_credentials(user, passwd):
        result = omrs.getPatient(user, passwd, userid)
        return result
    else:
        return None
Example #3
0
def getAllPatients(uri, user, passwd):
    """Gets all patients from OpenMRS.
    
    Parameters:
        uri
            The server url.
        user
            A valid username.
        passwd
            A valid password.
    """
    logging.debug("getAllPatients")
    omrs = openmrs.OpenMRS(user, passwd, settings.OPENMRS_SERVER_URL)
    if omrs.validate_credentials(user, passwd):
        result = omrs.getAllPatients(user, passwd)
        return result
    else:
        return None
Example #4
0
def patient_list(request):
    """Accepts a request to return a list of all patients from the backing data
    store. Used for synching the mobile client.
    
    Warning: This can return a significant amount of patient data.
    
    Request parameters:
        username
            a valid username
        password
            a valid password
            
    Parameters:
        request
            A HTTP request for a patient list.
    
    :Authors: Sana dev team
    :Version: 1.1
    """
    logging.info("entering patient list proc")
    username = request.REQUEST.get("username", None)
    password = request.REQUEST.get("password", None)
    url = settings.OPENMRS_SERVER_URL
    try:
        #plist = getAllPatients(url, username, password)
        #data = parseAll(plist)
        #logging.info("we finished getting the patient list")
        #response = json_succeed(data)
        omrs = openmrs.OpenMRS(username, password, url)
        result = omrs.read_patient(username, password)
        data = openmrs.PatientForm().from_get(result)
        if len(data) == 1:
            data = data[0]
        response = json_succeed(data)
    except Exception, e:
        et, val, tb = sys.exc_info()
        trace = traceback.format_tb(tb)
        err = "Exception : %s %s %s" % (et, val, trace[0])
        for tbm in trace:
            logging.error(tbm)
        logging.error("Got exception while fetching patient list: %s" % e)
        response = json_fail("Problem while getting patient list: %s" % e)
Example #5
0
def patient_get(request, id):
    """Accepts a request to validate a patient id from the backing data store. 
    Successful retrieval will return a a SUCCESS message with the patient data 
    formatted as::
        
        <given_name><yyyy><mm><dd><family_name>f
    
    Request params:
        username
            a valid username
        password
            a valid password
            
    Parameters:
        request
            A patient request by id.
        id
            The id to look up.
    """
    logging.info("entering patient get proc")
    username = request.REQUEST.get("username", None)
    password = request.REQUEST.get("password", None)
    url = settings.OPENMRS_SERVER_URL
    logging.info("About to getPatient")
    try:
        #patient = getPatient(url, username, password, id)
        #data = parseOne(patient)
        omrs = openmrs.OpenMRS(username, password, url)
        result = omrs.read_patient(username, password, patient_id=id)
        data = openmrs.PatientForm().from_get(result)
        if len(data) == 1:
            data = data[0]
        response = json_succeed(data)

    except Exception, e:
        et, val, tb = sys.exc_info()
        trace = traceback.format_tb(tb)
        error = "Exception : %s %s %s" % (et, val, trace[0])
        for tbm in trace:
            logging.error(tbm)
        response = json_fail("couldn't get patient %s" % error)
Example #6
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', "No")
    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():
        # Short circuiting to get around nasty hack with Sana client
        #if enrolled == "Yes":
        if True:
            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:
            # TODO remove this deprecated bit
            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)
    #if len(patient_month) == 1:
    #    patient_month = "0%s" % patient_month
    logging.debug('month: %s' % months_dict.get(patient_month,patient_month))
    logging.debug('day: %s' %patient_day)
    logging.debug('year: %s' % patient_year)
    patient_birthdate = '%s/%s/%s' % (patient_day,
                                      months_dict.get(patient_month,patient_month),
                                      patient_year)

    if patient_id is None:
        patient_id = DEFAULT_PATIENT_ID

    if patient_gender in MALE:
        patient_gender = 'M'
    elif patient_gender in FEMALE:
        patient_gender = 'F'

    # Begin upload to the emr
    omrs = openmrs.OpenMRS(saved_procedure.upload_username,
                          saved_procedure.upload_password,
                          settings.OPENMRS_SERVER_URL)

    exists = omrs.read_patient(saved_procedure.upload_username,
                                 saved_procedure.upload_password,
                                 patient_id=patient_id).read()
    # Uncomment if you want to see the raw result.
    #logging.debug("patient exists: %s" % exists)
    pexists = cjson.decode(exists).get("results",None) if exists else None
    if not pexists:
        logging.debug("Creating new patient")
        omrs.create_patient(patient_id,
                            patient_first,
                            patient_last,
                            patient_gender,
                            patient_birthdate,
                            saved_procedure.upload_username,
                            saved_procedure.upload_password)
        omrs.delete_session()
    else:
        logging.debug("Updating patient.")
        #TODO omrs.update_patient
        omrs.delete_session()
    # 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
    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)
    return result, message