Beispiel #1
0
def my_patient_activity(request, template_name="pactcarehq/patients_dashboard.html"):
    """Return a list of all the patients in the system"""
    #using per patient instance lookup...slow, but reuasable
    context= RequestContext(request)

    if request.user.is_superuser == True:
        #patients = Patient.objects.all()
        assignments = get_db().view('pactcarehq/chw_assigned_patients').all()
    else:
        assignments = get_db().view('pactcarehq/chw_assigned_patients', key=request.user.username).all()

    chw_patient_dict = {}
    for res in assignments:
        chw = res['key']
        pact_id = res['value'].encode('ascii')
        if not chw_patient_dict.has_key(chw):
            chw_patient_dict[chw] = []
        chw_patient_dict[chw].append(PactPatient.view('pactcarehq/patient_pact_ids', key=pact_id, include_docs=True).first())

    #sorted_pts = sorted(patients, key=lambda p: p.couchdoc.last_name)
    #keys = [p.couchdoc.pact_id for p in sorted_pts]
    #context= RequestContext(request)

    chws = sorted(chw_patient_dict.keys())
    #patients = sorted(patients, key=lambda x: x.couchdoc.last_name)
    context['chw_patients_arr'] = [(x, chw_patient_dict[x]) for x in chws]
    #context['chw_patients'] = chw_patient_dict
    return render_to_response(template_name, context_instance=context)
Beispiel #2
0
def getpatient(pact_id):
    if patient_pactid_cache.has_key(pact_id):
        return patient_pactid_cache[pact_id]
    else:
        pt = PactPatient.view('pactcarehq/patient_pact_ids', key=str(pact_id), include_docs=True).first()
        patient_pactid_cache[pact_id] = pt
        return pt
Beispiel #3
0
    def testCreateDuplicatePatient(self):
        pt1 = self.testCreatePatient()

        try:
            newpatient = PactPatient()
            newpatient.first_name = 'mock'
            newpatient.last_name = lorem_ipsum.words(1)
            newpatient.birthdate = (datetime.utcnow() - timedelta(days=random.randint(0,7000))).date()
            newpatient.pact_id = pt1.pact_id
            newpatient.primary_hp = 'mock-hp-' + str(random.randint(0,100000))
            newpatient.gender = 'f'
            newpatient.save()
            self.fail("error, you should not be able to save a patient with duplicate pact ids")
        except DuplicateIdentifierException, e:
            pass #yay, success at finding the bad pactid
Beispiel #4
0
 def get_new_patient_doc_id(self):
     pts = PactPatient.view('patient/name_search_id', key=self.last_name.lower() + "_" + self.first_name.lower(), include_docs=True).all()
     for pt in pts:
         pact_id = str(pt.pact_id)
         new_id = pt._id
         if cmp(pact_id, str(self.pact_id)) == 0:
             return new_id
         else:
             print "non matching pact ids: |%s| != |%s|" % (self.pact_id, pact_id)
     return None
Beispiel #5
0
    def testDeletePatientFromCouchDoc(self):
        start_pt_count= Patient.objects.all().count()
        start_couch_pt_count = PactPatient.view('patient/all').count()
        pt_document = self.testCreatePatient()

        create_pt_count = Patient.objects.all().count()
        create_couch_pt_count = PactPatient.view('patient/all').count()

        #sanity check that it's there
        self.assertEquals(start_pt_count+1, create_pt_count)
        self.assertEquals(start_couch_pt_count+1, create_couch_pt_count)

        pt_document.delete()

        del_pt_count = Patient.objects.all().count()
        del_couch_pt_count = PactPatient.view('patient/all').count()

        self.assertEquals(start_pt_count, del_pt_count)
        self.assertEquals(start_couch_pt_count, del_couch_pt_count)
Beispiel #6
0
def debug_casexml_new(request):
    """
    Use the standard way for dimagi.case casexml generation method to get casexml.  This is case OTA Restore for Pact.
    """
    regblock = get_ghetto_registration_block(request.user)
    patient_blocks = [pt.ghetto_xml() for pt in PactPatient.view('patient/search', include_docs=True).all()]
    resp_text = "<restoredata>%s %s</restoredata>" % (regblock, '\n'.join(patient_blocks))
    template_name="pactcarehq/debug_casexml.html"
    context = RequestContext(request)
    context['casexml'] = resp_text
    return render_to_response(template_name, context_instance=context)
Beispiel #7
0
def get_caselist(request):
    """Intermediary/ghetto way of producing casexml, to be deprecated.
    """
    regblock= get_ghetto_registration_block(request.user)
    patient_block = ""
    patients = PactPatient.view("patient/search", include_docs=True)
    for pt in patients:
        patient_block += pt.ghetto_xml()
    resp_text = "<restoredata>%s %s</restoredata>" % (regblock, patient_block)
    #logging.error(resp_text)

    response = HttpResponse(mimetype='text/xml')
    response.write(resp_text)
    response['Content-Length'] = len(resp_text)
    return response
Beispiel #8
0
def show_dots_note(request, doc_id, template_name="pactcarehq/view_dots_submit.html"):
    context = RequestContext(request)
    xform = XFormInstance.get(doc_id)
    dots_note = {}
    raw = xform.to_json()['form']



    dots_note['chw'] = raw['Meta']['username']
    dots_note['encounter_date'] = raw['encounter_date']
    dots_note['schedued'] = raw['scheduled']
    dots_note['visit_type'] = raw['visit_type']
    dots_note['visit_kept'] = raw['visit_kept']
    dots_note['contact_type'] = raw['contact_type']
    
    if raw.has_key('observed_art'):
        dots_note['observed_art'] = raw['observed_art']
    else:
        dots_note['observed_art'] = 'No'

    if raw.has_key('observed_art_dose'):
        dots_note['observed_art_dose'] = raw['observed_art_dose']
    else:
        dots_note['observed_art_dose'] = 'No'
    if raw.has_key('observed_non_art_dose'):
        dots_note['observed_non_art_dose'] = raw['observed_non_art_dose']
    else:
        dots_note['observed_non_art_dose'] = 'No'

    if raw.has_key('observed_non_art'):
        dots_note['observed_non_art'] = raw['observed_non_art']
    else:
        dots_note['observed_non_art'] = 'No'
    try:
        raw['notes'] = raw['notes'].replace("'", "&quot;")
        raw['notes'] = raw['notes'].replace('"', "&quot;")
        raw['notes'] = raw['notes'].replace("\n", "<br>")
    except:
        raw['notes'] = ''



    context['dots_note'] = dots_note
    raw['pillbox_check']['check'] = ''
    raw['pillbox_check']['artnow'] = ''
    raw['pillbox_check']['nonartnow'] = ''
    raw['static'] = ''

    if raw.has_key('art_no_details'):
        raw['art_no_details'] = raw['art_no_details'].replace('"', "&quot;")
        raw['art_no_details'] = raw['art_no_details'].replace("'", '&apos;')
        raw['art_no_details'] = raw['art_no_details'].replace("\n", '<br>')

    if raw.has_key('non_art_no_details'):
        raw['non_art_no_details'] = raw['non_art_no_details'].replace('"', "&quot;")
        raw['non_art_no_details'] = raw['non_art_no_details'].replace("'", '&apos;')
        raw['non_art_no_details'] = raw['non_art_no_details'].replace("\n", '<br>')
    

    #for key, val in raw.items():
        #print "%s: %s" % (key, val)
    context['raw_note'] = simplejson.dumps(raw)
    case_id = xform['form']['case']['case_id']

    ###########################################################
    #for dev purposes this needs to be done for testing
    #but this is important still tog et the patient info for display
    #case_id = _hack_get_old_caseid(case_id)
    patient = PactPatient.view('patient/all', key=case_id, include_docs=True).first()
    if patient == None:
        patient_name = "Unknown"
    else:
        patient_name = patient.first_name + " " + patient.last_name
    context['patient_name'] = patient_name
    ##############################################################



    comment_docs = CSimpleComment.view('patient/all_comments', key=doc_id, include_docs=True).all()
    comment_arr = []
    for cdoc in comment_docs:
        if cdoc.deprecated:
            continue
        comment_arr.append([cdoc, cdoc.created])

    comment_arr = sorted(comment_arr, key=lambda x: x[1], reverse=True)
    context['comments'] = comment_arr

    if request.method == 'POST':
            form = ProgressNoteComment(data=request.POST)
            context['form'] = form
            if form.is_valid():
                edit_comment = form.cleaned_data["comment"]
                ccomment = CSimpleComment()
                ccomment.doc_fk_id = doc_id
                ccomment.comment = edit_comment
                ccomment.created_by = request.user.username
                ccomment.created = datetime.utcnow()
                ccomment.save()
                return HttpResponseRedirect(request.path)
    else:
        #it's a GET, get the default form
        if request.GET.has_key('comment'):
            context['form'] = ProgressNoteComment()
    return render_to_response(template_name, context_instance=context)
Beispiel #9
0
def show_progress_note(request, doc_id, template_name="pactcarehq/view_progress_submit.html"):
    context = RequestContext(request)
    xform = XFormInstance.get(doc_id)
    progress_note = xform['form']['note']
    progress_note['memo'] = progress_note['memo'].replace('"', '&quot;')
    progress_note['memo'] = progress_note['memo'].replace("'", '&apos;')
    progress_note['memo'] = progress_note['memo'].replace("\n", '<br>')
    progress_note['memo'] = progress_note['memo'].replace("\t", '&nbsp;')

    progress_note['adherence']['freetext'] = progress_note['adherence']['freetext'].replace('"', '&quot;')
    progress_note['adherence']['freetext'] = progress_note['adherence']['freetext'].replace("\n", '<br>')
    progress_note['adherence']['freetext'] = progress_note['adherence']['freetext'].replace("\t", '&nbsp;')
    progress_note['adherence']['freetext'] = progress_note['adherence']['freetext'].replace("'", '&apos;')

    try:
        progress_note['times']['other_location'] = progress_note['times']['other_location'].replace("'", "&quot;")
    except:
        pass
    try:
        progress_note['adherence']['freetext'] = progress_note['adherence']['freetext'].replace("'", "&quot;")
    except:
        pass

    progress_note['chw'] = xform.form['Meta']['username']
    context['progress_note'] = simplejson.dumps(xform.to_json()['form']['note'])

    case_id = xform['form']['case']['case_id']



    ###########################################################
    #for dev purposes this needs to be done for testing
    #but this is important still tog et the patient info for display
    #case_id = _hack_get_old_caseid(case_id)
    patient = PactPatient.view('patient/all', key=case_id, include_docs=True).first()
    if patient == None:
        patient_name = "Unknown"
    else:
        patient_name = patient.first_name + " " + patient.last_name
    context['patient_name'] = patient_name
    ##############################################################



    comment_docs = CSimpleComment.view('patient/all_comments', key=doc_id, include_docs=True).all()
    comment_arr = []
    for cdoc in comment_docs:
        if cdoc.deprecated:
            continue
        comment_arr.append([cdoc, cdoc.created])

    comment_arr = sorted(comment_arr, key=lambda x: x[1], reverse=True)
    context['comments'] = comment_arr

    if request.method == 'POST':
            form = ProgressNoteComment(data=request.POST)
            context['form'] = form
            if form.is_valid():
                edit_comment = form.cleaned_data["comment"]
                ccomment = CSimpleComment()
                ccomment.doc_fk_id = doc_id
                ccomment.comment = edit_comment
                ccomment.created_by = request.user.username
                ccomment.created = datetime.utcnow()
                ccomment.save()
                return HttpResponseRedirect(reverse('show_progress_note', kwargs= {'doc_id': doc_id}))
    else:
        #it's a GET, get the default form
        if request.GET.has_key('comment'):
            context['form'] = ProgressNoteComment()
    return render_to_response(template_name, context_instance=context)
Beispiel #10
0
def _get_submissions_for_user(username):
    """For a given username, return an array of submissions with an element [doc_id, date, patient_name, formtype]"""
    xform_submissions = XFormInstance.view("pactcarehq/all_submits", key=username, include_docs=True).all()
    submissions = []
    for xform in xform_submissions:
        if not xform.form.has_key('case'):
            continue
        if not xform.form['case'].has_key('case_id'):
            continue
        case_id = xform.form['case']['case_id']

        #for dev purposes this needs to be done for testing
        #case_id = _hack_get_old_caseid(case_id)
        if not patient_case_id_cache.has_key(case_id):
            patient = PactPatient.view('pactpatient/by_case_id', key=case_id, include_docs=True).first()
            patient_case_id_cache[case_id]= patient
        patient = patient_case_id_cache[case_id]
        
        if patient == None:
            patient_name = "Unknown"
        else:
            patient_name = patient.last_name

        xmlns = xform['xmlns']

        def stringify_delta(td):
            #where it's 0:07:06 H:M:S
            presplits = str(td).split(',')

            splits = presplits[-1].split(':')
            hours = int(splits[0])
            mins = int(splits[1])
            secs = int(splits[2])
            if secs > 30:
                mins+= 1
                secs = 0
            if mins > 30:
                hours += 1
                mins = 0
            newsplit = []
            days = False
            if len(presplits) == 2 and presplits[0] != "-1 day":
                #there's a day here
                newsplit.append(presplits[0])
                days=True

            if hours > 0:
                newsplit.append("%d hr" % (hours))
            if mins > 0 and days == False:
                newsplit.append("%d min" % (mins))
            return ', '.join(newsplit)


        started = xform.get_form['Meta']['TimeStart']
        ended = xform.get_form['Meta']['TimeEnd']
        start_end = stringify_delta(ended - started)
        received = xform['received_on']
        end_received = stringify_delta(received - ended)

        if xmlns == 'http://dev.commcarehq.org/pact/dots_form':
            formtype = "DOTS"
            submissions.append([xform._id, xform.form['encounter_date'], patient, formtype, started, start_end, end_received, received])
        elif xmlns == "http://dev.commcarehq.org/pact/progress_note":
            formtype = "Progress Note"
            submissions.append([xform._id, xform.form['note']['encounter_date'], patient, formtype,started, start_end, end_received, received])
        elif xmlns == "http://dev.commcarehq.org/pact/bloodwork":
            formtype = "Bloodwork"
            #TODO implement bloodwork view
#            submissions.append([xform._id, xform.form['case']['date_modified'].date(), patient_name, formtype,started, start_end, end_received, received])
        else:
            formtype = "Unknown"
            #submissions.append([xform._id, xform.form['Meta']['TimeEnd'], patient_name, formtype, started, start_end, end_received, received])
    submissions=sorted(submissions, key=lambda x: x[1])
    return submissions
Beispiel #11
0
    def testCreatePatient(self):
        oldptcount = Patient.objects.all().count()
        oldcptcount = PactPatient.view('patient/all').count()
        
        newpatient = PactPatient()
        newpatient.first_name = 'mock'
        newpatient.last_name = lorem_ipsum.words(1)
        newpatient.birthdate = (datetime.utcnow() - timedelta(days=random.randint(0,7000))).date()
        newpatient.pact_id = 'mock_id-' + str(random.randint(0,100000))
        newpatient.primary_hp = 'mock-hp-' + str(random.randint(0,100000))
        newpatient.gender = 'f'
        newpatient.save()

        newptcount = Patient.objects.all().count()
        newcptcount = PactPatient.view('patient/all').count()

        self.assertEquals(oldptcount+1, newptcount)
        self.assertEquals(oldcptcount+1, newcptcount)
        return newpatient