Exemplo n.º 1
0
 def test_bulk_insert_should_throw_error_if_file_does_not_exist(self):
     p = Patient()
     p.save()
     s = Sample(patient=p)
     s.save()
     self.assertRaises(
         IOError, Clonotype.import_adaptive, s, '/fake/path/to/fake/file')
Exemplo n.º 2
0
 def validate(self, data):
     validated_data = super(PatientForm).validate(data)
     validated_data['inclusion_code'] = Patient.hash(
         validated_data['inclusion_code'])
     validated_data['inclusion_nb'] = Patient.hash(
         validated_data['inclusion_nb'])
     return validated_data
Exemplo n.º 3
0
def create_profile_for_new_user(sender, created, instance, **kwargs):
    # TODO - use this signal to create blank patient profile 
    if created:
        owner1 = User.objects.get(id = 1)
        profile = Patient(user=instance)
        profile.save()

    pass
Exemplo n.º 4
0
    def managePatients(self, force, patientNumber):
        if (Patient.objects.all().count() != 0):
            self.stdout.write("\tPatients already exist in the system\n")
            if not force:
                return None

        self.stdout.write("\tDeleting all the Patients in the system\n")
        Patient.objects.all().delete()

        self.stdout.write("\tCreating the random Patients\n")
        first_names = ('Afonso', 'Alexandre', 'André', 'Artur', 'António',
                       'Ângelo', 'Mateus', 'Matias', 'Martim', 'Miguel',
                       'Marco', 'Mário', 'Micael', 'Jaime', 'José', 'João',
                       'Joaquim', 'Jorge', 'Joel', 'Isaac', 'Ivo', 'Ezequiel',
                       'Adolfo', 'Ianis', 'Teodoro', 'Salomão', 'Elvis')

        last_names = ('Silva', 'Santos', 'Ferreira', 'Pereira', 'Oliveira',
                      'Costa', 'Rodrigues', 'Martins', 'Jesus', 'Sousa',
                      'Fernandes', 'Gonçalves', 'Gomes', 'Lopes', 'Marques',
                      'Alves', 'Almeida', 'Ribeiro', 'Pinto', 'Carvalho',
                      'Teixeira', 'Moreira', 'Correia', 'Mendes', 'Nunes',
                      'Soares', 'Vieira', 'Monteiro', 'Cardoso', 'Rocha',
                      'Raposo', 'Neves', 'Coelho', 'Cruz', 'Cunha', 'Pires',
                      'Ramos', 'Reis', 'Simões', 'Antunes')

        for x in range(patientNumber / 2):
            fname = random.choice(first_names)
            lname = random.choice(last_names)
            Patient(first_name=fname + " " + random.choice(first_names),
                    last_name=random.choice(last_names) + " " + lname,
                    status=Patient.DISCHARGED,
                    gender="M",
                    birthdate=self.dateRandom("1960-01-01", "2000-01-01",
                                              '%Y-%m-%d'),
                    phone="234" + str(random.randint(100, 999)) +
                    str(random.randint(100, 999)),
                    email=(fname + "." + lname + "@mail.com").lower()).save()

        first_names = ('Pérola', 'Lua', 'Josiane', 'Chloe', 'Giulia', 'Perla',
                       'Teresa', 'Joana', 'Juliana', 'Júlia', 'Luísa',
                       'Leonor', 'Letícia', 'Sofia', 'Luana', 'Liliana',
                       'Lara', 'Maria', 'Margarida', 'Marta', 'Tânia',
                       'Matilde', 'Nádia', 'Olívia', 'Pilar', 'Rafaela',
                       'Rita', 'Sara')
        for x in range(patientNumber / 2):
            fname = random.choice(first_names)
            lname = random.choice(last_names)
            Patient(first_name=fname + " " + random.choice(first_names),
                    last_name=random.choice(last_names) + " " + lname,
                    status=Patient.DISCHARGED,
                    gender="F",
                    birthdate=self.dateRandom("1960-01-01", "2000-01-01",
                                              '%Y-%m-%d'),
                    phone="234" + str(random.randint(100, 999)) +
                    str(random.randint(100, 999)),
                    email=fname + "." + lname + "@mail.com").save()
Exemplo n.º 5
0
    def test_import_adaptive_data_to_database(self):
        # Make a test sample
        p = Patient()
        p.save()
        s = Sample(patient=p)
        s.save()

       # Model can read in a file
        Clonotype.import_adaptive(s, 'clonotypes/tests/data/test_adaptive.tsv')
        all_clonotypes = Clonotype.objects.all()
        self.assertEquals(len(all_clonotypes), 100)
Exemplo n.º 6
0
    def test_blank_true_for_non_required_fields(self, patientd):
        """
        mixer don't autopopulate blank fields
        """
        d = {i: patientd[i] for i in ['name', 'firstname', 'birthdate']}
        a = Patient(name=d['name'],
                    firstname=d['firstname'],
                    birthdate=d['birthdate'])
        a.save()
        b = Patient.objects.get(id=a.id)

        assert a == b
Exemplo n.º 7
0
    def test_patient_has_disease(self):
        all_patients_in_db = Patient.objects.all()
        self.assertEquals(len(all_patients_in_db), 0)

        # can create a patient that is male
        man = Patient()
        man.disease = "Ankylosing Spondylitis"
        man.save()

        # check db to see if patient exists
        man_in_db = Patient.objects.get(disease=man.disease)
        self.assertEquals(man.disease, man_in_db.disease)
Exemplo n.º 8
0
    def test_import_miTCR_to_database(self):
        # Make a test sample
        p = Patient()
        p.save()
        s = Sample(patient=p)
        s.save()

       # Model can read in a file
        Clonotype.import_mitcr(s, 'clonotypes/tests/data/test_mitcr.txt')
        all_clonotypes = Clonotype.objects.all()
        self.assertEquals(len(all_clonotypes), 100)
        self.fail('todo')
Exemplo n.º 9
0
    def test_patient_has_name(self):
        # first check that db is empty
        all_patients_in_db = Patient.objects.all()
        self.assertEquals(len(all_patients_in_db), 0)

        # can create a patient that is male
        man = Patient()
        man.name = "Vernon Davis"
        man.save()

        # check db to see if patient exists
        man_in_db = Patient.objects.get(name=man.name)
        self.assertEquals(man.name, man_in_db.name)
Exemplo n.º 10
0
    def test_patient_has_birthday(self):
        all_patients_in_db = Patient.objects.all()
        self.assertEquals(len(all_patients_in_db), 0)

        # can create a patient that is male
        man = Patient()
        # man.birthday = timezone.now()
        man.birthday = datetime.date(2011, 11, 11)
        man.save()

        # check db to see if patient exists
        man_in_db = Patient.objects.get(birthday=man.birthday)
        self.assertEquals(man.birthday, man_in_db.birthday)
Exemplo n.º 11
0
def consult(request):
    if request.method == "POST":
        form = request.POST
        consult = Consultation()
        pat_name = Patient()
        pat_name.name = form['patient_id']
        consult.medical_history = form['medical_history']
        consult.admission = form['admission']
        consult.test_types = form['test_types']
        consult.notes = form['notes']
        consult.prescription = form['prescription']
        consult.save()  #insert in database

        #give us a new id of the recorded item
        return redirect('patient:detail', patient.pk)
    return render(request, 'consultations/consult.html')
Exemplo n.º 12
0
def index(request):
    try:
        dept = get_object_or_404(Department, pk = request.user.profile.department.pk)
    except:
        return HttpResponse('You are not assigned to any departments')
        
    # queues = dept.get_queues()
    queues = Queue.get_all_queues_of_hospital(dept.hospital)
    # patients_visited_today = Patient.total_number_of_patients_today()
    first_queue = dept.queue_set.first()
    if first_queue:
        average_wait_time =first_queue.get_waittime()
    else:
        average_wait_time = 0 
    active_patients = VirtualQueue.get_active_patients()
    bounce_rate = VirtualQueue.get_bounce_rate()
    unique_patients = Patient.get_total_number_of_patients()
    context={
        'queues': queues, 
        'department': dept,
        'average_wait_time' : average_wait_time,
        'active_patients' : active_patients,
        'unique_patients' : unique_patients,
        'bounce_rate' : bounce_rate,

        # 'patients_visited_today' : patients_visited_today,
        }
    return render(request, 'queues/index.html', context)
Exemplo n.º 13
0
def Add_patient(request):
    if request.method =="POST":
        form =request.POST
        #print(form)
        patient= Patient()
        patient.name = form['name']
        patient.mobile = form['mobile']
        patient.id_number = form['id_number']
        patient.address = form['address']
        patient.age = form['age']
        patient.gender = form['gender']
        #patient.address = form['address']
        patient.save()   #insert in database
        
        #give us a new id of the recorded item
        return redirect ('patients:detail', patient.pk)
    return render(request, 'patients/add_patient.html')
Exemplo n.º 14
0
    def test_create_clonotypes_for_a_sample(self):
        p = Patient()
        p.save()
        s = Sample(patient=p)
        s.save()
        r = RecombinationFactory()

        c = Clonotype(
            sample=s,
            recombination=r,
            frequency=9.336458E-6,
            count=2,
        )
        c.save()

        # Get all clonotypes from database
        all_clonotypes = Clonotype.objects.all()

        self.assertEqual(all_clonotypes[0], c)
Exemplo n.º 15
0
    def create(self, validated_data):
        user = self.context.get('request').user
        if user.is_authenticated:
            # hospital = get_user_hospital(user)
            # if hospital is None:
            #     raise serializers.ValidationError('Unknown hospital')

            # validated_data['hospital'] = hospital
            user = get_user_profile(user)

            assigned_caregivers = validated_data.pop("assigned_caregivers",
                                                     None)
            bed_id = validated_data.pop("bed", None)
            start_date = validated_data.pop("stay_start_date", None)
            validated_data.pop("stay_id", None)

            patient = Patient(**validated_data)

            if bed_id:
                bed = Bed.objects.filter(id=bed_id).first()
                if bed is None:
                    raise serializers.ValidationError('Bed id (' + bed_id +
                                                      ') was not found')

                rea = bed.unit.reanimation_service if bed.unit else None

                if rea is None:  # should never happen
                    raise serializers.ValidationError(
                        f'Bed id ({bed_id}) does not belong to a Reanimation service'
                    )

                if rea not in user.authorized_reanimation_services.all():
                    raise serializers.ValidationError(
                        f'The bed is in Reanimation {bed_id}, and the user can\'t manage it'
                    )
                if bed.is_unusable:
                    raise serializers.ValidationError(
                        f'The bed {bed.unit_index} in Reanimation {bed_id} is not usable'
                    )
                if get_current_unit_stay(bed):
                    raise serializers.ValidationError(
                        f'The bed {bed.unit_index} in Reanimation {bed_id} is already occupied'
                    )
                patient.current_reanimation_service = rea
                patient.save()
                patient.assigned_caregivers.set(assigned_caregivers)
                UnitStay.objects.create(created_by=user,
                                        patient=patient,
                                        bed=bed,
                                        start_date=start_date)

            else:
                patient.save()
                patient.assigned_caregivers.set(assigned_caregivers)

            return patient
        else:
            raise PermissionDenied
Exemplo n.º 16
0
class PatientCVsViewSet(viewsets.ModelViewSet):
    queryset = Patient.all(active=True)
    serializer_class = PatientSerializer

    def retrieve(self, request, *args, **kwargs):
        patient = self.get_object()
        return self.buildResponse(patient)

    #Refactor this URGENT
    def buildResponse(self, patient):
        headers = CVGroup.all()
        headerSerialized = CVGroupSerializer(headers, many=True)

        results = []
        for group in headers:
            obj = {"group": group.title}
            cvs = CVPatient.all(patient=patient, group=group)
            content = []
            cvsSplitedByDate = [
                list(grp)
                for i, grp in groupby(sorted(cvs.values()),
                                      key=lambda item: item["measure_date"])
            ]

            # These nested fors hurts my soul, but i don't know a better solution
            for cvsInThatDate in cvsSplitedByDate:
                cvToAddInResponse = {
                    "measure_date":
                    cvsInThatDate[0]["measure_date"].strftime("%Y-%m-%d %H:%M")
                }
                for cv in cvsInThatDate:
                    cvName = ClinicalVariable.objects.get(
                        id=cv["variable_id"]).variable
                    cvToAddInResponse[cvName] = cv["value"]
                content += [cvToAddInResponse]

            obj["content"] = content
            results += [obj]

        return Response({"headers": headerSerialized.data, "results": results})

    @list_route(methods=['post'])
    @transaction.atomic
    def addVariables(self, request, *args, **kwargs):
        measure_date = timezone.now()
        group = CVGroup.objects.get(title=request.data["group"])
        patient = Patient.objects.get(id=request.data["patient"])

        for cv in request.data:
            if (cv != "group" and cv != "patient"):
                variable = cv
                value = request.data[cv]
                CVPatient.new(patient, group, variable, value, measure_date)

        return self.buildResponse(patient)
Exemplo n.º 17
0
def add_patient(request,room_name):
    if request.method == 'POST':
        form = AdminPatientRegistrationForm(request.POST)
        if form.is_valid():
            patient = Patient(
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                email=form.cleaned_data.get('email'),
                phone_number = form.cleaned_data.get('phone_number'),
                age = form.cleaned_data['age'],
                gender = form.cleaned_data['gender'],
                verified=True,
                added_by = request.user
            )
            patient.save()
            queue = Queue.get_queue_by_name(name=room_name)
            inqueue = VirtualQueue(patient=patient, queue=queue)
            inqueue.save()
            send_update_notification(room_name)
    return redirect('queues:room', room_name)
Exemplo n.º 18
0
    def get_patients_qs(self):
        samples = set()

        node_ids = [n.pk for n in self.analysisnode_ptr.get_roots()]
        roots = AnalysisNode.objects.filter(
            pk__in=node_ids).select_subclasses()
        for node in roots:
            samples.update(node.get_samples())

        return Patient.filter_for_user(
            self.analysis.user).filter(sample__in=samples)
Exemplo n.º 19
0
    def create_patient_match_phenotypes(self, phenotype):
        patient = Patient(phenotype=phenotype)
        patient.save(phenotype_matcher=self.phenotype_matcher)

        patient.process_phenotype_if_changed(
            phenotype_matcher=self.phenotype_matcher)
        return patient.patient_text_phenotype.phenotype_description.get_results(
        )
Exemplo n.º 20
0
    def _update_patient(self, patient, row, new=False):
        patient.unique_id = row["Patient Number"]
        patient.government_id = row["State Patient Number"]
        patient.diagnosed_date = datetime.strptime(row["Date Announced"],
                                                   "%d/%m/%Y")
        if row["Age Bracket"].strip():
            patient.age = int(row["Age Bracket"])
        if row["Gender"] == "M":
            patient.gender = Gender.MALE
        elif row["Gender"] == "F":
            patient.gender = Gender.FEMALE
        elif row["Gender"]:
            patient.gender = Gender.OTHERS
        else:
            patient.gender = Gender.UNKNOWN
        city = row.get("Detected City", None).strip()
        patient.detected_city = city
        patient.detected_district = row["Detected District"]
        state = row.get("Detected State", None).strip()
        patient.detected_state = state

        if new or patient.detected_city != city:
            patient.detected_city_pt = Patient.get_point_for_location(
                city=city, state=state)

        patient.current_location_pt = patient.detected_city_pt
        patient.nationality = ""
        if row["Current Status"] in PatientStatus.CHOICES:
            patient.current_status = row["Current Status"]
        patient.status_change_date = self._safe_parse_datetime(
            row["Status Change Date"])

        patient.notes = row["Notes"]
        if row["Backup Notes"].strip() and row["Backup Notes"] != row["Notes"]:
            patient.notes += ".\n" + row["Backup Notes"]
        patient.nationality = row["Nationality"]
        patient.save()

        links = row["Contracted from which Patient (Suspected)"].split(",")
        if new or patient.contacts.count() != len(links):
            self._add_contacts(patient, links)

        sources = [
            row[s] for s in ["Source_1", "Source_2", "Source_3"]
            if row.get(s, "").strip()
        ]
        if new or patient.source_set.count() != len(sources):
            self._add_sources(patient, sources)
Exemplo n.º 21
0
    def create(self, request):
        try:
            result = ''
            data = request.POST.dict().get('data')
            try:
                data = json.loads(data)
            except Exception as e:
                print(e)
                pass
            patient = data.get('patient')
            patient_name = patient.get('name').strip()
            patients = Patient.objects.filter(name=patient_name)
            if len(patients) > 0:
                return HttpResponse(status=400)
            p = Patient()
            p.name = patient_name
            p.age = patient.get('age').strip()
            p.phone = patient.get('phone').strip()
            p.gender = patient.get('gender').strip()
            p.save()

            treatments = data.get('treatments')
            for treatment in treatments:
                pictures = treatment.get('pictures')
                t = Treatment()
                t.name = treatment.get('name').strip()
                t.detail = treatment.get('detail')
                t.patient = p
                t.save()
                for picture in pictures:
                    pic = Picture()
                    pic.treatment = t
                    pic.name = picture.get('name').strip()
                    pic.data = picture.get('data')
                    pic.save()
            return HttpResponse(status=201)
        except Exception as e:
            return HttpResponse(status=500)
Exemplo n.º 22
0
 def test_patient_objects_are_named_after_their_name(self):
     p = Patient()
     p.name = "Lady Gaga"
     self.assertEquals(unicode(p), "Lady Gaga")
Exemplo n.º 23
0
    def test_patient_has_gender(self):
        # first check that db is empty
        all_patients_in_db = Patient.objects.all()
        self.assertEquals(len(all_patients_in_db), 0)

        # can create a patient that is male
        man = Patient()
        man.gender = "M"
        man.save()

        # check db to see if patient exists
        men_in_db = Patient.objects.filter(gender="M")
        self.assertEquals(len(men_in_db), 1)

        # can create a patient that is female
        woman = Patient()
        woman.gender = "F"
        woman.save()

        women_in_db = Patient.objects.filter(gender="F")
        self.assertEquals(len(women_in_db), 1)

        # can create a patient with unknown gender
        person = Patient()
        person.save()
        androgynous_people_in_db = Patient.objects.filter(gender="")
        self.assertEquals(len(androgynous_people_in_db), 1)
Exemplo n.º 24
0
def test_patient_correpted_data(ss):
    "should not fail with corrupted date, because of readonly schema"
    a = Patient(name="ùlùlù#", firstname="mkljlij", birthdate="1234-12-12")
    a.save()
    patients_detail(ss, a.id)
    patients_list(ss)
Exemplo n.º 25
0
 def listAdmitted(self, request, *args, **kwargs):
     '''
     Return a list of active patients that are admitted in the hospital
     '''
     self.queryset = Patient.all(status=Patient.ADMITTED)
     return super(PatientViewSet, self).list(request, *args, **kwargs)
Exemplo n.º 26
0
def populate():

    hosp1 = Hospital(name='Strong')
    hosp2 = Hospital(name='Rochester General')
    hosp1.save()
    hosp2.save()

    user_content = ContentType.objects.get_for_model(User)
    patientPerm = Permission.objects.create(codename='patient',
                                            name='Is Patient',
                                            content_type=user_content)
    doctorPerm = Permission.objects.create(codename='doctor',
                                           name='Is Doctor',
                                           content_type=user_content)
    nursePerm = Permission.objects.create(codename='nurse',
                                          name='Is Nurse',
                                          content_type=user_content)
    patientPerm.save()
    doctorPerm.save()
    nursePerm.save()

    patientuser1 = User.objects.create_user(username='******',
                                            email='*****@*****.**',
                                            password='******')
    patientuser1.first_name = 'Test'
    patientuser1.last_name = 'Patient'
    patientuser1.user_permissions.add(patientPerm)
    patientuser1.save()

    patient1 = Patient(firstName= 'Test',\
                 lastName= 'Patient', \
                 hospital=hosp1, \
                 userNameField='test_patient', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='test road.', \
                 phone='(888) 888-8888', \
                 insuranceID= '001', \
                 insuranceName='testcare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient1.save()

    patientuser2 = User.objects.create_user(username='******',
                                            email='*****@*****.**',
                                            password='******')
    patientuser2.first_name = 'Richard'
    patientuser2.last_name = 'Posterior'
    patientuser2.user_permissions.add(patientPerm)
    patientuser2.save()

    patient2 = Patient(firstName= 'Richard',\
                 lastName= 'Posterior', \
                 hospital=hosp1, \
                 userNameField='richard', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='007 Bond st.', \
                 phone='(888) 999-8888', \
                 insuranceID= '002', \
                 insuranceName='apathetiCare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient2.save()

    patientuser3 = User.objects.create_user(username='******',
                                            email='*****@*****.**',
                                            password='******')
    patientuser3.first_name = 'Bill'
    patientuser3.last_name = 'Gates'
    patientuser3.user_permissions.add(patientPerm)
    patientuser3.save()

    patient3 = Patient(firstName= 'Bill',\
                 lastName= 'Gates', \
                 hospital=hosp2, \
                 userNameField='bill', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='010 Silicon Val.', \
                 phone='(888) 777-8888', \
                 insuranceID= '003', \
                 insuranceName='apathetiCare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient3.save()
    patientuser4 = User.objects.create_user(username='******',
                                            email='*****@*****.**',
                                            password='******')
    patientuser4.first_name = 'Rick'
    patientuser4.last_name = 'Astley'
    patientuser4.user_permissions.add(patientPerm)
    patientuser4.save()

    patient4 = Patient(firstName= 'Rick',\
                 lastName= 'Astley', \
                 hospital=hosp2, \
                 userNameField='rastley', \
                 email='*****@*****.**', \
                 city='You', \
                 state='Down.', \
                 address1='Gunna 137.', \
                 phone='(YOU) 11P-N3V4', \
                 insuranceID= '004', \
                 insuranceName='notGunnaHurtYou', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient4.save()

    doctorUser1 = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******')
    doctorUser1.first_name = 'Test'
    doctorUser1.last_name = 'Doctor'
    doctorUser1.user_permissions.add(doctorPerm)
    doctorUser1.save()
    doctor1 = Doctor(userNameField= 'test_doctor',\
                 firstName= 'Test',\
                 lastName= 'Doctor',\
                 phone= '(333) 333-3333')

    doctor1.save()

    doctorUser2 = User.objects.create_user(username='******',
                                           email='*****@*****.**',
                                           password='******')
    doctorUser2.first_name = 'Test'
    doctorUser2.last_name = 'Doctor'
    doctorUser2.user_permissions.add(doctorPerm)
    doctorUser2.save()
    doctor2 = Doctor(userNameField= 'mister',\
                 firstName= 'Mister',\
                 lastName= 'Labotamy',\
                 phone= '(585) 315-6030')

    doctor2.save()

    nurseUser1 = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
    nurseUser1.first_name = 'Test'
    nurseUser1.last_name = 'Nurse'
    nurseUser1.user_permissions.add(nursePerm)
    nurseUser1.save()
    nurse1 = Nurse(userNameField = 'test_nurse',\
                firstName = 'Test',\
                lastName = 'Nurse',\
                phone = '(555) 555-5555',\
                hospital = hosp1)
    nurse1.save()

    nurseUser2 = User.objects.create_user(username='******',
                                          email='*****@*****.**',
                                          password='******')
    nurseUser2.first_name = 'Amy'
    nurseUser2.last_name = 'Nursington'
    nurseUser2.user_permissions.add(nursePerm)
    nurseUser2.save()
    nurse2 = Nurse(userNameField = 'amy',\
             firstName = 'Amy',\
                lastName = 'Nursington',\
                phone = '(444) 444-4444',\
                hospital = hosp2)
    nurse2.save()
    admin = User.objects.create_superuser(username='******',
                                          password='******',
                                          email='*****@*****.**')
    admin.first_name = 'Test'
    admin.last_name = 'Admin'
    admin.save()
def populate():
    hosp = Hospital(name = 'Test Hospital')
    hosp.save()

    user_content = ContentType.objects.get_for_model(User)
    patientPerm = Permission.objects.create(codename='patient',\
                                            name='Is Patient',\
                                            content_type=user_content)
    doctorPerm = Permission.objects.create(codename='doctor',\
                                           name='Is Doctor',\
                                           content_type=user_content)

    nursePerm = Permission.objects.create(codename='nurse',\
                                          name='Is Nurse',\
                                          content_type=user_content)        
    patientPerm.save()
    doctorPerm.save()
    nursePerm.save()
        
    
    u1 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u1.first_name = 'Test'
    u1.last_name = 'Patient'
    u1.user_permissions.add(patientPerm)
    u1.save()
    u2 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u2.first_name = 'Test'
    u2.last_name = 'Doctor'
    u2.user_permissions.add(doctorPerm)
    u2.save()
    u3 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u3.first_name = 'Test'
    u3.last_name = 'Nurse'
    u3.user_permissions.add(nursePerm)
    u3.save()
    p1 = Patient(firstName= 'Test',\
                 lastName= 'Patient', \
                 hospital=hosp, \
                 userNameField='test_patient', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='test road.', \
                 phone='(888) 888-8888', \
                 insuranceID= '001', \
                 insuranceName='testcare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')

    p1.save()
    doc = Doctor(userNameField= 'test_doctor',\
                 firstName= 'Test',\
                 lastName= 'Doctor',\
                 phone= '(555) 555-5555')

    doc.save()
    nur = Nurse(userNameField = 'test_nurse',\
                firstName = 'Test',\
                lastName = 'Nurse',\
                phone = '(555) 555-5555',\
                hospital = hosp)
    nur.save()
Exemplo n.º 28
0
from datetime import date

Patient.objects.all().delete()
with open('Patients.csv', encoding='cp1251') as file:
    reader = DictReader(file)
    patients = []
    for row in reader:
        day, month, year = (int(x) for x in row['DateReceiving'].split('.'))
        if row['LastName']=='':
            log.warn('Empty last name for %s', row['PatientNumber'])
            row['LastName']='!!{}!!'.format(row['PatientNumber'])
        patients += [Patient(
            id = row['PatientNumber'],
            last_name = row['LastName'],
            first_name = row['FirstName'],
            middle_name = row['MiddleName'],
            registration_date = date(year, month, day),
            years = row['Years'] or None ,
            months = row['Months'] or None,
            attending_doctor = row['Director'])]
    Patient.objects.bulk_create(patients)
    

Patient.analyzes.through.objects.all().delete()    
with open('Analyses.csv', encoding='cp1251') as file:
    reader = DictReader(file)
    analyzes = {}
    for row in reader:
        if row['Appendix']!='+':
            log.warn('Strange appendix for (%s, %s)', row['PatientNumber'], row['AllergenNumber'])
        if row['OD']!='':
Exemplo n.º 29
0
def patients_qs_for_ontology_term(user, ontology_term):
    return Patient.filter_for_user(user).filter(
        **{
            PATIENT_ONTOLOGY_TERM_PATH: ontology_term
        }).order_by("id")
Exemplo n.º 30
0
def get_patient_form(request):
    return Response(Patient.get_react_description())
Exemplo n.º 31
0
 def _create_new_patient(self, row):
     print(f"Adding patient {row['Patient Number']}")
     patient = Patient()
     self._update_patient(patient, row, new=True)
Exemplo n.º 32
0
    def _create_new_patient(row):
        print(f"Adding patient {row['Patient number']}")
        patient = Patient()

        patient.unique_id = row["Patient number"]
        patient.diagnosed_date = datetime.strptime(row["Date Announced"],
                                                   "%d/%m/%Y")
        patient.status_change_date = datetime.strptime(
            row["Status Change Date"], "%d/%m/%Y")
        if row["Age Bracket"].strip():
            patient.age = int(row["Age Bracket"])
        if row["Gender"] == "M":
            patient.gender = Gender.MALE
        elif row["Gender"] == "F":
            patient.gender = Gender.FEMALE
        elif row["Gender"]:
            patient.gender = Gender.OTHERS
        else:
            patient.gender = Gender.UNKNOWN
        city = row.get("Detected City", None).strip()
        patient.detected_city = city
        patient.detected_district = row["Detected District"]
        state = row.get("Detected State", None).strip()

        patient.detected_state = state
        patient.detected_city_pt = Patient.get_point_for_location(city=city,
                                                                  state=state)
        patient.current_location_pt = patient.detected_city_pt
        patient.nationality = ""
        if row["Current Status"] in PatientStatus.CHOICES:
            patient.current_status = row["Current Status"]

        patient.notes = row["Notes"]
        patient.source = "\n".join(
            [row["Source_1"], row["Source_2"], row["Source_3"]]).strip()
        patient.nationality = row["Nationality"]

        patient.save()
    def _create_new_patient(row):
        print(f"Adding patient {row['Patient number']}")
        patient = Patient()

        patient.unique_id = row["Patient number"]
        patient.government_id = row["State Patient Number"]
        patient.diagnosed_date = datetime.strptime(row["Date Announced"],
                                                   "%d/%m/%Y")
        if row["Age Bracket"].strip():
            patient.age = int(row["Age Bracket"])
        if row["Gender"] == "M":
            patient.gender = Gender.MALE
        elif row["Gender"] == "F":
            patient.gender = Gender.FEMALE
        elif row["Gender"]:
            patient.gender = Gender.OTHERS
        else:
            patient.gender = Gender.UNKNOWN
        city = row.get("Detected City", None).strip()
        patient.detected_city = city
        patient.detected_district = row["Detected District"]
        state = row.get("Detected State", None).strip()

        patient.detected_state = state
        patient.detected_city_pt = Patient.get_point_for_location(city=city,
                                                                  state=state)
        patient.current_location_pt = patient.detected_city_pt
        patient.nationality = ""
        if row["Current Status"] in PatientStatus.CHOICES:
            patient.current_status = row["Current Status"]
        patient.status_change_date = datetime.strptime(
            row["Status Change Date"], "%d/%m/%Y")

        patient.notes = row["Notes"]
        if row["Backup Notes"].strip() and row["Backup Notes"] != row["Notes"]:
            patient.notes += ".\n" + row["Backup Notes"]
        patient.nationality = row["Nationality"]
        patient.save()

        links = row["Contracted from which Patient (Suspected)"].split(",")
        for link in links:
            link = link.strip().strip("P")
            try:
                contact = Patient.objects.get(unique_id=link)
                patient.contacts.add(contact)
            except Patient.DoesNotExist:
                continue
        patient.save()

        for source in ["Source_1", "Source_2", "Source_3"]:
            text = row.get(source, "")
            if not text:
                continue
            if text.startswith("http") or text.startswith("www"):
                patient.source_set.create(url=text, is_verified=True)
            else:
                patient.source_set.create(description=text, is_verified=True)
Exemplo n.º 34
0
 def listDischarged(self, request, *args, **kwargs):
     '''
     Return a list of active patients that are discharged from the hospital
     '''
     self.queryset = Patient.all(status=Patient.DISCHARGED)
     return super(PatientViewSet, self).list(request, *args, **kwargs)
 def gen_patient(self, mrn):
     patient = Patient()
     patient.mrn = mrn
     if randint(0, 1):
         patient.gender = 'male'
         patient.first_name = self._factory.first_name_male()
         patient.middle_name = self._factory.first_name_male()
     else:
         patient.gender = 'female'
         patient.first_name = self._factory.first_name_female()
         patient.middle_name = self._factory.first_name_female()
     patient.last_name = self._factory.last_name()
     offset = timedelta(days=randint(28, 67) * 365)
     patient.birthdate = (self._factory.date_time_this_century() - offset)
     # Values are in centimeters
     patient.height = randint(140, 180)
     # Values are in kg
     patient.weight = randint(60, 90) + round(random(), 2)
     patient.is_sample = True
     return patient
Exemplo n.º 36
0
# Start making the object
for index, item in df.iterrows():
    print(index)
    p = Patient(
        case_number = item['Case #'],
        sex = item['Sex'],
        age = item['Age'],
        nationality = item['Nationality'],
        overseas_travel = overseas(item['OverseasTravelHistory']),
        country_visited_0 = item['Country1Visited'],
        country_visited_1 = item['Country2Visited'],
        country_visited_2 = '',
        exposure = item['Exposure'],
        # exposure_link = '',
        # symptoms = symptoms(item['Symptoms']),
        onset_date = date_helper(item['OnsetMonth'],item['OnsetDate']),
        admission_date = date_helper(item['AdmissionMonth'],item['AdmissionDate']),
        lab_confirmation_date = date_helper(item['LabConfirmMonth'],item['LabConfirmDate']),
        admitted_to = hospital(item['HospitalID']),
        residence_city_mun = item['ResidenceCityMun'],
        city_mun_psgc = item['PSGC_MUNI'],
        residence_prov = item['ResidenceProv'],
        prov_psgc = item['PSGC_PROV'],
        status = item['Status'],
        death_date = date_helper(item['DeathMonth'],item['DeathDate']),
        death_cause = item['DeathCause'],
        remarks = item['Remarks']

    )
    p.save()
    symptoms(p,item['Symptoms'])
def populate():
    hosp = Hospital(name='Test Hospital')
    hosp.save()

    user_content = ContentType.objects.get_for_model(User)
    patientPerm = Permission.objects.create(codename='patient',\
                                            name='Is Patient',\
                                            content_type=user_content)
    doctorPerm = Permission.objects.create(codename='doctor',\
                                           name='Is Doctor',\
                                           content_type=user_content)

    nursePerm = Permission.objects.create(codename='nurse',\
                                          name='Is Nurse',\
                                          content_type=user_content)
    patientPerm.save()
    doctorPerm.save()
    nursePerm.save()


    u1 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u1.first_name = 'Test'
    u1.last_name = 'Patient'
    u1.user_permissions.add(patientPerm)
    u1.save()
    u2 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u2.first_name = 'Test'
    u2.last_name = 'Doctor'
    u2.user_permissions.add(doctorPerm)
    u2.save()
    u3 = User.objects.create_user(username='******',\
                                  email='*****@*****.**',\
                                  password = '******')
    u3.first_name = 'Test'
    u3.last_name = 'Nurse'
    u3.user_permissions.add(nursePerm)
    u3.save()
    p1 = Patient(firstName= 'Test',\
                 lastName= 'Patient', \
                 hospital=hosp, \
                 userNameField='test_patient', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='test road.', \
                 phone='(888) 888-8888', \
                 insuranceID= '001', \
                 insuranceName='testcare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')

    p1.save()
    doc = Doctor(userNameField= 'test_doctor',\
                 firstName= 'Test',\
                 lastName= 'Doctor',\
                 phone= '(555) 555-5555')

    doc.save()
    nur = Nurse(userNameField = 'test_nurse',\
                firstName = 'Test',\
                lastName = 'Nurse',\
                phone = '(555) 555-5555',\
                hospital = hosp)
    nur.save()
Exemplo n.º 38
0
def populate():

    hosp1 = Hospital(name = 'Strong')
    hosp2 = Hospital(name = 'Rochester General')
    hosp1.save()
    hosp2.save()

    user_content = ContentType.objects.get_for_model(User)
    patientPerm = Permission.objects.create(codename='patient',name='Is Patient',content_type=user_content)
    doctorPerm = Permission.objects.create(codename='doctor',name='Is Doctor',content_type=user_content)
    nursePerm = Permission.objects.create(codename='nurse',name='Is Nurse',content_type=user_content)       
    patientPerm.save()
    doctorPerm.save()
    nursePerm.save()
        
    
    patientuser1 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    patientuser1.first_name = 'Test'
    patientuser1.last_name = 'Patient'
    patientuser1.user_permissions.add(patientPerm)
    patientuser1.save()

    patient1 = Patient(firstName= 'Test',\
                 lastName= 'Patient', \
                 hospital=hosp1, \
                 userNameField='test_patient', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='test road.', \
                 phone='(888) 888-8888', \
                 insuranceID= '001', \
                 insuranceName='testcare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient1.save()

    patientuser2 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    patientuser2.first_name = 'Richard'
    patientuser2.last_name = 'Posterior'
    patientuser2.user_permissions.add(patientPerm)
    patientuser2.save()

    patient2 = Patient(firstName= 'Richard',\
                 lastName= 'Posterior', \
                 hospital=hosp1, \
                 userNameField='richard', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='007 Bond st.', \
                 phone='(888) 999-8888', \
                 insuranceID= '002', \
                 insuranceName='apathetiCare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient2.save()    

    patientuser3 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    patientuser3.first_name = 'Bill'
    patientuser3.last_name = 'Gates'
    patientuser3.user_permissions.add(patientPerm)
    patientuser3.save()

    patient3 = Patient(firstName= 'Bill',\
                 lastName= 'Gates', \
                 hospital=hosp2, \
                 userNameField='bill', \
                 email='*****@*****.**', \
                 city='Rochester', \
                 state='New York', \
                 address1='010 Silicon Val.', \
                 phone='(888) 777-8888', \
                 insuranceID= '003', \
                 insuranceName='apathetiCare', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient3.save()        
    patientuser4 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    patientuser4.first_name = 'Rick'
    patientuser4.last_name = 'Astley'
    patientuser4.user_permissions.add(patientPerm)
    patientuser4.save()

    patient4 = Patient(firstName= 'Rick',\
                 lastName= 'Astley', \
                 hospital=hosp2, \
                 userNameField='rastley', \
                 email='*****@*****.**', \
                 city='You', \
                 state='Down.', \
                 address1='Gunna 137.', \
                 phone='(YOU) 11P-N3V4', \
                 insuranceID= '004', \
                 insuranceName='notGunnaHurtYou', \
                 emergencyContactEmail='*****@*****.**', \
                 emergencyContactFirstName='Stuart', \
                 emergencyContactLastName='Burtner', \
                 emergencyContactPhone='(555) 555-5555', \
                 medicalInformation='nothing')
    patient4.save()        

    doctorUser1 = User.objects.create_user(username='******',email='*****@*****.**', password = '******')
    doctorUser1.first_name = 'Test'
    doctorUser1.last_name = 'Doctor'
    doctorUser1.user_permissions.add(doctorPerm)
    doctorUser1.save()
    doctor1 = Doctor(userNameField= 'test_doctor',\
                 firstName= 'Test',\
                 lastName= 'Doctor',\
                 phone= '(333) 333-3333')

    doctor1.save()

    doctorUser2 = User.objects.create_user(username='******',email='*****@*****.**', password = '******')
    doctorUser2.first_name = 'Test'
    doctorUser2.last_name = 'Doctor'
    doctorUser2.user_permissions.add(doctorPerm)
    doctorUser2.save()    
    doctor2 = Doctor(userNameField= 'mister',\
                 firstName= 'Mister',\
                 lastName= 'Labotamy',\
                 phone= '(585) 315-6030')

    doctor2.save()

    nurseUser1 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    nurseUser1.first_name = 'Test'
    nurseUser1.last_name = 'Nurse'
    nurseUser1.user_permissions.add(nursePerm)
    nurseUser1.save()
    nurse1 = Nurse(userNameField = 'test_nurse',\
                firstName = 'Test',\
                lastName = 'Nurse',\
                phone = '(555) 555-5555',\
                hospital = hosp1)
    nurse1.save()

    nurseUser2 = User.objects.create_user(username='******',email='*****@*****.**',password = '******')
    nurseUser2.first_name = 'Amy'
    nurseUser2.last_name = 'Nursington'
    nurseUser2.user_permissions.add(nursePerm)
    nurseUser2.save()
    nurse2 = Nurse(userNameField = 'amy',\
            	firstName = 'Amy',\
                lastName = 'Nursington',\
                phone = '(444) 444-4444',\
                hospital = hosp2)    
    nurse2.save()
    admin = User.objects.create_superuser(username='******',password='******',email='*****@*****.**')
    admin.first_name='Test'
    admin.last_name='Admin'
    admin.save()