Beispiel #1
0
 def _check_if_readings_too_low(
         self,
         patient: PatientProfile
 ) -> None:
     # See if we have already made such a notification in the past
     # week for the patient.
     existing_entries = NursingQueueEntry.objects.filter(
         patient=patient,
         entry_type=NursingQueueEntry.ENTRY_TYPE_READINGS_TOO_LOW,
         datetime_added__gt=now() - timedelta(days=7)
     )
     # Abort if we do
     if len(existing_entries) > 0:
         return
     interval = patient.get_readings_too_low_interval()
     cutoff = now() - timedelta(days=interval)
     too_low_threshold = patient.get_readings_too_low_threshold()
     too_low_limit = patient.get_readings_too_low_limit()
     readings = patient.user.glucose_readings.filter(
         reading_datetime_utc__gt=cutoff,
         glucose_value__lte=too_low_threshold
     )
     if len(readings) >= too_low_limit:
         NursingQueueEntry.objects.create(
             patient=patient,
             entry_type=NursingQueueEntry.ENTRY_TYPE_READINGS_TOO_LOW,
             due_date=(now() + timedelta(days=7)).date()
         )
Beispiel #2
0
def batch_csv_export(request):
    # Create CSV
    batch_ids = request.POST.get('batch_ids').split(',')
    patients = User.objects.filter(pk__in=batch_ids)
    PatientProfile.generate_csv('/tmp/genesiscsv', patients)
    # get content
    with open('/tmp/genesiscsv') as f:
        content = f.read()
    # delete CSV
    os.remove('/tmp/genesiscsv')
    # render response
    response = HttpResponse(content, content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="export.csv"'
    return response
Beispiel #3
0
 def save(self, *args, **kwargs):
     # If we have too many, do this asynchronously.
     if len(self.datas) > 200:
         task_args = [self.initial_group.id]
         if self.cleaned_data['company']:
             task_args.append(self.cleaned_data['company'].id)
         else:
             task_args.append(None)
         chord(
             process_patient_form_data_row.subtask([data] + task_args)
             for data in self.datas)(process_patient_form_data.subtask(
                 [self.user.id]))
     else:
         patient_ids = []
         for form in self.forms:
             patient = form.save(commit=False)
             patient.patient_profile.company = self.cleaned_data['company']
             patient.patient_profile.save()
             patient_ids.append(patient.pk)
         patients = User.objects.filter(id__in=patient_ids)
         content = PatientProfile.generate_csv2(patients)
         self.download = TemporaryDownload.objects.create(
             for_user=self.user,
             content=content,
             content_type='text/csv',
             filename='imported_patients.csv')
Beispiel #4
0
    def clean(self):
        self.forms = []
        self.datas = []
        csv_data = read_csv_file(self.cleaned_data['csv'],
                                 self.CSV_FIELD_NAMES)
        patients = User.objects.filter(patient_profile__isnull=False)
        taken_usernames = list(
            map(lambda x: x['username'], patients.values('username')))
        for count, data in enumerate(csv_data, 1):
            if not data['first_name']:
                continue
            data['phone_0_phone'] = data['phone']
            ptype = data['phone_type'].lower()
            if ptype == 'contact':
                data['phone_0_is_contact'] = True
            elif ptype == 'cell':
                data['phone_0_is_cell'] = True
            del data['phone'], data['phone_type']
            data['email_confirm'] = data['email']

            try:
                month, day, year = data['date_of_birth'].split('/')
            except ValueError:
                pass
            else:
                if len(year) == 2:
                    full_year = expand_birthday_year(year)
                    data['date_of_birth'] = '/'.join(
                        [month, day, str(full_year)])
            raw_data = data.copy()
            line_form_kwargs = {'initial_group': self.initial_group}
            username = data.pop('username', None)
            if username:
                try:
                    user = patients.get(username=username)
                except User.DoesNotExist:
                    raise forms.ValidationError(
                        "Invalid username: {}".format(username))
                line_form_kwargs['instance'] = user
            else:
                new_username = PatientProfile.generate_username(
                    data['email'],
                    data['first_name'],
                    data['last_name'],
                    also_skip=taken_usernames,
                    skip_db_check=True)
                taken_usernames.append(new_username)
                line_form_kwargs['supplied_username'] = new_username
                raw_data['username'] = new_username
            data['company'] = self.cleaned_data['company'].id
            p_form = ImportPatientLineForm(data, **line_form_kwargs)
            if not p_form.is_valid():
                raise forms.ValidationError("Line {0} is invalid: {1}".format(
                    count,
                    p_form.errors.as_text().replace('\n', ' ')))
            self.datas.append(raw_data)
            self.forms.append(p_form)
            return self.cleaned_data
Beispiel #5
0
 def _populate_queue_entries_for_patient(self, patient: PatientProfile) -> None:
     """Populate all queue entries for the given patient."""
     nursing_group = patient.get_nursing_group()
     if nursing_group is None:
         return
     print(f"Checking {patient}")
     self._check_if_readings_too_high(patient)
     self._check_if_readings_too_low(patient)
     self._check_if_not_enough_readings(patient)
Beispiel #6
0
 def _check_if_not_enough_readings(
         self,
         patient: PatientProfile
 ) -> None:
     # See if we have already made such a notification in the past
     # week for the patient.
     existing_entries = NursingQueueEntry.objects.filter(
         patient=patient,
         entry_type=NursingQueueEntry.ENTRY_TYPE_NOT_ENOUGH_RECENT_READINGS,
         datetime_added__gt=now() - timedelta(days=7)
     )
     # Abort if we do
     if len(existing_entries) > 0:
         return
     interval = patient.get_not_enough_recent_readings_interval()
     cutoff = now() - timedelta(days=interval)
     limit = patient.get_not_enough_recent_readings_minimum()
     readings = patient.user.glucose_readings.filter(reading_datetime_utc__gt=cutoff)
     if len(readings) < limit:
         NursingQueueEntry.objects.create(
             patient=patient,
             entry_type=NursingQueueEntry.ENTRY_TYPE_NOT_ENOUGH_RECENT_READINGS,
             due_date=(now() + timedelta(days=7)).date()
         )
Beispiel #7
0
def process_patient_form_data(patient_ids, user_id):
    from genesishealth.apps.accounts.models import PatientProfile
    from django.contrib.auth.models import User
    from genesishealth.apps.reports.models import TemporaryDownload
    try:
        user = User.objects.get(id=user_id)
    except User.DoesNotExist:
        return
    patients = User.objects.filter(id__in=patient_ids)
    content = PatientProfile.generate_csv2(patients)
    download = TemporaryDownload.objects.create(
        for_user=user,
        content=content,
        content_type='text/csv',
        filename='imported_patients.csv')
    download.send_email("Your recently imported patients.")