pagination_types.py 3.04 KB
# -*- coding: utf-8 -*-
from django.utils.encoding import force_unicode

from datetime import datetime
from django.contrib.auth.models import User
from django.forms import Form, ChoiceField, Select, ModelChoiceField, \
    DateField, DateInput
from django.utils.translation import ugettext_lazy as _

from history.models import HistoryFrame

types = {}


def lexeme_history_list(params, user):
    frames = HistoryFrame.objects.exclude(lexeme=None)
    frames = apply_history_filters(params, frames)

    # lexemes = Lexeme.filter_visible(Lexeme.all_objects, user)\
    #     .exclude(entry='')
    # frames = frames.filter(lexeme_id__in=lexemes)\
    frames = frames.exclude(lexeme__entry='')
    frames = frames.order_by(params['order_by'])
    return frames


def pattern_history_list(params, user):
    frames = HistoryFrame.objects.exclude(pattern=None)
    frames = apply_history_filters(params, frames)

    frames = frames.exclude(pattern__name__startswith=u'nowy wzór')
    frames = frames.order_by(params['order_by'])
    return frames


def apply_history_filters(params, frames):
    for field, lookup, value in params['filters']:
        if field == 'user':
            if lookup == 'eq':
                frames = frames.filter(user__pk=value)
            elif lookup == 'ne':
                frames = frames.exclude(user__username=value)
        if field == 'time':
            try:
                date = datetime.strptime(value, force_unicode(_('%Y/%m/%d')))
                if lookup == 'from':
                    frames = frames.filter(transaction_began__gte=date)
                elif lookup == 'to':
                    frames = frames.filter(transaction_began__lte=date)
            except ValueError:
                pass
    return frames


class HistoryFilterFieldForm(Form):
    field = ChoiceField(
        choices=[], label=u'', widget=Select(attrs={'class': 'field-choice'}))

    def __init__(self, **kwargs):
        super(HistoryFilterFieldForm, self).__init__(**kwargs)
        filters = HISTORY_FILTERS
        choices = [(key, value[0]) for key, value in filters.iteritems()]
        self.fields['field'].choices = choices


class UserFilterForm(Form):
    user = ModelChoiceField(
        queryset=User.objects.order_by('username'), label=u'',
        widget=Select(attrs={'class': 'value'}))


class TimeFilterForm(Form):
    time = DateField(
        input_formats=['%d.%m.%Y'], label=u'',
        widget=DateInput(attrs={'class': 'datepicker value'}))


HISTORY_FILTERS = {
    'user': (
        _(u'User'),
        [('eq', _(u'equals'))],
        UserFilterForm,
    ),
    'time': (
        _(u'Date'),
        [('from', _(u'from')), ('to', _(u'to'))],
        TimeFilterForm,
    ),
}


def dummy_perm(user, object, action):
    return True


types['lexeme_history'] = (
    lexeme_history_list,
    'lexeme_history_item.html',
    dummy_perm,
    {},
    HISTORY_FILTERS,
    HistoryFilterFieldForm,
)

types['pattern_history'] = (
    pattern_history_list,
    'pattern_history_item.html',
    dummy_perm,
    {},
    HISTORY_FILTERS,
    HistoryFilterFieldForm,
)