Пример #1
0
class CompaniesWithEntryTypes(dd.VentilatingTable, contacts.Companies):
    label = _("Companies with Entry Types")
    hide_zero_rows = True
    parameters = mixins.ObservedPeriod()
    params_layout = "start_date end_date"
    editable = False
    auto_fit_column_widths = True

    @classmethod
    def param_defaults(cls, ar, **kw):
        kw = super(CompaniesWithEntryTypes, cls).param_defaults(ar, **kw)
        kw.update(end_date=settings.SITE.today())
        return kw

    @classmethod
    def get_ventilated_columns(self):
        def w(et):
            # return a getter function for a RequestField on the given
            # EntryType.

            def func(fld, obj, ar):
                #~ mi = ar.master_instance
                #~ if mi is None: return None
                pv = dict(start_date=ar.param_values.start_date,
                          end_date=ar.param_values.end_date)
                if et is not None:
                    pv.update(entry_type=et)
                pv.update(company=obj)
                return Entries.request(param_values=pv)

            return func

        for et in EntryType.objects.all():
            yield dd.RequestField(w(et), verbose_name=unicode(et))
        yield dd.RequestField(w(None), verbose_name=_("Total"))
Пример #2
0
class Entries(dd.Table):
    model = Entry
    detail_layout = """
    id user date company
    subject
    body
    """
    insert_layout = """
    user date company
    subject
    """
    parameters = mixins.ObservedPeriod(
        entry_type=models.ForeignKey(
            EntryType,
            blank=True,
            null=True,
            help_text=_("Show only entries of this type.")),
        company=models.ForeignKey(
            'contacts.Company',
            blank=True,
            null=True,
            help_text=_("Show only entries of this company.")),
        user=models.ForeignKey(settings.SITE.user_model,
                               blank=True,
                               null=True,
                               help_text=_("Show only entries by this user.")))
    params_layout = """
    user start_date end_date
    company entry_type
    """

    @classmethod
    def get_request_queryset(cls, ar):
        qs = super(Entries, cls).get_request_queryset(ar)
        if ar.param_values.end_date:
            qs = qs.filter(date__lte=ar.param_values.end_date)
        if ar.param_values.start_date:
            qs = qs.filter(date__gte=ar.param_values.start_date)
        if ar.param_values.user:
            qs = qs.filter(user=ar.param_values.user)
        if ar.param_values.entry_type:
            qs = qs.filter(entry_type=ar.param_values.entry_type)
        if ar.param_values.company:
            qs = qs.filter(company=ar.param_values.company)
        return qs

    @classmethod
    def param_defaults(cls, ar, **kw):
        kw = super(Entries, cls).param_defaults(ar, **kw)
        kw.update(user=ar.get_user())
        return kw
Пример #3
0
class PeriodTable(dd.Table):
    parameters = mixins.ObservedPeriod(observed_event=PeriodEvents.field(
        blank=True))
    params_layout = "start_date end_date observed_event"

    @classmethod
    def get_request_queryset(self, ar):
        qs = super(PeriodTable, self).get_request_queryset(ar)

        pv = ar.param_values
        ce = pv.observed_event
        if ce:
            qs = ce.add_filter(qs, pv)
        return qs
Пример #4
0
class Excerpts(dd.Table):
    """Base class for all tables on :class:`Excerpt`."""
    # label = _("Excerpts history")
    icon_name = 'script'
    required_roles = dd.required((ExcerptsUser, OfficeOperator))

    model = 'excerpts.Excerpt'
    detail_layout = ExcerptDetail()
    insert_layout = """
    excerpt_type project
    company contact_person
    """
    column_names = ("id excerpt_type owner project "
                    "company language build_time *")
    # order_by = ['-build_time', 'id']
    order_by = ['-id']
    auto_fit_column_widths = True
    allow_create = False

    parameters = mixins.ObservedPeriod(
        excerpt_type=models.ForeignKey('excerpts.ExcerptType',
                                       blank=True,
                                       null=True),
        pcertifying=dd.YesNo.field(_("Certifying excerpts"), blank=True))
    params_layout = """
    start_date end_date pcertifying
    user excerpt_type"""

    # simple_parameters = ['user', 'excerpt_type']

    @classmethod
    def get_simple_parameters(cls):
        s = super(Excerpts, cls).get_simple_parameters()
        s.add('excerpt_type')
        return s

    @classmethod
    def get_request_queryset(cls, ar):
        qs = super(Excerpts, cls).get_request_queryset(ar)
        pv = ar.param_values

        if pv.pcertifying == dd.YesNo.yes:
            qs = qs.filter(excerpt_type__certifying=True)
        elif pv.pcertifying == dd.YesNo.no:
            qs = qs.filter(excerpt_type__certifying=False)

        return qs
Пример #5
0
class Bookings(dd.Table):
    model = 'rooms.Booking'
    #~ order_by = ['date','start_time']
    detail_layout = BookingDetail()
    insert_layout = """
    start_date start_time end_time
    room event_type
    company contact_person
    """
    column_names = "start_date company room  *"
    order_by = ['start_date']

    parameters = mixins.ObservedPeriod(
        company=models.ForeignKey('contacts.Company', blank=True, null=True),
        state=BookingStates.field(blank=True),
    )
    params_layout = """company state"""

    @classmethod
    def get_simple_parameters(cls):
        s = super(Bookings, cls).get_simple_parameters()
        s.add('company')
        s.add('state')
        return s

    # simple_parameters = 'company state'.split()

    @classmethod
    def get_request_queryset(self, ar):
        qs = super(Bookings, self).get_request_queryset(ar)
        if isinstance(qs, list):
            return qs
        # for n in self.simple_param_fields:
        #     v = ar.param_values.get(n)
        #     if v:
        #         qs = qs.filter(**{n: v})
        #         #~ print 20130530, qs.query

        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Bookings, self).get_title_tags(ar):
            yield t
Пример #6
0
class Uploads(dd.Table):
    "Shows all Uploads"
    model = 'uploads.Upload'
    required_roles = dd.login_required((OfficeUser, OfficeOperator))
    column_names = "file type user owner description *"
    order_by = ['-id']

    detail_layout = dd.DetailLayout("""
    file user
    upload_area type description
    owner
    """,
                                    window_size=(80, 'auto'))

    insert_layout = """
    type
    description
    file
    user
    """

    parameters = mixins.ObservedPeriod(
        # user=models.ForeignKey(
        #     'users.User', blank=True, null=True,
        #     verbose_name=_("Uploaded by")),
        upload_type=models.ForeignKey(
            'uploads.UploadType', blank=True, null=True))
    params_layout = "start_date end_date user upload_type"

    # simple_parameters = ['user']

    @classmethod
    def get_request_queryset(cls, ar):
        qs = super(Uploads, cls).get_request_queryset(ar)
        pv = ar.param_values

        if pv.user:
            qs = qs.filter(user=pv.user)

        if pv.upload_type:
            qs = qs.filter(type=pv.upload_type)

        return qs
Пример #7
0
class Coachings(dd.Table):
    required_roles = dd.required(CoachingsStaff)
    help_text = _("Liste des accompagnements.")
    model = 'coachings.Coaching'

    parameters = mixins.ObservedPeriod(
        coached_by=models.ForeignKey(
            'users.User',
            blank=True,
            null=True,
            verbose_name=_("Coached by"),
            help_text="""Nur Begleitungen dieses Benutzers."""),
        and_coached_by=models.ForeignKey(
            'users.User',
            blank=True,
            null=True,
            verbose_name=_("and by"),
            help_text="""... und auch Begleitungen dieses Benutzers."""),
        observed_event=dd.PeriodEvents.field(
            blank=True, default=dd.PeriodEvents.active.as_callable),
        primary_coachings=dd.YesNo.field(
            _("Primary coachings"),
            blank=True,
            help_text="""Accompagnements primaires."""),
        coaching_type=models.ForeignKey(
            'coachings.CoachingType',
            blank=True,
            null=True,
            help_text="""Nur Begleitungen dieses Dienstes."""),
        ending=models.ForeignKey(
            'coachings.CoachingEnding',
            blank=True,
            null=True,
            help_text="""Nur Begleitungen mit diesem Beendigungsgrund."""),
    )
    params_layout = """
    start_date end_date observed_event coached_by and_coached_by
    primary_coachings coaching_type ending
    """
    params_panel_hidden = True

    #~ @classmethod
    #~ def param_defaults(self,ar,**kw):
    #~ kw = super(Coachings,self).param_defaults(ar,**kw)
    #~ D = datetime.date
    #~ kw.update(start_date = D.today())
    #~ kw.update(end_date = D.today())
    #~ return kw

    @classmethod
    def get_request_queryset(self, ar):
        qs = super(Coachings, self).get_request_queryset(ar)
        pv = ar.param_values
        coaches = []
        for u in (pv.coached_by, pv.and_coached_by):
            if u is not None:
                coaches.append(u)
        if len(coaches):
            qs = qs.filter(user__in=coaches)

        ce = pv.observed_event
        if ce is not None:
            qs = ce.add_filter(qs, pv)

        if pv.primary_coachings == dd.YesNo.yes:
            qs = qs.filter(primary=True)
        elif pv.primary_coachings == dd.YesNo.no:
            qs = qs.filter(primary=False)
        if pv.coaching_type is not None:
            qs = qs.filter(type=pv.coaching_type)
        if pv.ending is not None:
            qs = qs.filter(ending=pv.ending)
        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Coachings, self).get_title_tags(ar):
            yield t

        pv = ar.param_values

        if pv.observed_event:
            yield unicode(pv.observed_event)

        if pv.coached_by:
            s = unicode(self.parameters['coached_by'].verbose_name) + \
                ' ' + unicode(pv.coached_by)
            if pv.and_coached_by:
                s += " %s %s" % (unicode(_('and')), pv.and_coached_by)
            yield s

        if pv.primary_coachings:
            yield unicode(self.parameters['primary_coachings'].verbose_name) \
                + ' ' + unicode(pv.primary_coachings)

    @classmethod
    def get_create_permission(self, ar):
        """Reception clerks can see coachings, but cannot modify them nor add
        new ones.

        """

        if not ar.get_user().profile.has_required_roles([CoachingsUser]):
            #if not ar.get_user().profile.coaching_level:
            return False
        return super(Coachings, self).get_create_permission(ar)
Пример #8
0
class Events(dd.Table):
    """Table which shows all calendar events.

    .. attribute:: show_appointments

        Whether only :term:`appointments <appointment>` should be
        shown.  "Yes" means only appointments, "No"
        means no appointments and leaving it to blank shows both types
        of events.

        An appointment is an event whose *event type* has
        :attr:`appointment
        <lino_xl.lib.cal.models.EventType.appointment>` checked.

    """

    help_text = _("A List of calendar entries. Each entry is called an event.")
    model = 'cal.Event'
    required_roles = dd.required(OfficeStaff)
    column_names = 'when_text:20 user summary event_type id *'

    # hidden_columns = """
    # priority access_class transparent
    # owner created modified
    # description
    # sequence auto_type build_time owner owner_id owner_type
    # end_date end_time
    # """

    order_by = ["start_date", "start_time", "id"]

    detail_layout = EventDetail()
    insert_layout = EventInsert()

    params_panel_hidden = True

    parameters = mixins.ObservedPeriod(
        user=dd.ForeignKey(settings.SITE.user_model,
                           verbose_name=_("Managed by"),
                           blank=True, null=True,
                           help_text=_("Only rows managed by this user.")),
        project=dd.ForeignKey(settings.SITE.project_model,
                              blank=True, null=True),
        event_type=dd.ForeignKey('cal.EventType', blank=True, null=True),
        room=dd.ForeignKey('cal.Room', blank=True, null=True),
        assigned_to=dd.ForeignKey(settings.SITE.user_model,
                                  verbose_name=_("Assigned to"),
                                  blank=True, null=True,
                                  help_text=_(
                                      "Only events assigned to this user.")),
        state=EventStates.field(blank=True,
                                help_text=_("Only rows having this state.")),
        # unclear = models.BooleanField(_("Unclear events"))
        observed_event=EventEvents.field(blank=True),
        show_appointments=dd.YesNo.field(_("Appointments"), blank=True),
    )

    params_layout = """
    start_date end_date observed_event state
    user assigned_to project event_type room show_appointments
    """
    # ~ next = NextDateAction() # doesn't yet work. 20121203

    fixed_states = set(EventStates.filter(fixed=True))
    # pending_states = set([es for es in EventStates if not es.fixed])
    pending_states = set(EventStates.filter(fixed=False))

    @classmethod
    def get_request_queryset(self, ar):
        # logger.info("20121010 Clients.get_request_queryset %s",ar.param_values)
        qs = super(Events, self).get_request_queryset(ar)
        pv = ar.param_values

        if pv.user:
            qs = qs.filter(user=pv.user)
        if pv.assigned_to:
            qs = qs.filter(assigned_to=pv.assigned_to)

        if settings.SITE.project_model is not None and pv.project:
            qs = qs.filter(project=pv.project)

        if pv.event_type:
            qs = qs.filter(event_type=pv.event_type)
        else:
            if pv.show_appointments == dd.YesNo.yes:
                qs = qs.filter(event_type__is_appointment=True)
            elif pv.show_appointments == dd.YesNo.no:
                qs = qs.filter(event_type__is_appointment=False)

        if pv.state:
            qs = qs.filter(state=pv.state)

        if pv.room:
            qs = qs.filter(room=pv.room)

        if pv.observed_event == EventEvents.stable:
            qs = qs.filter(state__in=self.fixed_states)
        elif pv.observed_event == EventEvents.pending:
            qs = qs.filter(state__in=self.pending_states)

        if pv.start_date:
            qs = qs.filter(start_date__gte=pv.start_date)
        if pv.end_date:
            qs = qs.filter(start_date__lte=pv.end_date)
        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Events, self).get_title_tags(ar):
            yield t
        pv = ar.param_values
        if pv.start_date or pv.end_date:
            yield daterange_text(
                pv.start_date,
                pv.end_date)

        if pv.state:
            yield unicode(pv.state)

        if pv.event_type:
            yield unicode(pv.event_type)

        # if pv.user:
        #     yield unicode(pv.user)

        if pv.room:
            yield unicode(pv.room)

        if settings.SITE.project_model is not None and pv.project:
            yield unicode(pv.project)

        if pv.assigned_to:
            yield unicode(self.parameters['assigned_to'].verbose_name) \
                + ' ' + unicode(pv.assigned_to)

    @classmethod
    def apply_cell_format(self, ar, row, col, recno, td):
        """
        Enhance today by making background color a bit darker.
        """
        if row.start_date == settings.SITE.today():
            td.attrib.update(bgcolor="#bbbbbb")

    @classmethod
    def param_defaults(self, ar, **kw):
        kw = super(Events, self).param_defaults(ar, **kw)
        kw.update(start_date=settings.SITE.site_config.hide_events_before)
        return kw
Пример #9
0
class Guests(dd.Table):
    "The default table for :class:`Guest`."
    help_text = _("""A guest is a partner invited to an event. """)
    model = 'cal.Guest'
    required_roles = dd.required(dd.SiteStaff, OfficeUser)
    column_names = 'partner role workflow_buttons remark event *'
    detail_layout = """
    event partner role
    state remark workflow_buttons
    # outbox.MailsByController
    """
    insert_layout = dd.InsertLayout("""
    event
    partner
    role
    """, window_size=(60, 'auto'))

    parameters = mixins.ObservedPeriod(
        user=dd.ForeignKey(settings.SITE.user_model,
                           verbose_name=_("Responsible user"),
                           blank=True, null=True,
                           help_text=_("Only rows managed by this user.")),
        project=dd.ForeignKey(settings.SITE.project_model,
                              blank=True, null=True),
        partner=dd.ForeignKey(dd.plugins.cal.partner_model,
                              blank=True, null=True),

        event_state=EventStates.field(
            blank=True,
            verbose_name=_("Event state"),
            help_text=_("Only rows having this event state.")),
        guest_state=GuestStates.field(
            blank=True,
            verbose_name=_("Guest state"),
            help_text=_("Only rows having this guest state.")),
    )

    params_layout = """start_date end_date user event_state guest_state
    project partner"""

    @classmethod
    def get_request_queryset(self, ar):
        # logger.info("20121010 Clients.get_request_queryset %s",ar.param_values)
        qs = super(Guests, self).get_request_queryset(ar)

        if isinstance(qs, list):
            return qs

        if ar.param_values.user:
            qs = qs.filter(event__user=ar.param_values.user)
        if settings.SITE.project_model is not None and ar.param_values.project:
            qs = qs.filter(event__project=ar.param_values.project)

        if ar.param_values.event_state:
            qs = qs.filter(event__state=ar.param_values.event_state)

        if ar.param_values.guest_state:
            qs = qs.filter(state=ar.param_values.guest_state)

        if ar.param_values.partner:
            qs = qs.filter(partner=ar.param_values.partner)

        if ar.param_values.start_date:
            if ar.param_values.end_date:
                qs = qs.filter(
                    event__start_date__gte=ar.param_values.start_date)
            else:
                qs = qs.filter(event__start_date=ar.param_values.start_date)
        if ar.param_values.end_date:
            qs = qs.filter(event__end_date__lte=ar.param_values.end_date)
        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Guests, self).get_title_tags(ar):
            yield t
        pv = ar.param_values
        if pv.start_date or pv.end_date:
            yield unicode(_("Dates %(min)s to %(max)s") % dict(
                min=pv.start_date or'...',
                max=pv.end_date or '...'))

        if pv.event_state:
            yield unicode(pv.event_state)

        if pv.partner:
            yield unicode(pv.partner)

        if pv.guest_state:
            yield unicode(pv.guest_state)

        # if pv.user:
        #     yield unicode(pv.user)

        if settings.SITE.project_model is not None and pv.project:
            yield unicode(pv.project)
Пример #10
0
class Tasks(dd.Table):
    help_text = _("""A calendar task is something you need to do.""")
    model = 'cal.Task'
    required_roles = dd.required(OfficeStaff)
    column_names = 'start_date summary workflow_buttons *'
    order_by = ["start_date", "start_time"]

    detail_layout = """
    start_date due_date id workflow_buttons
    summary
    user project
    #event_type owner created:20 modified:20
    description #notes.NotesByTask
    """

    insert_layout = dd.InsertLayout("""
    summary
    user project
    """, window_size=(50, 'auto'))

    params_panel_hidden = True

    parameters = mixins.ObservedPeriod(
        user=dd.ForeignKey(settings.SITE.user_model,
                           verbose_name=_("Managed by"),
                           blank=True, null=True,
                           help_text=_("Only rows managed by this user.")),
        project=dd.ForeignKey(settings.SITE.project_model,
                              blank=True, null=True),
        state=TaskStates.field(blank=True,
                               help_text=_("Only rows having this state.")),
    )

    params_layout = """
    start_date end_date user state project
    """

    @classmethod
    def get_request_queryset(self, ar):
        # logger.info("20121010 Clients.get_request_queryset %s",ar.param_values)
        qs = super(Tasks, self).get_request_queryset(ar)

        if ar.param_values.user:
            qs = qs.filter(user=ar.param_values.user)

        if settings.SITE.project_model is not None and ar.param_values.project:
            qs = qs.filter(project=ar.param_values.project)

        if ar.param_values.state:
            qs = qs.filter(state=ar.param_values.state)

        if ar.param_values.start_date:
            qs = qs.filter(start_date__gte=ar.param_values.start_date)
        if ar.param_values.end_date:
            qs = qs.filter(start_date__lte=ar.param_values.end_date)
        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Tasks, self).get_title_tags(ar):
            yield t
        if ar.param_values.start_date or ar.param_values.end_date:
            yield unicode(_("Dates %(min)s to %(max)s") % dict(
                min=ar.param_values.start_date or'...',
                max=ar.param_values.end_date or '...'))

        if ar.param_values.state:
            yield unicode(ar.param_values.state)

        # if ar.param_values.user:
        #     yield unicode(ar.param_values.user)

        if settings.SITE.project_model is not None and ar.param_values.project:
            yield unicode(ar.param_values.project)

    @classmethod
    def apply_cell_format(self, ar, row, col, recno, td):
        """
        Enhance today by making background color a bit darker.
        """
        if row.start_date == settings.SITE.today():
            td.attrib.update(bgcolor="gold")
Пример #11
0
class Enrolments(dd.Table):
    """Base class for all enrolment tables."""

    _course_area = None

    # debug_permissions=20130531
    model = 'courses.Enrolment'
    stay_in_grid = True
    parameters = mixins.ObservedPeriod(
        author=dd.ForeignKey(settings.SITE.user_model, blank=True, null=True),
        state=EnrolmentStates.field(blank=True, null=True),
        course_state=CourseStates.field(_("Course state"),
                                        blank=True,
                                        null=True),
        participants_only=models.BooleanField(
            _("Participants only"),
            help_text=_("Hide cancelled enrolments. "
                        "Ignored if you specify an explicit enrolment state."),
            default=True),
    )
    params_layout = """start_date end_date author state \
    course_state participants_only"""
    order_by = ['request_date']
    column_names = 'request_date course pupil workflow_buttons user *'
    # hidden_columns = 'id state'
    insert_layout = """
    request_date user
    course pupil
    remark
    """
    detail_layout = """
    request_date user start_date end_date
    course pupil
    remark workflow_buttons
    confirmation_details
    """

    @classmethod
    def get_known_values(self):
        if self._course_area is not None:
            return dict(course_area=self._course_area)
        return dict()

    @classmethod
    def create_instance(self, ar, **kw):
        if self._course_area is not None:
            kw.update(course_area=self._course_area)
        # dd.logger.info("20160714 %s", kw)
        return super(Enrolments, self).create_instance(ar, **kw)

    @classmethod
    def get_actor_label(self):
        if self._course_area is not None:
            return self._course_area.text
        return super(Enrolments, self).get_actor_label()

    @classmethod
    def get_request_queryset(self, ar):
        qs = super(Enrolments, self).get_request_queryset(ar)
        if isinstance(qs, list):
            return qs
        pv = ar.param_values
        if pv.author is not None:
            qs = qs.filter(user=pv.author)

        if pv.state:
            qs = qs.filter(state=pv.state)
        else:
            if pv.participants_only:
                qs = qs.exclude(state=EnrolmentStates.cancelled)

        if pv.course_state:
            qs = qs.filter(course__state=pv.course_state)

        if pv.start_date or pv.end_date:
            qs = PeriodEvents.active.add_filter(qs, pv)

        # if pv.start_date is None or pv.end_date is None:
        #     period = None
        # else:
        #     period = (pv.start_date, pv.end_date)
        # if period is not None:
        #     qs = qs.filter(dd.inrange_filter('request_date', period))

        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Enrolments, self).get_title_tags(ar):
            yield t

        if ar.param_values.state:
            yield unicode(ar.param_values.state)
        elif not ar.param_values.participants_only:
            yield unicode(_("Also ")) + unicode(EnrolmentStates.cancelled.text)
        if ar.param_values.course_state:
            yield unicode(
                settings.SITE.modules.courses.Course._meta.verbose_name) \
                + ' ' + unicode(ar.param_values.course_state)
        if ar.param_values.author:
            yield unicode(ar.param_values.author)
Пример #12
0
class Activities(dd.Table):
    """Base table for all activities.
    """
    _course_area = None
    required_roles = dd.required(CoursesUser)
    model = 'courses.Course'
    detail_layout = CourseDetail()
    insert_layout = """
    start_date
    line teacher
    """
    column_names = "start_date enrolments_until line teacher " \
                   "room workflow_buttons *"
    # order_by = ['start_date']
    # order_by = 'line__name room__name start_date'.split()
    # order_by = ['name']
    order_by = ['-start_date', '-start_time']
    auto_fit_column_widths = True

    parameters = mixins.ObservedPeriod(
        line=models.ForeignKey('courses.Line', blank=True, null=True),
        topic=models.ForeignKey('courses.Topic', blank=True, null=True),
        teacher=models.ForeignKey(teacher_model, blank=True, null=True),
        user=models.ForeignKey(settings.SITE.user_model, blank=True,
                               null=True),
        state=CourseStates.field(blank=True),
        can_enroll=dd.YesNo.field(blank=True),
    )

    params_layout = """topic line teacher state can_enroll:10 \
    start_date end_date"""

    # simple_parameters = 'line teacher state user'.split()

    @classmethod
    def create_instance(self, ar, **kw):
        # dd.logger.info("20160714 %s", kw)
        obj = super(Activities, self).create_instance(ar, **kw)
        if self._course_area is not None:
            obj.course_area = self._course_area
        return obj

    @classmethod
    def get_actor_label(self):
        if self._course_area is not None:
            return self._course_area.text
        return super(Activities, self).get_actor_label()

    @classmethod
    def get_simple_parameters(cls):
        s = super(Activities, cls).get_simple_parameters()
        s.add('line')
        s.add('teacher')
        s.add('state')
        s.add('user')
        return s

    @classmethod
    def get_request_queryset(self, ar):
        # dd.logger.info("20160223 %s", self)
        qs = super(Activities, self).get_request_queryset(ar)
        if isinstance(qs, list):
            return qs

        if self._course_area is not None:
            qs = qs.filter(line__course_area=self._course_area)

        pv = ar.param_values
        if pv.topic:
            qs = qs.filter(line__topic=pv.topic)

        flt = Q(enrolments_until__isnull=True)
        flt |= Q(enrolments_until__gte=dd.today())
        if pv.can_enroll == dd.YesNo.yes:
            qs = qs.filter(flt)
        elif pv.can_enroll == dd.YesNo.no:
            qs = qs.exclude(flt)
        qs = PeriodEvents.active.add_filter(qs, pv)
        # if pv.start_date:
        #     # dd.logger.info("20160512 start_date is %r", pv.start_date)
        #     qs = PeriodEvents.started.add_filter(qs, pv)
        #     # qs = qs.filter(start_date__gte=pv.start_date)
        # if pv.end_date:
        #     qs = PeriodEvents.ended.add_filter(qs, pv)
        #     # qs = qs.filter(end_date__lte=pv.end_date)
        # dd.logger.info("20160512 %s", qs.query)
        return qs

    @classmethod
    def get_title_tags(self, ar):
        for t in super(Activities, self).get_title_tags(ar):
            yield t

        if ar.param_values.topic:
            yield unicode(ar.param_values.topic)
Пример #13
0
class Movements(dd.Table):
    """
    The base table for all tables working on :class:`Movement`.
    Defines filtering parameters and general behaviour.

    Subclassed by e.g. :class:`AllMovements`,
    :class:`MovementsByVoucher`,
    :class:`MovementsByAccount` and :class:`MovementsByPartner`.

    See also :class:`lino_cosi.lib.ledger.models.Movement`.
    """

    model = 'ledger.Movement'
    required_roles = dd.login_required(LedgerUser)
    column_names = 'value_date voucher_link description \
    debit credit match_link cleared *'

    sum_text_column = 2

    editable = False
    parameters = mixins.ObservedPeriod(
        year=FiscalYears.field(blank=True),
        journal_group=JournalGroups.field(blank=True),
        partner=dd.ForeignKey('contacts.Partner', blank=True, null=True),
        project=dd.ForeignKey(dd.plugins.ledger.project_model,
                              blank=True,
                              null=True),
        account=dd.ForeignKey('accounts.Account', blank=True, null=True),
        journal=JournalRef(blank=True),
        cleared=dd.YesNo.field(_("Show cleared movements"), blank=True))
    params_layout = """
    start_date end_date cleared
    journal_group journal year project partner account"""

    @classmethod
    def get_request_queryset(cls, ar):
        qs = super(Movements, cls).get_request_queryset(ar)

        pv = ar.param_values
        if pv.cleared == dd.YesNo.yes:
            qs = qs.filter(cleared=True)
        elif pv.cleared == dd.YesNo.no:
            qs = qs.filter(cleared=False)

        # if ar.param_values.partner:
        #     qs = qs.filter(partner=ar.param_values.partner)
        # if ar.param_values.paccount:
        #     qs = qs.filter(account=ar.param_values.paccount)
        if pv.year:
            qs = qs.filter(voucher__accounting_period__year=pv.year)
        if pv.journal_group:
            qs = qs.filter(voucher__journal__journal_group=pv.journal_group)
        if pv.journal:
            qs = qs.filter(voucher__journal=pv.journal)
        return qs

    @classmethod
    def get_sum_text(self, ar, sums):
        bal = sums['debit'] - sums['credit']
        return _("Balance {1} ({0} movements)").format(ar.get_total_count(),
                                                       bal)

    @classmethod
    def get_simple_parameters(cls):
        p = super(Movements, cls).get_simple_parameters()
        p.add('partner')
        p.add('project')
        # p.add('journal_group')
        # p.add('year')
        p.add('account')
        return p

    @classmethod
    def get_title_tags(cls, ar):
        for t in super(Movements, cls).get_title_tags(ar):
            yield t
        pv = ar.param_values
        if pv.journal is not None:
            yield pv.journal.ref
        if pv.journal_group is not None:
            yield unicode(pv.journal_group)
        if pv.year is not None:
            yield unicode(pv.year)
        if pv.cleared == dd.YesNo.no:
            yield unicode(_("only uncleared"))
        elif pv.cleared == dd.YesNo.yes:
            yield unicode(_("only cleared"))

    @dd.displayfield(_("Description"))
    def description(cls, self, ar):
        if ar is None:
            return ''
        elems = []
        elems.append(ar.obj2html(self.account))
        voucher = self.voucher.get_mti_leaf()
        if voucher.narration:
            elems.append(voucher.narration)
        p = voucher.get_partner()
        if p is not None:
            elems.append(ar.obj2html(p))
        if self.project:
            elems.append(ar.obj2html(self.project))
        return E.p(*join_elems(elems, " / "))