Ejemplo n.º 1
0
 def _get_settings(self):
     # return a python dictionary representing the pickled data.
     try:
         import pickle
     except ImportError:
         import cPickle as pickle
     from helpdesk.lib import b64decode
     try:
         if six.PY2:
             return pickle.loads(b64decode(str(self.settings_pickled)))
         else:
             return pickle.loads(b64decode(self.settings_pickled.encode('utf-8')))
     except pickle.UnpicklingError:
         return {}
Ejemplo n.º 2
0
 def _get_settings(self):
     # return a python dictionary representing the pickled data.
     from helpdesk.lib import b64decode
     try:
         return cPickle.loads(b64decode(str(self.settings_pickled)))
     except cPickle.UnpicklingError:
         return {}
Ejemplo n.º 3
0
 def _get_settings(self):
     # return a python dictionary representing the pickled data.
     from helpdesk.lib import b64decode
     try:
         return pickle.loads(b64decode(str(self.settings_pickled)))
     except pickle.UnpicklingError:
         return {}
Ejemplo n.º 4
0
def unpickle_settings(settings_pickled):
    # return a python dictionary representing the pickled data.
    try:
        import pickle
    except ImportError:
        import cPickle as pickle
    from helpdesk.lib import b64decode
    try:
        return pickle.loads(b64decode(settings_pickled.encode('utf-8')))
    except Exception:
        return {}
Ejemplo n.º 5
0
def run_report(request, report):
    if Ticket.objects.all().count() == 0 or report not in ('queuemonth', 'usermonth', 'queuestatus', 'queuepriority', 'userstatus', 'userpriority', 'userqueue'):
        return HttpResponseRedirect(reverse("helpdesk_report_index"))

    report_queryset = Ticket.objects.all().select_related()
   
    from_saved_query = False
    saved_query = None

    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_report_index'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_report_index'))

        import cPickle
        from helpdesk.lib import b64decode
        query_params = cPickle.loads(b64decode(str(saved_query.query)))
        report_queryset = apply_query(report_queryset, query_params)

    from collections import defaultdict
    summarytable = defaultdict(int)

    months = (
        _('Jan'),
        _('Feb'),
        _('Mar'),
        _('Apr'),
        _('May'),
        _('Jun'),
        _('Jul'),
        _('Aug'),
        _('Sep'),
        _('Oct'),
        _('Nov'),
        _('Dec'),
    )
    
    first_ticket = Ticket.objects.all().order_by('created')[0]
    first_month = first_ticket.created.month
    first_year = first_ticket.created.year

    last_ticket = Ticket.objects.all().order_by('-created')[0]
    last_month = last_ticket.created.month
    last_year = last_ticket.created.year

    periods = []
    year, month = first_year, first_month
    working = True
    periods.append("%s %s" % (months[month], year))

    while working:
        month += 1
        if month > 12:
            year += 1
            month = 1
        if (year > last_year) or (month > last_month and year >= last_year):
            working = False
        periods.append("%s %s" % (months[month], year))

    if report == 'userpriority':
        title = _('User by Priority')
        col1heading = _('User')
        possible_options = [t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES]
        charttype = 'bar'

    elif report == 'userqueue':
        title = _('User by Queue')
        col1heading = _('User')
        possible_options = [q.title.encode('utf-8') for q in Queue.objects.all()]
        charttype = 'bar'

    elif report == 'userstatus':
        title = _('User by Status')
        col1heading = _('User')
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'usermonth':
        title = _('User by Month')
        col1heading = _('User')
        possible_options = periods
        charttype = 'date'

    elif report == 'queuepriority':
        title = _('Queue by Priority')
        col1heading = _('Queue')
        possible_options = [t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES]
        charttype = 'bar'

    elif report == 'queuestatus':
        title = _('Queue by Status')
        col1heading = _('Queue')
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'queuemonth':
        title = _('Queue by Month')
        col1heading = _('Queue')
        possible_options = periods
        charttype = 'date'



    for ticket in report_queryset:
        if report == 'userpriority':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'userqueue':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.queue.title

        elif report == 'userstatus':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'usermonth':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s %s' % (months[ticket.created.month], ticket.created.year)

        elif report == 'queuepriority':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'queuestatus':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'queuemonth':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s %s' % (months[ticket.created.month], ticket.created.year)

        summarytable[metric1, metric2] += 1
    
    table = []
    
    header1 = sorted(set(list( i.encode('utf-8') for i,_ in summarytable.keys() )))

    column_headings = [col1heading] + possible_options

    # Pivot the data so that 'header1' fields are always first column
    # in the row, and 'possible_options' are always the 2nd - nth columns.
    for item in header1:
        data = []
        for hdr in possible_options:
            data.append(summarytable[item, hdr])
        table.append([item] + data)

    return render_to_response('helpdesk/report_output.html',
        RequestContext(request, {
            'title': title,
            'charttype': charttype,
            'data': table,
            'headings': column_headings,
            'from_saved_query': from_saved_query,
            'saved_query': saved_query,
        }))
Ejemplo n.º 6
0
def ticket_list(request):
    context = {}

    # Query_params will hold a dictionary of paramaters relating to
    # a query, to be saved if needed:
    query_params = {
        'filtering': {},
        'sorting': None,
        'sortreverse': False,
        'keyword': None,
        'other_filter': None,
        }

    from_saved_query = False

    # If the user is coming from the header/navigation search box, lets' first
    # look at their query to see if they have entered a valid ticket number. If
    # they have, just redirect to that ticket number. Otherwise, we treat it as
    # a keyword search.

    if request.GET.get('search_type', None) == 'header':
        query = request.GET.get('q')
        filter = None
        if query.find('-') > 0:
            queue, id = query.split('-')
            try:
                id = int(id)
            except ValueError:
                id = None

            if id:
                filter = {'queue__slug': queue, 'id': id }
        else:
            try:
                query = int(query)
            except ValueError:
                query = None

            if query:
                filter = {'id': int(query) }

        if filter:
            try:
                ticket = Ticket.objects.get(**filter)
                return HttpResponseRedirect(ticket.staff_url)
            except Ticket.DoesNotExist:
                # Go on to standard keyword searching
                pass

    saved_query = None
    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_list'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_list'))

        import cPickle
        from helpdesk.lib import b64decode
        query_params = cPickle.loads(b64decode(str(saved_query.query)))
    elif not (  request.GET.has_key('queue')
            or  request.GET.has_key('assigned_to')
            or  request.GET.has_key('status')
            or  request.GET.has_key('q')
            or  request.GET.has_key('sort')
            or  request.GET.has_key('sortreverse') 
            or  request.GET.has_key('tags') ):

        # Fall-back if no querying is being done, force the list to only
        # show open/reopened/resolved (not closed) cases sorted by creation
        # date.

        query_params = {
            'filtering': {'status__in': [1, 2, 3]},
            'sorting': 'created',
        }
    else:
        queues = request.GET.getlist('queue')
        if queues:
            queues = [int(q) for q in queues]
            query_params['filtering']['queue__id__in'] = queues

        owners = request.GET.getlist('assigned_to')
        if owners:
            owners = [int(u) for u in owners]
            query_params['filtering']['assigned_to__id__in'] = owners

        statuses = request.GET.getlist('status')
        if statuses:
            statuses = [int(s) for s in statuses]
            query_params['filtering']['status__in'] = statuses

        date_from = request.GET.get('date_from')
        if date_from:
            query_params['filtering']['created__gte'] = date_from
        
        date_to = request.GET.get('date_to')
        if date_to:
            query_params['filtering']['created__lte'] = date_to

        ### KEYWORD SEARCHING
        q = request.GET.get('q', None)

        if q:
            qset = (
                Q(title__icontains=q) |
                Q(description__icontains=q) |
                Q(resolution__icontains=q) |
                Q(submitter_email__icontains=q)
            )
            context = dict(context, query=q)

            query_params['other_filter'] = qset

        ### SORTING
        sort = request.GET.get('sort', None)
        if sort not in ('status', 'assigned_to', 'created', 'title', 'queue', 'priority'):
            sort = 'created'
        query_params['sorting'] = sort

        sortreverse = request.GET.get('sortreverse', None)
        query_params['sortreverse'] = sortreverse

    ticket_qs = apply_query(Ticket.objects.select_related(), query_params)
#    print >> sys.stderr,  str(ticket_qs.query)

    ## TAG MATCHING
    if HAS_TAG_SUPPORT:
        tags = request.GET.getlist('tags')
        if tags:
            ticket_qs = TaggedItem.objects.get_by_model(ticket_qs, tags)
            query_params['tags'] = tags

    ticket_paginator = paginator.Paginator(ticket_qs, request.user.usersettings.settings.get('tickets_per_page') or 20)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
         page = 1

    try:
        tickets = ticket_paginator.page(page)
    except (paginator.EmptyPage, paginator.InvalidPage):
        tickets = ticket_paginator.page(ticket_paginator.num_pages)

    search_message = ''
    if context.has_key('query') and settings.DATABASE_ENGINE.startswith('sqlite'):
        search_message = _('<p><strong>Note:</strong> Your keyword search is case sensitive because of your database. This means the search will <strong>not</strong> be accurate. By switching to a different database system you will gain better searching! For more information, read the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching">Django Documentation on string matching in SQLite</a>.')


    import cPickle
    from helpdesk.lib import b64encode
    urlsafe_query = b64encode(cPickle.dumps(query_params))

    user_saved_queries = SavedSearch.objects.filter(Q(user=request.user) | Q(shared__exact=True))

    query_string = []
    for get_key, get_value in request.GET.iteritems():
        if get_key != "page":
            query_string.append("%s=%s" % (get_key, get_value))

    tag_choices = [] 
    if HAS_TAG_SUPPORT:
        # FIXME: restrict this to tags that are actually in use
        tag_choices = Tag.objects.all()

    return render_to_response('helpdesk/ticket_list.html',
        RequestContext(request, dict(
            context,
            query_string="&".join(query_string),
            tickets=tickets,
            user_choices=User.objects.filter(Q(is_superuser=True), is_active=True),
            queue_choices=Queue.objects.all(),
            status_choices=Ticket.STATUS_CHOICES,
            tag_choices=tag_choices,
            urlsafe_query=urlsafe_query,
            user_saved_queries=user_saved_queries,
            query_params=query_params,
            from_saved_query=from_saved_query,
            saved_query=saved_query,
            search_message=search_message,
            tags_enabled=HAS_TAG_SUPPORT
        )))
Ejemplo n.º 7
0
def run_report(request, report):
    if Ticket.objects.all().count() == 0 or report not in (
        "queuemonth",
        "usermonth",
        "queuestatus",
        "queuepriority",
        "userstatus",
        "userpriority",
        "userqueue",
    ):
        return HttpResponseRedirect(reverse("helpdesk_report_index"))

    report_queryset = Ticket.objects.all().select_related()

    from_saved_query = False
    saved_query = None

    if request.GET.get("saved_query", None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get("saved_query"))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse("helpdesk_report_index"))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse("helpdesk_report_index"))

        import cPickle
        from helpdesk.lib import b64decode

        query_params = cPickle.loads(b64decode(str(saved_query.query)))
        report_queryset = apply_query(report_queryset, query_params)

    from collections import defaultdict

    summarytable = defaultdict(int)

    months = (
        _("Jan"),
        _("Feb"),
        _("Mar"),
        _("Apr"),
        _("May"),
        _("Jun"),
        _("Jul"),
        _("Aug"),
        _("Sep"),
        _("Oct"),
        _("Nov"),
        _("Dec"),
    )

    first_ticket = Ticket.objects.all().order_by("created")[0]
    first_month = first_ticket.created.month
    first_year = first_ticket.created.year

    last_ticket = Ticket.objects.all().order_by("-created")[0]
    last_month = last_ticket.created.month
    last_year = last_ticket.created.year

    periods = []
    year, month = first_year, first_month
    working = True
    periods.append("%s %s" % (months[month - 1], year))

    while working:
        month += 1
        if month > 12:
            year += 1
            month = 1
        if (year > last_year) or (month > last_month and year >= last_year):
            working = False
        periods.append("%s %s" % (months[month - 1], year))

    if report == "userpriority":
        title = _("User by Priority")
        col1heading = _("User")
        possible_options = [t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES]
        charttype = "bar"

    elif report == "userqueue":
        title = _("User by Queue")
        col1heading = _("User")
        possible_options = [q.title.encode("utf-8") for q in Queue.objects.all()]
        charttype = "bar"

    elif report == "userstatus":
        title = _("User by Status")
        col1heading = _("User")
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = "bar"

    elif report == "usermonth":
        title = _("User by Month")
        col1heading = _("User")
        possible_options = periods
        charttype = "date"

    elif report == "queuepriority":
        title = _("Queue by Priority")
        col1heading = _("Queue")
        possible_options = [t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES]
        charttype = "bar"

    elif report == "queuestatus":
        title = _("Queue by Status")
        col1heading = _("Queue")
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = "bar"

    elif report == "queuemonth":
        title = _("Queue by Month")
        col1heading = _("Queue")
        possible_options = periods
        charttype = "date"

    for ticket in report_queryset:
        if report == "userpriority":
            metric1 = u"%s" % ticket.get_assigned_to
            metric2 = u"%s" % ticket.get_priority_display()

        elif report == "userqueue":
            metric1 = u"%s" % ticket.get_assigned_to
            metric2 = u"%s" % ticket.queue.title

        elif report == "userstatus":
            metric1 = u"%s" % ticket.get_assigned_to
            metric2 = u"%s" % ticket.get_status_display()

        elif report == "usermonth":
            metric1 = u"%s" % ticket.get_assigned_to
            metric2 = u"%s %s" % (months[ticket.created.month - 1], ticket.created.year)

        elif report == "queuepriority":
            metric1 = u"%s" % ticket.queue.title
            metric2 = u"%s" % ticket.get_priority_display()

        elif report == "queuestatus":
            metric1 = u"%s" % ticket.queue.title
            metric2 = u"%s" % ticket.get_status_display()

        elif report == "queuemonth":
            metric1 = u"%s" % ticket.queue.title
            metric2 = u"%s %s" % (months[ticket.created.month - 1], ticket.created.year)

        summarytable[metric1, metric2] += 1

    table = []

    header1 = sorted(set(list(i.encode("utf-8") for i, _ in summarytable.keys())))

    column_headings = [col1heading] + possible_options

    # Pivot the data so that 'header1' fields are always first column
    # in the row, and 'possible_options' are always the 2nd - nth columns.
    for item in header1:
        data = []
        for hdr in possible_options:
            data.append(summarytable[item, hdr])
        table.append([item] + data)

    return render_to_response(
        "helpdesk/report_output.html",
        RequestContext(
            request,
            {
                "title": title,
                "charttype": charttype,
                "data": table,
                "headings": column_headings,
                "from_saved_query": from_saved_query,
                "saved_query": saved_query,
            },
        ),
    )
Ejemplo n.º 8
0
def ticket_list(request):
    context = {}

    # Query_params will hold a dictionary of paramaters relating to
    # a query, to be saved if needed:
    query_params = {
        'filtering': {},
        'sorting': None,
        'sortreverse': False,
        'keyword': None,
        'other_filter': None,
    }

    from_saved_query = False

    # If the user is coming from the header/navigation search box, lets' first
    # look at their query to see if they have entered a valid ticket number. If
    # they have, just redirect to that ticket number. Otherwise, we treat it as
    # a keyword search.

    if request.GET.get('search_type', None) == 'header':
        query = request.GET.get('q')
        filter = None
        if query.find('-') > 0:
            queue, id = query.split('-')
            try:
                id = int(id)
            except ValueError:
                id = None

            if id:
                filter = {'queue__slug': queue, 'id': id}
        else:
            try:
                query = int(query)
            except ValueError:
                query = None

            if query:
                filter = {'id': int(query)}

        if filter:
            try:
                ticket = Ticket.objects.get(**filter)
                return HttpResponseRedirect(ticket.staff_url)
            except Ticket.DoesNotExist:
                # Go on to standard keyword searching
                pass

    saved_query = None
    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(
                pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_list'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_list'))

        import cPickle
        from helpdesk.lib import b64decode
        query_params = cPickle.loads(b64decode(str(saved_query.query)))
    elif not (request.GET.has_key('queue')
              or request.GET.has_key('assigned_to')
              or request.GET.has_key('status') or request.GET.has_key('q') or
              request.GET.has_key('sort') or request.GET.has_key('sortreverse')
              or request.GET.has_key('tags')):

        # Fall-back if no querying is being done, force the list to only
        # show open/reopened/resolved (not closed) cases sorted by creation
        # date.

        query_params = {
            'filtering': {
                'status__in': [1, 2, 3]
            },
            'sorting': 'created',
        }
    else:
        queues = request.GET.getlist('queue')
        if queues:
            try:
                queues = [int(q) for q in queues]
                query_params['filtering']['queue__id__in'] = queues
            except ValueError:
                pass

        owners = request.GET.getlist('assigned_to')
        if owners:
            try:
                owners = [int(u) for u in owners]
                query_params['filtering']['assigned_to__id__in'] = owners
            except ValueError:
                pass

        statuses = request.GET.getlist('status')
        if statuses:
            try:
                statuses = [int(s) for s in statuses]
                query_params['filtering']['status__in'] = statuses
            except ValueError:
                pass

        date_from = request.GET.get('date_from')
        if date_from:
            query_params['filtering']['created__gte'] = date_from

        date_to = request.GET.get('date_to')
        if date_to:
            query_params['filtering']['created__lte'] = date_to

        ### KEYWORD SEARCHING
        q = request.GET.get('q', None)

        if q:
            qset = (Q(title__icontains=q) | Q(description__icontains=q)
                    | Q(resolution__icontains=q)
                    | Q(submitter_email__icontains=q))
            context = dict(context, query=q)

            query_params['other_filter'] = qset

        ### SORTING
        sort = request.GET.get('sort', None)
        if sort not in ('status', 'assigned_to', 'created', 'title', 'queue',
                        'priority'):
            sort = 'created'
        query_params['sorting'] = sort

        sortreverse = request.GET.get('sortreverse', None)
        query_params['sortreverse'] = sortreverse

    try:
        ticket_qs = apply_query(Ticket.objects.select_related(), query_params)
    except ValidationError:
        # invalid parameters in query, return default query
        query_params = {
            'filtering': {
                'status__in': [1, 2, 3]
            },
            'sorting': 'created',
        }
        ticket_qs = apply_query(Ticket.objects.select_related(), query_params)

    ## TAG MATCHING
    if HAS_TAGGING_SUPPORT:
        tags = request.GET.getlist('tags')
        if tags:
            ticket_qs = TaggedItem.objects.get_by_model(ticket_qs, tags)
            query_params['tags'] = tags

    if HAS_TAGGIT_SUPPORT:
        tags = request.GET.getlist('tags')
        if tags:
            ticket_qs = Ticket.objects.filter(tags__name__in=tags)
            query_params['tags'] = tags

    ticket_paginator = paginator.Paginator(
        ticket_qs,
        request.user.usersettings.settings.get('tickets_per_page') or 20)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        tickets = ticket_paginator.page(page)
    except (paginator.EmptyPage, paginator.InvalidPage):
        tickets = ticket_paginator.page(ticket_paginator.num_pages)

    search_message = ''
    if context.has_key('query') and settings.DATABASE_ENGINE.startswith(
            'sqlite'):
        search_message = _(
            '<p><strong>Note:</strong> Your keyword search is case sensitive because of your database. This means the search will <strong>not</strong> be accurate. By switching to a different database system you will gain better searching! For more information, read the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching">Django Documentation on string matching in SQLite</a>.'
        )

    import cPickle
    from helpdesk.lib import b64encode
    urlsafe_query = b64encode(cPickle.dumps(query_params))

    user_saved_queries = SavedSearch.objects.filter(
        Q(user=request.user) | Q(shared__exact=True))

    query_string = []
    for get_key, get_value in request.GET.iteritems():
        if get_key != "page":
            query_string.append("%s=%s" % (get_key, get_value))

    tag_choices = []
    if HAS_TAGGING_SUPPORT or HAS_TAGGIT_SUPPORT:
        # FIXME: restrict this to tags that are actually in use
        tag_choices = Tag.objects.all()

    return render_to_response(
        'helpdesk/ticket_list.html',
        RequestContext(
            request,
            dict(
                context,
                query_string="&".join(query_string),
                tickets=tickets,
                user_choices=User.objects.filter(is_active=True),
                queue_choices=Queue.objects.all(),
                status_choices=Ticket.STATUS_CHOICES,
                tag_choices=tag_choices,
                urlsafe_query=urlsafe_query,
                user_saved_queries=user_saved_queries,
                query_params=query_params,
                from_saved_query=from_saved_query,
                saved_query=saved_query,
                search_message=search_message,
                tagging_enabled=HAS_TAGGING_SUPPORT,
                taggit_enabled=HAS_TAGGIT_SUPPORT,
            )))
Ejemplo n.º 9
0
def run_report(request, report):
    if Ticket.objects.all().count() == 0 or report not in (
            'queuemonth', 'usermonth', 'queuestatus', 'queuepriority',
            'userstatus', 'userpriority', 'userqueue'):
        return HttpResponseRedirect(reverse("helpdesk_report_index"))

    report_queryset = Ticket.objects.all().select_related()

    from_saved_query = False
    saved_query = None

    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(
                pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_report_index'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_report_index'))

        import cPickle
        from helpdesk.lib import b64decode
        query_params = cPickle.loads(b64decode(str(saved_query.query)))
        report_queryset = apply_query(report_queryset, query_params)

    from collections import defaultdict
    summarytable = defaultdict(int)

    months = (
        _('Jan'),
        _('Feb'),
        _('Mar'),
        _('Apr'),
        _('May'),
        _('Jun'),
        _('Jul'),
        _('Aug'),
        _('Sep'),
        _('Oct'),
        _('Nov'),
        _('Dec'),
    )

    first_ticket = Ticket.objects.all().order_by('created')[0]
    first_month = first_ticket.created.month
    first_year = first_ticket.created.year

    last_ticket = Ticket.objects.all().order_by('-created')[0]
    last_month = last_ticket.created.month
    last_year = last_ticket.created.year

    periods = []
    year, month = first_year, first_month
    working = True
    periods.append("%s %s" % (months[month - 1], year))

    while working:
        month += 1
        if month > 12:
            year += 1
            month = 1
        if (year > last_year) or (month > last_month and year >= last_year):
            working = False
        periods.append("%s %s" % (months[month - 1], year))

    if report == 'userpriority':
        title = _('User by Priority')
        col1heading = _('User')
        possible_options = [
            t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES
        ]
        charttype = 'bar'

    elif report == 'userqueue':
        title = _('User by Queue')
        col1heading = _('User')
        possible_options = [
            q.title.encode('utf-8') for q in Queue.objects.all()
        ]
        charttype = 'bar'

    elif report == 'userstatus':
        title = _('User by Status')
        col1heading = _('User')
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'usermonth':
        title = _('User by Month')
        col1heading = _('User')
        possible_options = periods
        charttype = 'date'

    elif report == 'queuepriority':
        title = _('Queue by Priority')
        col1heading = _('Queue')
        possible_options = [
            t[1].__unicode__() for t in Ticket.PRIORITY_CHOICES
        ]
        charttype = 'bar'

    elif report == 'queuestatus':
        title = _('Queue by Status')
        col1heading = _('Queue')
        possible_options = [s[1].__unicode__() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'queuemonth':
        title = _('Queue by Month')
        col1heading = _('Queue')
        possible_options = periods
        charttype = 'date'

    for ticket in report_queryset:
        if report == 'userpriority':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'userqueue':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.queue.title

        elif report == 'userstatus':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'usermonth':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s %s' % (months[ticket.created.month - 1],
                                  ticket.created.year)

        elif report == 'queuepriority':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'queuestatus':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'queuemonth':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s %s' % (months[ticket.created.month - 1],
                                  ticket.created.year)

        summarytable[metric1, metric2] += 1

    table = []

    header1 = sorted(
        set(list(i.encode('utf-8') for i, _ in summarytable.keys())))

    column_headings = [col1heading] + possible_options

    # Pivot the data so that 'header1' fields are always first column
    # in the row, and 'possible_options' are always the 2nd - nth columns.
    for item in header1:
        data = []
        for hdr in possible_options:
            data.append(summarytable[item, hdr])
        table.append([item] + data)

    return render_to_response(
        'helpdesk/report_output.html',
        RequestContext(
            request, {
                'title': title,
                'charttype': charttype,
                'data': table,
                'headings': column_headings,
                'from_saved_query': from_saved_query,
                'saved_query': saved_query,
            }))
Ejemplo n.º 10
0
def public_ticket_list(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    context = {}

    # Query_params will hold a dictionary of parameters relating to
    # a query, to be saved if needed:
    query_params = {
        'filtering': {},
        'sorting': None,
        'sortreverse': True,
        'keyword': None,
        'other_filter': None,
    }

    from_saved_query = False

    # If the user is coming from the header/navigation search box, lets' first
    # look at their query to see if they have entered a valid ticket number. If
    # they have, just redirect to that ticket number. Otherwise, we treat it as
    # a keyword search.

    if request.GET.get('search_type', None) == 'header':
        query = request.GET.get('q')
        filter = None
        if query.find('-') > 0:
            try:
                queue, id = query.split('-')
                id = int(id)
            except ValueError:
                id = None

            if id:
                filter = {'queue__slug': queue, 'id': id}
        else:
            try:
                query = int(query)
            except ValueError:
                query = None

            if query:
                filter = {'id': int(query)}

        if filter:
            try:
                ticket = Ticket.objects.get(**filter)
                return HttpResponseRedirect(ticket.staff_url)
            except Ticket.DoesNotExist:
                # Go on to standard keyword searching
                pass

    saved_query = None
    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(
                pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_list'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_list'))

        try:
            import pickle
        except ImportError:
            import cPickle as pickle
        from helpdesk.lib import b64decode
        query_params = pickle.loads(b64decode(str(saved_query.query)))
    elif not ('queue' in request.GET or 'assigned_to' in request.GET
              or 'status' in request.GET or 'q' in request.GET
              or 'sort' in request.GET or 'sortreverse' in request.GET):

        # Fall-back if no querying is being done, force the list to only
        # show open/reopened/resolved (not closed) cases sorted by creation
        # date.

        query_params = {
            'filtering': {
                'status__in': [1, 2, 3]
            },
            'sorting': 'created',
        }
    else:
        queues = request.GET.getlist('queue')
        if queues:
            try:
                queues = [int(q) for q in queues]
                query_params['filtering']['queue__id__in'] = queues
            except ValueError:
                pass

        owners = request.GET.getlist('assigned_to')
        if owners:
            try:
                owners = [int(u) for u in owners]
                query_params['filtering']['assigned_to__id__in'] = owners
            except ValueError:
                pass

        statuses = request.GET.getlist('status')
        if statuses:
            try:
                statuses = [int(s) for s in statuses]
                query_params['filtering']['status__in'] = statuses
            except ValueError:
                pass

        types = request.GET.getlist('types')
        if types:
            try:
                types = [int(s) for s in types]
                query_params['filtering']['type__in'] = types
            except ValueError:
                pass

        date_from = request.GET.get('date_from')
        if date_from:
            query_params['filtering']['created__gte'] = date_from

        date_to = request.GET.get('date_to')
        if date_to:
            query_params['filtering']['created__lte'] = date_to

        ### KEYWORD SEARCHING
        q = request.GET.get('q', None)

        if q:
            qset = (Q(title__icontains=q) | Q(description__icontains=q)
                    | Q(resolution__icontains=q)
                    | Q(submitter_email__icontains=q))
            context = dict(context, query=q)

            query_params['other_filter'] = qset

        ### SORTING
        sort = request.GET.get('sort', None)
        if sort not in ('status', 'assigned_to', 'created', 'title', 'queue',
                        'priority'):
            sort = 'created'
        query_params['sorting'] = sort

        sortreverse = request.GET.get('sortreverse', None)
        query_params['sortreverse'] = sortreverse

    tickets = Ticket.objects.select_related()
    queue_choices = Queue.objects.all()

    try:
        ticket_qs = apply_query(tickets, query_params)
    except ValidationError:
        # invalid parameters in query, return default query
        query_params = {
            'filtering': {
                'status__in': [1, 2, 3]
            },
            'sorting': 'created',
        }
        ticket_qs = apply_query(tickets, query_params)

    ticket_paginator = paginator.Paginator(ticket_qs, 20)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        tickets = ticket_paginator.page(page)
    except (paginator.EmptyPage, paginator.InvalidPage):
        tickets = ticket_paginator.page(ticket_paginator.num_pages)

    search_message = ''

    from helpdesk.lib import b64encode

    try:
        import pickle
    except ImportError:
        import cPickle as pickle
    urlsafe_query = b64encode(pickle.dumps(query_params))

    user_saved_queries = SavedSearch.objects.filter(
        Q(user=request.user) | Q(shared__exact=True))

    querydict = request.GET.copy()
    querydict.pop('page', 1)

    print "TICKET TYPES:"
    print Ticket.TICKET_TYPE

    return render_to_response(
        'helpdesk/public_ticket_list.html',
        RequestContext(
            request,
            dict(
                context,
                query_string=querydict.urlencode(),
                tickets=tickets,
                user_choices=User.objects.filter(is_active=True,
                                                 is_staff=True),
                queue_choices=queue_choices,
                status_choices=Ticket.STATUS_CHOICES,
                type_choices=Ticket.TICKET_TYPE,
                urlsafe_query=urlsafe_query,
                user_saved_queries=user_saved_queries,
                query_params=query_params,
                from_saved_query=from_saved_query,
                saved_query=saved_query,
                search_message=search_message,
            )))
Ejemplo n.º 11
0
def public_ticket_list(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect(reverse('login'))
    context = {}

    # Query_params will hold a dictionary of parameters relating to
    # a query, to be saved if needed:
    query_params = {
        'filtering': {},
        'sorting': None,
        'sortreverse': True,
        'keyword': None,
        'other_filter': None,
        }

    from_saved_query = False

    # If the user is coming from the header/navigation search box, lets' first
    # look at their query to see if they have entered a valid ticket number. If
    # they have, just redirect to that ticket number. Otherwise, we treat it as
    # a keyword search.

    if request.GET.get('search_type', None) == 'header':
        query = request.GET.get('q')
        filter = None
        if query.find('-') > 0:
            try:
                queue, id = query.split('-')
                id = int(id)
            except ValueError:
                id = None

            if id:
                filter = {'queue__slug': queue, 'id': id }
        else:
            try:
                query = int(query)
            except ValueError:
                query = None

            if query:
                filter = {'id': int(query) }

        if filter:
            try:
                ticket = Ticket.objects.get(**filter)
                return HttpResponseRedirect(ticket.staff_url)
            except Ticket.DoesNotExist:
                # Go on to standard keyword searching
                pass

    saved_query = None
    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_list'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_list'))

        try:
            import pickle
        except ImportError:
            import cPickle as pickle
        from helpdesk.lib import b64decode
        query_params = pickle.loads(b64decode(str(saved_query.query)))
    elif not (  'queue' in request.GET
            or  'assigned_to' in request.GET
            or  'status' in request.GET
            or  'q' in request.GET
            or  'sort' in request.GET
            or  'sortreverse' in request.GET
                ):

        # Fall-back if no querying is being done, force the list to only
        # show open/reopened/resolved (not closed) cases sorted by creation
        # date.

        query_params = {
            'filtering': {'status__in': [1, 2, 3]},
            'sorting': 'created',
        }
    else:
        queues = request.GET.getlist('queue')
        if queues:
            try:
                queues = [int(q) for q in queues]
                query_params['filtering']['queue__id__in'] = queues
            except ValueError:
                pass

        owners = request.GET.getlist('assigned_to')
        if owners:
            try:
                owners = [int(u) for u in owners]
                query_params['filtering']['assigned_to__id__in'] = owners
            except ValueError:
                pass

        statuses = request.GET.getlist('status')
        if statuses:
            try:
                statuses = [int(s) for s in statuses]
                query_params['filtering']['status__in'] = statuses
            except ValueError:
                pass

        types = request.GET.getlist('types')
        if types:
            try:
                types = [int(s) for s in types]
                query_params['filtering']['type__in'] = types
            except ValueError:
                pass

        date_from = request.GET.get('date_from')
        if date_from:
            query_params['filtering']['created__gte'] = date_from

        date_to = request.GET.get('date_to')
        if date_to:
            query_params['filtering']['created__lte'] = date_to

        ### KEYWORD SEARCHING
        q = request.GET.get('q', None)

        if q:
            qset = (
                Q(title__icontains=q) |
                Q(description__icontains=q) |
                Q(resolution__icontains=q) |
                Q(submitter_email__icontains=q)
            )
            context = dict(context, query=q)

            query_params['other_filter'] = qset

        ### SORTING
        sort = request.GET.get('sort', None)
        if sort not in ('status', 'assigned_to', 'created', 'title', 'queue', 'priority'):
            sort = 'created'
        query_params['sorting'] = sort

        sortreverse = request.GET.get('sortreverse', None)
        query_params['sortreverse'] = sortreverse

    tickets = Ticket.objects.select_related()
    queue_choices = Queue.objects.all()


    try:
        ticket_qs = apply_query(tickets, query_params)
    except ValidationError:
        # invalid parameters in query, return default query
        query_params = {
            'filtering': {'status__in': [1, 2, 3]},
            'sorting': 'created',
        }
        ticket_qs = apply_query(tickets, query_params)

    ticket_paginator = paginator.Paginator(ticket_qs, 20)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    try:
        tickets = ticket_paginator.page(page)
    except (paginator.EmptyPage, paginator.InvalidPage):
        tickets = ticket_paginator.page(ticket_paginator.num_pages)

    search_message = ''

    from helpdesk.lib import b64encode

    try:
        import pickle
    except ImportError:
        import cPickle as pickle
    urlsafe_query = b64encode(pickle.dumps(query_params))

    user_saved_queries = SavedSearch.objects.filter(Q(user=request.user) | Q(shared__exact=True))

    querydict = request.GET.copy()
    querydict.pop('page', 1)

    print "TICKET TYPES:"
    print Ticket.TICKET_TYPE

    return render_to_response('helpdesk/public_ticket_list.html',
        RequestContext(request, dict(
            context,
            query_string=querydict.urlencode(),
            tickets=tickets,
            user_choices=User.objects.filter(is_active=True,is_staff=True),
            queue_choices=queue_choices,
            status_choices=Ticket.STATUS_CHOICES,
            type_choices=Ticket.TICKET_TYPE,
            urlsafe_query=urlsafe_query,
            user_saved_queries=user_saved_queries,
            query_params=query_params,
            from_saved_query=from_saved_query,
            saved_query=saved_query,
            search_message=search_message,
        )))
Ejemplo n.º 12
0
def ticket_list(request):
    context = {}

    # Query_params will hold a dictionary of parameters relating to
    # a query, to be saved if needed:
    query_params = {"filtering": {}, "sorting": None, "sortreverse": False, "keyword": None, "other_filter": None}

    from_saved_query = False

    # If the user is coming from the header/navigation search box, lets' first
    # look at their query to see if they have entered a valid ticket number. If
    # they have, just redirect to that ticket number. Otherwise, we treat it as
    # a keyword search.

    if request.GET.get("search_type", None) == "header":
        query = request.GET.get("q")
        filter = None
        if query.find("-") > 0:
            try:
                queue, id = query.split("-")
                id = int(id)
            except ValueError:
                id = None

            if id:
                filter = {"queue__slug": queue, "id": id}
        else:
            try:
                query = int(query)
            except ValueError:
                query = None

            if query:
                filter = {"id": int(query)}

        if filter:
            try:
                ticket = Ticket.objects.get(**filter)
                return HttpResponseRedirect(ticket.staff_url)
            except Ticket.DoesNotExist:
                # Go on to standard keyword searching
                pass

    saved_query = None
    if request.GET.get("saved_query", None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get("saved_query"))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse("helpdesk_list"))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse("helpdesk_list"))

        import cPickle
        from helpdesk.lib import b64decode

        query_params = cPickle.loads(b64decode(str(saved_query.query)))
    elif not (
        request.GET.has_key("queue")
        or request.GET.has_key("assigned_to")
        or request.GET.has_key("status")
        or request.GET.has_key("q")
        or request.GET.has_key("sort")
        or request.GET.has_key("sortreverse")
        or request.GET.has_key("tags")
    ):

        # Fall-back if no querying is being done, force the list to only
        # show open/reopened/resolved (not closed) cases sorted by creation
        # date.

        query_params = {"filtering": {"status__in": [1, 2, 3]}, "sorting": "created"}
    else:
        queues = request.GET.getlist("queue")
        if queues:
            try:
                queues = [int(q) for q in queues]
                query_params["filtering"]["queue__id__in"] = queues
            except ValueError:
                pass

        owners = request.GET.getlist("assigned_to")
        if owners:
            try:
                owners = [int(u) for u in owners]
                query_params["filtering"]["assigned_to__id__in"] = owners
            except ValueError:
                pass

        statuses = request.GET.getlist("status")
        if statuses:
            try:
                statuses = [int(s) for s in statuses]
                query_params["filtering"]["status__in"] = statuses
            except ValueError:
                pass

        date_from = request.GET.get("date_from")
        if date_from:
            query_params["filtering"]["created__gte"] = date_from

        date_to = request.GET.get("date_to")
        if date_to:
            query_params["filtering"]["created__lte"] = date_to

        ### KEYWORD SEARCHING
        q = request.GET.get("q", None)

        if q:
            qset = (
                Q(title__icontains=q)
                | Q(description__icontains=q)
                | Q(resolution__icontains=q)
                | Q(submitter_email__icontains=q)
            )
            context = dict(context, query=q)

            query_params["other_filter"] = qset

        ### SORTING
        sort = request.GET.get("sort", None)
        if sort not in ("status", "assigned_to", "created", "title", "queue", "priority"):
            sort = "created"
        query_params["sorting"] = sort

        sortreverse = request.GET.get("sortreverse", None)
        query_params["sortreverse"] = sortreverse

    try:
        ticket_qs = apply_query(Ticket.objects.select_related(), query_params)
    except ValidationError:
        # invalid parameters in query, return default query
        query_params = {"filtering": {"status__in": [1, 2, 3]}, "sorting": "created"}
        ticket_qs = apply_query(Ticket.objects.select_related(), query_params)

    ## TAG MATCHING
    if HAS_TAG_SUPPORT:
        tags = request.GET.getlist("tags")
        if tags:
            ticket_qs = TaggedItem.objects.get_by_model(ticket_qs, tags)
            query_params["tags"] = tags

    ticket_paginator = paginator.Paginator(ticket_qs, request.user.usersettings.settings.get("tickets_per_page") or 20)
    try:
        page = int(request.GET.get("page", "1"))
    except ValueError:
        page = 1

    try:
        tickets = ticket_paginator.page(page)
    except (paginator.EmptyPage, paginator.InvalidPage):
        tickets = ticket_paginator.page(ticket_paginator.num_pages)

    search_message = ""
    if context.has_key("query") and settings.DATABASES["default"]["ENGINE"].endswith("sqlite"):
        search_message = _(
            '<p><strong>Note:</strong> Your keyword search is case sensitive because of your database. This means the search will <strong>not</strong> be accurate. By switching to a different database system you will gain better searching! For more information, read the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching">Django Documentation on string matching in SQLite</a>.'
        )

    import cPickle
    from helpdesk.lib import b64encode

    urlsafe_query = b64encode(cPickle.dumps(query_params))

    user_saved_queries = SavedSearch.objects.filter(Q(user=request.user) | Q(shared__exact=True))

    querydict = request.GET.copy()
    querydict.pop("page", 1)

    tag_choices = []
    if HAS_TAG_SUPPORT:
        # FIXME: restrict this to tags that are actually in use
        tag_choices = Tag.objects.all()

    return render_to_response(
        "helpdesk/ticket_list.html",
        RequestContext(
            request,
            dict(
                context,
                query_string=querydict.urlencode(),
                tickets=tickets,
                user_choices=User.objects.filter(is_active=True, is_staff=True),
                queue_choices=Queue.objects.all(),
                status_choices=Ticket.STATUS_CHOICES,
                tag_choices=tag_choices,
                urlsafe_query=urlsafe_query,
                user_saved_queries=user_saved_queries,
                query_params=query_params,
                from_saved_query=from_saved_query,
                saved_query=saved_query,
                search_message=search_message,
                tags_enabled=HAS_TAG_SUPPORT,
            ),
        ),
    )
Ejemplo n.º 13
0
def run_report(request, report):
    if Ticket.objects.all().count() == 0 or report not in ('queuemonth', 'usermonth', 'queuestatus', 'queuepriority', 'userstatus', 'userpriority', 'userqueue', 'daysuntilticketclosedbymonth'):
        return HttpResponseRedirect(reverse("helpdesk_report_index"))

    report_queryset = Ticket.objects.all().select_related().filter(
        queue__in=_get_user_queues(request.user)
    )

    from_saved_query = False
    saved_query = None

    if request.GET.get('saved_query', None):
        from_saved_query = True
        try:
            saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
        except SavedSearch.DoesNotExist:
            return HttpResponseRedirect(reverse('helpdesk_report_index'))
        if not (saved_query.shared or saved_query.user == request.user):
            return HttpResponseRedirect(reverse('helpdesk_report_index'))

        try:
            import pickle
        except ImportError:
            import cPickle as pickle
        from helpdesk.lib import b64decode
        query_params = pickle.loads(b64decode(str(saved_query.query)))
        report_queryset = apply_query(report_queryset, query_params)

    from collections import defaultdict
    summarytable = defaultdict(int)
    # a second table for more complex queries
    summarytable2 = defaultdict(int)

    month_name = lambda m: MONTHS_3[m].title()

    first_ticket = Ticket.objects.all().order_by('created')[0]
    first_month = first_ticket.created.month
    first_year = first_ticket.created.year

    last_ticket = Ticket.objects.all().order_by('-created')[0]
    last_month = last_ticket.created.month
    last_year = last_ticket.created.year

    periods = []
    year, month = first_year, first_month
    working = True
    periods.append("%s %s" % (month_name(month), year))

    while working:
        month += 1
        if month > 12:
            year += 1
            month = 1
        if (year > last_year) or (month > last_month and year >= last_year):
            working = False
        periods.append("%s %s" % (month_name(month), year))

    if report == 'userpriority':
        title = _('User by Priority')
        col1heading = _('User')
        possible_options = [t[1].title() for t in Ticket.PRIORITY_CHOICES]
        charttype = 'bar'

    elif report == 'userqueue':
        title = _('User by Queue')
        col1heading = _('User')
        queue_options = _get_user_queues(request.user)
        possible_options = [q.title for q in queue_options]
        charttype = 'bar'

    elif report == 'userstatus':
        title = _('User by Status')
        col1heading = _('User')
        possible_options = [s[1].title() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'usermonth':
        title = _('User by Month')
        col1heading = _('User')
        possible_options = periods
        charttype = 'date'

    elif report == 'queuepriority':
        title = _('Queue by Priority')
        col1heading = _('Queue')
        possible_options = [t[1].title() for t in Ticket.PRIORITY_CHOICES]
        charttype = 'bar'

    elif report == 'queuestatus':
        title = _('Queue by Status')
        col1heading = _('Queue')
        possible_options = [s[1].title() for s in Ticket.STATUS_CHOICES]
        charttype = 'bar'

    elif report == 'queuemonth':
        title = _('Queue by Month')
        col1heading = _('Queue')
        possible_options = periods
        charttype = 'date'

    elif report == 'daysuntilticketclosedbymonth':
        title = _('Days until ticket closed by Month')
        col1heading = _('Queue')
        possible_options = periods
        charttype = 'date'

    metric3 = False
    for ticket in report_queryset:
        if report == 'userpriority':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'userqueue':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.queue.title

        elif report == 'userstatus':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'usermonth':
            metric1 = u'%s' % ticket.get_assigned_to
            metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)

        elif report == 'queuepriority':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_priority_display()

        elif report == 'queuestatus':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s' % ticket.get_status_display()

        elif report == 'queuemonth':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)

        elif report == 'daysuntilticketclosedbymonth':
            metric1 = u'%s' % ticket.queue.title
            metric2 = u'%s %s' % (month_name(ticket.created.month), ticket.created.year)
            metric3 = ticket.modified - ticket.created
            metric3 = metric3.days

        summarytable[metric1, metric2] += 1
        if metric3:
            if report == 'daysuntilticketclosedbymonth':
                summarytable2[metric1, metric2] += metric3

    table = []

    if report == 'daysuntilticketclosedbymonth':
        for key in summarytable2.keys():
            summarytable[key] = summarytable2[key] / summarytable[key]

    header1 = sorted(set(list(i for i, _ in summarytable.keys())))

    column_headings = [col1heading] + possible_options

    # Pivot the data so that 'header1' fields are always first column
    # in the row, and 'possible_options' are always the 2nd - nth columns.
    for item in header1:
        data = []
        for hdr in possible_options:
            data.append(summarytable[item, hdr])
        table.append([item] + data)

    return render_to_response('helpdesk/report_output.html',
        RequestContext(request, {
            'title': title,
            'charttype': charttype,
            'data': table,
            'headings': column_headings,
            'from_saved_query': from_saved_query,
            'saved_query': saved_query,
        }))
Ejemplo n.º 14
0
    def get_queryset(self):
      request = self.request
      context = {}
      query_params = {
          'filtering': {},
          'sorting': None,
          'sortreverse': False,
          'keyword': None,
          'other_filter': None,
          }

      if request.GET.get('saved_query', None):
          self.from_saved_query = True
          try:
              self.saved_query = SavedSearch.objects.get(pk=request.GET.get('saved_query'))
          except SavedSearch.DoesNotExist:
              return HttpResponseRedirect(reverse('helpdesk_ticket_list'))
          if not (self.saved_query.shared or self.saved_query.user_id == request.user.id):
              return HttpResponseRedirect(reverse('helpdesk_ticket_list'))

          try:
              import pickle
          except ImportError:
              import cPickle as pickle
          from helpdesk.lib import b64decode
          query_params = pickle.loads(b64decode(str(self.saved_query.query)))
      elif not (  'queue' in request.GET
              or  'assigned_to' in request.GET
              or  'status' in request.GET
              or  'q' in request.GET
              or  'sort' in request.GET
              or  'sortreverse' in request.GET
                  ):

          # Fall-back if no querying is being done, force the list to only
          # show open/reopened/resolved (not closed) cases sorted by creation
          # date.

          query_params = {
              'filtering': {'status__in': [1, 2, 3]},
              'sorting': 'created',
          }
      else:
          queues = request.GET.getlist('queue')
          if queues:
              try:
                  queues = [int(q) for q in queues]
                  query_params['filtering']['queue__id__in'] = queues
              except ValueError:
                  pass

          owners = request.GET.getlist('assigned_to')
          if owners:
              try:
                  owners = [int(u) for u in owners]
                  query_params['filtering']['assigned_to__id__in'] = owners
              except ValueError:
                  pass

          statuses = request.GET.getlist('status')
          if statuses:
              try:
                  statuses = [int(s) for s in statuses]
                  query_params['filtering']['status__in'] = statuses
              except ValueError:
                  pass

          date_from = request.GET.get('date_from')
          if date_from:
              query_params['filtering']['created__gte'] = date_from

          date_to = request.GET.get('date_to')
          if date_to:
              query_params['filtering']['created__lte'] = date_to

          ### KEYWORD SEARCHING
          q = request.GET.get('q', None)

          if q:
              qset = (
                  Q(title__icontains=q) |
                  Q(description__icontains=q) |
                  Q(resolution__icontains=q) |
                  Q(submitter_email__icontains=q)
              )
              context = dict(context, query=q)

              query_params['other_filter'] = qset

          ### SORTING
          sort = request.GET.get('sort', None)
          if sort not in ('status', 'assigned_to', 'created', 'title', 'queue', 'priority'):
              sort = 'created'
          query_params['sorting'] = sort

          sortreverse = request.GET.get('sortreverse', None)
          query_params['sortreverse'] = sortreverse

      # ToDo
      # Make permission check
      tickets = Ticket.objects.filter().select_related()

      try:
          ticket_qs = apply_query(tickets, query_params)
      except ValidationError:
          # invalid parameters in query, return default query
          query_params = {
              'filtering': {'status__in': [1, 2, 3]},
              'sorting': 'created',
          }
          ticket_qs = apply_query(tickets, query_params)

      """
      ticket_paginator = paginator.Paginator(ticket_qs, request.user.usersettings.settings.get('tickets_per_page') or 20)
      try:
          page = int(request.GET.get('page', '1'))
      except ValueError:
           page = 1

      try:
          tickets = ticket_paginator.page(page)
      except (paginator.EmptyPage, paginator.InvalidPage):
          tickets = ticket_paginator.page(ticket_paginator.num_pages)
      """
      tickets = ticket_qs

      if 'query' in context and settings.DATABASES['default']['ENGINE'].endswith('sqlite'):
          self.search_message = _('<p><strong>Note:</strong> Your keyword search is case sensitive because of your database. This means the search will <strong>not</strong> be accurate. By switching to a different database system you will gain better searching! For more information, read the <a href="http://docs.djangoproject.com/en/dev/ref/databases/#sqlite-string-matching">Django Documentation on string matching in SQLite</a>.')

      try:
          import pickle
      except ImportError:
          import cPickle as pickle
      from helpdesk.lib import b64encode
      self.urlsafe_query = b64encode(pickle.dumps(query_params))
      self.query_params = query_params

      self.user_saved_queries = SavedSearch.objects.filter(Q(user_id=request.user.id) | Q(shared__exact=True))
      return tickets