def submit_photos(request, treatment_id):
    treatment = get_object_or_404(Treatment, id=treatment_id)
    user = request.user
    if request.method == "POST":
        post = request.POST
        
        treatment_dict = dict(patient = user.patient)
        
        try:
            pictures_ids = post['pictures_ids']
            pictures_ids = pictures_ids.split(',')
            if len(pictures_ids) < 1:
                error = u"Número minimo de fotos exigidas é 1. Você enviou menos fotos que isso, tente enviar novamente com o número correto de fotos."
                return render_to_response("message.html", {'error': error}, context_instance=RequestContext(request))
        except:
            error = u"Ocorreu um erro ao tentar ler as fotos. Tente enviar o formulário novamente mais tarde."
            return render_to_response("message.html", {'error': error}, context_instance=RequestContext(request))
            
        for pid in pictures_ids:
            try:
                picture = Picture.objects.get(pk=int(pid))
                treatment_picture = TreatmentPicture.objects.get_or_create(picture=picture, treatment=treatment)
            except:
                import traceback
                error = traceback.format_exc()
                send_error_report("ERROR - Failed to create treatment photos", error)
                for i in treatment.treatment_pictures.all():
                    i.picture.delete()
                treatment.delete()
                error = u"Ocorreu um erro ao tentar processar as novas fotos. Tente novamente mais tarde. Se o erro persistir os administradores serão notificados para resolver o problema o mais rápido possível."
                return render_to_response("message.html", {'error': error}, context_instance=RequestContext(request))

            success = u"Novas fotos adicionadas com sucesso! O médico será notificado e prosseguirá com a avaliação em breve."
            treatment.more_photos_submitted()
            return render_to_response("message.html", {'success': success}, context_instance=RequestContext(request))

    if user.is_patient():
        if treatment.patient == user.patient:
            return render_to_response("treatments/submit_photos.html", locals(), context_instance=RequestContext(request))
    error = "You don't have permission to access this treatment."
    return render_to_response("message.html", {'error': error}, context_instance=RequestContext(request))
Example #2
0
def paypal_payment_completed(sender, **kwargs):
    ipn_obj = sender
    # Undertake some action depending upon `ipn_obj`.
    treatment_id = ipn_obj.invoice
    try:
        treatment = Treatment.objects.get(id = treatment_id)
        treatment.paid = True
        treatment.save()
        
        treatment_status = TreatmentStatus(status="IQ", treatment=treatment)
        treatment_status.save()
        
        treatment_queue = TreatmentQueue(treatment=treatment)
        treatment_queue.save()
    except:
        # TODO: IMPORTANT!
        # Add code to send emails to admins and log the transaction in case of failure
        
        import traceback
        error = traceback.format_exc()
        subject = "ERROR - Failed to completed payment procedure"
        send_error_report(subject, error)
Example #3
0
def free_treatment(request):
    if request.method == "POST":
        post = request.POST
        try:
            treatment_id = post['treatment_id']
        except:
            return message_error(u"Formulário inválido.")
        
        try:
            treatment = Treatment.objects.get(id=treatment_id)
        except:
            return message_error(u"Avaliação não encontrada.")
            
        if system.GET_FREE_TREATMENTS() > 0:
            f_t = Config.objects.get(key="free_treatments")
            f_t.value = int(f_t.value) - 1
            f_t.save()
        else:
            return message_error(u"Não existem mais gratuidades no momento.")
            
        try:
            treatment.paid = True
            treatment.save()

            treatment_status = TreatmentStatus(status="IQ", treatment=treatment)
            treatment_status.save()

            treatment_queue = TreatmentQueue(treatment=treatment)
            treatment_queue.save()
        except:
            import traceback
            error = traceback.format_exc()
            subject = "ERROR - Failed to completed payment procedure"
            send_error_report(subject, error)
            
        return render_to_response("message.html", {"success": u"Avaliação enviada com sucesso. Já se encontra na fila de espera. Você será notificado das atualizações na sua avaliação pelo sistema e pelo seu email registrado. Aguarde."}, context_instance=RequestContext(request))
    else:
        return message_error(u"Não pode ser acessado dessa maneira.")
def start_new_treatment(request):
    appearance_time_scale_choices = Treatment.time_scale_choices
    
    num_photos = system.GET_MIN_NUM_PHOTOS()
    
    user = request.user
    
    if user.is_doctor() is True:
        post = True
        error = u"Você como médico não pode iniciar uma avaliação."
        return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))
    
    if request.method == "POST":
        post = request.POST
        
        treatment_dict = dict(patient = user.patient)
        
        try:
            pictures_ids = post['pictures_ids']
            pictures_ids = pictures_ids.split(',')
            if len(pictures_ids) < num_photos:
                error = u"Número mínimo de fotos exigidas são %s. Você enviou menos fotos que isso, tente enviar novamente com o número correto de fotos." % MIN_NUM_PHOTOS
                return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))
        except:
            error = u"Ocorreu um erro ao tentar ler as fotos. Tente enviar o formulário novamente mais tarde."
            return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))
        
        try:
            treatment_dict.update(dict(
            multiple_lesions = (post['multiple_lesions'] == "multiple"),
            appearance_time_scale = post['appearance_time_scale'],
            appearance_time = int(post['appearance_time']),
            permanent = (post['permanent'] == "true"),
            currently_undergoing_treatment = (post['currently_undergoing_treatment'] == "true"),
            family_history = (post['family_history'] == "true")
            ))
        except:
            error = u"Erro ao processar campos do formulario. Tente novamente, preenchendo todos os campos corretamente."
            return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))
        
        try:
            treatment_dict.update(dict(
            itches = (post.get('itches', False) == "true"),
            burns = (post.get('burns', False) == "true"),
            hurts = (post.get('hurts', False) == "true"),
            continuously_itchy = (post.get('continuously_itchy', False) == "true"),
            itchy_during_daytime = (post.get('itchy_during_daytime', False) == "true"),
            itchy_during_nighttime = (post.get('itchy_during_nighttime', False) == "true"),
            numb = (post.get('numb', False) == "true"),
            sensitive_to_touch = (post.get('sensitive_to_touch', False) == "true"),
            has_grown = (post.get('has_grown', False) == "true"),
            has_changed_spread = (post.get('has_changed_spread', False) == "true")
            ))
        except MultiValueDictKeyError:
            pass
            
        treatment_dict.update(dict(
        currently_undergoing_treatment_obs = post['currently_undergoing_treatment_obs'],
        family_history_obs = post['family_history_obs']
        ))
        
        treatment = Treatment(**treatment_dict)
        
        treatment.save()
        
        for pid in pictures_ids:
            try:
                picture = Picture.objects.get(pk=int(pid))
                treatment_picture = TreatmentPicture.objects.get_or_create(picture=picture, treatment=treatment)
            except:
                import traceback
                error = traceback.format_exc()
                send_error_report("ERROR - Failed to create treatment photos", error)
                for i in treatment.treatment_pictures.all():
                    i.picture.delete()
                treatment.delete()
                error = u"Ocorreu um erro duranto o processamento dos dados."
                return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))

        success = "Consulta registrada com sucesso!"
        
        request.method = "GET"
        return toa_new_treatment(request)
        
    return render_to_response("treatments/start_new_treatment.html", locals(), context_instance=RequestContext(request))