Example #1
0
def _topic_messages(request,
                    referral_id,
                    topic_id,
                    object_id,
                    template_name="messages/messages_topic.html"):
    client_id = object_id

    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)
    referral = Referral.objects.get(
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

    if not _access_check(request, object) and not _access_check_referral_write(
            request, referral):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    messagetopic = MessageTopic.objects.get(pk=topic_id)

    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
Example #2
0
def attach_form(request, object_id=None, referral_id=None, attach_id=None):
    '''
        object_id  : Person.id
        referra_id : Referral.id
        attach_id  : ReferralAttach.id
    '''

    # html variables
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)
    attach_list = ReferralAttach.objects.filter( referral=referral_id, referral__service__organization=request.user.get_profile().org_active )
    object = Client.objects.get(pk=object_id, person__organization=request.user.get_profile().org_active)
    types = REFERRAL_ATTACH_TYPE

    # permission to write
    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    # update 
    if attach_id:
        attach = ReferralAttach.objects.get( pk=attach_id, referral=referral_id, referral__service__organization=request.user.get_profile().org_active )
        attach_list = ReferralAttach.objects.filter( referral=referral_id, referral__service__organization=request.user.get_profile().org_active ).exclude(id=attach.id)

    # permission to read file, user is a professional and/or psychologist.
    is_professional = request.user.get_profile().person.is_careprofessional() 
    is_psychologist = False
    
    if is_professional:
        if str(request.user.get_profile().person.careprofessional.professionalIdentification.profession) == "Psicólogo": # hardcode
            is_psychologist = True

    return render_to_response('upload/upload_attach.html', locals(), context_instance=RequestContext(request))
Example #3
0
def _referral_messages(request,
                       referral_id,
                       object_id,
                       template_name="messages/messages_referral.html"):
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)
    client_id = object_id
    referral = Referral.objects.get(
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

    if not request.user.get_profile().person.is_client():
        # check if professional can read it
        if not _access_check(request,
                             object) and not _access_check_referral_write(
                                 request, referral):
            return render_to_response('403.html', {
                'object':
                _("Oops! You don't have access for this service!"),
            },
                                      context_instance=RequestContext(request))

        if not referral.topics.all():
            return HttpResponseRedirect(
                '/client/%s/referral/%s/messages/newtopic' %
                (object.id, referral.id))
    #topics = MessageTopic.objects.filter(referral=referral, referral__service__organization=request.user.get_profile().org_active).order_by('messages__sent_at').reverse().distinct()
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))
def _new_topic_message(request, referral_id, topic_id, object_id, redirect_to=None):

    client_id = object_id
    object = get_object_or_404(
        Client, pk=object_id, person__organization=request.user.get_profile().org_active)
    referral = Referral.objects.get(
        pk=referral_id, service__organization=request.user.get_profile().org_active)

    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    messagetopic = MessageTopic.objects.get(pk=topic_id)
    if request.POST.get('message'):
        from datetime import datetime
        message = Message()
        message.sender = request.user
        message.sent_at = datetime.now
        message.body = request.POST['message']
        message.topic = messagetopic
        message.save()

        from django.shortcuts import redirect
        return redirect(redirect_to or "/client/%s/referral/%s/messages/topic/%s" % (client_id, referral_id, topic_id))
    else:
        return HttpResponseRedirect(redirect_to or '/client/%s/referral/%s/messages/topic/%s' % (object.id, referral.id, topic_id))
Example #5
0
def _topic_messages(request, referral_id, topic_id, object_id, template_name="messages/messages_topic.html"):
    client_id = object_id

    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)
    referral = Referral.objects.get(pk=referral_id, service__organization=request.user.get_profile().org_active)

    if not _access_check(request, object) and not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    messagetopic = MessageTopic.objects.get(pk=topic_id)

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Example #6
0
def _referral_messages(request, referral_id, object_id, template_name="messages/messages_referral.html"):
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)
    client_id = object_id
    referral = Referral.objects.get(pk=referral_id, service__organization=request.user.get_profile().org_active)

    if not request.user.get_profile().person.is_client():
        # check if professional can read it
        if not _access_check(request, object) and not _access_check_referral_write(request, referral):
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        if not referral.topics.all():
            return HttpResponseRedirect('/client/%s/referral/%s/messages/newtopic' % (object.id, referral.id))
    #topics = MessageTopic.objects.filter(referral=referral, referral__service__organization=request.user.get_profile().org_active).order_by('messages__sent_at').reverse().distinct()
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))
Example #7
0
def attach_form(request, object_id = '', referral_id = ''):
    user = request.user
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)
    organization = user.get_profile().org_active.id

    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    types = REFERRAL_ATTACH_TYPE

    #indication = Indication.objects.get(referral = object_id)
    attachs = ReferralAttach.objects.filter(referral = referral_id, referral__service__organization=request.user.get_profile().org_active)
    object = Client.objects.get(pk = object_id, person__organization=request.user.get_profile().org_active)

    return render_to_response('upload/upload_attach.html', locals(), context_instance=RequestContext(request))
Example #8
0
def attach_save(request, object_id = None, client_id = None):

    referral = get_object_or_404(Referral, pk=object_id, service__organization=request.user.get_profile().org_active)
    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    if request.method == 'POST':
        user = request.user
        filename = ''

        if 'file' in request.FILES:
            path = '%s/img/organization/%s' % (MEDIA_ROOT, user.get_profile().org_active.id)
            if not os.path.exists(path):
                os.mkdir(path)
                os.chmod(path, 0777)

            path = '%s/img/organization/%s/attach' % (MEDIA_ROOT, user.get_profile().org_active.id)
            if not os.path.exists(path):
                os.mkdir(path)
                os.chmod(path, 0777)

            try:
                    filename = request.FILES['file']
                    file = str(uuid.uuid4()) + '.'+ (str(filename).split('.')[-1])
                    destination = open('%s/%s' % (path,  file), 'w+')
                    for chunk in filename.chunks():
                        destination.write(chunk)
                    destination.close()
                        
                    attachs = ReferralAttach.objects.filter(referral = object_id, referral__service__organization=request.user.get_profile().org_active)

                    attach = ReferralAttach()
                    attach.filename = '%s' % request.FILES['file']
                    attach.file = '%s' % file
                    attach.description = request.POST.get('description')
                    attach.type = request.POST.get('doc_type')
                    attach.only_professionals = True if request.POST.get('onlyprofessionals') == 'True' else False
                    attach.only_psychologists = True if request.POST.get('onlypsychologists') == 'True' else False

                    

                    attach.referral = Referral.objects.get(pk = object_id, service__organization=request.user.get_profile().org_active)
                    attach.save()
    
            except IOError:
                print "error sending file"

        return HttpResponseRedirect('/upload/client/%s/attach/%s/' % (client_id, object_id))
Example #9
0
def new_message_topic(request, referral_id, object_id, template_name="messages/messages_referral.html"):
    client_id = object_id
    referral = Referral.objects.get(pk=referral_id, service__organization=request.user.get_profile().org_active)
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)

    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    if not request.POST:
        return render_to_response('messages/messages_newtopic.html', locals(), context_instance=RequestContext(request))

    else:
        messagetopic = MessageTopic()
        messagetopic.referral = referral
        messagetopic.subject = request.POST['topic']
        if request.POST.get('topic'):
            messagetopic.save()
            messages.success(request, _('Message topic created successfully'))
            return HttpResponseRedirect('/client/%s/referral/%s/messages/topic/%s' % (client_id, referral.id, messagetopic.id))
        else:
            return HttpResponseRedirect('/client/%s/referral/%s/messages/' % (object.id, referral.id))
Example #10
0
def _new_topic_message(request,
                       referral_id,
                       topic_id,
                       object_id,
                       redirect_to=None):

    client_id = object_id
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)
    referral = Referral.objects.get(
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

    if not _access_check_referral_write(request, referral):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    messagetopic = MessageTopic.objects.get(pk=topic_id)
    if request.POST.get('message'):
        from datetime import datetime
        message = Message()
        message.sender = request.user
        message.sent_at = datetime.now
        message.body = request.POST['message']
        message.topic = messagetopic
        message.save()

        from django.shortcuts import redirect
        return redirect(redirect_to
                        or "/client/%s/referral/%s/messages/topic/%s" %
                        (client_id, referral_id, topic_id))
    else:
        return HttpResponseRedirect(
            redirect_to or '/client/%s/referral/%s/messages/topic/%s' %
            (object.id, referral.id, topic_id))
Example #11
0
def attach_form(request, object_id='', referral_id=''):
    user = request.user
    referral = get_object_or_404(
        Referral,
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)
    organization = user.get_profile().org_active.id

    if not _access_check_referral_write(request, referral):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    types = REFERRAL_ATTACH_TYPE

    #indication = Indication.objects.get(referral = object_id)
    attachs = ReferralAttach.objects.filter(
        referral=referral_id,
        referral__service__organization=request.user.get_profile().org_active)
    object = Client.objects.get(
        pk=object_id,
        person__organization=request.user.get_profile().org_active)

    # Finding if the user is a secretary or a psychologist.
    is_secretary = user.get_profile().person.is_secretary()
    is_professional = user.get_profile().person.is_careprofessional()
    is_psychologist = False

    if is_professional:
        if str(user.get_profile().person.careprofessional.
               professionalIdentification.profession) == "Psicólogo":
            is_psychologist = True

    return render_to_response('upload/upload_attach.html',
                              locals(),
                              context_instance=RequestContext(request))
Example #12
0
def new_message_topic(request,
                      referral_id,
                      object_id,
                      template_name="messages/messages_referral.html"):
    client_id = object_id
    referral = Referral.objects.get(
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)

    if not _access_check_referral_write(request, referral):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    if not request.POST:
        return render_to_response('messages/messages_newtopic.html',
                                  locals(),
                                  context_instance=RequestContext(request))

    else:
        messagetopic = MessageTopic()
        messagetopic.referral = referral
        messagetopic.subject = request.POST['topic']
        if request.POST.get('topic'):
            messagetopic.save()
            messages.success(request, _('Message topic created successfully'))
            return HttpResponseRedirect(
                '/client/%s/referral/%s/messages/topic/%s' %
                (client_id, referral.id, messagetopic.id))
        else:
            return HttpResponseRedirect('/client/%s/referral/%s/messages/' %
                                        (object.id, referral.id))
Example #13
0
def attach_form(request, object_id = '', referral_id = ''):
    user = request.user
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)
    organization = user.get_profile().org_active.id

    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    types = REFERRAL_ATTACH_TYPE

    #indication = Indication.objects.get(referral = object_id)
    attachs = ReferralAttach.objects.filter(referral = referral_id, referral__service__organization=request.user.get_profile().org_active)
    object = Client.objects.get(pk = object_id, person__organization=request.user.get_profile().org_active)

    # Finding if the user is a secretary or a psychologist.
    is_secretary = user.get_profile().person.is_secretary()
    is_professional = user.get_profile().person.is_careprofessional() 
    is_psychologist = False
    
    if is_professional:
        if str(user.get_profile().person.careprofessional.professionalIdentification.profession) == "Psicólogo":
            is_psychologist = True

    return render_to_response('upload/upload_attach.html', locals(), context_instance=RequestContext(request))
Example #14
0
def occurrence_confirmation_form(
    request,
    pk,
    template='schedule/schedule_occurrence_confirmation_form.html',
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):

    occurrence = get_object_or_404(
        ScheduleOccurrence,
        pk=pk,
        event__referral__service__organization=request.user.get_profile(
        ).org_active)

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [
            device.pk
            for device in (occurrence.occurrenceconfirmation.device.all())
        ]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(
            pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':
        if denied_to_write:
            return render_to_response('403.html', {
                'object':
                _("Oops! You don't have access for this service!"),
            },
                                      context_instance=RequestContext(request))
        form = form_class(request.POST,
                          instance=occurrence_confirmation,
                          initial={
                              'device': initial_device,
                          })
        if form.is_valid():
            data = form.save(commit=False)
            data.occurrence = occurrence
            # client not arrive, dont save datetime field
            if int(data.presence) not in (1, 2, 6, 7):
                data.date_started = None
                data.date_finished = None
            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()
            messages.success(request,
                             _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)
        else:
            form.fields['device'].widget.choices = [(
                i.id, i
            ) for i in DeviceDetails.objects.active(request.user.get_profile(
            ).org_active).filter(
                Q(room=occurrence.room) | Q(mobility=2, lendable=True)
                | Q(place=occurrence.room.place, mobility=2, lendable=False))]
            return render_to_response(template,
                                      dict(occurrence=occurrence,
                                           form=form,
                                           object=object,
                                           referral=occurrence.event.referral),
                                      context_instance=RequestContext(request))
    else:
        # load initial data if client dont arrive
        if hasattr(occurrence_confirmation, 'presence') and int(
                occurrence_confirmation.presence) not in (1, 2, 6, 7):
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation,
                          initial={
                              'occurrence': occurrence,
                              'start_time': occurrence.start_time,
                              'end_time': occurrence.end_time,
                              'device': initial_device,
                          })

        form.fields['device'].widget.choices = [
            (i.id, i)
            for i in DeviceDetails.objects.active(request.user.get_profile(
            ).org_active).filter(
                Q(room=occurrence.room) | Q(mobility="2", lendable=True)
                | Q(place=occurrence.room.place, mobility="2", lendable=False))
        ]

        #Validating the events to be dated with input and output
        if (((occurrence_confirmation
              and int(occurrence_confirmation.presence)) > 2) and
            ((occurrence_confirmation
              and int(occurrence_confirmation.presence)) < 6)
                or ((occurrence_confirmation
                     and int(occurrence_confirmation.presence)) > 7)):
            occurrences_that_require_dates = True
        else:
            occurrences_that_require_dates = None

        #Creating dictionaries to return instance to template
        events_for_return = dict(
            occurrence=occurrence,
            form=form,
            object=object,
            referral=occurrence.event.referral,
            occurrence_confirmation=occurrence_confirmation,
            hide_date_field=occurrences_that_require_dates,
            #True if occurrence_confirmation and int(occurrence_confirmation.presence) > 7 else None,
            denied_to_write=denied_to_write)

    return render_to_response(template,
                              events_for_return,
                              context_instance=RequestContext(request))
def occurrence_confirmation_form_group(
    request,
    pk,
    template='schedule/schedule_occurrence_confirmation_form_group.html',
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):
    '''
        confirmation event for a member of group
        choose a covenant of service and create a payment based in covenant
    '''

    occurrence = get_object_or_404(
        ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    covenant_list = occurrence.event.referral.service.covenant.all().order_by('name')
    receive_list = []

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [
            device.pk for device in occurrence.occurrenceconfirmation.device.all()]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(
            pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(
        Client, pk=client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    # update occurrence and payments or new payment.
    if request.method == 'POST':

        # permission
        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        # Calls method to create new payment form.
        create_new_payment_form()

        # update payments, not required.
        for x in Receive.objects.filter(occurrence=occurrence):

            prefix = 'receive_form---%s' % x.id  # hardcore Jquery
            form_receive = ReceiveFormUpdate(
                request.POST, instance=x, prefix=prefix)

            receive_list.append(form_receive)

            if form_receive.is_valid():
                form_payment = form_receive.save()

        # occurrence
        form = form_class(request.POST, instance=occurrence_confirmation, initial={
                          'device': initial_device, })

        # Calls method that validates payment form.
        valid_payment_form()

    else:
        # load initial data if client dont arrive
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1, 2):
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence': occurrence,
            'start_time': occurrence.start_time,
            'end_time': occurrence.end_time,
            'device': initial_device,
        })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(
            Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]

        # payments of occurrence, update form.
        for x in Receive.objects.filter(occurrence=occurrence):
            # for many forms and one submit.
            prefix = 'receive_form---%s' % x.id
            receive_list.append(ReceiveFormUpdate(instance=x, prefix=prefix))


    # just one out if errors
    return render_to_response(
        template,
        dict(
            occurrence=occurrence,
            form=form,
            object=object,
            referral=occurrence.event.referral,
            occurrence_confirmation=occurrence_confirmation,
            hide_date_field=True if occurrence_confirmation and int(
                occurrence_confirmation.presence) > 2 else None,
            denied_to_write=denied_to_write,
            receive_list=receive_list,
            covenant_list=covenant_list,
            receive_new_form=ReceiveFormNew(
                prefix='receive_form---TEMPID999FORM'),
        ),
        context_instance=RequestContext(request)
    )
def occurrence_confirmation_form(
    request,
    pk,
    template='schedule/schedule_occurrence_confirmation_form.html',
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):
    '''
        confirmation event
    '''

    occurrence = get_object_or_404(
        ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    receive_list = []

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:

        initial_device = [
            device.pk for device in occurrence.occurrenceconfirmation.device.all()]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(
            pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(
        Client, pk=client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':

        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        form = form_class(request.POST, instance=occurrence_confirmation, initial={
                          'device': initial_device, })

        # receive
        payment_valid = True

        for x in Receive.objects.filter(occurrence=occurrence):
            prefix = 'receive_form---%s' % x.id  # hardcore Jquery
            form_receive = ReceiveFormUpdate(
                request.POST, instance=x, prefix=prefix)

            receive_list.append(form_receive)

            if form_receive.is_valid():
                form_payment = form_receive.save()
            else:
                payment_valid = False

        # Calls method that validates payment form if payment is valid.
        ocurrence_payment()

    # not request.POST
    else:
        # load initial data if client dont arrive
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1, 2):
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence': occurrence,
            'start_time': occurrence.start_time,
            'end_time': occurrence.end_time,
            'device': initial_device,
        })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(
            Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]

        # payment form
        for x in Receive.objects.filter(occurrence=occurrence):
            prefix = 'receive_form---%s' % x.id
            receive_list.append(ReceiveFormUpdate(instance=x, prefix=prefix))

    if occurrence_confirmation and int(occurrence_confirmation.presence) > 2:
        hide_date_field = True
    else:
        hide_date_field = None

    render_to_response = render_to_response(template,
                                            dict(
                                                occurrence=occurrence,
                                                form=form,
                                                object=object,
                                                referral=occurrence.event.referral,
                                                occurrence_confirmation=occurrence_confirmation,
                                                hide_date_field=hide_date_field,
                                                denied_to_write=denied_to_write,
                                                receive_list=receive_list,
                                            ),
                                            context_instance=RequestContext(
                                                request)
                                            )

    return render_to_response
Example #17
0
def occurrence_confirmation_form(
    request,
    pk,
    template='schedule/schedule_occurrence_confirmation_form.html',
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):

    occurrence = get_object_or_404(
        ScheduleOccurrence, pk=pk,
        event__referral__service__organization=request.user.get_profile(
            ).org_active)

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in (
            occurrence.occurrenceconfirmation.device.all())]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response(
            '403.html',
            {'object': _("Oops! You don't have access for this service!"), },
            context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(
            pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(
        Client, pk=client_id,
        person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':
        if denied_to_write:
            return render_to_response(
                '403.html',
                {'object': _(
                    "Oops! You don't have access for this service!"), },
                context_instance=RequestContext(request))
        form = form_class(
            request.POST,
            instance=occurrence_confirmation,
            initial={'device': initial_device, })
        if form.is_valid():
            data = form.save(commit=False)
            data.occurrence = occurrence
            # client not arrive, dont save datetime field
            if int(data.presence) not in (1, 2, 6, 7):
                data.date_started = None
                data.date_finished = None
            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()
            messages.success(request, _(
                'Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)
        else:
            form.fields['device'].widget.choices = [(
                i.id, i) for i in DeviceDetails.objects.active(
                    request.user.get_profile().org_active).filter(
                        Q(room=occurrence.room) |
                        Q(mobility=2, lendable=True) |
                        Q(
                            place=occurrence.room.place,
                            mobility=2,
                            lendable=False))]
            return render_to_response(
                template,
                dict(
                    occurrence=occurrence,
                    form=form,
                    object=object,
                    referral=occurrence.event.referral),
                context_instance=RequestContext(request)
            )
    else:
        # load initial data if client dont arrive
        if hasattr(occurrence_confirmation, 'presence') and int(
            occurrence_confirmation.presence) not in (1, 2, 6, 7):
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence': occurrence,
            'start_time': occurrence.start_time,
            'end_time': occurrence.end_time,
            'device': initial_device,
            })

        form.fields['device'].widget.choices = [(
            i.id, i) for i in DeviceDetails.objects.active(
                request.user.get_profile().org_active).filter(
                    Q(room=occurrence.room) |
                    Q(mobility="2", lendable=True) |
                    Q(
                        place=occurrence.room.place,
                        mobility="2",
                        lendable=False))]

        #Validating the events to be dated with input and output
        if (((occurrence_confirmation and int(occurrence_confirmation.presence)) > 2 ) and
            ((occurrence_confirmation and int(occurrence_confirmation.presence)) < 6) or
            ((occurrence_confirmation and int(occurrence_confirmation.presence)) > 7)):
            occurrences_that_require_dates = True
        else:
            occurrences_that_require_dates = None

        #Creating dictionaries to return instance to template
        events_for_return = dict(
            occurrence=occurrence,
            form=form,
            object=object,
            referral=occurrence.event.referral,
            occurrence_confirmation=occurrence_confirmation,
            hide_date_field=occurrences_that_require_dates,
            #True if occurrence_confirmation and int(occurrence_confirmation.presence) > 7 else None,
            denied_to_write=denied_to_write)

    return render_to_response(template, events_for_return, context_instance=RequestContext(request))
Example #18
0
def occurrence_confirmation_form(
    request,
    pk,
    template="schedule/schedule_occurrence_confirmation_form.html",
    form_class=OccurrenceConfirmationForm,
    client_id=None,
    redirect_to=None,
):

    occurrence = get_object_or_404(
        ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active
    )

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in occurrence.occurrenceconfirmation.device.all()]

    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response(
            "403.html",
            {"object": _("Oops! You don't have access for this service!")},
            context_instance=RequestContext(request),
        )

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None

    object = get_object_or_None(Client, pk=client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write

    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == "POST":
        if denied_to_write:
            return render_to_response(
                "403.html",
                {"object": _("Oops! You don't have access for this service!")},
                context_instance=RequestContext(request),
            )
        form = form_class(request.POST, instance=occurrence_confirmation, initial={"device": initial_device})
        if form.is_valid():
            data = form.save(commit=False)
            data.occurrence = occurrence
            if int(data.presence) not in (1, 2):  # client not arrive, dont save datetime field
                data.date_started = None
                data.date_finished = None
            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST["occurrence_annotation"]
            occurrence.save()
            messages.success(request, _("Occurrence confirmation updated successfully"))
            return http.HttpResponseRedirect(redirect_to or request.path)
        else:
            form.fields["device"].widget.choices = [
                (i.id, i)
                for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(
                    Q(room=occurrence.room)
                    | Q(mobility=2, lendable=True)
                    | Q(place=occurrence.room.place, mobility=2, lendable=False)
                )
            ]
            return render_to_response(
                template,
                dict(occurrence=occurrence, form=form, object=object, referral=occurrence.event.referral),
                context_instance=RequestContext(request),
            )
    else:
        if hasattr(occurrence_confirmation, "presence") and int(occurrence_confirmation.presence) not in (
            1,
            2,
        ):  # load initial data if client dont arrive
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(
            instance=occurrence_confirmation,
            initial={
                "occurrence": occurrence,
                "start_time": occurrence.start_time,
                "end_time": occurrence.end_time,
                "device": initial_device,
            },
        )

        form.fields["device"].widget.choices = [
            (i.id, i)
            for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(
                Q(room=occurrence.room)
                | Q(mobility="2", lendable=True)
                | Q(place=occurrence.room.place, mobility="2", lendable=False)
            )
        ]

    return render_to_response(
        template,
        dict(
            occurrence=occurrence,
            form=form,
            object=object,
            referral=occurrence.event.referral,
            occurrence_confirmation=occurrence_confirmation,
            hide_date_field=True if occurrence_confirmation and int(occurrence_confirmation.presence) > 2 else None,
            denied_to_write=denied_to_write,
        ),
        context_instance=RequestContext(request),
    )
Example #19
0
def occurrence_confirmation_form_group(
        request, 
        pk, 
        template='schedule/schedule_occurrence_confirmation_form_group.html',
        form_class=OccurrenceConfirmationForm,
        client_id = None,
        redirect_to = None,
    ):

    '''
        confirmation event for a member of group
        choose a covenant of service and create a payment based in covenant
    '''

    occurrence = get_object_or_404(ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    covenant_list = occurrence.event.referral.service.covenant.all().order_by('name')
    receive_list = []

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in occurrence.occurrenceconfirmation.device.all()]
        
    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(pk = occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None
    
    object = get_object_or_None(Client, pk = client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    # update occurrence and payments or new payment.
    if request.method == 'POST':

        # permission
        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))


        # new payment form, not required.
        if not request.POST.get('select_covenant_receive') == '000' :

            covenant = Covenant.objects.get( pk=request.POST.get('select_covenant_receive'), organization=request.user.get_profile().org_active ) 
            pfx = 'receive_form---TEMPID999FORM' # hardcode Jquery 
            form_receive_new = ReceiveFormNew(request.POST, prefix=pfx, initial={ 'launch_date': date.today() })

            if form_receive_new.is_valid():

                fpn = form_receive_new.save()
                fpn.occurrence.add(occurrence)

                # from covenant
                fpn.covenant_payment_way_options = ''
                for pw in covenant.payment_way.all():
                    x = "(%s,'%s')," % ( pw.id , pw.name ) # need be a dict
                    fpn.covenant_payment_way_options += x

                fpn.covenant_payment_way_selected = request.POST.getlist('TEMPID999FORM-pw')
                fpn.save()


        # update payments, not required.
        for x in Receive.objects.filter(occurrence=occurrence):
            pfx = 'receive_form---%s' % x.id # hardcode Jquery 
            # new! fill payment date today
            if not x.launch_date:
                receive_list.append(ReceiveFormUpdate(request.POST, instance=x, prefix=pfx, initial={'launch_date':date.today()}))
            else:
                receive_list.append(ReceiveFormUpdate(request.POST, instance=x, prefix=pfx))

            if form_receive.is_valid():
                fp = form_receive.save()


        # occurrence
        form = form_class(request.POST, instance=occurrence_confirmation, initial={ 'device':initial_device, })

        if form.is_valid():
            data = form.save(commit=False)
            data.occurrence = occurrence

            if int(data.presence) not in (1,2): # client not arrive, dont save datetime field
                data.date_started = None
                data.date_finished = None

            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()

            messages.success(request, _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)
        else:
            form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility=2, lendable=True) | Q(place =  occurrence.room.place, mobility=2, lendable=False))]

            messages.error(request, _(u'Campo inválido ou obrigatório'))

    else:
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1,2): # load initial data if client dont arrive
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence':occurrence, 
            'start_time':occurrence.start_time, 
            'end_time':occurrence.end_time,
            'device': initial_device,
            })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]

        # payments of occurrence, update form.
        for x in Receive.objects.filter(occurrence=occurrence):
            pfx = 'receive_form---%s' % x.id # for many forms and one submit.
            receive_list.append( ReceiveFormUpdate(instance=x, prefix=pfx) )


    # just one out if errors
    return render_to_response(
        template,
        dict(
                occurrence=occurrence,
                form=form,
                object=object,
                referral=occurrence.event.referral,
                occurrence_confirmation=occurrence_confirmation,
                hide_date_field=True if occurrence_confirmation and int(occurrence_confirmation.presence) > 2 else None,
                denied_to_write = denied_to_write,
                receive_list = receive_list,
                covenant_list = covenant_list,
                receive_new_form = ReceiveFormNew(prefix='receive_form---TEMPID999FORM'),
            ),
        context_instance=RequestContext(request)
    )
Example #20
0
def occurrence_confirmation_form(
        request, 
        pk, 
        template='schedule/schedule_occurrence_confirmation_form.html',
        form_class=OccurrenceConfirmationForm,
        client_id = None,
        redirect_to = None,
    ):

    '''
        confirmation event
    '''

    occurrence = get_object_or_404(ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    receive_list = []
    
    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in occurrence.occurrenceconfirmation.device.all()]
        
    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(pk=occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None
    
    object = get_object_or_None(Client, pk=client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':

        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        form = form_class(request.POST, instance=occurrence_confirmation, initial={'device':initial_device})

        # receive
        payment_valid = True

        for x in Receive.objects.filter(occurrence=occurrence):

            pfx = 'receive_form---%s' % x.id # hardcode Jquery 
            form_receive = ReceiveFormUpdate(request.POST, instance=x, prefix=pfx)

            receive_list.append(form_receive)

            if form_receive.is_valid():
                fp = form_receive.save()
            else:
                payment_valid = False

        # occurrence
        if form.is_valid() and payment_valid :

            occurrence_confirmation = form.save(commit=False)
            occurrence_confirmation.occurrence = occurrence

            if int(occurrence_confirmation.presence) not in (1,2): # client not arrive, dont save datetime field
                occurrence_confirmation.date_started = None
                occurrence_confirmation.date_finished = None

            occurrence_confirmation.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()

            # sendmail for careprofessional when presence is 4 or 5
            if hasattr(occurrence_confirmation,'presence'):
                if occurrence_confirmation.presence == 4 or occurrence_confirmation.presence == 5 :
                    schedule_notify_email(request.user.get_profile().org_active, occurrence, occurrence_confirmation)

            messages.success(request, _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)

        else:
            form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility=2, lendable=True) | Q(place = occurrence.room.place, mobility=2, lendable=False))]
            messages.error(request, _(u'Campo inválido ou obrigatório'))

    # not request.POST
    else:
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1,2): # load initial data if client dont arrive
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence':occurrence, 
            'start_time':occurrence.start_time, 
            'end_time':occurrence.end_time,
            'device': initial_device,
            })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]

        # payment form
        for x in Receive.objects.filter(occurrence=occurrence):
            pfx = 'receive_form---%s' % x.id

            # new! fill payment date today
            if not x.launch_date:
                receive_list.append( ReceiveFormUpdate(instance=x, prefix=pfx, initial={ 'launch_date':date.today() }) )
            else:
                receive_list.append( ReceiveFormUpdate(instance=x, prefix=pfx) )

    return render_to_response(
        template,
        dict(
                occurrence=occurrence,
                form=form,
                object=object,
                referral=occurrence.event.referral,
                occurrence_confirmation=occurrence_confirmation,
                hide_date_field=True if occurrence_confirmation and int(occurrence_confirmation.presence) > 2 else None,
                denied_to_write = denied_to_write,
                receive_list = receive_list,
            ),
        context_instance=RequestContext(request)
    )
Example #21
0
def attach_save(request, referral_id=None, object_id=None, attach_id=None):

    '''
        object_id  : Person.id
        referra_id : Referral.id
        attach_id  : ReferralAttach.id
    '''

    # html variables
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)
    types = REFERRAL_ATTACH_TYPE

    # update 
    if attach_id:
        attach = ReferralAttach.objects.get( pk=attach_id, referral=referral_id, referral__service__organization=request.user.get_profile().org_active )

    if not _access_check_referral_write(request, referral):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    if request.method == 'POST':

        user = request.user

        # new attach 
        if not attach_id :

            filename = ''

            if 'file' in request.FILES:

                path = '%s/img/organization/%s' % (MEDIA_ROOT, user.get_profile().org_active.id)
                if not os.path.exists(path):
                    os.mkdir(path)
                    os.chmod(path, 0777)

                path = '%s/img/organization/%s/attach' % (MEDIA_ROOT, user.get_profile().org_active.id)
                if not os.path.exists(path):
                    os.mkdir(path)
                    os.chmod(path, 0777)

                try:
                    filename = request.FILES['file']
                    file = str(uuid.uuid4()) + '.'+ (str(filename).split('.')[-1])
                    destination = open('%s/%s' % (path,  file), 'w+')
                    for chunk in filename.chunks():
                        destination.write(chunk)
                    destination.close()
                        
                    attach = ReferralAttach()
                    attach.filename = '%s' % request.FILES['file']
                    attach.file = '%s' % file
                    attach.description = request.POST.get('description')
                    attach.type = request.POST.get('doc_type')
                    attach.permission = request.POST.get('permission')
                    attach.referral = Referral.objects.get(pk=referral_id, service__organization=request.user.get_profile().org_active)

                    attach.save()
        
                except IOError:
                    print "error sending file"

        # update 
        else:

            attach.description = request.POST.get('description')
            attach.type = request.POST.get('doc_type')
            attach.permission = request.POST.get('permission')
            attach.save()

        messages.success(request,  _('Documento salvo com sucesso!'))

        return HttpResponseRedirect('/upload/client/%s/referral/%s/' % (object_id, referral_id) )
Example #22
0
def attach_save(request, object_id=None, client_id=None):

    referral = get_object_or_404(
        Referral,
        pk=object_id,
        service__organization=request.user.get_profile().org_active)
    if not _access_check_referral_write(request, referral):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    if request.method == 'POST':
        user = request.user
        filename = ''

        if 'file' in request.FILES:
            path = '%s/img/organization/%s' % (
                MEDIA_ROOT, user.get_profile().org_active.id)
            if not os.path.exists(path):
                os.mkdir(path)
                os.chmod(path, 0777)

            path = '%s/img/organization/%s/attach' % (
                MEDIA_ROOT, user.get_profile().org_active.id)
            if not os.path.exists(path):
                os.mkdir(path)
                os.chmod(path, 0777)

            try:
                filename = request.FILES['file']
                file = str(uuid.uuid4()) + '.' + (str(filename).split('.')[-1])
                destination = open('%s/%s' % (path, file), 'w+')
                for chunk in filename.chunks():
                    destination.write(chunk)
                destination.close()

                attachs = ReferralAttach.objects.filter(
                    referral=object_id,
                    referral__service__organization=request.user.get_profile(
                    ).org_active)

                attach = ReferralAttach()
                attach.filename = '%s' % request.FILES['file']
                attach.file = '%s' % file
                attach.description = request.POST.get('description')
                attach.type = request.POST.get('doc_type')
                attach.only_professionals = True if request.POST.get(
                    'onlyprofessionals') == 'True' else False
                attach.only_psychologists = True if request.POST.get(
                    'onlypsychologists') == 'True' else False

                attach.referral = Referral.objects.get(
                    pk=object_id,
                    service__organization=request.user.get_profile(
                    ).org_active)
                attach.save()

            except IOError:
                print "error sending file"

        return HttpResponseRedirect('/upload/client/%s/attach/%s/' %
                                    (client_id, object_id))
Example #23
0
def occurrence_confirmation_form_group(
        request, 
        pk, 
        template='schedule/schedule_occurrence_confirmation_form_group.html',
        form_class=OccurrenceConfirmationForm,
        client_id = None,
        redirect_to = None,
    ):

    '''
        confirmation event for a member of group
        choose a covenant of service and create a payment based in covenant
    '''

    occurrence = get_object_or_404(ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    covenant_list = occurrence.event.referral.service.covenant.all().order_by('name')
    receive_list = []

    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in occurrence.occurrenceconfirmation.device.all()]
        
    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(pk = occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None
    
    object = get_object_or_None(Client, pk = client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    # update occurrence and payments or new payment.
    if request.method == 'POST':

        # permission
        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))


        # new payment form, not required.
        if not request.POST.get('select_covenant_receive') == '000' :

            covenant = Covenant.objects.get( pk=request.POST.get('select_covenant_receive'), organization=request.user.get_profile().org_active ) 

            pfx = 'receive_form---TEMPID999FORM' # hardcore Jquery 
            form_receive_new = ReceiveFormNew(request.POST, prefix=pfx)

            if form_receive_new.is_valid():

                fpn = form_receive_new.save()
                fpn.occurrence.add(occurrence)

                # from covenant
                fpn.covenant_payment_way_options = ''
                for pw in covenant.payment_way.all():
                    x = "(%s,'%s')," % ( pw.id , pw.name ) # need be a dict
                    fpn.covenant_payment_way_options += x

                fpn.covenant_payment_way_selected = request.POST.getlist('TEMPID999FORM-pw')
                fpn.save()


        # update payments, not required.
        for x in Receive.objects.filter(occurrence=occurrence):

            pfx = 'receive_form---%s' % x.id # hardcore Jquery 
            form_receive = ReceiveFormUpdate(request.POST, instance=x, prefix=pfx)

            receive_list.append(form_receive)

            if form_receive.is_valid():
                fp = form_receive.save()


        # occurrence
        form = form_class(request.POST, instance = occurrence_confirmation, initial={ 'device':initial_device, })

        if form.is_valid():

            data = form.save(commit=False)
            data.occurrence = occurrence

            if int(data.presence) not in (1,2): # client not arrive, dont save datetime field
                data.date_started = None
                data.date_finished = None

            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()

            messages.success(request, _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)

        else:

            form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility=2, lendable=True) | Q(place =  occurrence.room.place, mobility=2, lendable=False))]

            messages.error(request, _(u'Campo inválido ou obrigatório'))

    else:
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1,2): # load initial data if client dont arrive
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence':occurrence, 
            'start_time':occurrence.start_time, 
            'end_time':occurrence.end_time,
            'device': initial_device,
            })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]

        # payments of occurrence, update form.
        for x in Receive.objects.filter(occurrence=occurrence):
            pfx = 'receive_form---%s' % x.id # for many forms and one submit.
            receive_list.append( ReceiveFormUpdate(instance=x, prefix=pfx) )


    # just one out if errors
    return render_to_response(
        template,
        dict(
                occurrence=occurrence,
                form=form,
                object=object,
                referral=occurrence.event.referral,
                occurrence_confirmation=occurrence_confirmation,
                hide_date_field=True if occurrence_confirmation and int(occurrence_confirmation.presence) > 2 else None,
                denied_to_write = denied_to_write,
                receive_list = receive_list,
                covenant_list = covenant_list,
                receive_new_form = ReceiveFormNew(prefix='receive_form---TEMPID999FORM'),
            ),
        context_instance=RequestContext(request)
    )
Example #24
0
def occurrence_confirmation_form(
        request, 
        pk, 
        template='schedule/schedule_occurrence_confirmation_form.html',
        form_class=OccurrenceConfirmationForm,
        client_id = None,
        redirect_to = None,
    ):

    occurrence = get_object_or_404(ScheduleOccurrence, pk=pk, event__referral__service__organization=request.user.get_profile().org_active)
    payment_list = []
    
    if not occurrence.scheduleoccurrence.was_confirmed():
        initial_device = [device.pk for device in occurrence.device.all()]
    else:
        initial_device = [device.pk for device in occurrence.occurrenceconfirmation.device.all()]
        
    # check if requested user have perms to read it
    if not _access_check_by_occurrence(request, occurrence):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    try:
        occurrence_confirmation = OccurrenceConfirmation.objects.get(pk = occurrence.occurrenceconfirmation.id)
    except:
        occurrence_confirmation = None
    
    object = get_object_or_None(Client, pk = client_id, person__organization=request.user.get_profile().org_active)

    from gestorpsi.client.views import _access_check_referral_write
    denied_to_write = None

    if not _access_check_referral_write(request, occurrence.event.referral):
        denied_to_write = True

    if request.method == 'POST':

        if denied_to_write:
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        form = form_class(request.POST, instance = occurrence_confirmation, initial={ 'device':initial_device, })

        # payment
        payment_valid = True

        for x in Payment.objects.filter(occurrence=occurrence):

            pfx = 'payment_form-%s' % x.id # hardcore Jquery 
            form_payment = PaymentForm(request.POST, instance=x, prefix=pfx)

            payment_list.append(form_payment)

            if form_payment.is_valid():
                fp = form_payment.save()
            else:
                payment_valid = False

        if form.is_valid() and payment_valid :

            data = form.save(commit=False)
            data.occurrence = occurrence

            if int(data.presence) not in (1,2): # client not arrive, dont save datetime field
                data.date_started = None
                data.date_finished = None

            data.save()
            form.save_m2m()

            # save occurrence comment
            occurrence.annotation = request.POST['occurrence_annotation']
            occurrence.save()

            messages.success(request, _('Occurrence confirmation updated successfully'))
            return http.HttpResponseRedirect(redirect_to or request.path)

        else:

            form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility=2, lendable=True) | Q(place =  occurrence.room.place, mobility=2, lendable=False))]

            messages.error(request, _(u'Campo inválido ou obrigatório'))

            return render_to_response(
                template,
                dict(occurrence=occurrence,
                    form=form,
                    object=object,
                    referral=occurrence.event.referral,
                    payment_list=payment_list,
                    ),
                context_instance=RequestContext(request)
            )
    else:
        if hasattr(occurrence_confirmation, 'presence') and int(occurrence_confirmation.presence) not in (1,2): # load initial data if client dont arrive
            occurrence_confirmation.date_started = occurrence.start_time
            occurrence_confirmation.date_finished = occurrence.end_time

        form = form_class(instance=occurrence_confirmation, initial={
            'occurrence':occurrence, 
            'start_time':occurrence.start_time, 
            'end_time':occurrence.end_time,
            'device': initial_device,
            })

        form.fields['device'].widget.choices = [(i.id, i) for i in DeviceDetails.objects.active(request.user.get_profile().org_active).filter(Q(room=occurrence.room) | Q(mobility="2", lendable=True) | Q(place=occurrence.room.place, mobility="2", lendable=False))]


        # payment form
        for x in Payment.objects.filter(occurrence=occurrence):
            pfx = 'payment_form-%s' % x.id
            payment_list.append( PaymentForm(instance=x, prefix=pfx) )


    return render_to_response(
        template,
        dict(
                occurrence=occurrence,
                form=form,
                object=object,
                referral=occurrence.event.referral,
                occurrence_confirmation=occurrence_confirmation,
                hide_date_field=True if occurrence_confirmation and int(occurrence_confirmation.presence) > 2 else None,
                denied_to_write = denied_to_write,
                payment_list = payment_list,
            ),
        context_instance=RequestContext(request)
    )