Esempio n. 1
0
def parse_ped(ped_file,experiment_id):
    f = open(ped_file,'r')
    f.readline()
    patients = []
    for line in f:
        line = line.strip().split(',')
        p = Patient(patient_name = line[0], affliction_status=line[6]=='1', family=Family.objects.get_or_create(family_name=line[1])[0], gender= ('male' if line[5]=='0' else 'female'),experiment=Experiment.objects.get(pk=experiment_id))
        patients.append(p)
    Patient.objects.bulk_create(patients)
    print 'Saved %s Patients in the First Pass' % len(patients)
    f.close()
    f = open(ped_file,'r')
    f.readline()
    patients = []
    for line in f:
        changed = False
        line = line.strip().split(',')
        p = Patient.objects.get(patient_name=line[0],experiment_id__exact=experiment_id)
        if line[3] != '?':
            changed=True
            p.father = Patient.objects.get(patient_name=line[3],experiment_id__exact=experiment_id)
        if line[4] != '?':
            changed=True
            p.mother = Patient.objects.get(patient_name=line[4],experiment_id__exact=experiment_id)
        if changed:
            patients.append(p)
            p.save()
    print 'Updated %s Patients in the Second Pass' % len(patients)
Esempio n. 2
0
def handleNewUser(request):
    user = User(user_name=request.POST['user_name'],
                password=request.POST['password'],
                userType='patient')
    user.save()
    patient = Patient(user_id=str(user.pk))
    patient.save()
    request.session['user_id'] = str(user.pk)
    return redirect('patient:index')
Esempio n. 3
0
 def custom_signup(self, request, user):
     is_doctor = self.validated_data.get('is_doctor', False)
     if is_doctor:
         doctor = Doctor()
         doctor.user = user
         doctor.save()
     else:
         patient = Patient()
         patient.user = user
         patient.save()
Esempio n. 4
0
 def handle(self, *args, **options):
     book = pyExcelerator.parse_xls("excel.xls")
     patient_excel = book[0][1]
     diagnosis_excel = book[1][1]
     mkb = get_mkb(diagnosis_excel)
     for num_row in range(2, 2238):
         d_info = get_diagnosis_info(patient_excel, num_row, mkb)
         p_info = get_patient_info(patient_excel, num_row, d_info)
         if not p_info:
             continue
         patient = Patient(**p_info)
         patient.save()
         if not d_info:
             print patient_excel.get((num_row, 2))
             raise Exception(u'Нет информации по пациенту')
         d_info['patient'] = patient
         diagnosis = Diagnosis(**d_info)
         diagnosis.save()
Esempio n. 5
0
File: tests.py Progetto: leofn/nes
    def create_patient_mock(self, name='Pacient Test', user=None, gender_name='Masculino', date_birth='2001-01-15'):
        """ Cria um participante para ser utilizado durante os testes """

        gender = self.create_gender_mock(gender_name)
        p_mock = Patient()
        p_mock.name = name
        p_mock.date_birth = date_birth
        # p_mock.cpf = '374.276.738-08'
        p_mock.gender = gender
        p_mock.changed_by = user
        p_mock.save()
        return p_mock
Esempio n. 6
0
def create(request):
    if request.method == 'POST':
        try:
            data = loads(request.body)
            if data['name'] == '' or hasattr(data, 'name'):
                return JsonResponse({'message': 'unsuccessful createing'},
                                    safe=False)
            _Patient = Patient(name=data['name'],
                               family=data['family'],
                               national_code=data['national_code'],
                               birthday=data['birthday'],
                               gender=data['gender'])
            _Patient.save()
            return JsonResponse({'message': 'successful create new Patient'},
                                safe=False)
        except:
            return JsonResponse({'message': 'unsuccessful createing'},
                                safe=False)
    return JsonResponse({'message': 'most use POST method'}, safe=False)
Esempio n. 7
0
def record_patient(request):
    birth = request.POST['birthday']
    fname = request.POST['first_name']
    lname = request.POST['last_name']
    usrname = request.POST['username']
    user = User.objects.create_user(username=usrname,
                                    password=request.POST['ssn'],
                                    first_name=fname,
                                    last_name=lname,
                                    email=request.POST['email'])
    user.save()

    section = request.POST['section']
    room = request.POST['room']
    rec = Receptionist.objects.get(user=request.user)
    patient = Patient(username=usrname,
                      parent_hospital=rec.hospital,
                      user_type=2,
                      user=user,
                      firstname=fname,
                      lastname=lname,
                      Tel=request.POST['Tel'],
                      ssn=request.POST['ssn'],
                      birthday=birth,
                      age=request.POST['age'],
                      marital_status=request.POST['marital_status'],
                      occupation=request.POST['occupation'],
                      country=request.POST['country'],
                      city=request.POST['city'],
                      district=request.POST['district'],
                      street=request.POST['street'],
                      alley=request.POST['alley'],
                      building_no=request.POST['building_no'],
                      postal_code=request.POST['postal_code'],
                      gender=request.POST['gender'],
                      patient_room=room,
                      patient_section=section)
    patient.save()

    return patient
Esempio n. 8
0
def new(request):
	if request.method == 'POST':
		json_data = simplejson.loads(request.raw_post_data)
		try:
			patient = dict(json_data['patient'])
			name = patient['name']
			dateOfBirth = time.strptime(patient['dateOfBirth'], "%d-%m-%Y")
			identification = patient['identification']
			phoneNumber = patient['phoneNumber']
			ethnicity = patient['ethnicity']
			p = Patient(name=name, 
				identification=identification, 
				dateOfBirth=date(dateOfBirth.tm_year, dateOfBirth.tm_mon, dateOfBirth.tm_mday), 
				phoneNumber=phoneNumber, 
				ethnicity=ethnicity)
			p.save() 
		except KeyError:
			return HttpResponseServerError("Malformed Data, missing key")
		return HttpResponse(p, content_type="application/json", status=200)

	else:
		return HttpResponse("Only JSON post accepted", status=404)
Esempio n. 9
0
def book_slot(request, slot_id):
    if request.is_ajax():
        s = Slot.objects.get(id=slot_id)
        if request.POST["patient"] is None or int(request.POST["patient"]) == 0:
            # new Patient
            s.informations = request.POST["informations"]
            p = Patient(email=unicode(request.POST["email"]), first_name=unicode(request.POST["first_name"]),
                        last_name=unicode(request.POST["last_name"]), telephone=unicode(request.POST["telephone"]))
            p.confirm = string_random(32)
            p.save()
            mail_patient_welcome(request, p)
            s.patient = p
            s.informations = unicode(request.POST["informations"])
        else:
            p = Patient.objects.get(id=int(request.POST["patient"]))
            s.patient = p
        s.booked = True
        s.save()
        s.icalendar()
        mail_patient_new_appointment(request, s)
        d = {'return': True, 'slot': s.as_json()}
        return HttpResponse(json.dumps(d))
Esempio n. 10
0
File: tests.py Progetto: INCF/nes
    def create_patient_mock(self, name='Pacient Test', user=None, gender_name='Masculino', date_birth='2001-01-15'):
        """ Cria um participante para ser utilizado durante os testes """

        gender = self.create_gender_mock(gender_name)
        p_mock = Patient()
        p_mock.name = name
        p_mock.date_birth = date_birth
        # p_mock.cpf = '374.276.738-08'
        p_mock.gender = gender
        p_mock.changed_by = user
        p_mock.save()
        return p_mock
Esempio n. 11
0
def api_patient_create(request):
    user = Users.objects.get(pk=1)

    patient = Patient()

    if request.method == 'POST':
        serializer = PatientSerializer(patient, data=request.data)

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Esempio n. 12
0
def register(request):
    try:
        if not (request.user.is_authenticated() and request.user.profile.user_type==0)  :
            return HttpResponse("server_message: Access Denied")
    except:
            return HttpResponse("server_message: Access Denied")
    c={}
    if request.method=="POST":
       try:
                birth=request.POST['birthday']
                fname=request.POST['first_name']
                lname=request.POST['last_name']
                user=User.objects.create_user(username=request.POST['username'] ,
                        password=request.POST['ssn'],
                        first_name=fname,
                        last_name=lname,
                        email=request.POST['email']
                        )
                user.save()
                rec=Receptionist.objects.get(user=request.user)
                patient=Patient(
                        parent_hospital=rec.hospital,
                        user_type=2,
                        user=user,
                        firstname=fname,
                        lastname=lname,
                        Tel=request.POST['tel'],
                        ssn=request.POST['ssn'],
                        birthday=birth,
                        age=request.POST['age'],
                        marital_status=request.POST['marital_status'],
                        occupation=request.POST['occupation'],
                        country=request.POST['country'],
                        city=request.POST['city'],
                        district=request.POST['district'],
                        street=request.POST['street'],
                        alley=request.POST['alley'],
                        building_no=request.POST['building_no'],
                        postal_code=request.POST['postal_code']
                     )
                patient.save()
       except:
          try:
            if user: user.delete()
            if patient: patient.delete()
          except:
              pass
          return HttpResponse("An Error Has Occured During Registration, Since Required Fields Are Not  \
                              Entered Properly , Please Try Again" )


       c.update(csrf(request))
       return HttpResponseRedirect(reverse('rec_app:patients-list'))
    return render_to_response('patient/register.html',c,context_instance=RequestContext(request))
Esempio n. 13
0
def create_patient(request):
    form_title = "Add New Patient"
    if request.method == 'POST':
        form = PersonForm(request.POST)
        if form.is_valid():
            patient = Patient()
            patient.surname = request.POST['surname']
            patient.firstname = request.POST['firstname']
            patient.othername = request.POST['othername']
            patient.prefix = Prefix.objects.get(pk=request.POST['prefix'])
            patient.id_number = "{}-{}".format(
                date.today().strftime('%Y-%m'),
                1 if len(Patient.objects.all()) == 0 else
                (Patient.objects.all().order_by('-id')[0].id) + 1)
            patient.save()
            return HttpResponseRedirect(
                reverse('patient:view_patient', args=(patient.id, )))
    else:
        form = PersonForm()

    return render(request, 'patient/create_patient.html', {
        'form': form,
        'form_title': form_title
    })
Esempio n. 14
0
def create_patient(firstname, middlename, lastname, sex):    
    try:
        usr = User.objects.get(first_name=firstname, last_name=lastname)
        return Patient.objects.get(user=usr) 
    except Exception, e:
        firstclean = firstname.replace("'","")
        lastclean = lastname.replace("'","")            
        
        dob = date(random.randint(1955,2008), random.randint(1,12), random.randint(1,28))            
        pt = Patient()    
        pt.sex = sex
        pt.dob = dob
        
        pt.user = create_user(username=firstclean.lower() + "_" + lastclean.lower(), password='******', firstname=firstname, lastname=lastname)
        
        pt.is_primary = True
        
        pt.save()
        transaction.commit()
    
        return pt
Esempio n. 15
0
def patient_signup(request, a_id):
    ac = Account.objects.get(id=a_id)
    if request.method == 'POST':
        name = request.POST['name']
        phone = request.POST['phone']
        latitude = request.POST['latitude']
        longitude = request.POST['longitude']

        new_p = Patient(p_name=name,
                        p_phone=phone,
                        p_latitude=latitude,
                        p_longitude=longitude)
        new_p.save()
        ac.a_patient = new_p
        new_p.p_account = ac
        ac.save()
        new_p.save()
        return HttpResponseRedirect(
            reverse('patient:usermain', args=(new_p.id, )))

    return render(request, 'patient_signup.html', {'a': ac})
Esempio n. 16
0
from patient.models import Patient

f = open('customers.csv', 'r', encoding='utf-8')
info = []
rdr = csv.reader(f)
for row in rdr:
    name, phone, local, domain, passwd, payments, lat, lng = row
    tuple = (name, phone, local, domain, passwd, payments, lat, lng)
    info.append(tuple)
f.close()

count = 0
instancesa = []
instancesp = []
for (name, phone, local, domain, passwd, payments, lat, lng) in info:
    if name != 'name' and phone != 'phone':
        if count % 100 == 0:
            print(count)
        a = Account(a_local=local, a_domain=domain, a_password=passwd)
        p = Patient(p_name=name,
                    p_phone=phone,
                    p_latitude=lat,
                    p_longitude=lng)
        a.save()
        p.save()
        a.a_patient = p
        p.p_account = a
        a.save()
        p.save()
        count += 1
Esempio n. 17
0
def insert_patient(request):
    patient=Patient(Pt_name=request.POST["Pt_name"],\
                 Pt_bdate=request.POST["Pt_bdate"],\
                 Pt_man=request.POST["Pt_man"])
    patient.save()
    return redirect("/")
Esempio n. 18
0
def run():    
    reader = csv.reader(stdin)
    rows = iter(reader)
    header = rows.next()
    if tuple(header) != tuple(HEADER):
        raise Exception("incorrect header")
    patients_arr = []
    structure = (
        ('phone', 3, ('type', 'value')),
        ('address', 2, ('type', 'street', 'city', 'postal code', 'country')),
        ('provider', 9, ('type', 'number')),
    )
    def normalize(s):
        return s.lower().replace(' ',  '_')
    
    for row in rows:
        data = dict(zip(map(normalize, HEADER), row))
        patient_dict = dict()
        #for key in map(normalize, ('PACTID', 'Given Name', 'Family Name', 'CHW Membership')):
        for key in map(normalize, ('PACTID',
                                   'Given Name',
                                   'Family Name',
                                   'DOB',
                                   'Gender',
                                   'Arm',
                                   'HP',
                                   'ART Regimen',
                                   'Non-ART Regimen',
                                   'DOT - Sunday',
                                   'DOT - Monday',
                                   'DOT - Tuesday',
                                   'DOT - Wednesday',
                                   'DOT - Thursday',
                                   'DOT - Friday',
                                   'DOT - Saturday')):
            patient_dict[key] = data[key]
        for key, N, fields in structure:
            patient_dict[key] = []
            for i in range(1,N+1):
                format = "%s %d - %%s" % (key, i)                             
                patient_dict[key].append(tuple([data.get(normalize(format % f), '') for f in fields]))
        
        patients_arr.append(patient_dict)

#
#    # patients_arr = [{'pactid':123, 'phone':[{'type':...]}]
#    def get_user(first, last):
#        users = User.objects.filter(first_name=first_name, last_name=last_name)
#        if users.count():
#            if users.count() > 1:
#                print "Multiple users named %s %s" % (first_name, last_name)
#            # This is not a smart way to deal with two people with the same name
#            user = users[0]
#        else:
#            username = '******'.join(map(normalize, (first_name, last_name)))
#            while User.objects.filter(username=username):
#                username += '_'
#            user = User.objects.create_user(username, '', 'demo')
#            user.first_name = first_name
#            user.last_name = last_name
#            user.save()
#        return user
#
    for patient_dict in patients_arr:
        first_name, last_name = patient_dict['given_name'], patient_dict['family_name']
        #user = get_user(first_name, last_name)
        
        sex = patient_dict['gender'].lower()[0]
        dob = datetime.strptime(patient_dict['dob'], "%m/%d/%Y").date() #%m/%d/%Y
        pact_id = patient_dict['pactid']

        arm = patient_dict['arm']
        hp = patient_dict['hp']

        art_regimen = patient_dict['art_regimen']
        non_art_regimen = patient_dict['non-art_regimen']

        ptquerystring = last_name.lower() + first_name.lower() + dob.strftime("%Y-%m-%d")
        existing_pts = PactPatient.view("patient/search", key=ptquerystring, include_docs=True).count()

        if existing_pts > 0:
            print "Patient already exists, skipping"
            continue

        django_patient = Patient()
        django_patient.doc_id=None
        django_patient.save()

        cpatient = PactPatient(django_uuid=django_patient.id,
                            pact_id=pact_id,
                            first_name = first_name,
                            last_name=last_name,
                            middle_name = '',
                            gender = sex,
                            birthdate = dob,
                            art_regimen=art_regimen,
                            non_art_regimen=non_art_regimen,
                            primary_hp = hp,
                            arm = arm)


        raw_phones = patient_dict['phone']
        couched_phones = []
        addresses = patient_dict['address']
        couched_addresses = []
        #chw_membership = patient_dict['chw_membership']
        providers = patient_dict['provider']


        #pt_model.notes = str([chw_membership,providers])
        #pt_model.save()
#        patient_dict.user = user
#        patient_dict.sex="f"
#        patient_dict.save()

        for phone in raw_phones:
            ident = phone[0]
            val = phone[1]
            newphone = CPhone(description=ident, number=val, created=datetime.utcnow())
            cpatient.phones.append(newphone)

        for addr in addresses:            
            if addr[0] == '' and addr [1] == '' and addr[2] == '':
                continue
            newaddress = CAddress(type=addr[0], street=addr[1], city=addr[2], state="MA", postal_code=addr[3])
            cpatient.address.append(newaddress)

        days_of_week = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday']
        for day in days_of_week:
            cschedule= CDotSchedule(day_of_week=day, hp_username=patient_dict['dot_-_%s' % day])
            cpatient.dots_schedule.append(cschedule)


        cpatient.save()
        django_patient.doc_id = cpatient._id
        django_patient.save()
Esempio n. 19
0
def update_patient(conn, doc):
    print(doc)
    patient = Patient.objects.filter(
        extend__agilecrm=doc['id']).order_by('id').first()
    if not patient:
        patient = Patient(extend={'agilecrm': doc['id']})
    attrs = {p['name']: p['value'] for p in doc['properties']}
    patient.name = attrs['Case Name']

    patient.extend['case_id'] = attrs['name']
    if 'Date of Birth' in attrs:
        patient.birthday = time.strftime(
            '%Y-%m-%d', time.gmtime(int(attrs['Date of Birth'])))
    if 'Gender' in attrs:
        patient.extend['sex'] = attrs['Gender']
    if 'Appellation' in attrs:
        patient.extend['title'] = attrs['Appellation']
    if 'Last Bill' in attrs:
        url = attrs['Last Bill']
        if url.startswith('http://') or url.startswith('https://'):
            patient.extend['bill_url'] = url
    if 'Online Payment' in attrs:
        url = attrs['Online Payment']
        if url.startswith('http://') or url.startswith('https://'):
            patient.extend['payment_url'] = url

    patient.save()

    crm_guardians = set()
    crm_master_guardians = set()
    if 'Family Members' in attrs:
        for crm_customer_id in json.loads(attrs['Family Members']):
            crm_guardians.add(int(crm_customer_id))
    if 'Contact Window' in attrs:
        for crm_customer_id in json.loads(attrs['Contact Window']):
            crm_guardians.add(int(crm_customer_id))
            crm_master_guardians.add(int(crm_customer_id))

    for g in patient.guardian_set.select_related('customer').all():
        crm_customer_id = g.customer.profile.get('agilecrm')
        if crm_customer_id in crm_guardians:
            crm_guardians.remove(crm_customer_id)
            g.master = crm_customer_id in crm_master_guardians
            g.save()
        else:
            g.delete()

    for crm_customer_id in crm_guardians:
        c = Customer.objects.filter(
            profile__agilecrm=crm_customer_id).order_by('id').first()
        if not c:
            c = create_customer(conn, crm_customer_id)
        g = patient.guardian_set.filter(customer=c).first()
        if g:
            g.relation = patient.extend.get('title', '未填寫')
            g.master = crm_customer_id in crm_master_guardians
            g.save()
        else:
            patient.guardian_set.create(customer=c,
                                        relation=patient.extend.get(
                                            'title', '未填寫'),
                                        master=crm_customer_id
                                        in crm_master_guardians)

    employee = update_employee(doc['owner'])
    relations = patient.manager_set.filter(relation='照護經理')
    if relations.count() == 1:
        relation = relations[0]
        if relation.employee_id != employee.id:
            relation.employee = employee
            relation.save()
    else:
        if relations.count() > 1:
            relations.delete()
        patient.manager_set.create(employee=employee, relation='照護經理')
Esempio n. 20
0
def register_user(request):
    if request.method == 'POST':
        name = request.POST['name']

        phone = request.POST['phone']
        address = request.POST['address']
        age = request.POST['age']
        gender = request.POST['gender']
        total_disease = request.POST['total_disease']
        total_medicine = request.POST['total_medicine']
        # total_price = request.POST['price']
        adhar = request.POST['adhar']

        print(total_disease)
        print(total_medicine)

        patient = Patient()
        patient.name = name

        patient.phone = phone
        patient.age = age
        patient.sex = gender
        patient.address = address
        # patient.total_bill = total_price
        patient.aadhar_id = adhar
        patient.save()

        i = 1
        j = 1

        while i <= int(total_disease):
            disease_name = request.POST['disease' + str(i)]
            disease_obj = get_object_or_404(Disease, name=disease_name)
            disease_allot = DiseaseAllot()
            disease_allot.patient = patient
            disease_allot.disease = disease_obj
            disease_allot.name = disease_name
            disease_allot.save()
            i += 1

        while j <= int(total_medicine):
            medicine_name = request.POST['medicine' + str(j)]
            medicine_qty = request.POST['quantity' + str(j)]

            medicine_obj = get_object_or_404(Medicine, name=medicine_name)

            medicine_allot = MedicineAllot()
            medicine_allot.name = medicine_name
            medicine_allot.patient = patient

            medicine_allot.medicine = medicine_obj

            total_qty = int(medicine_obj.total_quantity) - int(medicine_qty)

            if total_qty > 0:
                medicine_obj.total_quantity = total_qty
                medicine_allot.quantity = medicine_qty
                # medicine_allot.price = int(medicine_obj.tablet_price) * int(medicine_qty)
                messages.success(
                    request,
                    str(total_qty) + " tablets of " + str(medicine_obj.name) +
                    " left in stock")

            elif total_qty == 0:
                medicine_obj.total_quantity = total_qty
                medicine_allot.quantity = medicine_qty
                # medicine_allot.price = int(medicine_obj.tablet_price) * int(medicine_qty)
                medicine_obj.available = False
                messages.success(request,
                                 medicine_obj.name + " is out of stock")

            else:
                medicine_obj.total_quantity = 0
                medicine_obj.available = False
                medicine_allot.quantity = int(medicine_obj.total_quantity)
                # medicine_allot.price = int(medicine_obj.tablet_price) * int(medicine_obj.total_quantity)
                messages.success(request,
                                 medicine_obj.name + " is out of stock")

            medicine_obj.save()
            medicine_allot.save()
            j += 1

        messages.success(request, "User Registered Successfully.")
        return HttpResponseRedirect('/patient/add_patient')

    else:
        return render(request, 'patient/add_patient.html', {})