Example #1
0
def chatlist_load(request):
    if request.method == 'GET':
        user_id = int(request.GET['user_id'])  # id's are stored as ints

        # [Django - how do I select a particular column from a model?](https://stackoverflow.com/questions/10704926/django-how-do-i-select-a-particular-column-from-a-model)
        # chatlist_as_sender = set(Message.objects.filter(
        #     sender=user).values_list('receiver', flat=True))
        messages = Message.objects.filter(sender=user_id)\
            | Message.objects.filter(receiver=user_id)
        chatlist = messages.values_list('sender', 'receiver',
                                        'created_at').order_by('-created_at')

        chatlist_no_dups = []
        chatset = set()
        for chat in chatlist:
            if chat[0] == user_id and chat[1] not in chatset:
                chatlist_no_dups.append(chat[1])
                chatset.add(chat[1])
            elif chat[1] == user_id and chat[0] not in chatset:
                chatlist_no_dups.append(chat[0])
                chatset.add(chat[0])

        # chatlist_users = User.objects.filter(
        #     pk__in=chatlist_no_dups).values_list('id', 'username')

        json_res = serializers.serialize(
            'json',
            User.objects.filter(pk__in=chatlist_no_dups),
            fields=('id', 'username'))
        return HttpResponse(json_res, content_type='application/json')
Example #2
0
    def get_context_data(self, **kwargs):
        user = self.object
        context = {}

        count_types = OrderedDict()

        fields_or_lookup = (
            {'collaborators__contains': user.username},
            {'fullname_and_username__contains': user.username},
        )

        counter_class = {}
        #{
        #    'wiki': WikiCollabCount,
        #    'ticket': TicketCollabCount,
        #}

        types = ['thread']
        #types.extend(['ticket', 'wiki', 'changeset', 'attachment'])

        messages = Message.objects.filter(from_address__user__pk=user.pk)
        for type in types:
            CounterClass = counter_class.get(type)
            if CounterClass:
                try:
                    counter = CounterClass.objects.get(author=user.username)
                except CounterClass.DoesNotExist:
                    count_types[trans(type)] = 0
                else:
                    count_types[trans(type)] = counter.count
            elif type == 'thread':
                count_types[trans(type)] = messages.count()
            else:
                sqs = SearchQuerySet()
                for filter_or in fields_or_lookup:
                    sqs = sqs.filter_or(type=type, **filter_or)
                count_types[trans(type)] = sqs.count()

        context['type_count'] = count_types

        sqs = SearchQuerySet()
        for filter_or in fields_or_lookup:
            sqs = sqs.filter_or(**filter_or).exclude(type='thread')

        context['results'] = sqs.order_by('-modified', '-created')[:10]

        email_pks = [addr.pk for addr in user.emails.iterator()]
        query = Message.objects.filter(from_address__in=email_pks)
        query = query.order_by('-received_time')
        context['emails'] = query[:10]

        count_by = 'thread__mailinglist__name'
        context['list_activity'] = dict(messages.values_list(count_by)\
                                           .annotate(Count(count_by))\
                                           .order_by(count_by))

        context.update(kwargs)
        return super(UserProfileDetailView, self).get_context_data(**context)
Example #3
0
    def get_context_data(self, **kwargs):
        user = self.object
        context = {}

        count_types = OrderedDict()

        fields_or_lookup = (
            {
                'collaborators__contains': user.username
            },
            {
                'fullname_and_username__contains': user.username
            },
        )

        counter_class = {
            'wiki': WikiCollabCount,
            'ticket': TicketCollabCount,
        }

        messages = Message.objects.filter(from_address__user__pk=user.pk)
        for type in ['thread', 'ticket', 'wiki', 'changeset', 'attachment']:
            CounterClass = counter_class.get(type)
            if CounterClass:
                try:
                    counter = CounterClass.objects.get(author=user.username)
                except CounterClass.DoesNotExist:
                    count_types[trans(type)] = 0
                else:
                    count_types[trans(type)] = counter.count
            elif type == 'thread':
                count_types[trans(type)] = messages.count()
            else:
                sqs = SearchQuerySet()
                for filter_or in fields_or_lookup:
                    sqs = sqs.filter_or(type=type, **filter_or)
                count_types[trans(type)] = sqs.count()

        context['type_count'] = count_types

        sqs = SearchQuerySet()
        for filter_or in fields_or_lookup:
            sqs = sqs.filter_or(**filter_or).exclude(type='thread')

        context['results'] = sqs.order_by('-modified', '-created')[:10]

        email_pks = [addr.pk for addr in user.emails.iterator()]
        query = Message.objects.filter(from_address__in=email_pks)
        query = query.order_by('-received_time')
        context['emails'] = query[:10]

        count_by = 'thread__mailinglist__name'
        context['list_activity'] = dict(messages.values_list(count_by)\
                                           .annotate(Count(count_by))\
                                           .order_by(count_by))

        context.update(kwargs)
        return super(UserProfileDetailView, self).get_context_data(**context)
Example #4
0
    def get_context_data(self, **kwargs):
        user = self.object
        context = {}

        count_types = OrderedDict()

        fields_or_lookup = (
            {"collaborators__contains": user.username},
            {"fullname_and_username__contains": user.username},
        )

        counter_class = {"wiki": WikiCollabCount, "ticket": TicketCollabCount}

        messages = Message.objects.filter(from_address__user__pk=user.pk)
        for type in ["thread", "ticket", "wiki", "changeset", "attachment"]:
            CounterClass = counter_class.get(type)
            if CounterClass:
                try:
                    counter = CounterClass.objects.get(author=user.username)
                except CounterClass.DoesNotExist:
                    count_types[trans(type)] = 0
                else:
                    count_types[trans(type)] = counter.count
            elif type == "thread":
                count_types[trans(type)] = messages.count()
            else:
                sqs = SearchQuerySet()
                for filter_or in fields_or_lookup:
                    sqs = sqs.filter_or(type=type, **filter_or)
                count_types[trans(type)] = sqs.count()

        context["type_count"] = count_types

        sqs = SearchQuerySet()
        for filter_or in fields_or_lookup:
            sqs = sqs.filter_or(**filter_or).exclude(type="thread")

        context["results"] = sqs.order_by("-modified", "-created")[:10]

        email_pks = [addr.pk for addr in user.emails.iterator()]
        query = Message.objects.filter(from_address__in=email_pks)
        query = query.order_by("-received_time")
        context["emails"] = query[:10]

        count_by = "thread__mailinglist__name"
        context["list_activity"] = dict(messages.values_list(count_by).annotate(Count(count_by)).order_by(count_by))

        context.update(kwargs)
        return super(UserProfileDetailView, self).get_context_data(**context)
def ureporter_profile(request, connection_pk):
    from script.models import ScriptSession, ScriptResponse, Script

    connection = get_object_or_404(Connection, pk=connection_pk)
    session = ScriptSession.objects.filter(connection__pk=connection_pk)
    messages = Message.objects.filter(connection=connection).order_by('-date')
    contact = connection.contact
    if contact:
        #get the proxy
        contact = Ureporter.objects.get(pk=connection.contact.pk)

    reporter_form = EditReporterForm(instance=contact)
    total_outgoing = messages.filter(direction='O',
                                     connection__pk=connection_pk).count()
    total_incoming = messages.filter(direction='I',
                                     connection__pk=connection_pk).count()
    try:
        response_rate = contact.responses.values_list(
            'poll').distinct().count() * 100 / float(
                Poll.objects.filter(contacts=contact).distinct().count())
    except (ZeroDivisionError, ValueError):
        response_rate = None


#    gr_poll = Poll.objects.get(pk=121)
    gr_poll = Script.objects.get(slug="autoreg_en").steps.get(order=1).poll
    how_did_u_hear = None
    if session:
        try:
            how_did_u_hear = \
                session[0].responses.filter(response__poll=gr_poll)[0].response.message.text
        except (ScriptResponse.DoesNotExist, IndexError):
            how_did_u_hear = 'N/A'
    if request.GET.get('download', None):
        data = []
        data = messages.values_list(
            'text', 'direction', 'date',
            'connection__contact__reporting_location__name').iterator()
        headers = ['Message', 'Direction', 'Date', 'District']

        return ExcelResponse(data=data, headers=headers)
    columns = [('Message', True, 'text', SimpleSorter()),
               ('connection', True, 'connection', SimpleSorter()),
               ('Date', True, 'date', SimpleSorter()),
               ('Direction', True, 'direction', SimpleSorter())]

    # hack hack send the reply message by hacking the sendmessage form
    if request.method == 'POST':
        if not request.POST.get('text', None) == u'' and request.POST.get(
                'action'
        ) == u'ureport.forms.ReplyTextForm' and not request.POST.get(
                'page_action', None):
            rep_form = ReplyTextForm(request=request)
            Message.objects.create(connection=connection,
                                   direction='O',
                                   status='Q',
                                   text=request.POST.get('text'))
            return generic(
                request,
                model=Message,
                queryset=messages,
                total_outgoing=total_outgoing,
                total_incoming=total_incoming,
                response_rate=response_rate,
                how_did_u_hear=how_did_u_hear,
                contact=contact,
                reporter_form=reporter_form,
                objects_per_page=20,
                status_message='Message sent',
                status_message_type='success',
                results_title='Message History',
                selectable=False,
                partial_row=
                'ureport/partials/messages/message_history_row.html',
                base_template='ureport/message_history_base.html',
                action_forms=[ReplyTextForm],
                columns=columns,
                sort_column='date',
                sort_ascending=False,
            )

    return generic(
        request,
        model=Message,
        queryset=messages,
        contact=contact,
        total_outgoing=total_outgoing,
        total_incoming=total_incoming,
        response_rate=response_rate,
        objects_per_page=20,
        how_did_u_hear=how_did_u_hear,
        reporter_form=reporter_form,
        results_title='Message History',
        selectable=False,
        partial_row='ureport/partials/messages/message_history_row.html',
        base_template='ureport/message_history_base.html',
        action_forms=[ReplyTextForm],
        columns=columns,
        sort_column='date',
        sort_ascending=False,
    )
def ureporter_profile(request, connection_pk):
    from script.models import ScriptSession, ScriptResponse, Script

    connection = get_object_or_404(Connection, pk=connection_pk)
    session = ScriptSession.objects.filter(connection__pk=connection_pk)
    messages = Message.objects.filter(connection=connection).order_by('-date')
    contact=connection.contact
    if contact:
        #get the proxy
        contact = Ureporter.objects.get(pk=connection.contact.pk)

    reporter_form = EditReporterForm(instance=contact)
    total_outgoing = messages.filter(direction='O',
                                     connection__pk=connection_pk).count()
    total_incoming = messages.filter(direction='I',
                                     connection__pk=connection_pk).count()
    try:
        response_rate = contact.responses.values_list('poll').distinct().count() * 100 / float(Poll.objects.filter(contacts=contact).distinct().count())
    except (ZeroDivisionError, ValueError):
        response_rate = None
#    gr_poll = Poll.objects.get(pk=121)
    gr_poll = Script.objects.get(slug="autoreg_en").steps.get(order=1).poll
    how_did_u_hear = None
    if session:
        try:
            how_did_u_hear = \
                session[0].responses.filter(response__poll=gr_poll)[0].response.message.text
        except (ScriptResponse.DoesNotExist, IndexError):
            how_did_u_hear = 'N/A'
    if request.GET.get('download', None):
        data = []
        data = messages.values_list('text', 'direction', 'date',
                                    'connection__contact__reporting_location__name').iterator()
        headers = ['Message', 'Direction', 'Date', 'District']

        return ExcelResponse(data=data, headers=headers)
    columns = [
               ('Message', True, 'text', SimpleSorter()),
               ('connection', True, 'connection', SimpleSorter()),
               ('Date', True, 'date', SimpleSorter()),
               ('Direction', True, 'direction', SimpleSorter())
               ]

    # hack hack send the reply message by hacking the sendmessage form
    if request.method == 'POST' :
        if not request.POST.get('text', None) == u'' and request.POST.get('action') == u'ureport.forms.ReplyTextForm' and not request.POST.get('page_action',None):
            rep_form=ReplyTextForm(request=request)
            Message.objects.create(
                connection=connection, direction='O'
                , status='Q',
                text=request.POST.get('text'))
            return generic(
                request,
                model=Message,
                queryset=messages,
                total_outgoing=total_outgoing,
                total_incoming=total_incoming,
                response_rate=response_rate,
                how_did_u_hear=how_did_u_hear,
                contact=contact,
                reporter_form=reporter_form,
                objects_per_page=20,
                status_message='Message sent',
                status_message_type='success',
                results_title='Message History',
                selectable=False,
                partial_row='ureport/partials/messages/message_history_row.html',
                base_template='ureport/message_history_base.html',
                action_forms=[ReplyTextForm],
                columns=columns,
                sort_column='date',
                sort_ascending=False,
            )

    return generic(
        request,
        model=Message,
        queryset=messages,
        contact=contact,
        total_outgoing=total_outgoing,
        total_incoming=total_incoming,
        response_rate=response_rate,
        objects_per_page=20,
        how_did_u_hear=how_did_u_hear,
        reporter_form=reporter_form,
        results_title='Message History',
        selectable=False,
        partial_row='ureport/partials/messages/message_history_row.html',
        base_template='ureport/message_history_base.html',
        action_forms=[ReplyTextForm],
        columns=columns,
        sort_column='date',
        sort_ascending=False,
    )