Beispiel #1
0
def visit_edit(request, orgStr, patientStr, visitStr):
  """Edit an existing visit"""
  # need at least one "extra" option form, or the javascript breaks
  patient = models.Patient.get_by_short_string(patientStr)
  if not patient: raise Http404
  visit = patient.get_visit_by_short_string(visitStr)
  if not visit: raise Http404

  # NOTE(dan): patient and orgStr don't change, so they need not be params
  def render_this(visit, visitForm):
    return respond(request, 'visit_edit.html',
                   {'visit': visit, 'form': visitForm, 'orgStr': orgStr})

  if request.method != 'POST':
    visitForm = VisitForm(instance=visit)
    return render_this(visit, visitForm)

  visitForm = VisitForm(request.POST, instance=visit)

  if not visitForm.is_valid():
    logging.error('visit_edit: %s' % visitForm.errors)
    return render_this(visit, visitForm)

  # store the visit
  try:
    visit = visitForm.save(commit=False)
    # TODO(dan): Could possibly set up a Django signal to set_latest_visit
    # Don't set latest_visit param because this visit may not be the latest
    patient.set_latest_visit(force = True)
  except ValueError, err:
    visitForm.errors['__all__'] = unicode(err)
    return render_this(visit, visitForm)
Beispiel #2
0
def visit_new(request, orgStr, patientStr):
  """Create a new visit for a patient."""

  patient = models.Patient.get_by_short_string(patientStr)
  if not patient: raise Http404

  # NOTE(dan): orgStr and patient don't change, so they need not be params
  def render_this(visitForm):
    return respond(request, 'visit_new.html',
                   {'form': visitForm, 'patient': patient,
                    'orgStr': orgStr})

  if request.method != 'POST':
    visitForm = VisitForm(initial={'organization':orgStr})
    return render_this(visitForm)

  # You can only set parent upon construction, so make a newVisit
  newVisit = models.Visit(parent=patient)
  visitForm = VisitForm(request.POST, instance=newVisit)
  if not visitForm.is_valid():
    return render_this(visitForm)

  # store the visit
  visit = _store_new_visit(patient, visitForm, request.user)
  if not visit:
    return render_this(visitForm)

  # Email us whenever a visit is created.
  mailer.email_new_visit(visit)

  return HttpResponseRedirect(visit.get_view_url())
Beispiel #3
0
def patient_new_with_visit(request, orgStr):
  """Add a new patient and a new visit to the new patient in one screen.

  Note: You can add patients and visits without being logged in, but you will
  only be able to see the last one.
  """
  #logging.info("request.LANGUAGE_CODE: %s" % request.LANGUAGE_CODE)
  #logging.info("request: %s" % request)
  patient_exists = False

  if not models.organization_exists(orgStr):
    raise Http404

  # NOTE(dan): patient doesn't change, so it need not be a param
  def render_this(patient_exists, confirmationForm, patientForm, visitForm):
    return respond(request, 'patient_new_with_visit.html',
                   {'patient_exists': patient_exists,
                    'confirmationform': confirmationForm,
                    'patientform': patientForm,
                    'visitform': visitForm,
                    'orgStr' : orgStr})

  if request.method != 'POST':
    confirmationForm = ConfirmationForm()
    default_country = getattr(request.user, 'default_country', '')
    if default_country:
      patientForm = PatientForm(initial={'organization':orgStr, 'country': default_country})
    else:
      patientForm = PatientForm(initial={'organization':orgStr})
        
    visitForm = VisitForm(initial={'organization':orgStr})
  else:
    confirmationForm = ConfirmationForm(request.POST)
    patientForm = PatientForm(request.POST)
    visitForm = VisitForm(request.POST)

    if patientForm.is_valid() and visitForm.is_valid():
      # First check if patient exists based on name and date of birth
      name = patientForm.cleaned_data['name']
      birth_date = patientForm.cleaned_data['birth_date']
      patient = models.Patient.get_patient_by_name_birthdate(name, birth_date)
      if patient:
        patient_exists = True
        request.session['patient'] = patient
      
      # If patient is new
      if not patient_exists:
        # Need to store both
        if not _store_new_patient_and_new_visit(request, orgStr, patientForm, visitForm):
          return render_this(patient_exists, confirmationForm, patientForm, visitForm)
      # We already went through this once and there is another patient with same name and birthdate
      else:         
        if confirmationForm.is_valid():  
          confirmation_option = confirmationForm.cleaned_data['confirmation_option']
          if confirmation_option == 'addpatientvisit':
            # Need to store both
            if not _store_new_patient_and_new_visit(request, orgStr, patientForm, visitForm):
              return render_this(patient_exists, confirmationForm, patientForm, visitForm)
          else:              
            # Patient is still the same 
            patient = request.session['patient']                       
            # Just add the visit
            newVisit = models.Visit(parent = patient)
            visitForm = VisitForm(request.POST, instance = newVisit)
            visit = _store_new_visit(patient, visitForm, request.user)        
            if not visit:
              return render_this(patient_exists, confirmationForm, patientForm, visitForm)      
        else:
          return render_this(patient_exists, confirmationForm, patientForm, visitForm)        
            
      patient = request.session['patient']
      # Redirect to viewing
      return HttpResponseRedirect(patient.get_view_url())
                
  return render_this(patient_exists, confirmationForm, patientForm, visitForm)
Beispiel #4
0
def edit(request, patient_id):
    """ Просмотр и изменение информации о пациенте """
    patient = get_object_or_404(Patient, pk=patient_id)
    diagnosis_qs = patient.diagnosis_set.all()
    avalible_error = False
    try:
        period_visit = datetime.now() - patient.visit_set.latest().date_created
    except Visit.DoesNotExist:
        period_visit = datetime.now() - datetime(1970, 1, 1)
    is_need_save_visit = period_visit > timedelta(hours=12)
    if request.method == "POST":
        patient_form = PatientForm(request.POST,
                                   instance=patient)
        if patient_form.is_valid():
            patient = patient_form.save(commit=False)
        else:
            avalible_error = True
        visit_form = VisitForm(request.POST, prefix=VISIT_PREFIX)
        if not visit_form.is_valid():
            if period_visit > NIGHT_TIME:
                avalible_error = True
            else:
                is_need_save_visit = False
                visit_form = VisitForm(prefix=VISIT_PREFIX)
        else:
            is_need_save_visit = True

        diagnosis_formset = DiagnosisModelFormset(clear_ids(request),
                                                  prefix=DIAGNOSIS_PREFIX,
                                                  queryset=diagnosis_qs)
        if not diagnosis_formset.is_valid():
            avalible_error = True
        if not avalible_error:
            save_formset(diagnosis_formset, patient)
            patient.diagnosis_text = get_diagnosis_text(patient)
            patient.diagnosis_text_code = get_diagnosis_code(patient)
            patient.save()
            messages.add_message(request,
                                 messages.INFO,
                                 u'Информация о пациенте изменена')
            if visit_form.cleaned_data.get('is_visit', False):
                visit = visit_form.save(commit=False)
                #visit.mo = request.user.mo
                visit.patient = patient
                visit.save()
                visit_form = VisitForm(prefix=VISIT_PREFIX,
                                       initial={'mo': request.user.mo.pk})
            # если все сохранилось, то правильно выводим где флажки "удалить", а где текст
            diagnosis_formset = DiagnosisModelFormset(
                prefix=DIAGNOSIS_PREFIX,
                queryset=patient.diagnosis_set.all()
            )

    else:
        patient_form = PatientForm(instance=patient)
        diagnosis_formset = DiagnosisModelFormset(prefix=DIAGNOSIS_PREFIX,
                                                  queryset=diagnosis_qs)
        visit_form = VisitForm(prefix=VISIT_PREFIX,
                               initial={'mo': request.user.mo.pk})

    response = {'patient_form': patient_form,
                'diagnosis_formset': diagnosis_formset,
                'visit_form': visit_form,
                'visits_qs': patient.visit_set.all(),
                'patient': patient}
    return render_to_response('patient_edit.html',
                              response,
                              context_instance=RequestContext(request))
Beispiel #5
0
def add(request):
    """ Создание информации о пациенте """
    avalible_error = False
    error_texts = []
    if request.method == "POST":
        patient_form = PatientForm(request.POST)
        if patient_form.is_valid():
            patient = patient_form.save(commit=False)
        else:
            patient = None
            avalible_error = True
        visit_first_form = VisitFirstForm(request.POST,
                                          prefix=VISIT_FIRST_PREFIX)
        if not visit_first_form.is_valid():
            avalible_error = True
        visit_form = VisitForm(request.POST, prefix=VISIT_PREFIX)
        if not visit_form.is_valid() and not avalible_error:
            avalible_error = True
        diagnosis_formset = DiagnosisFormset(request.POST,
                                             prefix=DIAGNOSIS_PREFIX)
        if not diagnosis_formset.is_valid():
            avalible_error = True
        avalible_data = [v for f in diagnosis_formset.forms for v in f.cleaned_data]
        if  len(avalible_data) < 1:
            avalible_error = True
            error_texts.append(u'Нужно записать хотя бы 1 диагноз')
        if not avalible_error:
            try:
                p = patient
                ps = Patient.objects.filter(last_name = p.last_name, first_name = p.first_name, patronymic = p.patronymic, birthday=p.birthday, type = p.type)
                
                if len(ps) > 0:
                    raise
                    
            except:
                e = u'Данный тип пациента с таким ФИО и датой рождения <a href="%s" target="_blank">уже есть в реестре</a>' % reverse('patient_edit', kwargs={'patient_id': ps[0].pk})
                error_texts.append(e)
            else:
                visit_first = visit_first_form.save(commit=False)
                visit_first.is_add = True
                patient.date_registration = visit_first.date_created
                patient.save()
                save_formset(diagnosis_formset, patient)
                visit_first.patient = patient
                visit_first.save()
                if visit_form.cleaned_data.get('is_visit', False):
                    visit = visit_form.save(commit=False)
                    #visit.mo = request.user.mo
                    visit.patient = patient
                    visit.save()
                Patient.objects.filter(pk=patient.pk) \
                           .update(diagnosis_text = get_diagnosis_text(patient),
                                   diagnosis_text_code = get_diagnosis_code(patient))
                messages.add_message(request, messages.INFO, u'Пациент "%s" внесен в реестр' % patient.get_full_name())
            
                redirect_to = request.POST.get('__redirect_to')
                if redirect_to == 'edit':
                    url = reverse('patient_edit', kwargs={'patient_id': patient.pk})
                elif redirect_to == 'add':
                    url = reverse('patient_add')
                else:
                    url = reverse('patient_search')
                
                return redirect(url)
    else:
        patient_form = PatientForm()
        diagnosis_formset = DiagnosisFormset(prefix=DIAGNOSIS_PREFIX)
        visit_form = VisitForm(prefix=VISIT_PREFIX, initial={'mo': request.user.mo.pk})
        visit_first_form = VisitFirstForm(prefix=VISIT_FIRST_PREFIX,
                                           initial={'mo': request.user.mo.pk})

    response = {'patient_form': patient_form,
                'diagnosis_formset': diagnosis_formset,
                'visit_form': visit_form,
                'visit_first_form': visit_first_form,
                'error_texts': error_texts}
    return render_to_response('patient_add.html',
                              response,
                              context_instance=RequestContext(request))