示例#1
0
def table(request, **kwargs):
    search_params = {}
    mod_path, cls_name = settings.TICKET_CLASS.rsplit('.', 1)
    mod_path = mod_path.split('.').pop(0)
    tic = get_model(mod_path, cls_name).objects.select_related('type').all()

    if not request.user.is_staff:
        tic = tic.filter(customer=request.organisation)

    if 'search' in kwargs:
        is_search = True
        params = kwargs['search']

        if not request.user.is_staff:
            used_fields = []
            for ele in settings.TICKET_SEARCH_FIELDS:
                if not ele in settings.TICKET_NON_PUBLIC_FIELDS:
                    used_fields.append(ele)
        else:
            used_fields = settings.TICKET_SEARCH_FIELDS

        Qr = None
        fulltext = {}
        for field in params:
            if field == 'fulltext':
                if field in used_fields and get_ticket_model()._meta.get_field(field).get_internal_type() == 'CharField':
                    fulltext['%s__icontains' % field] = params[field]

            else:
                if params[field] != None and params[field] != '':
                    if get_ticket_model()._meta.get_field(field).get_internal_type() == 'CharField':
                        search_params['%s__icontains' % field] = params[field]
                    else:
                        search_params[field] = params[field]

        tic = tic.filter(**search_params)
    else:
        tic = tic.filter(closed=False)
        is_search = False

    pretty = prettyValues(search_params)
    list_caption = kwargs.get('list_caption')
    if 'report' in request.GET:
        list_caption = tickets_reports.objects.get(pk=request.GET['report']).name

    paginator = Paginator(tic, 20)
    page = request.GET.get('page')
    try:
        tic_lines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        tic_lines = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        tic_lines = paginator.page(paginator.num_pages)

    board_form = AddToBordForm()
    board_form.fields['board'].queryset = board_form.fields['board'].queryset.filter(c_user=request.user)

    return render_to_response('tickets/list.html', {'lines': tic_lines, 'is_search': is_search, 'pretty': pretty, 'list_caption': list_caption, 'board_form': board_form}, RequestContext(request))
示例#2
0
    def forwards(self, orm):
        user = User.objects.all()[0]

        tickets = get_ticket_model().objects.all()
        for tic in tickets:
            """
            possible changes:
            - ticket
            - comments
            - files
            """
            last_action_date = tic.u_date
            if tickets_comments.objects.filter(ticket=tic.id).count() > 0:
                last_action_date = max(
                    tickets_comments.objects.filter(
                        ticket=tic.id).order_by('c_date').last().c_date,
                    last_action_date)
            if tickets_files.objects.filter(ticket=tic.id).count() > 0:
                last_action_date = max(
                    tickets_files.objects.filter(
                        ticket=tic.id).order_by('c_date').last().c_date,
                    last_action_date)
            tic.last_action_date = last_action_date
            tic.save(user=user)

        tickets = get_ticket_model().objects.filter(closed=True)
        for tic in tickets:
            tic.close_date = tic.u_date
            tic.save(user=user)
示例#3
0
def createSimple(attributes={}, notify=True, **kwargs):
    from yats.forms import SimpleTickets

    request = kwargs['request']
    params = {}
    for key, value in attributes.iteritems():
        params[TracNameTofieldName(key)] = value

    fakePOST = QueryDict(mutable=True)
    fakePOST.update(params)

    form = SimpleTickets(fakePOST)
    if form.is_valid():
        cd = form.cleaned_data
        ticket = get_ticket_model()
        tic = ticket()
        tic.caption = cd['caption']
        tic.description = cd['description']
        if 'priority' not in cd or not cd['priority']:
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_PRIORITY'
                       ) and settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY:
                tic.priority_id = settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY
        else:
            tic.priority = cd['priority']
        tic.assigned = cd['assigned']
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER'
                   ) and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                tic.customer = request.organisation
            else:
                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT'
                   ) and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
        tic.deadline = cd['deadline']
        tic.save(user=request.user)

        if tic.assigned:
            touch_ticket(tic.assigned, tic.pk)

        for ele in form.changed_data:
            form.initial[ele] = ''
        remember_changes(request, form, tic)

        touch_ticket(request.user, tic.pk)

        if notify:
            mail_ticket(request,
                        tic.pk,
                        form,
                        rcpt=settings.TICKET_NEW_MAIL_RCPT)
            jabber_ticket(request,
                          tic.pk,
                          form,
                          rcpt=settings.TICKET_NEW_JABBER_RCPT)

        return get(tic.id, **kwargs)

    else:
        raise Exception('missing attributes')
示例#4
0
文件: tickets.py 项目: crystal3a/yats
def table(request, **kwargs):
    search_params = {}
    tic = get_ticket_model().objects.select_related('type').all()

    if 'search' in kwargs:
        is_search = True
        search_params, tic = build_ticket_search(request, tic, search_params, kwargs['search'])

    else:
        tic = tic.filter(closed=False)
        is_search = False

    pretty = prettyValues(search_params)
    list_caption = kwargs.get('list_caption')
    if 'report' in request.GET:
        list_caption = tickets_reports.objects.get(pk=request.GET['report']).name

    paginator = Paginator(tic, 20)
    page = request.GET.get('page')
    try:
        tic_lines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        tic_lines = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        tic_lines = paginator.page(paginator.num_pages)

    board_form = AddToBordForm()
    board_form.fields['board'].queryset = board_form.fields['board'].queryset.filter(c_user=request.user)

    return render(request, 'tickets/list.html', {'lines': tic_lines, 'is_search': is_search, 'pretty': pretty, 'list_caption': list_caption, 'board_form': board_form})
示例#5
0
文件: api.py 项目: teserak/yats
def get(id, **kwargs):
    """
    array ticket.get(int id)
    """
    exclude_list = FIELD_EXCLUDE_LIST
    #exclude_list.pop(exclude_list.index('id'))
    
    request = kwargs['request']
    
    if not request.user.is_staff:
        exclude_list = list(set(exclude_list + settings.TICKET_NON_PUBLIC_FIELDS))

    ticket = get_ticket_model().objects.get(pk=id)

    attributes = {}
    for field in ticket._meta.fields:
        if field.name in exclude_list:
            continue
        if type(field).__name__ in ['DateTimeField', 'BooleanField', 'NullBooleanField']:
            attributes[fieldNameToTracName(field.name)] = getattr(ticket, field.name)
        elif type(field).__name__ == 'DateField':
            if not getattr(ticket, field.name) == None:
                attributes[fieldNameToTracName(field.name)] = datetime.datetime.combine(getattr(ticket, field.name), datetime.datetime.min.time())
            else:
                attributes[fieldNameToTracName(field.name)] = None
            
        else:
            attributes[fieldNameToTracName(field.name)] = unicode(getattr(ticket, field.name))
    return [id, ticket.c_date, ticket.last_action_date, attributes]
示例#6
0
def get(id, **kwargs):
    """
    array ticket.get(int id)
    """
    exclude_list = FIELD_EXCLUDE_LIST
    #exclude_list.pop(exclude_list.index('id'))

    request = kwargs['request']

    if not request.user.is_staff:
        exclude_list = list(set(exclude_list + settings.TICKET_NON_PUBLIC_FIELDS))

    ticket = get_ticket_model().objects.get(pk=id)

    attributes = {}
    for field in ticket._meta.fields:
        if field.name in exclude_list:
            continue
        if type(field).__name__ in ['DateTimeField', 'BooleanField', 'NullBooleanField']:
            attributes[fieldNameToTracName(field.name)] = getattr(ticket, field.name)
        elif type(field).__name__ == 'DateField':
            if not getattr(ticket, field.name) == None:
                attributes[fieldNameToTracName(field.name)] = datetime.datetime.combine(getattr(ticket, field.name), datetime.datetime.min.time())
            else:
                attributes[fieldNameToTracName(field.name)] = None

        else:
            attributes[fieldNameToTracName(field.name)] = unicode(getattr(ticket, field.name))
    return [id, ticket.c_date, ticket.last_action_date, attributes]
示例#7
0
def buildYATSFields(exclude_list):
    TracFields = []
    TicketFields = {}
    tickets = get_ticket_model()
    t = tickets()
    for field in t._meta.fields:
        if field.name in exclude_list:
            continue

        if type(field).__name__ == 'ForeignKey':
            typename = 'select'
            options = []
            opts = apps.get_model(modulePathToModuleName(field.rel.to.__module__), field.rel.to.__name__).objects.all()
            for opt in opts:
                options.append(unicode(opt))

            TicketFields[field.name] = (modulePathToModuleName(field.rel.to.__module__), field.rel.to.__name__)

        else:
            typename = field.__class__.__name__

            # TODO: bool and boolnull and choices
            options = None

            TicketFields[field.name] = None

        value = {
                'name': field.name,
                'label': field.name,
                'type': typename
               }
        if options:
            value['options'] = options
        TracFields.append(value)
    return (TracFields, TicketFields)
示例#8
0
文件: tickets.py 项目: crystal3a/yats
def simple(request):
    if request.method == 'POST':
        form = SimpleTickets(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            ticket = get_ticket_model()
            tic = ticket()
            tic.caption = cd['caption']
            tic.description = cd['description']
            tic.priority = cd['priority']
            tic.assigned = cd['assigned']
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
                if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                    tic.customer = request.organisation
                else:
                    tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
                tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
            tic.deadline = cd['deadline']
            tic.save(user=request.user)

            if tic.assigned:
                touch_ticket(tic.assigned, tic.pk)

            for ele in form.changed_data:
                form.initial[ele] = ''
            remember_changes(request, form, tic)

            touch_ticket(request.user, tic.pk)

            return HttpResponseRedirect('/tickets/view/%s/' % tic.pk)

    else:
        form = SimpleTickets(initial={'assigned': request.user.id})
    return render(request, 'tickets/new.html', {'layout': 'horizontal', 'form': form, 'mode': 'simple'})
示例#9
0
def update(id, comment, attributes={}, notify=False, **kwargs):
    """
    array ticket.update(int id, string comment, struct attributes={}, boolean notify=False)
    Update a ticket, returning the new ticket in the same form as getTicket(). Requires a valid 'action' in attributes to support workflow.
    """
    from yats.forms import TicketsForm

    request = kwargs['request']
    params = {}
    for key, value in attributes.iteritems():
        params[TracNameTofieldName(key)] = value

    ticket = get_ticket_model().objects.get(pk=id)
    if ticket.closed:
        return Fault(_('ticket already closed'))

    fakePOST = QueryDict('', mutable=True)
    fakePOST.update(params)

    form = TicketsForm(fakePOST,
                       instance=ticket,
                       is_stuff=request.user.is_staff,
                       user=request.user,
                       customer=request.organisation.id)
    form.cleaned_data = params
    form._changed_data = [name for name in params]

    for key, value in params.iteritems():
        setattr(ticket, key, value)
        if key == 'assigned':
            touch_ticket(value, ticket.pk)
    ticket.save(user=request.user)

    remember_changes(request, form, ticket)

    touch_ticket(request.user, ticket.pk)

    if comment:
        from yats.models import tickets_comments

        com = tickets_comments()
        com.comment = _('ticket changed by %(user)s\n\n%(comment)s') % {
            'user': request.user,
            'comment': comment
        }
        com.ticket = ticket
        com.action = 4
        com.save(user=request.user)

        check_references(request, com)

    if notify:
        mail_ticket(request, ticket.pk, form, is_api=True)
        jabber_ticket(request, ticket.pk, form, is_api=True)

    return get(id, **kwargs)
示例#10
0
文件: api.py 项目: visitorone/yats
def query(*args, **kwargs):
    """
    array ticket.query(string qstr="status!=closed")
    """
    request = kwargs['request']

    tickets = get_ticket_model().objects.all()
    if len(args) > 0:
        tickets = tickets.filter(**search_terms(args[0]))

    ids = tickets.values_list('id', flat=True)
    return list(ids)
示例#11
0
文件: api.py 项目: teserak/yats
def query(*args, **kwargs):
    """
    array ticket.query(string qstr="status!=closed")
    """
    request = kwargs['request']

    tickets = get_ticket_model().objects.all()
    if len(args) > 0:
        tickets =  tickets.filter(**search_terms(args[0]))
    
    ids = tickets.values_list('id', flat=True)
    return list(ids)
示例#12
0
文件: api.py 项目: mediafactory/yats
def createSimple(attributes={}, notify=True, **kwargs):
    from yats.forms import SimpleTickets

    request = kwargs['request']
    params = {}
    for key, value in attributes.iteritems():
        params[TracNameTofieldName(key)] = value

    fakePOST = QueryDict(mutable=True)
    fakePOST.update(params)

    form = SimpleTickets(fakePOST)
    if form.is_valid():
        cd = form.cleaned_data
        ticket = get_ticket_model()
        tic = ticket()
        tic.caption = cd['caption']
        tic.description = cd['description']
        if 'priority' not in cd or not cd['priority']:
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_PRIORITY') and settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY:
                tic.priority_id = settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY
        else:
            tic.priority = cd['priority']
        tic.assigned = cd['assigned']
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                tic.customer = request.organisation
            else:
                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
        tic.deadline = cd['deadline']
        tic.show_start = cd['show_start']
        tic.save(user=request.user)

        if tic.assigned:
            touch_ticket(tic.assigned, tic.pk)

        for ele in form.changed_data:
            form.initial[ele] = ''
        remember_changes(request, form, tic)

        touch_ticket(request.user, tic.pk)

        if notify:
            mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT)
            jabber_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_JABBER_RCPT)

        return get(tic.id, **kwargs)

    else:
        raise Exception('missing attributes')
示例#13
0
    def last_modified(self):
        try:
            request = self._getRequestFromUrl(self.path)
            rep = tickets_reports.objects.get(active_record=True, pk=self._getReportFromUrl(self.path))
            tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
            search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))
            date = tic.latest('u_date')
            return datetime.strftime(
                date.last_action_date, '%a, %d %b %Y %H:%M:%S %z')

        except Exception:
            import sys
            a = sys.exc_info()
示例#14
0
    def forwards(self, orm):
        user = User.objects.all()[0]
        
        tickets = get_ticket_model().objects.all()
        for tic in tickets:
            """
            possible changes:
            - ticket
            - comments
            - files
            """
            last_action_date = tic.u_date
            if tickets_comments.objects.filter(ticket=tic.id).count() > 0:
                last_action_date = max(tickets_comments.objects.filter(ticket=tic.id).order_by('c_date').last().c_date, last_action_date)
            if tickets_files.objects.filter(ticket=tic.id).count() > 0:
                last_action_date = max(tickets_files.objects.filter(ticket=tic.id).order_by('c_date').last().c_date, last_action_date)
            tic.last_action_date = last_action_date
            tic.save(user=user)

        tickets = get_ticket_model().objects.filter(closed=True)
        for tic in tickets:
            tic.close_date = tic.u_date
            tic.save(user=user)
示例#15
0
文件: api.py 项目: mediafactory/yats
def update(id, comment, attributes={}, notify=False, **kwargs):
    """
    array ticket.update(int id, string comment, struct attributes={}, boolean notify=False)
    Update a ticket, returning the new ticket in the same form as getTicket(). Requires a valid 'action' in attributes to support workflow.
    """
    from yats.forms import TicketsForm

    request = kwargs['request']
    params = {}
    for key, value in attributes.iteritems():
        params[TracNameTofieldName(key)] = value

    ticket = get_ticket_model().objects.get(pk=id)
    if ticket.closed:
        return Fault(_('ticket already closed'))

    fakePOST = QueryDict('', mutable=True)
    fakePOST.update(params)

    form = TicketsForm(fakePOST, instance=ticket, is_stuff=request.user.is_staff, user=request.user, customer=request.organisation.id)
    form.cleaned_data = params
    form._changed_data = [name for name in params]

    for key, value in params.iteritems():
        setattr(ticket, key, value)
        if key == 'assigned':
            touch_ticket(value, ticket.pk)
    ticket.save(user=request.user)

    remember_changes(request, form, ticket)

    touch_ticket(request.user, ticket.pk)

    if comment:
        from yats.models import tickets_comments

        com = tickets_comments()
        com.comment = _('ticket changed by %(user)s\n\n%(comment)s') % {'user': request.user, 'comment': comment}
        com.ticket = ticket
        com.action = 4
        com.save(user=request.user)

        check_references(request, com)

    if notify:
        mail_ticket(request, ticket.pk, form, is_api=True)
        jabber_ticket(request, ticket.pk, form, is_api=True)

    return get(id, **kwargs)
示例#16
0
def simple(request):
    if request.method == 'POST':
        form = SimpleTickets(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            ticket = get_ticket_model()
            tic = ticket()
            tic.caption = cd['caption']
            tic.description = cd['description'].replace(u"\u00A0", " ")
            tic.priority = cd['priority']
            tic.assigned = cd['assigned']
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
                if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                    tic.customer = request.organisation
                else:
                    tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
            tic.component = cd['component']
            if not tic.component_id and hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
                tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
            tic.deadline = cd['deadline']
            tic.show_start = cd['show_start']
            tic.save(user=request.user)

            if tic.assigned:
                touch_ticket(tic.assigned, tic.pk)

            for ele in form.changed_data:
                form.initial[ele] = ''
            remember_changes(request, form, tic)

            touch_ticket(request.user, tic.pk)

            mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT)
            jabber_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_JABBER_RCPT)
            signal_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_SIGNAL_RCPT)

            return HttpResponseRedirect('/tickets/view/%s/' % tic.pk)

    else:
        if request.user.is_staff:
            initial = {'assigned': request.user.id}
        else:
            initial = {}
        form = SimpleTickets(initial=initial)
    return render(request, 'tickets/new.html', {'layout': 'horizontal', 'form': form, 'mode': 'simple'})
示例#17
0
def simple(request):
    if request.method == 'POST':
        form = SimpleTickets(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            ticket = get_ticket_model()
            tic = ticket()
            tic.caption = cd['caption']
            tic.description = cd['description'].replace(u"\u00A0", " ")
            tic.priority = cd['priority']
            tic.assigned = cd['assigned']
            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
                if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                    tic.customer = request.organisation
                else:
                    tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
            tic.component = cd['component']
            if not tic.component_id and hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
                tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
            tic.deadline = cd['deadline']
            tic.show_start = cd['show_start']
            tic.save(user=request.user)

            if tic.assigned:
                touch_ticket(tic.assigned, tic.pk)

            for ele in form.changed_data:
                form.initial[ele] = ''
            remember_changes(request, form, tic)

            touch_ticket(request.user, tic.pk)

            mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT)
            jabber_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_JABBER_RCPT)

            return HttpResponseRedirect('/tickets/view/%s/' % tic.pk)

    else:
        if request.user.is_staff:
            initial = {'assigned': request.user.id}
        else:
            initial = {}
        form = SimpleTickets(initial=initial)
    return render(request, 'tickets/new.html', {'layout': 'horizontal', 'form': form, 'mode': 'simple'})
示例#18
0
    def items(self):
        itms = {}
        try:
            request = self._getRequestFromUrl(self.path)
            if self.path == request.user.username:
                return itms
            rep = tickets_reports.objects.get(active_record=True, pk=self._getReportFromUrl(self.path))
            tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
            search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))

            for item in tic:
                text = self._itemToICal(item)
                itms.update(self._parse(text, ICAL_TYPES))

        except Exception:
            import sys
            a = sys.exc_info()

        return itms
示例#19
0
def kanban(request):
    flows = ticket_flow.objects.all().order_by('type')
    columns = []
    finish_state = -1
    days = UserProfile.objects.get(user=request.user).day_since_closed_tickets

    query = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()

    for flow in flows:
        search_params, flow.data = build_ticket_search_ext(request, query, convert_sarch({'state': flow.pk}))
        flow.data = flow.data.filter(Q(show_start=None) | Q(show_start__lte=timezone.now()))

        if flow.type == 2:
            flow.data = flow.data.filter(Q(assigned=None) | Q(assigned=request.user)).order_by('-close_date')
        else:
            flow.data = flow.data.filter(Q(assigned=None) | Q(assigned=request.user)).extra(select={'prio': 'COALESCE(caldav, 10)'}, order_by=['prio', '-c_date'])

        if flow.type == 1:
            columns.insert(0, flow)
        else:
            columns.append(flow)
            if flow.type == 2:
                finish_state = flow.pk
                flow.data = flow.data.filter(close_date__gte=datetime.date.today() - datetime.timedelta(days=days))

        seen_elements = {}
        seen = tickets_participants.objects.filter(user=request.user, ticket__in=flow.data.values_list('id', flat=True)).values_list('ticket_id', 'seen')
        for see in seen:
            seen_elements[see[0]] = see[1]

        seen = tickets_ignorants.objects.filter(user=request.user, ticket__in=flow.data.values_list('id', flat=True)).values_list('ticket_id')
        for see in seen:
            seen_elements[see[0]] = True

        flow.seen = seen_elements

    close = TicketCloseForm()
    reassign = TicketReassignForm()
    edges = ticket_flow_edges.objects.all().order_by('now')
    add_breadcrumbs(request, 0, 'k')
    cur_language = translation.get_language()
    return render(request, 'board/kanban.html', {'layout': 'horizontal', 'columns': columns, 'edges': edges, 'finish_state': finish_state, 'close': close, 'reassign': reassign, 'cur_language': cur_language})
示例#20
0
    def is_leaf(cls, path):
        """Return ``True`` if relative ``path`` is a leaf.

        A leaf is a WebDAV collection whose members are not collections.

        """
        result = False
        if '.ics' in path:
            try:
                request = cls._getRequestFromUrl(path)
                rep = tickets_reports.objects.get(active_record=True, pk=cls._getReportFromUrl(path))
                tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
                search_params, tic = build_ticket_search_ext(request, tic, json.loads(rep.search))

                result = (tic.exists())

            except Exception:
                import sys
                a = sys.exc_info()

        return result
示例#21
0
文件: views.py 项目: lou-viannay/yats
def kanban(request):
    flows = ticket_flow.objects.all().order_by('type')
    columns = []
    finish_state = -1
    days = UserProfile.objects.get(user=request.user).day_since_closed_tickets

    query = get_ticket_model().objects.select_related('type', 'state',
                                                      'assigned', 'priority',
                                                      'customer').all()

    for flow in flows:
        search_params, flow.data = build_ticket_search_ext(
            request, query, convert_sarch({'state': flow.pk}))
        flow.data = flow.data.filter(
            Q(show_start=None) | Q(show_start__lte=timezone.now()))

        if flow.type == 2:
            flow.data = flow.data.filter(
                Q(assigned=None)
                | Q(assigned=request.user)).order_by('-close_date')
        else:
            flow.data = flow.data.filter(
                Q(assigned=None) | Q(assigned=request.user)).extra(
                    select={'prio': 'COALESCE(caldav, 10)'},
                    order_by=['prio', '-c_date'])

        if flow.type == 1:
            columns.insert(0, flow)
        else:
            columns.append(flow)
            if flow.type == 2:
                finish_state = flow.pk
                flow.data = flow.data.filter(
                    close_date__gte=datetime.date.today() -
                    datetime.timedelta(days=days))

        seen_elements = {}
        seen = tickets_participants.objects.filter(
            user=request.user,
            ticket__in=flow.data.values_list('id', flat=True)).values_list(
                'ticket_id', 'seen')
        for see in seen:
            seen_elements[see[0]] = see[1]

        seen = tickets_ignorants.objects.filter(
            user=request.user,
            ticket__in=flow.data.values_list(
                'id', flat=True)).values_list('ticket_id')
        for see in seen:
            seen_elements[see[0]] = True

        flow.seen = seen_elements

    close = TicketCloseForm()
    reassign = TicketReassignForm()
    edges = ticket_flow_edges.objects.all().order_by('now')
    add_breadcrumbs(request, 0, 'k')
    cur_language = translation.get_language()
    return render(
        request, 'board/kanban.html', {
            'layout': 'horizontal',
            'columns': columns,
            'edges': edges,
            'finish_state': finish_state,
            'close': close,
            'reassign': reassign,
            'cur_language': cur_language
        })
示例#22
0
 def get_model(self):
     return get_ticket_model()
示例#23
0
def table(request, **kwargs):
    def pretty_condition(condition):
        if condition == 'AND':
            return _('AND')
        else:
            return _('OR')

    def pretty_operator(operator):
        if operator == 'is_null':
            return _('is null')
        elif operator == 'is_not_null':
            return _('is not null')
        elif operator == 'equal':
            return _('equal')
        elif operator == 'not_equal':
            return _('not equal')
        elif operator == 'begins_with':
            return _('begins with')
        elif operator == 'not_begins_with':
            return _('not begins with')
        elif operator == 'contains':
            return _('contains')
        elif operator == 'not_contains':
            return _('not contains')
        elif operator == 'ends_with':
            return _('ends with')
        elif operator == 'not_ends_with':
            return _('not ends with')
        elif operator == 'is_empty':
            return _('is empty')
        elif operator == 'is_not_empty':
            return _('is not empty')
        elif operator == 'less_or_equal':
            return _('less or equal')
        elif operator == 'less':
            return _('less')
        elif operator == 'greater_or_equal':
            return _('greater or equal')
        elif operator == 'greater':
            return _('greater')
        elif operator == 'between':
            return _('between')
        elif operator == 'not_between':
            return _('not between')

        return operator

    def pretty_value(value):
        if value is None:
            return ''
        if isinstance(value, (bool)):
            if value:
                return _('yes')
            else:
                return _('no')
        return unicode(value)

    def formatQuery(rules, condition):
        result = '('
        for rule in rules:
            if 'rules' in rule:
                result = ('%s %s %s' % (result, pretty_condition(condition), formatQuery(rule['rules'], rule['condition']))).strip()
                continue

            param = ('%s %s %s' % (rule['label'], pretty_operator(rule['operator']), pretty_value(rule['value']))).strip()
            if result != '(':
                result = '%s %s %s' % (result, pretty_condition(condition), param)
            else:
                result = ('%s%s' % (result, param)).strip()

        return '%s)' % result

    tic = get_ticket_model().objects.select_related('type').all()

    if 'search' in kwargs:
        is_search = True
        search_params, tic = build_ticket_search_ext(request, tic, kwargs['search'])

    else:
        tic = tic.filter(closed=False).order_by('-id')
        search_params = convert_sarch({'closed':False})
        is_search = False

    list_caption = kwargs.get('list_caption')
    if 'report' in request.GET:
        list_caption = tickets_reports.objects.get(pk=request.GET['report']).name

    paginator = Paginator(tic, 20)
    page = request.GET.get('page')
    try:
        tic_lines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        tic_lines = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        tic_lines = paginator.page(paginator.num_pages)

    board_form = AddToBordForm()
    board_form.fields['board'].queryset = board_form.fields['board'].queryset.filter(c_user=request.user)
    pretty_params = prettyValues(copy.deepcopy(search_params))
    pretty_query = formatQuery(pretty_params['rules'], pretty_params['condition'])
    return render(request, 'tickets/list.html', {'lines': tic_lines, 'is_search': is_search, 'search_params': pretty_params, 'list_caption': list_caption, 'board_form': board_form, 'query': json.dumps(search_params), 'sql': tic.query, 'pretty_query': pretty_query})
示例#24
0
文件: docs.py 项目: gthreepwood/yats
def docs_action(request, mode, docid):
    doc = docs.objects.get(pk=docid)
    if mode == 'view':
        form = DocsForm(user=request.user, instance=doc, view_only=True)
        add_breadcrumbs(request, docid, '*', caption=doc.caption[:20])

        files = docs_files.objects.filter(doc=doc, active_record=True)
        paginator = Paginator(files, 10)
        page = request.GET.get('page')
        try:
            files_lines = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            files_lines = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            files_lines = paginator.page(paginator.num_pages)

        return render(request, 'docs/view.html', {'layout': 'horizontal', 'form': form, 'doc': doc, 'files': files_lines})

    elif mode == 'edit':
        if request.method == 'POST':
            form = DocsForm(request.POST, user=request.user, instance=doc)
            if form.is_valid():
                doc = form.save()
                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

        form = DocsForm(user=request.user, instance=doc)
        return render(request, 'docs/edit.html', {'layout': 'horizontal', 'form': form, 'doc': doc})

    elif mode == 'delete':
        doc.delete(user=request.user)
        return HttpResponseRedirect('/search/?q=%s&models=yats.docs&models=web.test' % request.session.get('last_fulltextsearch', '*'))

    elif mode == 'ticket':
        ticket = get_ticket_model()
        tic = ticket()
        tic.caption = doc.caption
        tic.description = doc.text
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                tic.customer = request.organisation
            else:
                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
        if not tic.component_id and hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
        tic.save(user=request.user)

        add_breadcrumbs(request, str(tic.pk), '#', caption=tic.caption[:20])

        if hasattr(settings, 'KEEP_IT_SIMPLE') and settings.KEEP_IT_SIMPLE:
            return HttpResponseRedirect('/tickets/simple/%s/' % tic.pk)
        else:
            return HttpResponseRedirect('/tickets/edit/%s/' % tic.pk)

    elif mode == 'download':
        fileid = request.GET.get('file', -1)
        file_data = docs_files.objects.get(id=fileid, doc=doc)
        src = '%s%s.dat' % (get_doc_files_folder(), fileid)
        content_type = file_data.content_type
        if request.GET.get('preview') == 'yes' and os.path.isfile('%s%s.preview' % (get_doc_files_folder(), fileid)):
            src = '%s%s.preview' % (get_doc_files_folder(), fileid)
            content_type = 'imgae/png'

        if request.GET.get('resize', 'no') == 'yes' and ('image' in file_data.content_type or 'pdf' in file_data.content_type):
            img = resize_image('%s' % (src), (200, 150), 75)
            output = io.BytesIO()
            img.save(output, 'PNG')
            output.seek(0)
            response = StreamingHttpResponse(output, content_type='image/png')

        else:
            response = StreamingHttpResponse(open('%s' % (src), "rb"), content_type=content_type)

        if 'noDisposition' not in request.GET:
            if request.GET.get('preview') == 'yes' and os.path.isfile('%s%s.preview' % (get_doc_files_folder(), fileid)):
                response['Content-Disposition'] = 'attachment;filename=%s' % content_type
            else:
                response['Content-Disposition'] = 'attachment;filename=%s' % smart_str(file_data.name)
        return response

    elif mode == 'upload':
        if request.method == 'POST':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                if docs_files.objects.filter(active_record=True, doc=doc, checksum=request.FILES['file'].hash).count() > 0:
                    messages.add_message(request, messages.ERROR, _('File already exists: %s') % request.FILES['file'].name)
                    if request.GET.get('Ajax') == '1':
                        return HttpResponse('OK')
                    return HttpResponseRedirect('/docs/view/%s/' % doc.id)
                f = docs_files()
                f.name = request.FILES['file'].name
                f.size = request.FILES['file'].size
                f.checksum = request.FILES['file'].hash
                f.content_type = request.FILES['file'].content_type
                f.doc_id = doc.id
                f.public = True
                f.save(user=request.user)

                #add_history(request, tic, 5, request.FILES['file'].name)

                dest = get_doc_files_folder()
                if not os.path.exists(dest):
                    os.makedirs(dest)

                with open('%s%s.dat' % (dest, f.id), 'wb+') as destination:
                    for chunk in request.FILES['file'].chunks():
                        destination.write(chunk)

                if 'pdf' in f.content_type:
                    convertPDFtoImg('%s/%s.dat' % (dest, f.id), '%s/%s.preview' % (dest, f.id))
                else:
                    if 'image' not in f.content_type and isPreviewable(f.content_type):
                        tmp = convertOfficeTpPDF('%s/%s.dat' % (dest, f.id))
                        convertPDFtoImg(tmp, '%s/%s.preview' % (dest, f.id))
                        if os.path.isfile(tmp):
                            os.unlink(tmp)

                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

            else:
                msg = unicode(form.errors['file'])
                msg = re.sub('<[^<]+?>', '', msg)
                messages.add_message(request, messages.ERROR, msg)
                if request.GET.get('Ajax') == '1':
                    return HttpResponse('OK')
                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

        else:
            form = UploadFileForm()

        return render(request, 'docs/file.html', {'docid': doc, 'layout': 'horizontal', 'form': form})

    elif mode == 'delfile':
        file = docs_files.objects.get(pk=request.GET['fileid'], doc=doc)
        file.delete(user=request.user)

        #add_history(request, tic, 8, file.name)

        return HttpResponseRedirect('/docs/view/%s/#files' % doc.pk)
示例#25
0
    def append(self, name, text):
        import pydevd
        pydevd.settrace('192.168.33.1', 5678)

        new_items = self._parse(text, ICAL_TYPES, name)
        timezones = list(filter(
            lambda x: x.tag == ical.Timezone.tag, new_items.values()))

        request = self._getRequestFromUrl(self.path)

        for new_item in new_items.values():
            if new_item.tag == ical.Timezone.tag:
                continue

            if new_item.name not in self.items:
                self.items[new_item.name] = new_item

            text = ical.serialize(self.tag, self.headers, [new_item] + timezones)
            cal = vobject.readOne(text)

            # close ticket
            if hasattr(cal.vtodo, 'status') and cal.vtodo.status.value == 'COMPLETED':
                ticket = get_ticket_model()
                try:
                    flow_end = get_flow_end()
                    resolution = get_default_resolution()
                    close_comment = _('closed via CalDAV')

                    tic = ticket.objects.get(uuid=cal.vtodo.uid.value)
                    tic.resolution = resolution
                    tic.closed = True
                    tic.close_date = timezone.now()
                    tic.state = flow_end
                    tic.save(user=request.user)

                    com = tickets_comments()
                    com.comment = _('ticket closed - resolution: %(resolution)s\n\n%(comment)s') % {'resolution': resolution.name, 'comment': close_comment}
                    com.ticket = tic
                    com.action = 1
                    com.save(user=request.user)

                    check_references(request, com)

                    touch_ticket(request.user, tic.id)

                    add_history(request, tic, 1, close_comment)

                    mail_comment(request, com.pk)
                    jabber_comment(request, com.pk)

                except Exception:
                    pass

            # change or new
            else:
                params = {
                    'caption': cal.vtodo.summary.value,
                    'description': cal.vtodo.description.value if hasattr(cal.vtodo, 'description') else None,
                    'uuid': cal.vtodo.uid.value,
                    'show_start': cal.vtodo.due.value if hasattr(cal.vtodo, 'due') else None,
                    'priority': convertPrio(cal.vtodo.priority.value) if hasattr(cal.vtodo, 'priority') else None
                }
                fakePOST = QueryDict(mutable=True)
                fakePOST.update(params)

                form = SimpleTickets(fakePOST)
                if form.is_valid():
                    cd = form.cleaned_data
                    ticket = get_ticket_model()

                    # change ticket
                    try:
                        tic = ticket.objects.get(uuid=cal.vtodo.uid.value)
                        tic.caption = cd['caption']
                        tic.description = cd['description']
                        tic.priority = cd['priority']
                        # tic.assigned = cd['assigned']
                        tic.show_start = cd['show_start']
                        tic.save(user=request.user)

                    # new ticket
                    except ticket.DoesNotExist:
                        tic = ticket()
                        tic.caption = cd['caption']
                        tic.description = cd['description']
                        if 'priority' not in cd or not cd['priority']:
                            if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_PRIORITY') and settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY:
                                tic.priority_id = settings.KEEP_IT_SIMPLE_DEFAULT_PRIORITY
                        else:
                            tic.priority = cd['priority']
                        tic.assigned = request.user
                        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
                            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                                tic.customer = request.organisation
                            else:
                                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
                        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
                            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
                        tic.show_start = cd['show_start']
                        tic.uuid = cal.vtodo.uid.value
                        tic.save(user=request.user)

                    if tic.assigned:
                        touch_ticket(tic.assigned, tic.pk)

                    for ele in form.changed_data:
                        form.initial[ele] = ''
                    remember_changes(request, form, tic)

                    touch_ticket(request.user, tic.pk)

                    mail_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_MAIL_RCPT, is_api=True)
                    jabber_ticket(request, tic.pk, form, rcpt=settings.TICKET_NEW_JABBER_RCPT, is_api=True)

                else:
                    raise Exception(form.errors)
示例#26
0
文件: docs.py 项目: mediafactory/yats
def docs_action(request, mode, docid):
    doc = docs.objects.get(pk=docid)
    if mode == 'view':
        form = DocsForm(user=request.user, instance=doc, view_only=True)
        add_breadcrumbs(request, docid, '*', caption=doc.caption[:20])

        files = docs_files.objects.filter(doc=doc, active_record=True)
        paginator = Paginator(files, 10)
        page = request.GET.get('page')
        try:
            files_lines = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            files_lines = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            files_lines = paginator.page(paginator.num_pages)

        return render(request, 'docs/view.html', {'layout': 'horizontal', 'form': form, 'doc': doc, 'files': files_lines})

    elif mode == 'edit':
        if request.method == 'POST':
            form = DocsForm(request.POST, user=request.user, instance=doc)
            if form.is_valid():
                doc = form.save()
                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

        form = DocsForm(user=request.user, instance=doc)
        return render(request, 'docs/edit.html', {'layout': 'horizontal', 'form': form, 'doc': doc})

    elif mode == 'delete':
        doc.delete(user=request.user)
        return HttpResponseRedirect('/search/?q=%s&models=yats.docs&models=web.test' % request.session.get('last_fulltextsearch', '*'))

    elif mode == 'ticket':
        ticket = get_ticket_model()
        tic = ticket()
        tic.caption = doc.caption
        tic.description = doc.text
        if hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_CUSTOMER') and settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER:
            if settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOMER == -1:
                tic.customer = request.organisation
            else:
                tic.customer_id = settings.KEEP_IT_SIMPLE_DEFAULT_CUSTOME
        if not tic.component_id and hasattr(settings, 'KEEP_IT_SIMPLE_DEFAULT_COMPONENT') and settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT:
            tic.component_id = settings.KEEP_IT_SIMPLE_DEFAULT_COMPONENT
        tic.save(user=request.user)

        # add ref to doc
        com = tickets_comments()
        com.comment = _('see §%s') % doc.pk
        com.ticket_id = tic
        com.action = 3
        com.save(user=request.user)

        add_breadcrumbs(request, str(tic.pk), '#', caption=tic.caption[:20])

        if hasattr(settings, 'KEEP_IT_SIMPLE') and settings.KEEP_IT_SIMPLE:
            return HttpResponseRedirect('/tickets/simple/%s/' % tic.pk)
        else:
            return HttpResponseRedirect('/tickets/edit/%s/' % tic.pk)

    elif mode == 'download':
        fileid = request.GET.get('file', -1)
        file_data = docs_files.objects.get(id=fileid, doc=doc)
        src = '%s%s.dat' % (get_doc_files_folder(), fileid)
        content_type = file_data.content_type
        if request.GET.get('preview') == 'yes' and os.path.isfile('%s%s.preview' % (get_doc_files_folder(), fileid)):
            src = '%s%s.preview' % (get_doc_files_folder(), fileid)
            content_type = 'imgae/png'

        if request.GET.get('resize', 'no') == 'yes' and ('image' in file_data.content_type or 'pdf' in file_data.content_type):
            img = resize_image('%s' % (src), (200, 150), 75)
            output = io.BytesIO()
            img.save(output, 'PNG')
            output.seek(0)
            response = StreamingHttpResponse(output, content_type='image/png')

        else:
            response = StreamingHttpResponse(open('%s' % (src), "rb"), content_type=content_type)

        if 'noDisposition' not in request.GET:
            if request.GET.get('preview') == 'yes' and os.path.isfile('%s%s.preview' % (get_doc_files_folder(), fileid)):
                response['Content-Disposition'] = 'attachment;filename=%s' % content_type
            else:
                response['Content-Disposition'] = 'attachment;filename=%s' % smart_str(file_data.name)
        return response

    elif mode == 'upload':
        if request.method == 'POST':
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                if docs_files.objects.filter(active_record=True, doc=doc, checksum=request.FILES['file'].hash).count() > 0:
                    messages.add_message(request, messages.ERROR, _('File already exists: %s') % request.FILES['file'].name)
                    if request.GET.get('Ajax') == '1':
                        return HttpResponse('OK')
                    return HttpResponseRedirect('/docs/view/%s/' % doc.id)
                f = docs_files()
                f.name = request.FILES['file'].name
                f.size = request.FILES['file'].size
                f.checksum = request.FILES['file'].hash
                f.content_type = request.FILES['file'].content_type
                f.doc_id = doc.id
                f.public = True
                f.save(user=request.user)

                #add_history(request, tic, 5, request.FILES['file'].name)

                dest = get_doc_files_folder()
                if not os.path.exists(dest):
                    os.makedirs(dest)

                with open('%s%s.dat' % (dest, f.id), 'wb+') as destination:
                    for chunk in request.FILES['file'].chunks():
                        destination.write(chunk)

                if 'pdf' in f.content_type:
                    convertPDFtoImg('%s/%s.dat' % (dest, f.id), '%s/%s.preview' % (dest, f.id))
                else:
                    if 'image' not in f.content_type and isPreviewable(f.content_type):
                        tmp = convertOfficeTpPDF('%s/%s.dat' % (dest, f.id))
                        convertPDFtoImg(tmp, '%s/%s.preview' % (dest, f.id))
                        if os.path.isfile(tmp):
                            os.unlink(tmp)

                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

            else:
                msg = unicode(form.errors['file'])
                msg = re.sub('<[^<]+?>', '', msg)
                messages.add_message(request, messages.ERROR, msg)
                if request.GET.get('Ajax') == '1':
                    return HttpResponse('OK')
                return HttpResponseRedirect('/docs/view/%s/' % doc.pk)

        else:
            form = UploadFileForm()

        return render(request, 'docs/file.html', {'docid': doc, 'layout': 'horizontal', 'form': form})

    elif mode == 'delfile':
        file = docs_files.objects.get(pk=request.GET['fileid'], doc=doc)
        file.delete(user=request.user)

        #add_history(request, tic, 8, file.name)

        return HttpResponseRedirect('/docs/view/%s/#files' % doc.pk)
示例#27
0
文件: views.py 项目: shoreward/yats
def show_board(request, name):
    # http://bootsnipp.com/snippets/featured/kanban-board
    """
        board structure
        
        [
            {
                'column': 'closed',
                'query': {'closed': False},
                'limit': 10,
                'extra_filter': 1, # 1 = days since closed, 2 = days since created, 3 = days since last changed, 4 days since last action
                'days': 1, # days
                'order_by': 'id',
                'order_dir': ''
            }
        ]
    """

    if request.method == 'POST':
        if 'method' in request.POST:
            board = boards.objects.get(pk=request.POST['board'],
                                       c_user=request.user)
            try:
                columns = json.loads(board.columns)
            except:
                columns = []

            if request.POST['method'] == 'add':
                form = AddToBordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    col = {
                        'column': cd['column'],
                        'query': request.session['last_search'],
                        'limit': cd['limit'],
                        'order_by': cd['order_by'],
                        'order_dir': cd['order_dir']
                    }
                    if cd.get('extra_filter') and cd.get('days'):
                        col['extra_filter'] = cd['extra_filter']
                        col['days'] = cd['days']
                    columns.append(col)
                    board.columns = json.dumps(columns, cls=DjangoJSONEncoder)
                    board.save(user=request.user)

                else:
                    err_list = []
                    for field in form:
                        for err in field.errors:
                            err_list.append('%s: %s' % (field.name, err))
                    messages.add_message(
                        request, messages.ERROR,
                        _('data invalid: %s') % '\n'.join(err_list))

                return HttpResponseRedirect('/board/%s/' %
                                            urlquote_plus(board.name))

        else:
            board = boards()
            board.name = request.POST['boardname']
            board.save(user=request.user)

            return HttpResponseRedirect(
                '/board/%s/' % urlquote_plus(request.POST['boardname']))

    else:
        board = boards.objects.get(name=name, c_user=request.user)
        try:
            columns = json.loads(board.columns)
        except:
            columns = []

        if 'method' in request.GET and request.GET['method'] == 'del':
            new_columns = []
            for col in columns:
                if col['column'] != request.GET['column']:
                    new_columns.append(col)
            board.columns = json.dumps(new_columns, cls=DjangoJSONEncoder)
            board.save(user=request.user)

            return HttpResponseRedirect('/board/%s/' % urlquote_plus(name))

    for column in columns:
        column['query'] = get_ticket_model().objects.select_related(
            'priority').filter(**column['query']).order_by(
                '%s%s' %
                (column.get('order_dir', ''), column.get('order_by', 'id')))
        if column['limit']:
            column['query'] = column['query'][:column['limit']]
        if 'extra_filter' in column and 'days' in column and column[
                'extra_filter'] and column['days']:
            print type(column['extra_filter'])
            if column['extra_filter'] == '1':  # days since closed
                column['query'] = column['query'].filter(
                    close_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days'])).exclude(
                        close_date=None)
            if column['extra_filter'] == '2':  # days since created
                column['query'] = column['query'].filter(
                    c_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '3':  # days since last changed
                column['query'] = column['query'].filter(
                    u_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '4':  # days since last action
                column['query'] = column['query'].filter(
                    last_action_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))

    add_breadcrumbs(request, board.pk, '$')
    return render_to_response('board/view.html', {
        'columns': columns,
        'board': board
    }, RequestContext(request))
示例#28
0
def YATSSearch(request):
    def ValuesQuerySetToDict(vqs):
        return [item for item in vqs]

    tic = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
    data = json.loads(request.body)

    if 'extra_filter' in data:
        extra_filter = data['extra_filter']
        del data['extra_filter']
    else:
        extra_filter = None
    if 'days' in data:
        days = data['days']
        del data['days']
    else:
        days = None
    if 'exclude_own' in data:
        exclude_own = data['exclude_own']
        del data['exclude_own']
    else:
        exclude_own = False

    POST = QueryDict(mutable=True)
    POST.update(data)
    form = SearchForm(POST, include_list=settings.TICKET_SEARCH_FIELDS, is_stuff=request.user.is_staff, user=request.user, customer=request.organisation.id)
    form.is_valid()
    for err in form._errors:
        field = form.fields[err]
        # b = type(field)
        if err in ['c_user', 'assigned']:
            try:
                form.cleaned_data[err] = field.choices.queryset.get(username=data[err]).pk
            except:
                form.cleaned_data[err] = -1

        else:
            try:
                form.cleaned_data[err] = field.choices.queryset.get(name=data[err]).pk
            except:
                form.cleaned_data[err] = -1

    search_params, base_query = build_ticket_search(request, tic, {}, clean_search_values(form.cleaned_data))
    if extra_filter:
        if extra_filter == '1':  # days since closed
            base_query = base_query.filter(close_date__gte=datetime.date.today() - datetime.timedelta(days=days)).exclude(close_date=None)
        if extra_filter == '2':  # days since created
            base_query = base_query.filter(c_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '3':  # days since last changed
            base_query = base_query.filter(u_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '4':  # days since last action
            base_query = base_query.filter(last_action_date__gte=datetime.date.today() - datetime.timedelta(days=days))
        if extra_filter == '5':  # days since falling due
            base_query = base_query.filter(deadline__lte=timezone.now() - datetime.timedelta(days=days)).filter(deadline__isnull=False)

    if exclude_own:
        base_query = base_query.exclude(assigned=request.user)

    seen = tickets_participants.objects.filter(user=request.user, ticket__in=base_query.values_list('id', flat=True)).values_list('ticket_id', 'seen')
    seen_elements = {}
    for see in seen:
        seen_elements[see[0]] = see[1]

    neededColumns = ['id', 'caption', 'c_date', 'type__name', 'state__name', 'assigned__username', 'deadline', 'closed', 'priority__color', 'customer__name', 'customer__hourly_rate', 'billing_estimated_time', 'close_date', 'last_action_date']
    """
    availableColumns = []
    tickets = get_ticket_model()
    t = tickets()
    for field in t._meta.fields:
        if field.name in neededColumns:
            availableColumns.append(field.name)
    """
    result = ValuesQuerySetToDict(base_query.values(*neededColumns))

    for ele in result:
        ele['seen'] = 0
        if ele['id'] in seen_elements:
            if seen_elements[ele['id']]:
                ele['seen'] = 2
            else:
                ele['seen'] = 1

    return result
示例#29
0
文件: views.py 项目: lou-viannay/yats
def show_board(request, name):
    # http://bootsnipp.com/snippets/featured/kanban-board
    """
        board structure

        [
            {
                'column': 'closed',
                'query': {'closed': False},
                'limit': 10,
                'extra_filter': 1, # 1 = days since closed, 2 = days since created, 3 = days since last changed, 4 days since last action
                'days': 1, # days
                'order_by': 'id',
                'order_dir': ''
            }
        ]
    """

    name = unquote_plus(name)

    if request.method == 'POST':
        if 'method' in request.POST:
            board = boards.objects.get(active_record=True,
                                       pk=request.POST['board'],
                                       c_user=request.user)
            try:
                columns = json.loads(board.columns)
            except:
                columns = []

            if request.POST['method'] == 'add':
                form = AddToBordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    col = {
                        'column': cd['column'],
                        'query': request.session['last_search'],
                        'limit': cd['limit'],
                        'order_by': cd['order_by'],
                        'order_dir': cd['order_dir']
                    }
                    if cd.get('extra_filter') and cd.get('days'):
                        col['extra_filter'] = cd['extra_filter']
                        col['days'] = cd['days']
                    columns.append(col)
                    board.columns = json.dumps(columns, cls=DjangoJSONEncoder)
                    board.save(user=request.user)

                else:
                    err_list = []
                    for field in form:
                        for err in field.errors:
                            err_list.append('%s: %s' % (field.name, err))
                    messages.add_message(
                        request, messages.ERROR,
                        _('data invalid: %s') % '\n'.join(err_list))

                return HttpResponseRedirect('/board/%s/' %
                                            urlquote_plus(board.name))

        else:
            if request.POST['boardname'].strip() != '':
                if boards.objects.filter(active_record=True,
                                         c_user=request.user,
                                         name=request.POST['boardname']).count(
                                         ) == 0 and request.POST['boardname']:
                    board = boards()
                    board.name = request.POST['boardname'].strip()
                    board.save(user=request.user)

                    return HttpResponseRedirect(
                        '/board/%s/' %
                        urlquote_plus(request.POST['boardname']))

                else:
                    messages.add_message(
                        request, messages.ERROR,
                        _(u'A board with the name "%s" already exists' %
                          request.POST['boardname']))
                    return HttpResponseRedirect('/')
            else:
                messages.add_message(request, messages.ERROR,
                                     _(u'No name for a board given'))
                return HttpResponseRedirect('/')

    else:
        board = boards.objects.get(active_record=True,
                                   name=name,
                                   c_user=request.user)
        try:
            columns = json.loads(board.columns)
        except:
            columns = []

        if 'method' in request.GET and request.GET['method'] == 'del':
            new_columns = []
            for col in columns:
                if col['column'] != request.GET['column']:
                    new_columns.append(col)
            board.columns = json.dumps(new_columns, cls=DjangoJSONEncoder)
            board.save(user=request.user)

            return HttpResponseRedirect('/board/%s/' % urlquote_plus(name))

        elif 'method' in request.GET and request.GET['method'] == 'delete':
            board.delete(user=request.user)
            return HttpResponseRedirect('/')

    for column in columns:
        query = get_ticket_model().objects.select_related(
            'type', 'state', 'assigned', 'priority', 'customer').all()
        search_params, query = build_ticket_search_ext(request, query,
                                                       column['query'])
        column['query'] = query.order_by(
            '%s%s' %
            (column.get('order_dir', ''), column.get('order_by', 'id')))
        if 'extra_filter' in column and 'days' in column and column[
                'extra_filter'] and column['days']:
            if column['extra_filter'] == '1':  # days since closed
                column['query'] = column['query'].filter(
                    close_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days'])).exclude(
                        close_date=None)
            if column['extra_filter'] == '2':  # days since created
                column['query'] = column['query'].filter(
                    c_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '3':  # days since last changed
                column['query'] = column['query'].filter(
                    u_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '4':  # days since last action
                column['query'] = column['query'].filter(
                    last_action_date__gte=datetime.date.today() -
                    datetime.timedelta(days=column['days']))
        if not request.user.is_staff:
            column['query'] = column['query'].filter(
                customer=request.organisation)

        seen_elements = {}
        seen = tickets_participants.objects.filter(
            user=request.user,
            ticket__in=column['query'].values_list('id',
                                                   flat=True)).values_list(
                                                       'ticket_id', 'seen')
        for see in seen:
            seen_elements[see[0]] = see[1]

        seen = tickets_ignorants.objects.filter(
            user=request.user,
            ticket__in=column['query'].values_list(
                'id', flat=True)).values_list('ticket_id')
        for see in seen:
            seen_elements[see[0]] = True

        if column['limit']:
            column['query'] = column['query'][:column['limit']]
        column['seen'] = seen_elements

    add_breadcrumbs(request, board.pk, '$')
    return render(request, 'board/view.html', {
        'columns': columns,
        'board': board
    })
示例#30
0
def show_board(request, name):
    # http://bootsnipp.com/snippets/featured/kanban-board

    """
        board structure

        [
            {
                'column': 'closed',
                'query': {'closed': False},
                'limit': 10,
                'extra_filter': 1, # 1 = days since closed, 2 = days since created, 3 = days since last changed, 4 days since last action
                'days': 1, # days
                'order_by': 'id',
                'order_dir': ''
            }
        ]
    """

    if request.method == 'POST':
        if 'method' in request.POST:
            board = boards.objects.get(active_record=True, pk=request.POST['board'], c_user=request.user)
            try:
                columns = json.loads(board.columns)
            except:
                columns = []

            if request.POST['method'] == 'add':
                form = AddToBordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data
                    col = {
                           'column': cd['column'],
                           'query': request.session['last_search'],
                           'limit': cd['limit'],
                           'order_by': cd['order_by'],
                           'order_dir': cd['order_dir']
                           }
                    if cd.get('extra_filter') and cd.get('days'):
                        col['extra_filter'] = cd['extra_filter']
                        col['days'] = cd['days']
                    columns.append(col)
                    board.columns = json.dumps(columns, cls=DjangoJSONEncoder)
                    board.save(user=request.user)

                else:
                    err_list = []
                    for field in form:
                        for err in field.errors:
                            err_list.append('%s: %s' % (field.name, err))
                    messages.add_message(request, messages.ERROR, _('data invalid: %s') % '\n'.join(err_list))

                return HttpResponseRedirect('/board/%s/' % urlquote_plus(board.name))

        else:
            if request.POST['boardname'].strip() != '':
                if boards.objects.filter(active_record=True, c_user=request.user, name=request.POST['boardname']).count() == 0 and request.POST['boardname']:
                        board = boards()
                        board.name = request.POST['boardname'].strip()
                        board.save(user=request.user)

                        return HttpResponseRedirect('/board/%s/' % urlquote_plus(request.POST['boardname']))

                else:
                    messages.add_message(request, messages.ERROR, _(u'A board with the name "%s" already exists' % request.POST['boardname']))
                    return HttpResponseRedirect('/')
            else:
                messages.add_message(request, messages.ERROR, _(u'No name for a board given'))
                return HttpResponseRedirect('/')

    else:
        board = boards.objects.get(active_record=True, name=name, c_user=request.user)
        try:
            columns = json.loads(board.columns)
        except:
            columns = []

        if 'method' in request.GET and request.GET['method'] == 'del':
            new_columns = []
            for col in columns:
                if col['column'] != request.GET['column']:
                    new_columns.append(col)
            board.columns = json.dumps(new_columns, cls=DjangoJSONEncoder)
            board.save(user=request.user)

            return HttpResponseRedirect('/board/%s/' % urlquote_plus(name))

        elif 'method' in request.GET and request.GET['method'] == 'delete':
            board.delete(user=request.user)
            return HttpResponseRedirect('/')

    for column in columns:
        query = get_ticket_model().objects.select_related('type', 'state', 'assigned', 'priority', 'customer').all()
        search_params, query = build_ticket_search_ext(request, query, column['query'])
        column['query'] = query.order_by('%s%s' % (column.get('order_dir', ''), column.get('order_by', 'id')))
        if 'extra_filter' in column and 'days' in column and column['extra_filter'] and column['days']:
            if column['extra_filter'] == '1':  # days since closed
                column['query'] = column['query'].filter(close_date__gte=datetime.date.today() - datetime.timedelta(days=column['days'])).exclude(close_date=None)
            if column['extra_filter'] == '2':  # days since created
                column['query'] = column['query'].filter(c_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '3':  # days since last changed
                column['query'] = column['query'].filter(u_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '4':  # days since last action
                column['query'] = column['query'].filter(last_action_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
        if not request.user.is_staff:
            column['query'] = column['query'].filter(customer=request.organisation)

        seen_elements = {}
        seen = tickets_participants.objects.filter(user=request.user, ticket__in=column['query'].values_list('id', flat=True)).values_list('ticket_id', 'seen')
        for see in seen:
            seen_elements[see[0]] = see[1]

        seen = tickets_ignorants.objects.filter(user=request.user, ticket__in=column['query'].values_list('id', flat=True)).values_list('ticket_id')
        for see in seen:
            seen_elements[see[0]] = True

        if column['limit']:
            column['query'] = column['query'][:column['limit']]
        column['seen'] = seen_elements

    add_breadcrumbs(request, board.pk, '$')
    return render(request, 'board/view.html', {'columns': columns, 'board': board})
示例#31
0
文件: tickets.py 项目: achenxu/yats
def table(request, **kwargs):
    def pretty_condition(condition):
        if condition == 'AND':
            return _('AND')
        else:
            return _('OR')

    def pretty_operator(operator):
        if operator == 'is_null':
            return _('is null')
        elif operator == 'is_not_null':
            return _('is not null')
        elif operator == 'equal':
            return _('equal')
        elif operator == 'not_equal':
            return _('not equal')
        elif operator == 'begins_with':
            return _('begins with')
        elif operator == 'not_begins_with':
            return _('not begins with')
        elif operator == 'contains':
            return _('contains')
        elif operator == 'not_contains':
            return _('not contains')
        elif operator == 'ends_with':
            return _('ends with')
        elif operator == 'not_ends_with':
            return _('not ends with')
        elif operator == 'is_empty':
            return _('is empty')
        elif operator == 'is_not_empty':
            return _('is not empty')
        elif operator == 'less_or_equal':
            return _('less or equal')
        elif operator == 'less':
            return _('less')
        elif operator == 'greater_or_equal':
            return _('greater or equal')
        elif operator == 'greater':
            return _('greater')
        elif operator == 'between':
            return _('between')
        elif operator == 'not_between':
            return _('not between')

        return operator

    def pretty_value(value):
        if value is None:
            return ''
        if isinstance(value, (bool)):
            if value:
                return _('yes')
            else:
                return _('no')
        return unicode(value)

    def formatQuery(rules, condition):
        result = '('
        for rule in rules:
            if 'rules' in rule:
                result = (
                    '%s %s %s' %
                    (result, pretty_condition(condition),
                     formatQuery(rule['rules'], rule['condition']))).strip()
                continue

            param = ('%s %s %s' %
                     (rule['label'], pretty_operator(rule['operator']),
                      pretty_value(rule['value']))).strip()
            if result != '(':
                result = '%s %s %s' % (result, pretty_condition(condition),
                                       param)
            else:
                result = ('%s%s' % (result, param)).strip()

        return '%s)' % result

    tic = get_ticket_model().objects.select_related('type').all()

    if 'search' in kwargs:
        is_search = True
        search_params, tic = build_ticket_search_ext(request, tic,
                                                     kwargs['search'])

    else:
        tic = tic.filter(closed=False).order_by('-id')
        search_params = convert_sarch({'closed': False})
        is_search = False

    list_caption = kwargs.get('list_caption')
    if 'report' in request.GET:
        list_caption = tickets_reports.objects.get(
            pk=request.GET['report']).name

    paginator = Paginator(tic, 20)
    page = request.GET.get('page')
    try:
        tic_lines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        tic_lines = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        tic_lines = paginator.page(paginator.num_pages)

    board_form = AddToBordForm()
    board_form.fields['board'].queryset = board_form.fields[
        'board'].queryset.filter(c_user=request.user)
    pretty_params = prettyValues(copy.deepcopy(search_params))
    pretty_query = formatQuery(pretty_params['rules'],
                               pretty_params['condition'])
    return render(
        request, 'tickets/list.html', {
            'lines': tic_lines,
            'is_search': is_search,
            'search_params': pretty_params,
            'list_caption': list_caption,
            'board_form': board_form,
            'query': json.dumps(search_params),
            'sql': tic.query,
            'pretty_query': pretty_query
        })
示例#32
0
文件: views.py 项目: jonhairston/yats
def show_board(request, name):
    # http://bootsnipp.com/snippets/featured/kanban-board
    
    """
        board structure
        
        [
            {
                'column': 'closed',
                'query': {'closed': False},
                'limit': 10,
                'extra_filter': 1, # 1 = days since closed, 2 = days since created, 3 = days since last changed, 4 days since last action
                'days': 1, # days
                'order_by': 'id',
                'order_dir': ''
            }
        ]
    """
    
    if request.method == 'POST':
        if 'method' in request.POST:
            board = boards.objects.get(pk=request.POST['board'], c_user=request.user)
            try:
                columns = json.loads(board.columns)
            except:
                columns = []

            if request.POST['method'] == 'add':
                form = AddToBordForm(request.POST)
                if form.is_valid():
                    cd = form.cleaned_data 
                    col = {
                           'column': cd['column'],
                           'query': request.session['last_search'],
                           'limit': cd['limit'],
                           'order_by': cd['order_by'],
                           'order_dir': cd['order_dir']
                           }
                    if cd.get('extra_filter') and cd.get('days'):
                        col['extra_filter'] = cd['extra_filter']
                        col['days'] = cd['days']
                    columns.append(col)
                    board.columns = json.dumps(columns, cls=DjangoJSONEncoder)
                    board.save(user=request.user)
                
                else:
                    err_list = []
                    for field in form:
                        for err in field.errors:
                            err_list.append('%s: %s' % (field.name, err))
                    messages.add_message(request, messages.ERROR, _('data invalid: %s') % '\n'.join(err_list))
                
                return HttpResponseRedirect('/board/%s/' % urlquote_plus(board.name))
                
        else:
            board = boards()
            board.name = request.POST['boardname']
            board.save(user=request.user)
            
            return HttpResponseRedirect('/board/%s/' % urlquote_plus(request.POST['boardname']))
    
    else:
        board = boards.objects.get(name=name, c_user=request.user)
        try:
            columns = json.loads(board.columns)
        except:
            columns = []

        if 'method' in request.GET and request.GET['method'] == 'del':
            new_columns = []
            for col in columns:
                if col['column'] != request.GET['column']:
                    new_columns.append(col)
            board.columns = json.dumps(new_columns, cls=DjangoJSONEncoder)
            board.save(user=request.user)
            
            return HttpResponseRedirect('/board/%s/' % urlquote_plus(name))
            
    for column in columns:
        column['query'] = get_ticket_model().objects.select_related('priority').filter(**column['query']).order_by('%s%s' % (column.get('order_dir', ''), column.get('order_by', 'id')))
        if column['limit']:
            column['query'] = column['query'][:column['limit']]
        if 'extra_filter' in column and 'days' in column and column['extra_filter'] and column['days']:
            print type(column['extra_filter']) 
            if column['extra_filter'] == '1': # days since closed
                column['query'] = column['query'].filter(close_date__gte=datetime.date.today() - datetime.timedelta(days=column['days'])).exclude(close_date=None)
            if column['extra_filter'] == '2': # days since created
                column['query'] = column['query'].filter(c_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '3': # days since last changed
                column['query'] = column['query'].filter(u_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
            if column['extra_filter'] == '4': # days since last action
                column['query'] = column['query'].filter(last_action_date__gte=datetime.date.today() - datetime.timedelta(days=column['days']))
        
    add_breadcrumbs(request, board.pk, '$')
    return render_to_response('board/view.html', {'columns': columns, 'board': board}, RequestContext(request))