Exemplo n.º 1
0
def save(request, object_id=''):
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)

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

    object.admission_date = datetime.strptime(request.POST.get('admission_date'), '%d/%m/%Y')
    object.legacyRecord = request.POST.get('legacyRecord')
    object.comments = request.POST.get('comments')

    object.admissionreferral_set.all().delete()
    """ Referral Section """
    if request.POST.get('referral'):
        ar = AdmissionReferral()
        ar.referral_choice_id = ReferralChoice.objects.get(pk=request.POST.get('referral')).id
        ar.referral_organization = get_object_or_None(Organization, id=request.POST.get('referral_organization'))
        ar.referral_professional = get_object_or_None(CareProfessional, id=request.POST.get('referral_professional'))
        ar.signed_bythe_client = True if request.POST.get('signed') else False
        ar.client = object
        ar.save()

    object.save()

    messages.success(request, _('Admission saved successfully'))

    return HttpResponseRedirect('/client/%s/home' % object.id)
Exemplo n.º 2
0
def occupation(request, object_id, occupation_id=0):
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)

    # check access by requested user
    if not _access_check(request, object) or object.is_company():
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    occupation_object = get_object_or_None(Profession,
                                           id=occupation_id) or Profession()

    profession_form = ProfessionForm(instance=occupation_object)

    professions = [p for p in object.profession_set.all()]
    return render_to_response('demographic/demographic_occupation.html', {
        'object': object,
        'demographic_menu': True,
        'professions': professions,
        'profession_form': profession_form,
        'occupation': occupation_object,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 3
0
def contact_organization_save(request, object_id = None):
    object = get_object_or_None(Organization, pk=object_id) or Organization()

    # check if user is the owner of the register or have admistration profile
    if object.id and not have_organization_perms_save(request, object):
        return render_to_response('403.html', {'object': _("Access Denied"), }, context_instance=RequestContext(request))

    if not request.POST.get('name'):
        return HttpResponseRedirect(('/contact/form/organization/' if not object.id else ('/contact/form/organization/%s/') % object.id ))

    object.name = request.POST.get('name')
    object.short_name = slugify(object.name)
    object.organization = request.user.get_profile().org_active
    object.contact_owner = request.user.get_profile().person
    object.comment = request.POST.get('comments')

    from django.db import IntegrityError
    try:
        object.save()
    except IntegrityError:
        from django.db import connection
        connection.close()
        messages.success(request, _('This organization has already been registered'))
        return HttpResponseRedirect('/contact/form/organization/?clss=error')

    object = extra_data_save(request, object)
    
    messages.success(request, _('Organization contact saved successfully'))
    return HttpResponseRedirect('/contact/form/organization/%s/' % (object.id))
Exemplo n.º 4
0
def select_organization(request):
    """
        Select organization when user have more than one org.
        Change organization without logout of GPSI.
    """

    if not request.POST:
        return render_to_response('authentication/authentication_select_organization.html', { 'objects': request.user.profile.organization.distinct() })

    if request.POST:

        # selected org
        # check selected org, org cant be a user org list
        organization = get_object_or_None( Organization, pk=request.POST.get('organization') )

        if not organization in request.user.profile.organization.distinct():
            messages.error(request, _(u'Organização inválida e/ou não existe.'))
            return HttpResponseRedirect(reverse('authentication-select-organization'))


        # logoff and login of current org is not selected organization
        if not request.user.get_profile().org_active == organization:
            # load selected org
            request.user.get_profile().org_active = organization
            request.user.get_profile().save()

            # update roles according selected organization
            request.user.groups.clear()
            for role in request.user.get_profile().role_set.filter(organization=organization):
                request.user.groups.add(role.group)

            messages.success(request, _(u'Login para %s feito com sucesso.') % organization.name )

        return HttpResponseRedirect('/')
Exemplo n.º 5
0
def diagnosis_item_html(request, client_id, referral_id, diagnosis_id):
    client = get_object_or_404(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)

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

    referral = get_object_or_404(
        Referral,
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

    diagnosis = get_object_or_None(Diagnosis, pk=diagnosis_id) or Demand()

    if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile(
    ).org_active:
        raise Http404

    return render_to_response('ehr/ehr_diagnosis_list_item.html', {
        'i': diagnosis,
        'object': client,
        'referral': referral,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 6
0
def signature_save(request):

    user = request.user
    obj = Organization.objects.get(
        pk=user.get_profile().org_active.id)  # get org from logged user

    if request.POST:

        obj.prefered_plan = get_object_or_None(
            Plan, pk=request.POST.get('prefered_plan'))
        obj.payment_type = PaymentType.objects.get(
            pk=request.POST.get('payment_type'))
        obj.save()

        messages.success(request, _('Organization details saved successfully'))
        return HttpResponseRedirect('/organization/signature/')

    else:

        return render_to_response('organization/organization_signature.html', {
            'obj':
            obj,
            'plans':
            Plan.objects.filter(active=True,
                                visible_client=True).order_by('weight'),
            'payment_type':
            PaymentType.objects.filter(active=True,
                                       show_to_client=True).order_by('-name'),
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 7
0
def occupation(request, object_id, occupation_id=0):
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)

    # check access by requested user
    if not _access_check(request, object) or object.is_company():
        return render_to_response(
            "403.html",
            {"object": _("Oops! You don't have access for this service!")},
            context_instance=RequestContext(request),
        )

    occupation_object = get_object_or_None(Profession, id=occupation_id) or Profession()

    profession_form = ProfessionForm(instance=occupation_object)

    professions = [p for p in object.profession_set.all()]
    return render_to_response(
        "demographic/demographic_occupation.html",
        {
            "object": object,
            "demographic_menu": True,
            "professions": professions,
            "profession_form": profession_form,
            "occupation": occupation_object,
        },
        context_instance=RequestContext(request),
    )
Exemplo n.º 8
0
def professional_responsible_save(request, object, ids, names, subscriptions,
                                  organization_subscriptions, professions):

    ProfessionalResponsible.objects.filter(organization=object).delete()

    # required
    if range(len(names)) > 0:
        for x in range(len(names)):
            obj = []

            # Whitout Profession of the Professional
            if not professions[x]:
                if names[x]:
                    obj = (ProfessionalResponsible(
                        name=names[x],
                        subscription=subscriptions[x],
                        organization=object,
                        organization_subscription=organization_subscriptions[x]
                    ))
            else:
                # Whit Profession of the Professional
                if names[x]:
                    obj = (ProfessionalResponsible(
                        name=names[x],
                        subscription=subscriptions[x],
                        organization=object,
                        organization_subscription=organization_subscriptions[
                            x],
                        profession=get_object_or_None(Profession,
                                                      pk=professions[x])))

            if (len(names[x]) != 0 or len(subscriptions[x]) != 0):
                obj.save()
Exemplo n.º 9
0
def contact_organization_save(request, object_id=None):
    object = get_object_or_None(Organization, pk=object_id) or Organization()

    # check if user is the owner of the register or have admistration profile
    if object.id and not have_organization_perms_save(request, object):
        return render_to_response('403.html', {
            'object': _("Access Denied"),
        },
                                  context_instance=RequestContext(request))

    if not request.POST.get('name'):
        return HttpResponseRedirect(
            ('/contact/form/organization/' if not object.id else
             ('/contact/form/organization/%s/') % object.id))

    object.name = request.POST.get('name')
    object.short_name = slugify(object.name)
    object.organization = request.user.get_profile().org_active
    object.contact_owner = request.user.get_profile().person
    object.comment = request.POST.get('comments')

    from django.db import IntegrityError
    try:
        object.save()
    except IntegrityError:
        from django.db import connection
        connection.close()
        messages.success(request,
                         _('This organization has already been registered'))
        return HttpResponseRedirect('/contact/form/organization/')

    object = extra_data_save(request, object)

    messages.success(request, _('Organization contact saved successfully'))
    return HttpResponseRedirect('/contact/form/organization/%s/' % (object.id))
Exemplo n.º 10
0
def occupation_save(request, object_id, occupation_id=0):
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)
    # check access by requested user
    if not _access_check(request, object) or object.is_company():
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    occupation_object = get_object_or_None(Profession, id=occupation_id) or Profession()
    profession_form = ProfessionForm(request.POST, instance=occupation_object)

    ocup = request.POST.get('ocup_class').replace('-','')

    # occupation found
    try:
        profession = profession_form.save(commit=False)
        profession.profession = Occupation.objects.get(cbo_code=ocup)
        profession.client = object
        profession.save()
        messages.success(request, _('Occupation saved successfully'))
        professions = [p for p in object.profession_set.all()]
        return render_to_response('demographic/demographic_occupation.html', {
                                        'object': object,
                                        'demographic_menu': True,
                                        'professions': professions,
                                        'profession_form': profession_form,
                                        }, context_instance=RequestContext(request))
    # occupation not found
    except:
        messages.error(request, _('Occupation not found'))
        professions = [p for p in object.profession_set.all()]
        return render_to_response('demographic/demographic_occupation.html', {
                                        'object': object,
                                        'demographic_menu': True,
                                        'professions': professions,
                                        'profession_form': profession_form,
                                        }, context_instance=RequestContext(request))
Exemplo n.º 11
0
def select_organization(request):
    """
        Select organization when user have more than one org.
        Change organization without logout of GPSI.
    """

    if not request.POST:
        return render_to_response('authentication/authentication_select_organization.html', { 'objects': request.user.profile.organization.distinct() })

    if request.POST:

        # selected org
        # check selected org, org cant be a user org list
        organization = get_object_or_None( Organization, pk=request.POST.get('organization') )

        if not organization in request.user.profile.organization.distinct():
            messages.error(request, _(u'Organização inválida e/ou não existe.'))
            return HttpResponseRedirect(reverse('authentication-select-organization'))


        # logoff and login of current org is not selected organization
        if not request.user.get_profile().org_active == organization:
            # load selected org
            request.user.get_profile().org_active = organization
            request.user.get_profile().save()

            # update roles according selected organization
            request.user.groups.clear()
            for role in request.user.get_profile().role_set.filter(organization=organization):
                request.user.groups.add(role.group)

            messages.success(request, _(u'Login para %s feito com sucesso.') % organization.name )

        return HttpResponseRedirect('/')
Exemplo n.º 12
0
def form(request, object_id=None):

    object = get_object_or_404(Service, pk=object_id, organization=request.user.get_profile().org_active) if object_id else Service()
    selected_area = get_object_or_None(Area, area_code=request.POST.get('area')) or object.area

    if selected_area.area_code in GENERIC_AREA:
        form_area = GenericAreaForm(instance=object)
        form_area.fields['age_group'].queryset = selected_area.age_group.all()

    if selected_area.area_code in ('school', 'psychoedu'):
        form_area = SchoolAreaForm(instance=object)
        form_area.fields['education_level'].queryset = selected_area.education_level.all()

    if selected_area.area_code == 'organizational':
        form_area = OrganizationalAreaForm(instance=object)
        form_area.fields['hierarchical_level'].queryset = selected_area.hierarchical_level.all()

    # filter covenants for group or invidual
    if object.is_group:
        covenant_list = Covenant.objects.filter( charge=1, active=True, organization=request.user.get_profile().org_active )
    else:
        covenant_list = Covenant.objects.filter( active=True, organization=request.user.get_profile().org_active )

    form_area.fields['service_type'].queryset = selected_area.service_type.all()
    form_area.fields['modalities'].queryset = selected_area.modalities.all()

    # select a next color when new register
    if not object.pk:
        object.color = color_rand()
        #if not request.user.get_profile().org_active.service_set.all():
            #object.css_color_class = 1
        #else:
            #if not object.css_color_class:
                #object.css_color_class = (int(Service.objects.filter(organization=request.user.get_profile().org_active).latest('date').css_color_class) + 1) \
                                    #if int(Service.objects.filter(organization=request.user.get_profile().org_active).latest('date').css_color_class) <=24 \
                                    #else 1

    return render_to_response('service/service_form.html', {
        'object': object,
        'CareProfessionals': CareProfessional.objects.active(request.user.get_profile().org_active),
        'Students': CareProfessional.objects.students_active(request.user.get_profile().org_active),
        'AgeGroups': AgeGroup.objects.all(),
        'Areas': Area.objects.all(),
        'ServiceTypes': ServiceType.objects.all(),
        'Modalitys': Modality.objects.all(),
        'Professions': Profession.objects.all(),
        'area': selected_area,
        'form_area': form_area,
        'clss':request.GET.get('clss'),
        'client_list': _service_clients(request, object),
        'queue_list': _queue_list(request,object),
        'can_list_groups': False if not len(_group_list(request, object)) else True,
        'can_write_group': False if not _can_write_group(request, object) else True,
        'covenant_list': covenant_list,
        }, context_instance=RequestContext(request) )
Exemplo n.º 13
0
def save(request):

    user = request.user

    try:
        object = Organization.objects.get(pk= user.get_profile().org_active.id)
    except:
        object = Organization()
        object.short_name = slugify(request.POST['name'])
    
    if (object.short_name != request.POST['short_name']):
        if (Organization.objects.filter(short_name__iexact = request.POST['short_name']).count()):
            return HttpResponse("false")
        else:
            object.short_name = request.POST['short_name']
    
    #identity
    object.name = request.POST['name']
    object.trade_name = request.POST['trade_name']
    object.register_number = request.POST['register_number']
    object.cnes = request.POST['cnes']
    object.state_inscription = request.POST.get('state_inscription')
    object.city_inscription = request.POST['city_inscription']
    object.photo = request.POST['photo']
    object.visible = get_visible( request, request.POST.get('visible') )
    #profile
    object.person_type = get_object_or_None(PersonType, pk=request.POST.get('person_type'))
    object.unit_type = get_object_or_None(UnitType, pk=request.POST.get('unit_type'))
    object.environment = get_object_or_None(AdministrationEnvironment, pk=request.POST.get('environment'))
    object.management = get_object_or_None(Management, pk=request.POST.get('management'))
    object.source = get_object_or_None(Source, pk=request.POST.get('source'))
    object.dependence = get_object_or_None(Dependence, pk=request.POST.get('dependence'))
    object.activity = get_object_or_None(Activitie, pk=request.POST.get('activity'))
    """ provided types """
    object.provided_type.clear()

    for p in request.POST.getlist('provided_type'):
        object.provided_type.add(ProvidedType.objects.get(pk=p))

    object.comment = request.POST['comment']
    object.save()
   
    professional_responsible_save(request, object, request.POST.getlist('professionalId'), request.POST.getlist('professional_name'), request.POST.getlist('professional_subscription'), request.POST.getlist('professional_organization_subscription'), request.POST.getlist('service_profession'))

    phone_save(object, request.POST.getlist('phoneId'), request.POST.getlist('area'), request.POST.getlist('phoneNumber'), request.POST.getlist('ext'), request.POST.getlist('phoneType'))
    email_save(object, request.POST.getlist('email_id'), request.POST.getlist('email_email'), request.POST.getlist('email_type'))
    site_save(object, request.POST.getlist('site_id'), request.POST.getlist('site_description'), request.POST.getlist('site_site'))
    im_save(object, request.POST.getlist('im_id'), request.POST.getlist('im_identity'), request.POST.getlist('im_network'))
    address_save(object, request.POST.getlist('addressId'), request.POST.getlist('addressPrefix'),
    request.POST.getlist('addressLine1'), request.POST.getlist('addressLine2'),
    request.POST.getlist('addressNumber'), request.POST.getlist('neighborhood'),
    request.POST.getlist('zipCode'), request.POST.getlist('addressType'),
    request.POST.getlist('city'), request.POST.getlist('foreignCountry'),
    request.POST.getlist('foreignState'), request.POST.getlist('foreignCity'))

    messages.success(request, _('Organization details saved successfully'))
    return HttpResponseRedirect('/organization/')
Exemplo n.º 14
0
def save(request, object_id=''):
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)

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

    object.admission_date = datetime.strptime(
        request.POST.get('admission_date'), '%d/%m/%Y')
    object.legacyRecord = request.POST.get('legacyRecord')
    object.comments = request.POST.get('comments')

    object.admissionreferral_set.all().delete()
    """ Referral Section """
    if request.POST.get('referral'):
        ar = AdmissionReferral()
        ar.referral_choice_id = ReferralChoice.objects.get(
            pk=request.POST.get('referral')).id
        ar.referral_organization = get_object_or_None(
            Organization, id=request.POST.get('referral_organization'))
        ar.referral_professional = get_object_or_None(
            CareProfessional, id=request.POST.get('referral_professional'))
        ar.signed_bythe_client = True if request.POST.get('signed') else False
        ar.client = object
        ar.save()

    object.save()

    messages.success(request, _('Admission saved successfully'))

    return HttpResponseRedirect('/client/%s/home' % object.id)
Exemplo n.º 15
0
def occupation_save(request, object_id, occupation_id=0):
    object = get_object_or_404(
        Client,
        pk=object_id,
        person__organization=request.user.get_profile().org_active)
    # check access by requested user
    if not _access_check(request, object) or object.is_company():
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    occupation_object = get_object_or_None(Profession,
                                           id=occupation_id) or Profession()
    profession_form = ProfessionForm(request.POST, instance=occupation_object)

    ocup = request.POST.get('ocup_class').replace('-', '')

    # occupation found
    try:
        profession = profession_form.save(commit=False)
        profession.profession = Occupation.objects.get(cbo_code=ocup)
        profession.client = object
        profession.save()

        profession_form.instance = None

        messages.success(request, _('Occupation saved successfully'))
        professions = [p for p in object.profession_set.all()]
        return render_to_response('demographic/demographic_occupation.html', {
            'object': object,
            'demographic_menu': True,
            'professions': professions,
            'profession_form': profession_form,
        },
                                  context_instance=RequestContext(request))
    # occupation not found
    except:
        messages.success(request, _('Occupation not found'))
        professions = [p for p in object.profession_set.all()]
        return render_to_response('demographic/demographic_occupation.html', {
            'object': object,
            'demographic_menu': True,
            'professions': professions,
            'profession_form': profession_form,
            'clss': 'error',
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 16
0
def group_form(request, object_id=None, group_id=None):
    object = get_object_or_404(
        Service, pk=object_id, organization=request.user.get_profile().org_active)

    if not object.is_group:
        return render_to_response('403.html', {'object': _('Sorry, this service was configured without group support.')})

    if not object.active:
        return render_to_response('403.html', {'object': _('Sorry, this you can not add groups in disabled services.')})

    group = get_object_or_None(
        ServiceGroup, pk=group_id, service__organization=request.user.get_profile().org_active)

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

        form = ServiceGroupForm(
            request.POST, instance=group) if group else ServiceGroupForm(request.POST)
        if form.is_valid():
            group = form.save(commit=False)
            group.service = object
            group.save()
            messages.success(request, _('Group saved successfully'))
            return HttpResponseRedirect('/service/%s/group/%s/form/' % (object.id, group.id))

    else:
        if not group:  # adding new. only if have write permission on this service
            if not _can_write_group(request, object):
                return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        else:  # opening existing group
            if not _can_view_group(request, group):
                return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

        form = ServiceGroupForm(
            instance=group) if group else ServiceGroupForm()

    return render_to_response('service/service_group_form.html',
                              {'object': object,
                               'form': form,
                               'group': group,
                               'queue_list': _queue_list(request, object),
                               'client_list': _service_clients(request, object),
                               'hide_service_actions': True,
                               'have_write_perms': False if not _can_write_group(request, object) else True,
                               },
                              context_instance=RequestContext(request)
                              )
Exemplo n.º 17
0
def occupation_save(request, object_id, occupation_id=0):
    object = get_object_or_404(Client, pk=object_id, person__organization=request.user.get_profile().org_active)
    # check access by requested user
    if not _access_check(request, object) or object.is_company():
        return render_to_response(
            "403.html",
            {"object": _("Oops! You don't have access for this service!")},
            context_instance=RequestContext(request),
        )

    occupation_object = get_object_or_None(Profession, id=occupation_id) or Profession()
    profession_form = ProfessionForm(request.POST, instance=occupation_object)

    ocup = request.POST.get("ocup_class").replace("-", "")

    # occupation found
    try:
        profession = profession_form.save(commit=False)
        profession.profession = Occupation.objects.get(cbo_code=ocup)
        profession.client = object
        profession.save()
        messages.success(request, _("Occupation saved successfully"))
        professions = [p for p in object.profession_set.all()]
        return render_to_response(
            "demographic/demographic_occupation.html",
            {
                "object": object,
                "demographic_menu": True,
                "professions": professions,
                "profession_form": profession_form,
            },
            context_instance=RequestContext(request),
        )
    # occupation not found
    except:
        messages.success(request, _("Occupation not found"))
        professions = [p for p in object.profession_set.all()]
        return render_to_response(
            "demographic/demographic_occupation.html",
            {
                "object": object,
                "demographic_menu": True,
                "professions": professions,
                "profession_form": profession_form,
                "clss": "error",
            },
            context_instance=RequestContext(request),
        )
Exemplo n.º 18
0
def contact_professional_form(request, object_id=None):
    object = get_object_or_None(CareProfessional,
                                pk=object_id) or CareProfessional()
    organizations = Organization.objects.filter(
        organization=request.user.get_profile().org_active, visible=True)
    if object.active:
        organizations = organizations.filter(active=True)

    if object.id:  # register already exists. let's check access permissions
        if not False in [
                o.is_local() for o in object.person.organization.all()
        ]:  # POSSIBLE local contact, only visible for users from the same organization
            if request.user.get_profile().org_active not in [
                    i.organization for i in object.person.organization.all()
            ]:
                raise Http404
        else:  # POSSIBLE real organization. access allowed only if it has been set to Visible
            if False in [o.visible for o in object.person.organization.all()]:
                raise Http404

        # check if user will have permission to save it, and pass it to template
        if not have_careprofessional_perms_save(request, object):
            hide_save_buttom = True

    if object_id:
        phones = object.person.phones.all()
        addresses = object.person.address.all()
        emails = object.person.emails.all()
        websites = object.person.sites.all()
        ims = object.person.instantMessengers.all()

    countries = Country.objects.all()
    States = State.objects.all()
    AddressTypes = AddressType.objects.all()
    PhoneTypes = PhoneType.objects.all()
    EmailTypes = EmailType.objects.all()
    IMNetworks = IMNetwork.objects.all()
    professions = Profession.objects.all()

    try:
        Cities = City.objects.filter(state=request.user.get_profile().
                                     org_active.address.all()[0].city.state)
    except:
        Cities = {}

    return render_to_response('contact/contact_professional_form.html',
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 19
0
def contact_professional_form(request, object_id=None):
    object = get_object_or_None(
        CareProfessional, pk=object_id) or CareProfessional()
    organizations = Organization.objects.filter(
        organization=request.user.get_profile().org_active, visible=True)
    if object.active:
        organizations = organizations.filter(active=True)

    if object.id:  # register already exists. let's check access permissions
        # POSSIBLE local contact, only visible for users from the same
        # organization
        if not False in [o.is_local() for o in object.person.organization.all()]:
            if request.user.get_profile().org_active not in [i.organization for i in object.person.organization.all()]:
                raise Http404
        else:  # POSSIBLE real organization. access allowed only if it has been set to Visible
            if False in [o.visible for o in object.person.organization.all()]:
                raise Http404

        # check if user will have permission to save it, and pass it to
        # template
        if not have_careprofessional_perms_save(request, object):
            hide_save_buttom = True

    if object_id:
        phones = object.person.phones.all()
        addresses = object.person.address.all()
        emails = object.person.emails.all()
        websites = object.person.sites.all()
        ims = object.person.instantMessengers.all()

    countries = Country.objects.all()
    States = State.objects.all()
    AddressTypes = AddressType.objects.all()
    PhoneTypes = PhoneType.objects.all()
    EmailTypes = EmailType.objects.all()
    IMNetworks = IMNetwork.objects.all()
    professions = Profession.objects.all()

    try:
        Cities = City.objects.filter(
            state=request.user.get_profile().org_active.address.all()[0].city.state)
    except:
        Cities = {}

    return render_to_response('contact/contact_professional_form.html', locals(),
                              context_instance=RequestContext(request)
                              )
Exemplo n.º 20
0
def diagnosis_item_html(request, client_id, referral_id, diagnosis_id):
    client = get_object_or_404(Client, pk=client_id, person__organization=request.user.get_profile().org_active)

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

    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)

    diagnosis = get_object_or_None(Diagnosis, pk=diagnosis_id) or Demand()

    if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile().org_active:
        raise Http404

    return render_to_response('ehr/ehr_diagnosis_list_item.html', {
                                    'i': diagnosis,
                                    'object': client,
                                    'referral': referral,
                                    }, context_instance=RequestContext(request))
Exemplo n.º 21
0
    def clients(self,  user,  date_start, date_end, view, filter, service=None):
        """
        return a list of clients from selected report and selected range
        """
        
        """ admissions range """
        #date_start,date_end = Report().set_date(organization, date_start, date_end)
        query = AdmissionReferral.objects_inrange.all(user.get_profile().org_active, date_start, date_end)

        if 'overview' in view:
            if 'individuals' in filter:
                query = query.filter(client__person__company__isnull=True)
                verbose_name = _('Admission report - Individuals')

            if 'companies' in filter:
                query = query.filter(client__person__company__isnull=False)
                verbose_name = _('Admission report - Companies')
            
            if 'total' in filter:
                verbose_name = _('Admission report - Total')

        if 'signed' in view:
            if filter == 'signed':
                query = query.filter(signed_bythe_client=True)
                verbose_name = _('Admission report - Signed by client')

            if filter == 'notsigned':
                query = query.filter(signed_bythe_client=False)
                verbose_name = _('Admission report - Not signed by client')
            
        if 'knowledge' in view:
            query = query.filter(referral_choice=filter)
            obj = get_object_or_None(AdmissionIndication, pk=filter)
            verbose_name = _('Admission report - Knowledge - %s' % (obj.description))
        json = []

        if query:
            return verbose_name,Client.objects.from_user(user, None, [i.client.id for i in query]), Client.objects.from_organization(user.get_profile().org_active, query)
        
        return verbose_name,None
Exemplo n.º 22
0
def contact_organization_form(request, object_id=None):
    object = get_object_or_None(Organization, pk=object_id) or Organization()

    if object.id:  # register already exists. let's check access permissions
        if object.is_local(
        ):  # local contact, only visible for users from the same organization
            if object.organization != request.user.get_profile().org_active:
                raise Http404
        else:  # real organization. access allowed only if it has been set to Visible
            if not object.visible:  # organization set to NOT visible
                raise Http404

        # check if user will have permission to save it, and pass it to template
        if not have_organization_perms_save(request, object):
            hide_save_buttom = True

    try:
        Cities = City.objects.filter(state=request.user.get_profile().
                                     org_active.address.all()[0].city.state)
    except:
        Cities = {}

    countries = Country.objects.all()
    States = State.objects.all()
    AddressTypes = AddressType.objects.all()
    PhoneTypes = PhoneType.objects.all()
    EmailTypes = EmailType.objects.all()
    IMNetworks = IMNetwork.objects.all()

    phones = object.phones.all()
    addresses = object.address.all()
    emails = object.emails.all()
    websites = object.sites.all()
    ims = object.instantMessengers.all()

    clss = request.GET.get('clss')

    return render_to_response('contact/contact_organization_form.html',
                              locals(),
                              context_instance=RequestContext(request))
Exemplo n.º 23
0
def contact_organization_form(request, object_id=None):
    object = get_object_or_None(Organization, pk=object_id) or Organization()

    if object.id:  # register already exists. let's check access permissions
        if object.is_local():  # local contact, only visible for users from the same organization
            if object.organization != request.user.get_profile().org_active:
                raise Http404
        else:  # real organization. access allowed only if it has been set to Visible
            if not object.visible:  # organization set to NOT visible
                raise Http404

        # check if user will have permission to save it, and pass it to
        # template
        if not have_organization_perms_save(request, object):
            hide_save_buttom = True

    try:
        Cities = City.objects.filter(
            state=request.user.get_profile().org_active.address.all()[0].city.state)
    except:
        Cities = {}

    countries = Country.objects.all()
    States = State.objects.all()
    AddressTypes = AddressType.objects.all()
    PhoneTypes = PhoneType.objects.all()
    EmailTypes = EmailType.objects.all()
    IMNetworks = IMNetwork.objects.all()

    phones = object.phones.all()
    addresses = object.address.all()
    emails = object.emails.all()
    websites = object.sites.all()
    ims = object.instantMessengers.all()

    clss = request.GET.get('clss')

    return render_to_response('contact/contact_organization_form.html', locals(),
                              context_instance=RequestContext(request)
                              )
Exemplo n.º 24
0
def signature_save(request):

    user = request.user
    obj = Organization.objects.get(pk= user.get_profile().org_active.id) # get org from logged user

    if request.POST:

        obj.prefered_plan = get_object_or_None(Plan, pk=request.POST.get('prefered_plan'))
        obj.payment_type = PaymentType.objects.get( pk=request.POST.get('payment_type') )
        obj.save()

        messages.success(request, _('Organization details saved successfully'))
        return HttpResponseRedirect('/organization/signature/')

    else:

        return render_to_response('organization/organization_signature.html', {
            'obj': obj,
            'plans': Plan.objects.filter(form=1).order_by('weight'),
            'payment_type': PaymentType.objects.filter(active=True, show_to_client=True).order_by('-name'),
            },
            context_instance=RequestContext(request))
Exemplo n.º 25
0
def save_careprof(request, object_id, save_person, is_student=False):
    """
    This view function returns the informations about CareProfessional 
    @param request: this is a request sent by the browser.
    @type request: a instance of the class C{HttpRequest} created by the framework Django
    @param object: it is the tyoe of CareProfessional that must be filled.
    @type object: an instance of the built-in type C{CareProfessional}.            
    """
    if object_id:
        object = get_object_or_404(CareProfessional, pk=object_id, person__organization=request.user.get_profile().org_active)
    else:
        object = CareProfessional()

    if save_person:
        object.person = person_save(request, get_object_or_None(Person, pk=object.person_id) or Person())
    object.save()

    #exist_referral="False"
    list_from_form = request.POST.getlist('professional_service')

    # MAKE A LIST WHIT ID SERVICE
    list_db = []
    for y in object.prof_services.filter(organization=request.user.get_profile().org_active):
        list_db.append(y.id)

    # IF LIST_FROM_FORM > 0 THEN ADDED SERVICE 
    if len(list_from_form) > 0:
        for ps_id in list_from_form:
            ps = Service.objects.get(pk=ps_id)
            object.prof_services.add(ps)

    # COMPARES THE LIST_DB AND LIST_FORM, THE RESULT WILL BE SERVICES THAT WILL BE REMOVED
    if len(list_from_form) > 0:
        for x in list_from_form:
            try:
                indice = list_db.remove(x)
            except:
                pass

    ## REMOVE SERVICE 
    #if len(list_db) > 0:
        #for o in list_db:
            #if Referral.objects.charged().filter(professional = object, service = o, status = '01').count() > 0:
                #exist_referral="True"
            #else:
                #object.prof_services.remove(o)

    profile = get_object_or_None(ProfessionalProfile, pk=object.professionalProfile_id) or ProfessionalProfile()
    profile.initialProfessionalActivities = request.POST.get('professional_initialActivitiesDate')
    profile.save()
    object.professionalProfile = profile

    if (len(request.POST.getlist('professional_workplace'))):
        for o in profile.workplace.filter(organization=request.user.get_profile().org_active):
            profile.workplace.remove(o)
        for wplace_id in request.POST.getlist('professional_workplace'):
            profile.workplace.add(Place.objects.get(pk=wplace_id))

    if not is_student:
        if (len(request.POST.getlist('professional_agreement'))):
            profile.agreement.clear()
            for agreemt_id in request.POST.getlist('professional_agreement'):
                profile.agreement.add(Agreement.objects.get(pk=agreemt_id))

        if request.POST.get('professional_registerNumber') or request.POST.get('professional_area'):
            if not object.professionalIdentification:
                identification = ProfessionalIdentification()
            else:
                identification = object.professionalIdentification

            if request.POST.get('professional_registerNumber'):
                identification.registerNumber = request.POST.get('professional_registerNumber')

            if request.POST.get('professional_area'):
                identification.profession = get_object_or_None(Profession, id=request.POST.get('professional_area'))

            identification.save()
            object.professionalIdentification = identification

    object.save()
    return object
Exemplo n.º 26
0
def add_event(
        request, 
        template='schedule/schedule_form.html',
        event_form_class=ReferralForm,
        recurrence_form_class=ScheduleOccurrenceForm,
        redirect_to = None
    ):

    # have to contains dtstart variable in URL. URL from schedule have to contains date and time informations.
    if not 'dtstart' in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.method == 'POST':
        if int(request.POST.get('count')) > 40: # limit occurrence repeat
            return render_to_response('403.html', {'object':_('Sorry. You can not book more than 40 occurrence at the same time')})

        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if not request.POST.get('group'): # booking single client

                referral = get_object_or_404(Referral, pk=request.POST.get('referral'), service__organization=request.user.get_profile().org_active)
                event = recurrence_form.save(referral)

            else: # booking a group
                group = get_object_or_404(ServiceGroup, pk=request.POST.get('group'), service__organization=request.user.get_profile().org_active, active=True)
                if group.charged_members(): # this check is already done in template. just to prevent empty groups
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                event = recurrence_form.save(group_member.referral, True) # ignore busy check


            '''
                create a payment
            '''
            # Filter payment by pack or occurrence
            for x in referral.covenant.filter(Q(charge=1) | Q(charge=2) ).distinct():

                payment = Payment() # new

                # by pack
                if x.charge == 2:
                    # check not terminated pack of same referral
                    for p in Payment.objects.filter(occurrence__event=event, covenant_charge=2):
                        if not p.terminated_():
                            # not terminated pack
                            payment = p

                # by occurrence
                # new
                if not payment.id:
                    payment.name = x.name
                    payment.price = x.price
                    payment.off = 0
                    payment.total = x.price
                    payment.covenant_charge = x.charge
                    payment.save()

                    # by pack
                    payment.covenant_pack_size = x.event_time if x.charge == 2 else 0

                    # clear all
                    payment.covenant_payment_way_options = ''
                    for pw in x.payment_way.all():
                        x = "(%s,'%s')," % ( pw.id , pw.name )
                        payment.covenant_payment_way_options += x

                # add occurrence
                payment.occurrence.add( event.occurrences().latest('id') )
                # update m2m
                payment.save()


            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html', 
                    dict(event=event),
                    context_instance=RequestContext(request)
                )
    else:

        dtstart = parser.parse( request.GET['dtstart'] )
        room = get_object_or_None(Room, pk=request.GET.get('room'), place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(Client, pk = request.GET.get('client'), person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(Referral, pk = request.GET.get('referral'), service__organization=request.user.get_profile().org_active)
        event_form = event_form_class

        recurrence_form = recurrence_form_class(initial=dict(
                dtstart=dtstart, 
                day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"), 
                until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                room=room.id,
            ))

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

    return render_to_response(
        template,
        dict(
            dtstart=dtstart, 
            event_form=event_form, 
            recurrence_form=recurrence_form, 
            group  = ServiceGroup.objects.filter(service__organization = request.user.get_profile().org_active, active=True),
            room = room,
            object = client,
            referral = referral,
            room_id=room.id,
            ),
        context_instance=RequestContext(request)
    )
Exemplo n.º 27
0
def add_event(
    request, 
    template='schedule/schedule_form.html',
    event_form_class=ReferralForm,
    recurrence_form_class=ScheduleOccurrenceForm,
    redirect_to = None
):
    dtstart = None
    if request.method == 'POST':
        if int(request.POST.get('count')) > 40: # limit occurrence repeat
            return render_to_response('403.html', {'object':_('Sorry. You can not book more than 40 occurrence at the same time')})
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if not request.POST.get('group'): # booking single client
                referral = get_object_or_404(Referral, pk=request.POST.get('referral'), service__organization=request.user.get_profile().org_active)
                event = recurrence_form.save(referral)
            else: # booking a group
                group = get_object_or_404(ServiceGroup, pk=request.POST.get('group'), service__organization=request.user.get_profile().org_active, active=True)
                if group.charged_members(): # this check is already done in template. just to prevent empty groups
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                event = recurrence_form.save(group_member.referral, True) # ignore busy check
    
            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html', 
                    dict(event=event),
                    context_instance=RequestContext(request)
                )
    else:
        if 'dtstart' in request.GET:
            try:
                dtstart = parser.parse(request.GET['dtstart'])
            except:
                # TODO A badly formatted date is passed to add_event
                dtstart = datetime.now()

        room = get_object_or_None(Room, pk=request.GET.get('room'), place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(Client, pk = request.GET.get('client'), person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(Referral, pk = request.GET.get('referral'), service__organization=request.user.get_profile().org_active)
        
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(initial=dict(
            dtstart=dtstart, 
            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"), 
            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            room=room.id,
            ))

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

    return render_to_response(
        template,
        dict(
            dtstart=dtstart, 
            event_form=event_form, 
            recurrence_form=recurrence_form, 
            group  = ServiceGroup.objects.filter(service__organization = request.user.get_profile().org_active, active=True),
            room = room,
            object = client,
            referral = referral,
            room_id=room.id,
            ),
        context_instance=RequestContext(request)
    )
Exemplo n.º 28
0
def session_form(request, client_id, referral_id, session_id=0):
    if not settings.DEBUG and not request.is_ajax(): raise Http404

    client = get_object_or_404(Client, pk=client_id, person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)

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

    session = get_object_or_None(Session, pk=session_id) or Session()

    have_perms_to_write = None
    # check if logged user can write on it
    if _ehr_can_save(request, session):
        have_perms_to_write = True

    if session.pk and session.referral.service.organization != request.user.get_profile().org_active:
        raise Http404
    
    if request.method == 'POST':
        if not _access_ehr_check_write(request, referral):
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))
        
        form = SessionForm(request.POST, instance=session, initial={'occurrence':request.POST.get('occurrence')})

        form.fields['occurrence'].queryset = referral.occurrences().filter(session=None) if session_id==0 else referral.occurrences()
        form.fields['occurrence'].widget = forms.HiddenInput()

        if not form.is_valid() or session.pk and not _ehr_can_save(request, session):
            return render_to_response('ehr/ehr_session_form.html', {
                                            'object': client,
                                            'referral': referral,
                                            'session': session,
                                            'form': form,
                                            'clss':request.GET.get('clss'),
                                            'have_perms_to_write': have_perms_to_write,
                                            }, context_instance=RequestContext(request))

        else:
            session = form.save(commit=False)
            session.client_id = client.id
            session.referral_id = referral.id
            session.occurrence_id = ScheduleOccurrence.objects.get(pk=request.POST.get('occurrence')).id

            session.edit_status = _ehr_set_edit_status(request)

            session.save()

            url = '/client/%s/%s/session/%s/item/' % (client_id, referral_id, session.pk)
            return HttpResponse(simplejson.dumps({'occurrence_pk':request.POST.get('occurrence'), 'url':url}))

    else: # GET
        if request.GET.get('o') or session.pk:
            occurrence_pk = session.occurrence if session.pk else request.GET.get('o')
            form = SessionForm(instance=session, initial={'occurrence':occurrence_pk})
        else:
            form = SessionForm(instance=session)
            
        form.fields['occurrence'].queryset = referral.occurrences().filter(session=None) if session_id==0 else referral.occurrences()
        form.fields['occurrence'].widget = forms.HiddenInput()
            
        return render_to_response('ehr/ehr_session_form.html', {
                                        'object': client,
                                        'referral': referral,
                                        'session': session,
                                        'form': form,
                                        'clss':request.GET.get('clss'),
                                        'have_perms_to_write': have_perms_to_write,
                                        }, context_instance=RequestContext(request))
Exemplo n.º 29
0
def save_careprof(request, object_id, save_person, is_student=False):
    """
    This view function returns the informations about CareProfessional 
    @param request: this is a request sent by the browser.
    @type request: a instance of the class C{HttpRequest} created by the framework Django
    @param object: it is the tyoe of CareProfessional that must be filled.
    @type object: an instance of the built-in type C{CareProfessional}.            
    """

    if object_id:
        object = get_object_or_404(CareProfessional, pk=object_id, person__organization=request.user.get_profile().org_active)
    else:
        object = CareProfessional()

    if save_person:
        object.person = person_save(request, get_object_or_None(Person, pk=object.person_id) or Person())

    object.save()

    '''
        remove service before add
        check if service have referral before remove.
        cannot be removed if have referral.
    '''
    # all service that are in list_service cannot be removed because it have referral. Create a error message for service and show to user.
    list_to_remove = []

    # remove service, compare from form and db.
    for x in object.prof_services.all(): # professional
        if not x.id in request.POST.getlist('professional_service'):
            # check referral
            if Referral.objects.charged().filter( professional=object, service=x, status='01'):
                list_to_remove.append(x) # add to msg
            else:
                object.prof_services.remove(x) # remove from professional

    # add new service to professional
    for x in request.POST.getlist('professional_service'):
        object.prof_services.add(x) # no problem to replace


    profile = get_object_or_None(ProfessionalProfile, pk=object.professionalProfile_id) or ProfessionalProfile()
    profile.initialProfessionalActivities = request.POST.get('professional_initialActivitiesDate')
    profile.save()
    object.professionalProfile = profile

    # remove all workplace
    profile.workplace.clear()
    # update workplace
    for x in request.POST.getlist('professional_workplace'):
        profile.workplace.add( Place.objects.get( pk=x, organization=request.user.get_profile().org_active ) )

    if not is_student:

        if request.POST.get('professional_registerNumber') or request.POST.get('professional_area'):
            if not object.professionalIdentification:
                identification = ProfessionalIdentification()
            else:
                identification = object.professionalIdentification

            if request.POST.get('professional_registerNumber'):
                identification.registerNumber = request.POST.get('professional_registerNumber')

            if request.POST.get('professional_area'):
                identification.profession = get_object_or_None(Profession, id=request.POST.get('professional_area'))

            identification.save()
            object.professionalIdentification = identification

    object.save()
    return object, list_to_remove
Exemplo n.º 30
0
def save_careprof(request, object_id, save_person, is_student=False):
    """
    This view function returns the informations about CareProfessional 
    @param request: this is a request sent by the browser.
    @type request: a instance of the class C{HttpRequest} created by the framework Django
    @param object: it is the tyoe of CareProfessional that must be filled.
    @type object: an instance of the built-in type C{CareProfessional}.            
    """

    if object_id:
        object = get_object_or_404(
            CareProfessional,
            pk=object_id,
            person__organization=request.user.get_profile().org_active)
    else:
        object = CareProfessional()

    if save_person:
        object.person = person_save(
            request,
            get_object_or_None(Person, pk=object.person_id) or Person())

    object.save()
    '''
        remove service before add
        check if service have referral before remove.
        cannot be removed if have referral.
    '''
    # all service that are in list_service cannot be removed because it have referral. Create a error message for service and show to user.
    list_to_remove = []

    # remove service, compare from form and db.
    for x in object.prof_services.all():  # professional
        if not x.id in request.POST.getlist('professional_service'):
            # check referral
            if Referral.objects.charged().filter(professional=object,
                                                 service=x,
                                                 status='01'):
                list_to_remove.append(x)  # add to msg
            else:
                object.prof_services.remove(x)  # remove from professional

    # add new service to professional
    for x in request.POST.getlist('professional_service'):
        object.prof_services.add(x)  # no problem to replace

    profile = get_object_or_None(
        ProfessionalProfile,
        pk=object.professionalProfile_id) or ProfessionalProfile()
    profile.initialProfessionalActivities = request.POST.get(
        'professional_initialActivitiesDate')
    profile.save()
    object.professionalProfile = profile

    # remove all workplace
    profile.workplace.clear()
    # update workplace
    for x in request.POST.getlist('professional_workplace'):
        profile.workplace.add(
            Place.objects.get(
                pk=x, organization=request.user.get_profile().org_active))

    if not is_student:

        if request.POST.get('professional_registerNumber') or request.POST.get(
                'professional_area'):
            if not object.professionalIdentification:
                identification = ProfessionalIdentification()
            else:
                identification = object.professionalIdentification

            if request.POST.get('professional_registerNumber'):
                identification.registerNumber = request.POST.get(
                    'professional_registerNumber')

            if request.POST.get('professional_area'):
                identification.profession = get_object_or_None(
                    Profession, id=request.POST.get('professional_area'))

            identification.save()
            object.professionalIdentification = identification

    object.save()
    return object, list_to_remove
Exemplo n.º 31
0
def add_event(
    request,
    template="schedule/schedule_form.html",
    event_form_class=ReferralForm,
    recurrence_form_class=ScheduleOccurrenceForm,
    redirect_to=None,
):

    # have to contains dtstart variable in URL. URL from schedule have to contains date and time informations.
    if not "dtstart" in request.GET:
        return http.HttpResponseRedirect("/schedule/")

    if request.method == "POST":
        if int(request.POST.get("count")) > 40:  # limit occurrence repeat
            return render_to_response(
                "403.html", {"object": _("Sorry. You can not book more than 40 occurrence at the same time")}
            )
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if not request.POST.get("group"):  # booking single client
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get("referral"),
                    service__organization=request.user.get_profile().org_active,
                )
                event = recurrence_form.save(referral)
            else:  # booking a group
                group = get_object_or_404(
                    ServiceGroup,
                    pk=request.POST.get("group"),
                    service__organization=request.user.get_profile().org_active,
                    active=True,
                )
                if group.charged_members():  # this check is already done in template. just to prevent empty groups
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                event = recurrence_form.save(group_member.referral, True)  # ignore busy check

            if not event.errors:
                messages.success(request, _("Schedule saved successfully"))
                return http.HttpResponseRedirect(redirect_to or "/schedule/")
            else:
                return render_to_response(
                    "schedule/event_detail.html", dict(event=event), context_instance=RequestContext(request)
                )
    else:

        dtstart = parser.parse(request.GET["dtstart"])
        room = get_object_or_None(
            Room, pk=request.GET.get("room"), place__organization=request.user.get_profile().org_active
        )
        client = get_object_or_None(
            Client, pk=request.GET.get("client"), person__organization=request.user.get_profile().org_active
        )
        referral = get_object_or_None(
            Referral, pk=request.GET.get("referral"), service__organization=request.user.get_profile().org_active
        )
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(
            initial=dict(
                dtstart=dtstart,
                day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                room=room.id,
            )
        )

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

    return render_to_response(
        template,
        dict(
            dtstart=dtstart,
            event_form=event_form,
            recurrence_form=recurrence_form,
            group=ServiceGroup.objects.filter(service__organization=request.user.get_profile().org_active, active=True),
            room=room,
            object=client,
            referral=referral,
            room_id=room.id,
        ),
        context_instance=RequestContext(request),
    )
Exemplo n.º 32
0
def professional_responsible_save(request, object, ids, names, subscriptions, organization_subscriptions, professions):

    ProfessionalResponsible.objects.filter(organization=object).delete()

    # required
    if range(len(names)) > 0 :
        for x in range(len(names)):
            obj = []

            # Whitout Profession of the Professional
            if not professions[x]:
                if names[x]:
                    obj = (ProfessionalResponsible(name=names[x], subscription=subscriptions[x], organization=object, organization_subscription=organization_subscriptions[x] ))
            else:
                # Whit Profession of the Professional
                if names[x]:
                    obj = (ProfessionalResponsible(name=names[x], subscription=subscriptions[x], organization=object, organization_subscription=organization_subscriptions[x], profession=get_object_or_None(Profession, pk=professions[x])))

            if ( len(names[x]) != 0 or len(subscriptions[x]) !=0 ):
                obj.save()
Exemplo n.º 33
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)
    )
Exemplo n.º 34
0
def group_form(request, object_id=None, group_id=None):
    object = get_object_or_404(
        Service,
        pk=object_id,
        organization=request.user.get_profile().org_active)

    if not object.is_group:
        return render_to_response(
            '403.html', {
                'object':
                _('Sorry, this service was configured without group support.')
            })

    if not object.active:
        return render_to_response(
            '403.html', {
                'object':
                _('Sorry, this you can not add groups in disabled services.')
            })

    group = get_object_or_None(
        ServiceGroup,
        pk=group_id,
        service__organization=request.user.get_profile().org_active)

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

        form = ServiceGroupForm(request.POST,
                                instance=group) if group else ServiceGroupForm(
                                    request.POST)
        if form.is_valid():
            group = form.save(commit=False)
            group.service = object
            group.save()
            messages.success(request, _('Group saved successfully'))
            return HttpResponseRedirect('/service/%s/group/%s/form/' %
                                        (object.id, group.id))

    else:
        if not group:  # adding new. only if have write permission on this service
            if not _can_write_group(request, object):
                return render_to_response(
                    '403.html', {
                        'object':
                        _("Oops! You don't have access for this service!"),
                    },
                    context_instance=RequestContext(request))

        else:  # opening existing group
            if not _can_view_group(request, group):
                return render_to_response(
                    '403.html', {
                        'object':
                        _("Oops! You don't have access for this service!"),
                    },
                    context_instance=RequestContext(request))

        form = ServiceGroupForm(
            instance=group) if group else ServiceGroupForm()

    return render_to_response('service/service_group_form.html', {
        'object':
        object,
        'form':
        form,
        'group':
        group,
        'queue_list':
        _queue_list(request, object),
        'client_list':
        _service_clients(request, object),
        'hide_service_actions':
        True,
        'have_write_perms':
        False if not _can_write_group(request, object) else True,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 35
0
def demand_form(request, client_id, referral_id, demand_id=0):
    if not settings.DEBUG and not request.is_ajax(): raise Http404

    client = get_object_or_404(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(
        Referral,
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

    # check if logged user can write it
    if not _access_ehr_check_read(request, client):
        return render_to_response(
            '403.html', {
                'object': _("Oops! You don't have access for this service!"),
            },
            context_instance=RequestContext(request))

    demand = get_object_or_None(Demand, pk=demand_id) or Demand()

    if demand.pk and demand.referral.service.organization != request.user.get_profile(
    ).org_active:
        raise Http404

    have_perms_to_write = None
    # check if logged user can write on it, just to hide save button on template, is verified by post method also
    if _ehr_can_save(request, demand):
        have_perms_to_write = True
    """ need pass to template time unit forms """
    howlong_form = TimeUnitForm(instance=demand.how_long_it_happens,
                                prefix="howlong")
    frequency_form = TimeUnitForm(instance=demand.frequency,
                                  prefix="frequency")
    duration_form = TimeUnitForm(instance=demand.duration, prefix="duration")

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

        form = DemandForm(request.POST, instance=demand)
        form.fields['occurrence'].queryset = referral.occurrences()

        if not form.is_valid() or demand.pk and not _ehr_can_save(
                request, demand):
            return render_to_response(
                'ehr/ehr_demand_form.html', {
                    'object': client,
                    'referral': referral,
                    'form': form,
                    'howlong_form': howlong_form,
                    'frequency_form': frequency_form,
                    'duration_form': duration_form,
                    'have_perms_to_write': have_perms_to_write,
                },
                context_instance=RequestContext(request))
        else:
            demand = form.save(commit=False)
            demand.client_id = client.id
            demand.referral_id = referral.id
            demand.occurrence = get_object_or_None(
                ScheduleOccurrence, pk=request.POST.get(
                    'occurrence')) if request.POST.get('occurrence') else None

            demand.edit_status = _ehr_set_edit_status(request)

            if request.POST.get('howlong-unit'):
                howlong_form = TimeUnitForm(
                    request.POST,
                    instance=demand.how_long_it_happens
                    if demand.how_long_it_happens else TimeUnit(),
                    prefix="howlong")
                if not howlong_form.is_valid():
                    messages.error(
                        request,
                        _("There's an error in 'How long it happens' field."))
                    return HttpResponseRedirect(
                        '/client/%s/%s/demand/%s/' %
                        (client_id, referral_id,
                         demand.id)) if demand.id else HttpResponseRedirect(
                             '/client/%s/%s/demand/add/' %
                             (client_id, referral_id))
                demand.how_long_it_happens = howlong_form.save()
            else:
                demand.how_long_it_happens = None

            if request.POST.get('frequency-unit'):
                frequency_form = TimeUnitForm(request.POST,
                                              instance=demand.frequency if
                                              demand.frequency else TimeUnit(),
                                              prefix="frequency")
                if not frequency_form.is_valid():
                    messages.error(request,
                                   _("There's an error in 'Frequency' field."))
                    return HttpResponseRedirect(
                        '/client/%s/%s/demand/%s/' %
                        (client_id, referral_id,
                         demand.id)) if demand.id else HttpResponseRedirect(
                             '/client/%s/%s/demand/add/' %
                             (client_id, referral_id))
                demand.frequency = frequency_form.save()
            else:
                demand.frequency = None

            if request.POST.get('duration-unit'):
                duration_form = TimeUnitForm(request.POST,
                                             instance=demand.duration if
                                             demand.duration else TimeUnit(),
                                             prefix="duration")
                if not duration_form.is_valid():
                    messages.error(request,
                                   _("There's an error in 'Duration' field."))
                    return HttpResponseRedirect(
                        '/client/%s/%s/demand/%s/' %
                        (client_id, referral_id,
                         demand.id)) if demand.id else HttpResponseRedirect(
                             '/client/%s/%s/demand/add/' %
                             (client_id, referral_id))
                demand.duration = duration_form.save()
            else:
                demand.duration = None

            demand.save()
            return render_to_response('ehr/ehr_demand_form_done.html', {
                'demand': demand,
                'client': client,
                'referral': referral,
            },
                                      context_instance=RequestContext(request))

    else:
        form = DemandForm(instance=demand)
        form.fields['occurrence'].queryset = referral.occurrences()

        return render_to_response('ehr/ehr_demand_form.html', {
            'object': client,
            'referral': referral,
            'form': form,
            'howlong_form': howlong_form,
            'frequency_form': frequency_form,
            'duration_form': duration_form,
            'have_perms_to_write': have_perms_to_write,
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 36
0
def form(request, object_id=None):
    object = get_object_or_404(Service,
                               pk=object_id,
                               organization=request.user.get_profile().
                               org_active) if object_id else Service()
    selected_area = get_object_or_None(
        Area, area_code=request.POST.get('area')) or object.area

    if selected_area.area_code in GENERIC_AREA:
        form_area = GenericAreaForm(instance=object)
        form_area.fields['age_group'].queryset = selected_area.age_group.all()

    if selected_area.area_code in ('school', 'psychoedu'):
        form_area = SchoolAreaForm(instance=object)
        form_area.fields[
            'education_level'].queryset = selected_area.education_level.all()

    if selected_area.area_code == 'organizational':
        form_area = OrganizationalAreaForm(instance=object)
        form_area.fields[
            'hierarchical_level'].queryset = selected_area.hierarchical_level.all(
            )

    form_area.fields['service_type'].queryset = selected_area.service_type.all(
    )
    form_area.fields['modalities'].queryset = selected_area.modalities.all()

    # select a next color when new register
    if not object.pk:
        object.color = color_rand()
        #if not request.user.get_profile().org_active.service_set.all():
        #object.css_color_class = 1
        #else:
        #if not object.css_color_class:
        #object.css_color_class = (int(Service.objects.filter(organization=request.user.get_profile().org_active).latest('date').css_color_class) + 1) \
        #if int(Service.objects.filter(organization=request.user.get_profile().org_active).latest('date').css_color_class) <=24 \
        #else 1

    return render_to_response('service/service_form.html', {
        'object':
        object,
        'CareProfessionals':
        CareProfessional.objects.active(request.user.get_profile().org_active),
        'Students':
        CareProfessional.objects.students_active(
            request.user.get_profile().org_active),
        'AgeGroups':
        AgeGroup.objects.all(),
        'Areas':
        Area.objects.all(),
        'ServiceTypes':
        ServiceType.objects.all(),
        'Modalitys':
        Modality.objects.all(),
        'Professions':
        Profession.objects.all(),
        'area':
        selected_area,
        'form_area':
        form_area,
        'clss':
        request.GET.get('clss'),
        'client_list':
        _service_clients(request, object),
        'queue_list':
        _queue_list(request, object),
        'can_list_groups':
        False if not len(_group_list(request, object)) else True,
        'can_write_group':
        False if not _can_write_group(request, object) else True,
    },
                              context_instance=RequestContext(request))
Exemplo n.º 37
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),
    )
Exemplo n.º 38
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))
Exemplo n.º 39
0
def add_event(
    request,
    template='schedule/schedule_form.html',
    event_form_class=ReferralForm,
    recurrence_form_class=ScheduleOccurrenceForm,
    redirect_to=None
):

    # have to contains dtstart variable in URL. URL from schedule have to
    # contains date and time informations.
    if 'dtstart' not in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.method == 'POST':
        if int(request.POST.get('count')) > 40:  # limit occurrence repeat
            return render_to_response('403.html', {'object': _(
                'Sorry. You can not book more than 40 occurrence at the same \
time')})
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if invalid_delta_time(
                    request.POST.get('start_time_delta'),
                    request.POST.get('end_time_delta')):
                messages.error(
                    request,
                    _('The start time should be less than the end time'))
                return http.HttpResponseRedirect(
                    request.META.get('HTTP_REFERER') or '/schedule/')

            # filter devices based on selection
            devices = DeviceDetails.objects.filter(
                id__in=request.POST.getlist('device'))
            start_occurrence_date = end_occurrence_date = datetime(
                year=int(request.POST.get('until_year')),
                month=int(request.POST.get('until_month')),
                day=int(request.POST.get('until_day'))
                )
            # create a start delta time
            start_delta = timedelta(seconds=int(request.POST.get(
                'start_time_delta')))
            # checking till one minute before next session
            end_delta = timedelta(seconds=(int(request.POST.get(
                'end_time_delta')) - 1))
            # get correct start time of device schedule
            start_device_schedule = (start_occurrence_date + start_delta)

            end_device_schedule = (end_occurrence_date + end_delta)
            # try to check if there's any occurrence with the device in
            # specified time
            occurrence_start = Occurrence.objects.filter(
                start_time__range=(
                    start_device_schedule,
                    end_device_schedule),
                scheduleoccurrence__device__in=devices,
                )
            # check exact end time
            end_delta = timedelta(
                seconds=int(request.POST.get('end_time_delta')))
            end_device_schedule = (end_occurrence_date + end_delta)
            occurrence_end = Occurrence.objects.filter(
                end_time__range=(
                    start_device_schedule,
                    end_device_schedule),
                scheduleoccurrence__device__in=devices,
                )
            if len(occurrence_start) is not 0 or len(occurrence_end) is not 0:
                error = recurrence_form._errors.setdefault(
                    'device', ErrorList())
                error.append('Selected device is busy')
            if request.POST.get('tabtitle'):  # booking single client
                if verify_client(request.POST.get('referral')) is False:
                    messages.error(request, _('Check the mandatory fields'))
                    return http.HttpResponseRedirect(
                        request.META.get('HTTP_REFERER') or '/schedule/')
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get('referral'),
                    service__organization=request.user.get_profile(
                        ).org_active)
                event = recurrence_form.save(referral)
            elif request.POST.get('group'):  # booking a group
                group = get_object_or_404(
                    ServiceGroup,
                    pk=request.POST.get('group'),
                    service__organization=request.user.get_profile(
                        ).org_active,
                    active=True)
                # this check is already done in template. just to prevent
                # empty groups
                if group.charged_members():
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                # ignore busy check
                                event = recurrence_form.save(
                                    group_member.referral, True)
            else:
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get('select_referral'),
                    service__organization=request.user.get_profile(
                        ).org_active)
                event = recurrence_form.save(referral, True, True)
            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html',
                    dict(event=event),
                    context_instance=RequestContext(request)
                )
    else:

        dtstart = parser.parse(request.GET['dtstart'])
        room = get_object_or_None(
            Room,
            pk=request.GET.get('room'),
            place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(
            Client,
            pk=request.GET.get('client'),
            person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(
            Referral,
            pk=request.GET.get('referral'),
            service__organization=request.user.get_profile().org_active)
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(initial=dict(
            dtstart=dtstart,
            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            room=room.id,
        ))

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

    return render_to_response(
        template,
        dict(
            dtstart=dtstart,
            event_form=event_form,
            recurrence_form=recurrence_form,
            group=ServiceGroup.objects.filter(
                service__organization=request.user.get_profile().org_active,
                active=True),
            room=room,
            object=client,
            referral=referral,
            referrals=Referral.objects.all(),
            room_id=room.id,
            ),
        context_instance=RequestContext(request)
    )
Exemplo n.º 40
0
def session_form(request, client_id, referral_id, session_id=0):

    if not settings.DEBUG and not request.is_ajax(): raise Http404

    client = get_object_or_404(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(
        Referral,
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

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

    session = get_object_or_None(Session, pk=session_id) or Session()

    have_perms_to_write = None
    # check if logged user can write on it
    if _ehr_can_save(request, session):
        have_perms_to_write = True

    if session.pk and session.referral.service.organization != request.user.get_profile(
    ).org_active:
        raise Http404

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

        form = SessionForm(
            request.POST,
            instance=session,
            initial={'occurrence': request.POST.get('occurrence')})

        form.fields['occurrence'].queryset = referral.occurrences().filter(
            session=None) if session_id == 0 else referral.occurrences()
        form.fields['occurrence'].widget = forms.HiddenInput()

        if not form.is_valid() or session.pk and not _ehr_can_save(
                request, session):
            return render_to_response(
                'ehr/ehr_session_form.html', {
                    'object': client,
                    'referral': referral,
                    'session': session,
                    'form': form,
                    'have_perms_to_write': have_perms_to_write,
                },
                context_instance=RequestContext(request))

        else:
            session = form.save(commit=False)
            session.client_id = client.id
            session.referral_id = referral.id
            session.occurrence_id = ScheduleOccurrence.objects.get(
                pk=request.POST.get('occurrence')).id
            session.edit_status = _ehr_set_edit_status(request)
            session.save()  # true commit

            url = '/client/%s/%s/session/%s/item/' % (client_id, referral_id,
                                                      session.pk)
            return HttpResponse(
                simplejson.dumps({
                    'occurrence_pk':
                    request.POST.get('occurrence'),
                    'url':
                    url
                }))

    else:  # GET

        if request.GET.get('o') or session.pk:
            occurrence_pk = session.occurrence if session.pk else request.GET.get(
                'o')
            form = SessionForm(instance=session,
                               initial={'occurrence': occurrence_pk})
        else:
            form = SessionForm(instance=session)

        form.fields['occurrence'].queryset = referral.occurrences().filter(
            session=None) if session_id == 0 else referral.occurrences()
        form.fields['occurrence'].widget = forms.HiddenInput()

        return render_to_response('ehr/ehr_session_form.html', {
            'object': client,
            'referral': referral,
            'session': session,
            'form': form,
            'have_perms_to_write': have_perms_to_write,
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 41
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))
Exemplo n.º 42
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):
            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
Exemplo n.º 43
0
def demand_form(request, client_id, referral_id, demand_id=0):
    if not settings.DEBUG and not request.is_ajax(): raise Http404

    client = get_object_or_404(Client, pk=client_id, person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)

    # check if logged user can write it
    if not _access_ehr_check_read(request, client):
        return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))

    demand = get_object_or_None(Demand, pk=demand_id) or Demand()
    
    if demand.pk and demand.referral.service.organization != request.user.get_profile().org_active:
        raise Http404

    have_perms_to_write = None
    # check if logged user can write on it, just to hide save button on template, is verified by post method also
    if _ehr_can_save(request, demand):
        have_perms_to_write = True

    """ need pass to template time unit forms """
    howlong_form = TimeUnitForm(instance=demand.how_long_it_happens, prefix="howlong")
    frequency_form = TimeUnitForm(instance=demand.frequency, prefix="frequency")
    duration_form = TimeUnitForm(instance=demand.duration, prefix="duration")

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

        form = DemandForm(request.POST, instance=demand)
        form.fields['occurrence'].queryset = referral.occurrences()

        if not form.is_valid() or demand.pk and not _ehr_can_save(request, demand):
            return render_to_response('ehr/ehr_demand_form.html', {
                                'object': client,
                                'referral': referral,
                                'form': form,
                                'howlong_form': howlong_form,
                                'frequency_form': frequency_form,
                                'duration_form': duration_form,
                                'clss':request.GET.get('clss'),
                                'have_perms_to_write': have_perms_to_write,
                                }, context_instance=RequestContext(request))
        else:
            demand = form.save(commit=False)
            demand.client_id = client.id
            demand.referral_id = referral.id
            demand.occurrence = get_object_or_None(ScheduleOccurrence, pk=request.POST.get('occurrence')) if request.POST.get('occurrence') else None
            
            demand.edit_status = _ehr_set_edit_status(request)
            
            if request.POST.get('howlong-unit'):
                howlong_form = TimeUnitForm(request.POST, instance=demand.how_long_it_happens if demand.how_long_it_happens else TimeUnit(), prefix="howlong")
                if not howlong_form.is_valid():
                    messages.success(request, _("There's an error in 'How long it happens' field."))
                    return HttpResponseRedirect('/client/%s/%s/demand/%s/?clss=error' % (client_id, referral_id, demand.id)) if demand.id else HttpResponseRedirect('/client/%s/%s/demand/add/?clss=error' % (client_id, referral_id))
                demand.how_long_it_happens = howlong_form.save()
            else:
                demand.how_long_it_happens = None

            if request.POST.get('frequency-unit'):
                frequency_form = TimeUnitForm(request.POST, instance=demand.frequency if demand.frequency else TimeUnit(), prefix="frequency")
                if not frequency_form.is_valid():
                    messages.success(request, _("There's an error in 'Frequency' field."))
                    return HttpResponseRedirect('/client/%s/%s/demand/%s/?clss=error' % (client_id, referral_id, demand.id)) if demand.id else HttpResponseRedirect('/client/%s/%s/demand/add/?clss=error' % (client_id, referral_id))
                demand.frequency = frequency_form.save()
            else:
                demand.frequency = None

            if request.POST.get('duration-unit'):
                duration_form = TimeUnitForm(request.POST, instance=demand.duration if demand.duration else TimeUnit(), prefix="duration")
                if not duration_form.is_valid():
                    messages.success(request, _("There's an error in 'Duration' field."))
                    return HttpResponseRedirect('/client/%s/%s/demand/%s/?clss=error' % (client_id, referral_id, demand.id)) if demand.id else HttpResponseRedirect('/client/%s/%s/demand/add/?clss=error' % (client_id, referral_id))
                demand.duration = duration_form.save()
            else:
                demand.duration = None

            demand.save()
            return render_to_response('ehr/ehr_demand_form_done.html', {
                                'demand': demand,
                                'client': client,
                                'referral': referral,
                                }, context_instance=RequestContext(request))

    else:
        form = DemandForm(instance=demand)
        form.fields['occurrence'].queryset = referral.occurrences()
        
        return render_to_response('ehr/ehr_demand_form.html', {
                                        'object': client,
                                        'referral': referral,
                                        'form': form,
                                        'howlong_form': howlong_form,
                                        'frequency_form': frequency_form,
                                        'duration_form': duration_form,
                                        'clss':request.GET.get('clss'),
                                        'have_perms_to_write': have_perms_to_write,
                                        }, context_instance=RequestContext(request))
Exemplo n.º 44
0
def add_event(
        request, 
        template='schedule/schedule_form.html',
        event_form_class=ReferralForm,
        recurrence_form_class=ScheduleOccurrenceForm,
        redirect_to = None
    ):

    # have to contains dtstart variable in URL. URL from schedule have to contains date and time data.
    if not 'dtstart' in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.POST:

        # instance form
        recurrence_form = recurrence_form_class(request, request.POST)

        # no errors found, form is valid.
        if recurrence_form.is_valid():

            if not request.POST.get('group'): # booking single client

                referral = get_object_or_404(Referral, pk=request.POST.get('referral'), service__organization=request.user.get_profile().org_active)
                event = recurrence_form.save(referral)

            else: # booking a group
                group = get_object_or_404(ServiceGroup, pk=request.POST.get('group'), service__organization=request.user.get_profile().org_active, active=True)
                if group.charged_members(): # this check is already done in template. just to prevent empty groups
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                event = recurrence_form.save(group_member.referral, True) # ignore busy check

            if not request.POST.get('group'): # booking single client
                '''
                    Create a payment for each upcoming event when event by pack or occurrence
                    Event per period will be created by script run by crontab everyday
                '''
                # check if occurrences have one payment by pack or event opened
                for o in referral.upcoming_nopayment_occurrences_():

                    # exist a payment for event?
                    if Receive.objects.filter(occurrence=o).count() == 0 :

                        # Filter payment by pack or occurrence
                        for x in referral.covenant.filter(Q(charge=1) | Q(charge=2) ).distinct():

                            receive = Receive() # new

                            # by pack
                            if x.charge == 2:
                                # check not terminated pack of same referral
                                for p in Receive.objects.filter(occurrence__event=event, covenant_charge=2):
                                    if not p.terminated_():
                                        # not terminated pack
                                        receive = p

                            # by occurrence
                            # new
                            if not receive.id:
                                receive.name = x.name
                                receive.price = x.price
                                receive.off = 0
                                receive.total = x.price
                                receive.covenant_charge = x.charge
                                receive.covenant_id = x.id
                                receive.save()

                                # by pack
                                receive.covenant_pack_size = x.event_time if x.charge == 2 else 0

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

                            # add occurrence
                            receive.occurrence.add(o)
                            # update m2m
                            receive.save()


            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html', 
                    dict(event=event),
                    context_instance=RequestContext(request)
                )


    # mount form or return form errors

    # get from url
    dtstart = parser.parse( request.GET['dtstart'] )
    room = get_object_or_None(Room, pk=request.GET.get('room'), place__organization=request.user.get_profile().org_active)
    client = get_object_or_None(Client, pk=request.GET.get('client'), person__organization=request.user.get_profile().org_active)
    referral = get_object_or_None(Referral, pk=request.GET.get('referral'), service__organization=request.user.get_profile().org_active)
    event_form = event_form_class

    recurrence_form = recurrence_form_class( request,
                                             initial = dict(
                                                            dtstart=dtstart, 
                                                            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"), 
                                                            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                                                            room=room.id,
                                                        )
    )

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

    return render_to_response( template,
                               dict(
                                        dtstart = dtstart, 
                                        event_form = event_form, 
                                        recurrence_form = recurrence_form, 
                                        group = ServiceGroup.objects.filter(service__organization = request.user.get_profile().org_active, active=True),
                                        room = room,
                                        object = client,
                                        referral = referral,
                                        room_id = room.id,
                                    ),
                                context_instance=RequestContext(request)
    )
Exemplo n.º 45
0
def diagnosis_form(request, client_id, referral_id, diagnosis_id=0):
    client = get_object_or_404(Client, pk=client_id, person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(Referral, pk=referral_id, service__organization=request.user.get_profile().org_active)

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

    diagnosis = get_object_or_None(Diagnosis, pk=diagnosis_id) or Diagnosis()

    if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile().org_active:
        raise Http404

    have_perms_to_write = None
    # check if logged user can write on it, just to hide save button on template, is verified by post method also
    if _ehr_can_save(request, diagnosis):
        have_perms_to_write = True
    
    if request.method == 'POST':
        # check if logged user can write it
        if not _access_ehr_check_write(request, referral):
            return render_to_response('403.html', {'object': _("Oops! You don't have access for this service!"), }, context_instance=RequestContext(request))
        else:
            have_perms_to_write = True

        form = DiagnosisForm(request.POST, instance=diagnosis)
        
        if diagnosis.edit_status == '4':
            form._errors["demand"] = _("You cannot change a confirmed demand.")
        
        if not form.is_valid() or diagnosis.pk and not _ehr_can_save(request, diagnosis):
            return render_to_response('ehr/ehr_diagnosis_form.html', {
                                            'object': client,
                                            'referral': referral,
                                            'form': form,
                                            'have_perms_to_write': have_perms_to_write,
                                            }, context_instance=RequestContext(request))
        else:
            diagnosis = form.save(commit=False)
            diagnosis.client_id = client.id
            diagnosis.referral_id = referral.id
            diagnosis.occurrence = get_object_or_None(ScheduleOccurrence, pk=request.POST.get('occurrence')) if request.POST.get('occurrence') else None

            diagnosis.edit_status = _ehr_set_edit_status(request)

            diagnosis.save()
            return render_to_response('ehr/ehr_diagnosis_form_done.html', {
                                'diagnosis': diagnosis,
                                'client': client,
                                'referral': referral,
                                }, context_instance=RequestContext(request))
    else: # GET
        # check if logged user can write on it
        if _access_ehr_check_write(request, referral):
            have_perms_to_write = True

        diagnosis = get_object_or_None(Diagnosis, pk=diagnosis_id) or Diagnosis()

        if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile().org_active:
            raise Http404

        form = DiagnosisForm(instance=diagnosis, label_suffix='')
        if not diagnosis.diagnosis_date:
            form.initial = {'diagnosis_date': datetime.strftime(datetime.now(), "%d/%m/%Y")}
        form.fields['occurrence'].queryset = referral.occurrences()
        return render_to_response('ehr/ehr_diagnosis_form.html', {
                                        'object': client,
                                        'referral': referral,
                                        'form': form,
                                        'clss':request.GET.get('clss'),
                                        'have_perms_to_write': have_perms_to_write,
                                        }, context_instance=RequestContext(request))
Exemplo n.º 46
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)
    )
Exemplo n.º 47
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)
    )
Exemplo n.º 48
0
    def clients(self,  user,  date_start, date_end, view, filter, service=None):
        """
        return a list of clients from selected report and selected range
        """
        
        """ admissions range """
        organization = user.get_profile().org_active
        query = Referral.objects_inrange.all(organization, date_start, date_end)
        query_discharged = Referral.objects.filter(service__organization=organization, referraldischarge__date__gte=date_start, referraldischarge__date__lt=date_end)
        query_full = query
        service_pks = [s.pk for s in organization.service_set.all()]
        professional_pks = [p.pk for p in CareProfessional.objects.from_organization(organization)]
        if service:
            query = query.filter(service__pk=service)

        if view == 'overview':

            if filter == 'total':
                verbose_name = _('Referral Total')

            if filter == 'charged':
                query = query.filter()
                verbose_name = _('Referral Charged')

            if filter == 'discharged':
                query = query_discharged
                verbose_name = _('Referral Discharged')
            
            if filter == 'discharged_discussed':
                query = query_discharged.filter(referraldischarge__was_discussed_with_client=True)
                verbose_name = _('Referral Discharged Discussed')

            if filter == 'discharged_not_discussed':
                query = query.query_discharged(referraldischarge__was_discussed_with_client=False)
                verbose_name = _('Referral Discharged Not Discussed')

            if filter == 'internal':
                query = query.filter(referral__isnull=False)
                verbose_name = _('Referral Internals')

            if filter == 'external':
                query = query.filter(referralexternal__isnull=False)
                verbose_name = _('Referral Externals')
            
        if view == 'knowledge':
            query = query.filter(indication__indication_choice=filter)
            obj = get_object_or_None(ReferralIndicationChoice, pk=filter)
            verbose_name = _('Referral Knowledge - %s' % (obj.description))
            
        if view == 'services':
            query = query.filter(service=filter, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks)
            verbose_name = _(u'Referral Service - %s' % (obj))
            
        if view == 'internal':
            if not service:
                query = query.filter(service=filter, referral__isnull=False, service__pk__in=service_pks)
            else:
                query = query_full.filter(service=filter, referral__isnull=False, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks )
            verbose_name = _(u'Referral Internal to Service %s' % (obj))
            
        if view == 'internal_from':
            query = query.filter(referral__service=filter, referral__isnull=False, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks )
            verbose_name = _(u'Referral Internal from Service %s' % (obj))
            
        if view == 'external':
            query = query.filter(service=filter, referralexternal__isnull=False, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks )
            verbose_name = _(u'Referral External from Service %s' % (obj))
        
        if view == 'discharge':
            query = query_discharged.filter(service=filter, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks )
            verbose_name = _(u'Discharges from Service %s' % (obj))
        
        if view == 'discharge_reason':
            query = query_discharged.filter(referraldischarge__reason=filter)
            obj = get_object_or_None(ReferralDischargeReason, pk=filter)
            verbose_name = _(u'Discharged by reason %s' % (obj))
        
        if view == 'discharge_discussed':
            query = query_discharged.filter(service=filter, referraldischarge__was_discussed_with_client=True, service__pk__in=service_pks)
            obj = get_object_or_None(Service, pk=filter, pk__in=service_pks )
            verbose_name = _(u'Discharges discussed from Service %s' % (obj))

        if view == 'professional':
            query = query.filter(professional=filter, professional__pk__in=professional_pks)
            obj = get_object_or_None(CareProfessional, pk=filter, pk__in=professional_pks )
            verbose_name = _(u'Subscriptions to professional %s' % (obj))

        if query:
            pk_in = []
            for i in query:
                for c in i.client.all():
                    if c.id not in pk_in:
                        pk_in.append(c.id)

            return verbose_name,Client.objects.from_user(user, None, pk_in), Client.objects.from_organization(user.get_profile().org_active, query)
        
        return verbose_name,[], []
Exemplo n.º 49
0
def diagnosis_form(request, client_id, referral_id, diagnosis_id=0):
    client = get_object_or_404(
        Client,
        pk=client_id,
        person__organization=request.user.get_profile().org_active)
    referral = get_object_or_404(
        Referral,
        pk=referral_id,
        service__organization=request.user.get_profile().org_active)

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

    diagnosis = get_object_or_None(Diagnosis, pk=diagnosis_id) or Diagnosis()

    if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile(
    ).org_active:
        raise Http404

    have_perms_to_write = None
    # check if logged user can write on it, just to hide save button on template, is verified by post method also
    if _ehr_can_save(request, diagnosis):
        have_perms_to_write = True

    if request.method == 'POST':
        # check if logged user can write it
        if not _access_ehr_check_write(request, referral):
            return render_to_response('403.html', {
                'object':
                _("Oops! You don't have access for this service!"),
            },
                                      context_instance=RequestContext(request))
        else:
            have_perms_to_write = True

        form = DiagnosisForm(request.POST, instance=diagnosis)

        if diagnosis.edit_status == '4':
            form._errors["demand"] = _("You cannot change a confirmed demand.")

        if not form.is_valid() or diagnosis.pk and not _ehr_can_save(
                request, diagnosis):
            return render_to_response(
                'ehr/ehr_diagnosis_form.html', {
                    'object': client,
                    'referral': referral,
                    'form': form,
                    'have_perms_to_write': have_perms_to_write,
                },
                context_instance=RequestContext(request))
        else:
            diagnosis = form.save(commit=False)
            diagnosis.client_id = client.id
            diagnosis.referral_id = referral.id
            diagnosis.occurrence = get_object_or_None(
                ScheduleOccurrence, pk=request.POST.get(
                    'occurrence')) if request.POST.get('occurrence') else None

            diagnosis.edit_status = _ehr_set_edit_status(request)

            diagnosis.save()
            return render_to_response('ehr/ehr_diagnosis_form_done.html', {
                'diagnosis': diagnosis,
                'client': client,
                'referral': referral,
            },
                                      context_instance=RequestContext(request))
    else:  # GET
        # check if logged user can write on it
        if _access_ehr_check_write(request, referral):
            have_perms_to_write = True

        diagnosis = get_object_or_None(Diagnosis,
                                       pk=diagnosis_id) or Diagnosis()

        if diagnosis.pk and diagnosis.referral.service.organization != request.user.get_profile(
        ).org_active:
            raise Http404

        form = DiagnosisForm(instance=diagnosis, label_suffix='')
        if not diagnosis.diagnosis_date:
            form.initial = {
                'diagnosis_date': datetime.strftime(datetime.now(), "%d/%m/%Y")
            }
        form.fields['occurrence'].queryset = referral.occurrences()
        return render_to_response('ehr/ehr_diagnosis_form.html', {
            'object': client,
            'referral': referral,
            'form': form,
            'have_perms_to_write': have_perms_to_write,
        },
                                  context_instance=RequestContext(request))
Exemplo n.º 50
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)
    )
Exemplo n.º 51
0
def add_event(request,
              template='schedule/schedule_form.html',
              event_form_class=ReferralForm,
              recurrence_form_class=ScheduleOccurrenceForm,
              redirect_to=None):

    # have to contains dtstart variable in URL. URL from schedule have to
    # contains date and time informations.
    if 'dtstart' not in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    if request.method == 'POST':
        if int(request.POST.get('count')) > 40:  # limit occurrence repeat
            return render_to_response(
                '403.html', {
                    'object':
                    _('Sorry. You can not book more than 40 occurrence at the same \
time')
                })
        recurrence_form = recurrence_form_class(request.POST)

        if recurrence_form.is_valid():
            if invalid_delta_time(request.POST.get('start_time_delta'),
                                  request.POST.get('end_time_delta')):
                messages.error(
                    request,
                    _('The start time should be less than the end time'))
                return http.HttpResponseRedirect(
                    request.META.get('HTTP_REFERER') or '/schedule/')

            # filter devices based on selection
            devices = DeviceDetails.objects.filter(
                id__in=request.POST.getlist('device'))
            start_occurrence_date = end_occurrence_date = datetime(
                year=int(request.POST.get('until_year')),
                month=int(request.POST.get('until_month')),
                day=int(request.POST.get('until_day')))
            # create a start delta time
            start_delta = timedelta(
                seconds=int(request.POST.get('start_time_delta')))
            # checking till one minute before next session
            end_delta = timedelta(
                seconds=(int(request.POST.get('end_time_delta')) - 1))
            # get correct start time of device schedule
            start_device_schedule = (start_occurrence_date + start_delta)

            end_device_schedule = (end_occurrence_date + end_delta)
            # try to check if there's any occurrence with the device in
            # specified time
            occurrence_start = Occurrence.objects.filter(
                start_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            # check exact end time
            end_delta = timedelta(
                seconds=int(request.POST.get('end_time_delta')))
            end_device_schedule = (end_occurrence_date + end_delta)
            occurrence_end = Occurrence.objects.filter(
                end_time__range=(start_device_schedule, end_device_schedule),
                scheduleoccurrence__device__in=devices,
            )
            if len(occurrence_start) is not 0 or len(occurrence_end) is not 0:
                error = recurrence_form._errors.setdefault(
                    'device', ErrorList())
                error.append('Selected device is busy')
            if request.POST.get('tabtitle'):  # booking single client
                if verify_client(request.POST.get('referral')) is False:
                    messages.error(request, _('Check the mandatory fields'))
                    return http.HttpResponseRedirect(
                        request.META.get('HTTP_REFERER') or '/schedule/')
                referral = get_object_or_404(Referral,
                                             pk=request.POST.get('referral'),
                                             service__organization=request.
                                             user.get_profile().org_active)
                event = recurrence_form.save(referral)
            elif request.POST.get('group'):  # booking a group
                group = get_object_or_404(ServiceGroup,
                                          pk=request.POST.get('group'),
                                          service__organization=request.user.
                                          get_profile().org_active,
                                          active=True)
                # this check is already done in template. just to prevent
                # empty groups
                if group.charged_members():
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event.errors:
                                # ignore busy check
                                event = recurrence_form.save(
                                    group_member.referral, True)
            else:
                referral = get_object_or_404(
                    Referral,
                    pk=request.POST.get('select_referral'),
                    service__organization=request.user.get_profile(
                    ).org_active)
                event = recurrence_form.save(referral, True, True)
            if not event.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                return render_to_response(
                    'schedule/event_detail.html',
                    dict(event=event),
                    context_instance=RequestContext(request))
    else:

        dtstart = parser.parse(request.GET['dtstart'])
        room = get_object_or_None(
            Room,
            pk=request.GET.get('room'),
            place__organization=request.user.get_profile().org_active)
        client = get_object_or_None(
            Client,
            pk=request.GET.get('client'),
            person__organization=request.user.get_profile().org_active)
        referral = get_object_or_None(
            Referral,
            pk=request.GET.get('referral'),
            service__organization=request.user.get_profile().org_active)
        event_form = event_form_class()

        recurrence_form = recurrence_form_class(initial=dict(
            dtstart=dtstart,
            day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
            room=room.id,
        ))

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

    return render_to_response(
        template,
        dict(
            dtstart=dtstart,
            event_form=event_form,
            recurrence_form=recurrence_form,
            group=ServiceGroup.objects.filter(
                service__organization=request.user.get_profile().org_active,
                active=True),
            room=room,
            object=client,
            referral=referral,
            referrals=Referral.objects.all(),
            room_id=room.id,
        ),
        context_instance=RequestContext(request))
Exemplo n.º 52
0
def add_event(
        request, 
        template='schedule/schedule_form.html',
        event_form_class=ReferralForm,
        recurrence_form_class=ScheduleOccurrenceForm,
        redirect_to = None
    ):

    disable_check_busy = False
    to_confirm_conflict = False  # dont show checkbox to ignore conflict

    # have to contains dtstart variable in URL. URL from schedule have to contains date and time data.
    if not 'dtstart' in request.GET:
        return http.HttpResponseRedirect('/schedule/')

    # get from url
    dtstart = parser.parse( request.GET['dtstart'] )
    room = get_object_or_None(Room, pk=request.GET.get('room'), place__organization=request.user.get_profile().org_active)
    client = get_object_or_None(Client, pk=request.GET.get('client'), person__organization=request.user.get_profile().org_active)
    referral = get_object_or_None(Referral, pk=request.GET.get('referral'), service__organization=request.user.get_profile().org_active)
    event_form = event_form_class

    if request.POST:
        if request.POST.get('ignore_conflict') == 'on':
            disable_check_busy = True

        # instance form
        recurrence_form = recurrence_form_class(request, room.place, request.POST)

        # no errors found, form is valid.
        if recurrence_form.is_valid():
            if not request.POST.get('group'): # booking single client
                referral = get_object_or_404(Referral, pk=request.POST.get('referral'), service__organization=request.user.get_profile().org_active)
                event_form = recurrence_form.save(referral, disable_check_busy=disable_check_busy)

            else: # booking a group
                group = get_object_or_404(ServiceGroup, pk=request.POST.get('group'), service__organization=request.user.get_profile().org_active, active=True)
                if group.charged_members(): # this check is already done in template. just to prevent empty groups
                    first = True
                    for group_member in group.charged_members():
                        if first:
                            event_form = recurrence_form.save(group_member.referral)
                            first = False
                        else:
                            if not event_form.errors:
                                event_form = recurrence_form.save(group_member.referral, True) # ignore busy check

            if not request.POST.get('group'): # booking single client
                '''
                    Create a payment for each upcoming event when event by pack or occurrence
                    Event per period will be created by script run by crontab everyday
                '''
                # check if occurrences have one payment by pack or event opened
                for o in referral.upcoming_nopayment_occurrences_():

                    # exist a payment for event?
                    if Receive.objects.filter(occurrence=o).count() == 0 :

                        # Filter payment by pack or occurrence
                        for x in referral.covenant.filter(Q(charge=1) | Q(charge=2) ).distinct():
                            receive = Receive() # new

                            """
                                by pack, by event.
                                charge2 overwrite charge1
                            """
                            # by pack
                            if x.charge == 2:
                                # check not terminated pack of same referral
                                for p in Receive.objects.filter(occurrence__event=event_form, covenant_charge=2):
                                    if not p.terminated_()[0]:
                                        # not terminated pack
                                        receive = p

                            # by occurrence
                            # new
                            if not receive.id:
                                receive.name = x.name
                                receive.price = x.price
                                receive.off = 0
                                receive.total = x.price
                                receive.covenant_charge = x.charge
                                receive.covenant_id = x.id
                                receive.save()

                                # by pack
                                receive.covenant_pack_size = x.event_time if x.charge == 2 else 0

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

                            # add occurrence
                            receive.occurrence.add(o)
                            # update m2m
                            receive.save()

            if not event_form.errors:
                messages.success(request, _('Schedule saved successfully'))
                return http.HttpResponseRedirect(redirect_to or '/schedule/')
            else:
                messages.info(request, _(u'Conflito no agendamento.'))
                to_confirm_conflict = True  # show checkbox

    else:
        # mount form or return form errors
        # convert hour:minutes to second to set initial select
        interval_sec = time_delta_total_seconds( timedelta(minutes=int(request.user.get_profile().org_active.time_slot_schedule)) )
        start_sec = time_delta_total_seconds( timedelta(hours=dtstart.hour, minutes=dtstart.minute) )
        end_sec = start_sec + interval_sec

        recurrence_form = recurrence_form_class( request,
                                                 room.place, # start, end hour of place, render select in this range.
                                                 initial = dict(
                                                                dtstart=dtstart,
                                                                day=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                                                                until=datetime.strptime(dtstart.strftime("%Y-%m-%d"), "%Y-%m-%d"),
                                                                room=room.id,
                                                                start_time_delta=start_sec,
                                                                end_time_delta=end_sec,
                                                            )
        )

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

    return render_to_response(template,
                               dict(
                                        slot_time = request.user.get_profile().org_active.time_slot_schedule,
                                        dtstart = dtstart, 
                                        event_form = event_form, 
                                        recurrence_form = recurrence_form, 
                                        group = ServiceGroup.objects.filter(service__organization = request.user.get_profile().org_active, active=True),
                                        room = room,
                                        object = client,
                                        referral = referral,
                                        room_id = room.id,
                                        disable_check_busy = disable_check_busy,
                                        to_confirm_conflict = to_confirm_conflict,
                                    ),
                                context_instance=RequestContext(request)
    )