예제 #1
0
def new_poll(req):
    log.info("[new_poll] TRANSACTION START")
    if req.method == 'POST':
        log.info("[new-poll] - request recieved to create a poll")
        form = NewPollForm(req.POST, request=req)
        groups_form = GroupsFilter(req.POST, request=req)
        #         form.updateTypes() #Added to form directly already no need to add them again
        if form.is_valid() and groups_form.is_valid():
            # create our XForm
            question = form.cleaned_data['question_fr']
            default_response = form.cleaned_data['default_response_fr']
            provinces = form.cleaned_data['provinces']
            excluded_groups = groups_form.cleaned_data['group_list']
            if hasattr(Contact, 'groups'):
                groups = form.cleaned_data['groups']

            log.info("[new-poll] - finding all contacts for this poll...")
            if len(provinces):
                contacts = Contact.objects.filter(
                    reporting_location__in=provinces).filter(
                        groups__in=groups).exclude(groups__in=excluded_groups)
            else:
                if -1 in groups or '-1' in groups:
                    contacts = Contact.objects.all().exclude(
                        groups__in=excluded_groups)
                else:
                    contacts = Contact.objects.filter(
                        groups__in=groups).exclude(groups__in=excluded_groups)

            log.info("[new-poll] - found all contacts ok.")

            log.info("[new-poll] - setting up translations...")
            name = form.cleaned_data['name']
            p_type = form.cleaned_data['type']
            response_type = form.cleaned_data['response_type']
            if not form.cleaned_data['default_response_en'] == '' \
                and not form.cleaned_data['default_response_fr'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='en',
                                                      field=form.cleaned_data['default_response_fr'],
                                                      value=form.cleaned_data['default_response_en'])
            if not form.cleaned_data['default_response_ki'] == '' \
                and not form.cleaned_data['default_response_fr'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ki',
                                                      field=form.cleaned_data['default_response_fr'],
                                                      value=form.cleaned_data['default_response_ki'])

            if not form.cleaned_data['question_en'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='en',
                                                      field=form.cleaned_data['question_fr'],
                                                      value=form.cleaned_data['question_en'])

            if not form.cleaned_data['question_ki'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ki',
                                                      field=form.cleaned_data['question_fr'],
                                                      value=form.cleaned_data['question_ki'])

            log.info("[new-poll] - translations ok.")

            poll_type = (Poll.TYPE_TEXT
                         if p_type == NewPollForm.TYPE_YES_NO else p_type)

            poll = Poll.create_with_bulk(name, poll_type, question,
                                         default_response, contacts, req.user)

            if p_type == NewPollForm.TYPE_YES_NO:
                log.info("[new-poll] - is Y/N poll so adding categories...")
                poll.add_yesno_categories()
                log.info("[new-poll] - categories added ok.")

            if settings.SITE_ID:
                log.info(
                    "[new-poll] - SITE_ID is set, so adding the site to the poll"
                )
                poll.sites.add(Site.objects.get_current())
                log.info("[new-poll] - site added ok")

            log.info("[new-poll] - poll created ok.")
            log.info("[new_poll] TRANSACTION COMMIT")
            return redirect(reverse('ureport.views.view_poll', args=[poll.pk]))

    else:
        form = NewPollForm(request=req)
        groups_form = GroupsFilter(request=req)


#         form.updateTypes() #Added to form directly already no need to add them again

    log.info("[new_poll] TRANSACTION COMMIT")
    return render_to_response('ureport/new_poll.html', {
        'form': form,
        'groups_form': groups_form
    },
                              context_instance=RequestContext(req))
예제 #2
0
def new_poll(req):
    log.info("[new_poll] TRANSACTION START")
    if req.method == 'POST':
        log.info("[new-poll] - request recieved to create a poll")
        form = NewPollForm(req.POST, request=req)
        groups_form = GroupsFilter(req.POST, request=req)
        form.updateTypes()
        if form.is_valid() and groups_form.is_valid():
            # create our XForm
            is_urgent = form.cleaned_data['is_urgent']
            question = form.cleaned_data['question_en']
            default_response = form.cleaned_data['default_response_en']
            districts = form.cleaned_data['districts']
            excluded_groups = groups_form.cleaned_data['group_list']
            if hasattr(Contact, 'groups'):
                groups = form.cleaned_data['groups']

            log.info("[new-poll] - finding all contacts for this poll...")
            if len(districts):
                contacts = Contact.objects.filter(reporting_location__in=districts).filter(groups__in=groups).exclude(
                    groups__in=excluded_groups)
            else:
                contacts = Contact.objects.filter(groups__in=groups).exclude(groups__in=excluded_groups)

            log.info("[new-poll] - found all contacts ok.")

            log.info("[new-poll] - setting up translations...")
            name = form.cleaned_data['name']
            p_type = form.cleaned_data['type']
            response_type = form.cleaned_data['response_type']
            if not form.cleaned_data['default_response_luo'] == '' \
                and not form.cleaned_data['default_response_en'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=form.cleaned_data['default_response_en']
                    )
                translation.value = form.cleaned_data['default_response_luo']
                translation.save()
            if not form.cleaned_data['default_response_kdj'] == '' \
                and not form.cleaned_data['default_response_en'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='kdj',
                                                      field=form.cleaned_data['default_response_en']
                    )
                translation.value = form.cleaned_data['default_response_kdj']
                translation.save()
            if not form.cleaned_data['question_luo'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=form.cleaned_data['question_en']
                    )
                translation.value = form.cleaned_data['question_luo']
                translation.save()
            if not form.cleaned_data['question_kdj'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='kdj',
                                                      field=form.cleaned_data['question_en']
                    )
                translation.value = form.cleaned_data['question_kdj']
                translation.save()
            log.info("[new-poll] - translations ok.")

            poll_type = (Poll.TYPE_TEXT if p_type
                                           == NewPollForm.TYPE_YES_NO else p_type)

            poll = Poll.create_with_bulk(
                name,
                poll_type,
                question,
                default_response,
                contacts,
                req.user,
                is_urgent=is_urgent)

            if p_type == NewPollForm.TYPE_YES_NO:
                log.info("[new-poll] - is Y/N poll so adding categories...")
                poll.add_yesno_categories()
                log.info("[new-poll] - categories added ok.")

            if settings.SITE_ID:
                log.info("[new-poll] - SITE_ID is set, so adding the site to the poll")
                poll.sites.add(Site.objects.get_current())
                log.info("[new-poll] - site added ok")

            log.info("[new-poll] - poll created ok.")
            log.info("[new_poll] TRANSACTION COMMIT")
            return redirect(reverse('ureport.views.view_poll', args=[poll.pk]))

    else:
        form = NewPollForm(request=req)
        groups_form = GroupsFilter(request=req)
        form.updateTypes()

        log.info("[new_poll] TRANSACTION COMMIT")
    return render_to_response('ureport/new_poll.html', {'form': form, 'groups_form': groups_form},
                                  context_instance=RequestContext(req))
예제 #3
0
def new_poll(req):
    if req.method == 'POST':
        form = NewPollForm(req.POST)
        groups_form = GroupsFilter(req.POST)
        form.updateTypes()
        if form.is_valid() and groups_form.is_valid():
            # create our XForm
            question = form.cleaned_data['question_en']
            default_response = form.cleaned_data['default_response_en']
            districts = form.cleaned_data['districts']
            excluded_groups = groups_form.cleaned_data['group_list']
            if hasattr(Contact, 'groups'):
                groups = form.cleaned_data['groups']

            if len(districts):
                contacts = Contact.objects.filter(reporting_location__in=districts).filter(groups__in=groups).exclude(
                    groups__in=excluded_groups)
            else:
                contacts = Contact.objects.filter(groups__in=groups).exclude(groups__in=excluded_groups)

            name = form.cleaned_data['name']
            p_type = form.cleaned_data['type']
            response_type = form.cleaned_data['response_type']
            if not form.cleaned_data['default_response_luo'] == '' \
                and not form.cleaned_data['default_response_en'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=form.cleaned_data['default_response_en'],
                                                      value=form.cleaned_data['default_response_luo'])
            if not form.cleaned_data['default_response_kdj'] == '' \
                and not form.cleaned_data['default_response_en'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='kdj',
                                                      field=form.cleaned_data['default_response_en'],
                                                      value=form.cleaned_data['default_response_kdj'])

            if not form.cleaned_data['question_luo'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=form.cleaned_data['question_en'],
                                                      value=form.cleaned_data['question_luo'])

            if not form.cleaned_data['question_kdj'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='kdj',
                                                      field=form.cleaned_data['question_en'],
                                                      value=form.cleaned_data['question_kdj'])

            poll_type = (Poll.TYPE_TEXT if p_type
                                           == NewPollForm.TYPE_YES_NO else p_type)

            poll = Poll.create_with_bulk( \
                name,
                poll_type,
                question,
                default_response,
                contacts,
                req.user)

            if p_type == NewPollForm.TYPE_YES_NO:
                poll.add_yesno_categories()

            if settings.SITE_ID:
                poll.sites.add(Site.objects.get_current())

            return redirect(reverse('ureport.views.view_poll', args=[poll.pk]))

    else:
        form = NewPollForm()
        groups_form = GroupsFilter()
        form.updateTypes()

    return render_to_response('ureport/new_poll.html', {'form': form, 'groups_form': groups_form},
                              context_instance=RequestContext(req))
예제 #4
0
def mp_dashboard(request):
    from contact.forms import FilterGroupsForm, \
        MultipleDistictFilterForm, GenderFilterForm, AgeFilterForm

    groupform = AssignResponseGroupForm(request=request)
    if request.method == 'POST' and request.POST.get('groups', None):
        g_form = AssignResponseGroupForm(request.POST, request=request)
        if g_form.is_valid():
            request.session['groups'] = g_form.cleaned_data['groups']
    if not request.session.get('groups', None):
        mp_contacts = Contact.objects.filter(groups__name__in=['MP'])
    else:
        mp_contacts = \
            Contact.objects.filter(groups__in=request.session.get('groups'
                                   ))
    forms = [MultipleDistictFilterForm, FilterGroupsForm,
             GenderFilterForm, AgeFilterForm]
    filter_forms = []
    mp_conns = Connection.objects.filter(contact__in=mp_contacts)
    contacts = \
        Contact.objects.exclude(connection__in=Blacklist.objects.all()).distinct()
    message_list = Message.objects.filter(connection__in=mp_conns,
            direction='I').order_by('-date')
    if request.GET.get('ajax', None):
        date = datetime.datetime.now() - datetime.timedelta(seconds=15)
        msgs = Message.objects.filter(connection__in=mp_conns,
                direction='I').filter(date__gte=date)
        msgs_list = []
        if msgs:
            for msg in msgs:
                m = {}
                m['text'] = msg.text
                m['date'] = str(msg.date.date())
                m['name'] = msg.connection.contact.name
                m['number'] = msg.connection.identity
                if msg.connection.contact.reporting_location:
                    m['district'] = \
                        msg.connection.contact.reporting_location.name
                else:
                    m['district'] = 'N/A'

                m['group'] = msg.connection.contact.groups.all()[0].name
                msgs_list.append(m)
            return HttpResponse(mark_safe(simplejson.dumps(msgs_list)))
        else:
            return HttpResponse('success')

    old_contacts = contacts
    if request.POST and request.GET.get('filter', None):
        for form_class in forms:
            form_instance = form_class(request.POST, request=request)
            if form_instance.is_valid():
                contacts = form_instance.filter(request, contacts)
        if old_contacts.count() == contacts.count():
            return HttpResponse('No Contacts Selected')
        else:
            request.session['filtered'] = contacts
            return HttpResponse(str(contacts.count()))
    for form in forms:
        filter_forms.append(form(**{'request': request}))
    paginator = UreportPaginator(message_list, 10, body=6, padding=2)
    page = request.GET.get('page', 1)
    try:
        messages = paginator.page(page)
    except PageNotAnInteger:

        # If page is not an integer, deliver first page.

        messages = paginator.page(1)
    except EmptyPage:

        # If page is out of range (e.g. 9999), deliver last page of results.

        messages = paginator.page(paginator.num_pages)
    poll_form = NewPollForm()
    poll_form.updateTypes()

    if request.method == 'POST' and request.GET.get('poll', None):
        res_dict = request.POST.copy()
        res_dict.update({'groups': u'2'})
        poll_form = NewPollForm(res_dict)
        poll_form.updateTypes()

        # create poll

        if request.session.get('filtered', None) \
            and poll_form.is_valid():
            name = poll_form.cleaned_data['name']
            p_type = poll_form.cleaned_data['type']
            response_type = poll_form.cleaned_data['response_type']
            question = poll_form.cleaned_data['question']
            default_response = poll_form.cleaned_data['default_response'
                    ]

            if not poll_form.cleaned_data['default_response_luo'] == '' \
                and not poll_form.cleaned_data['default_response'] \
                == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                        field=poll_form.cleaned_data['default_response'
                        ],
                        value=poll_form.cleaned_data['default_response_luo'
                        ])

            if not poll_form.cleaned_data['question_luo'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                        field=poll_form.cleaned_data['question'],
                        value=poll_form.cleaned_data['question_luo'])

            poll_type = (Poll.TYPE_TEXT if p_type
                         == NewPollForm.TYPE_YES_NO else p_type)

            poll = Poll.create_with_bulk(
                name,
                poll_type,
                question,
                default_response,
                request.session.get('filtered'),
                request.user,
                )
            return redirect(reverse('poll.views.view_poll',
                            args=[poll.pk]))

    context_dict = {
        'poll_form': poll_form,
        'filter_forms': filter_forms,
        'messages': messages,
        'groupform': groupform,
        }

    return render_to_response('ureport/mp_dashboard.html',
                              context_dict,
                              context_instance=RequestContext(request))
예제 #5
0
def mp_dashboard(request):
    from contact.forms import FilterGroupsForm, \
        MultipleDistictFilterForm, GenderFilterForm, AgeFilterForm

    mp_contacts = Contact.objects.filter(groups__name__in=['MP'])

    forms = [
        MultipleDistictFilterForm, FilterGroupsForm, GenderFilterForm,
        AgeFilterForm
    ]
    filter_forms = []
    mp_conns = Connection.objects.filter(contact__in=mp_contacts)
    contacts = \
        Contact.objects.exclude(connection__in=Blacklist.objects.all()).distinct()
    message_list = Message.objects.filter(connection__in=mp_conns,
                                          direction='I').order_by('-date')
    if request.GET.get('ajax', None):
        date = datetime.datetime.now() - datetime.timedelta(seconds=15)
        msgs = Message.objects.filter(connection__in=mp_conns,
                                      direction='I').filter(date__gte=date)
        msgs_list = []
        if msgs:
            for msg in msgs:
                m = {}
                m['text'] = msg.text
                m['date'] = str(msg.date.date())
                m['name'] = msg.connection.contact.name
                m['number'] = msg.connection.identity
                if msg.connection.contact.reporting_location:
                    m['district'] = \
                        msg.connection.contact.reporting_location.name
                else:
                    m['district'] = 'N/A'

                m['group'] = msg.connection.contact.groups.all()[0].name
                msgs_list.append(m)
            return HttpResponse(mark_safe(simplejson.dumps(msgs_list)))
        else:
            return HttpResponse('success')

    old_contacts = contacts
    if request.POST and request.GET.get('filter', None):
        for form_class in forms:
            form_instance = form_class(request.POST, request=request)
            if form_instance.is_valid():
                contacts = form_instance.filter(request, contacts)
        if old_contacts.count() == contacts.count():
            return HttpResponse('No Contacts Selected')
        else:
            request.session['filtered'] = contacts
            return HttpResponse(str(contacts.count()))
    for form in forms:
        filter_forms.append(form(**{'request': request}))
    paginator = UreportPaginator(message_list, 10, body=6, padding=2)
    page = request.GET.get('page', 1)
    try:
        messages = paginator.page(page)
    except PageNotAnInteger:

        # If page is not an integer, deliver first page.

        messages = paginator.page(1)
    except EmptyPage:

        # If page is out of range (e.g. 9999), deliver last page of results.

        messages = paginator.page(paginator.num_pages)
    poll_form = NewPollForm()
    poll_form.updateTypes()

    if request.method == 'POST' and request.GET.get('poll', None):
        res_dict = request.POST.copy()
        res_dict.update({'groups': u'2'})
        poll_form = NewPollForm(res_dict)
        poll_form.updateTypes()

        # create poll

        if request.session.get('filtered', None) \
            and poll_form.is_valid():
            name = poll_form.cleaned_data['name']
            p_type = poll_form.cleaned_data['type']
            response_type = poll_form.cleaned_data['response_type']
            question = poll_form.cleaned_data['question']
            default_response = poll_form.cleaned_data['default_response']

            if not poll_form.cleaned_data['default_response_luo'] == '' \
                and not poll_form.cleaned_data['default_response'] \
                            == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=poll_form.cleaned_data['default_response'
                                                      ],
                                                      value=poll_form.cleaned_data['default_response_luo'
                                                      ])

            if not poll_form.cleaned_data['question_luo'] == '':
                (translation, created) = \
                    Translation.objects.get_or_create(language='ach',
                                                      field=poll_form.cleaned_data['question'],
                                                      value=poll_form.cleaned_data['question_luo'])

            poll_type = (Poll.TYPE_TEXT
                         if p_type == NewPollForm.TYPE_YES_NO else p_type)

            poll = Poll.create_with_bulk(
                name,
                poll_type,
                question,
                default_response,
                request.session.get('filtered'),
                request.user,
            )
            return redirect(reverse('poll.views.view_poll', args=[poll.pk]))

    context_dict = {
        'poll_form': poll_form,
        'filter_forms': filter_forms,
        'messages': messages,
    }

    return render_to_response('ureport/mp_dashboard.html',
                              context_dict,
                              context_instance=RequestContext(request))