Esempio n. 1
0
    def get_change_desc_html(self, f, old, new):
        from lino.core.choicelists import ChoiceListField
        if isinstance(f, models.TextField):
            old = old or ''
            new = new or ''
            return E.li(
                E.b(f.verbose_name), " : ",
                E.pre('\n'.join(
                    difflib.unified_diff(old.splitlines(),
                                         new.splitlines(),
                                         fromfile="before",
                                         tofile="after",
                                         lineterm=''))))

        if isinstance(f, models.DateTimeField):
            return
        if isinstance(f, models.ForeignKey):
            if old:
                old = f.rel.to.objects.get(pk=old)
            if new:
                new = f.rel.to.objects.get(pk=new)
        elif isinstance(f, ChoiceListField):
            if isinstance(old, six.string_types):
                old = f.choicelist.get_by_value(old)
            if isinstance(new, six.string_types):
                new = f.choicelist.get_by_value(new)
        else:
            old = obj2str(old)
            new = obj2str(new)
        return E.li(E.b(f.verbose_name), " : ",
                    u"{0} --> {1}".format(old, new))
Esempio n. 2
0
 def get_change_desc_html(self, f, old, new):
     from lino.core.choicelists import ChoiceListField
     if isinstance(f, models.TextField):
         old = old or ''
         new = new or ''
         return E.li(
             E.b(f.verbose_name), " : ",
             E.pre('\n'.join(difflib.unified_diff(
                 old.splitlines(), new.splitlines(),
                 fromfile="before", tofile="after", lineterm=''))))
         
     if isinstance(f, models.DateTimeField):
         return
     if isinstance(f, models.ForeignKey):
         if old:
             old = f.rel.to.objects.get(pk=old)
         if new:
             new = f.rel.to.objects.get(pk=new)
     elif isinstance(f, ChoiceListField):
         if isinstance(old, six.string_types):
             old = f.choicelist.get_by_value(old)
         if isinstance(new, six.string_types):
             new = f.choicelist.get_by_value(new)
     else:
         old = obj2str(old)
         new = obj2str(new)
     return E.li(
         E.b(f.verbose_name), " : ",
         u"{0} --> {1}".format(old, new))
Esempio n. 3
0
    def get_slave_summary(self, obj, ar):
        """Displays the uploads related to this controller as a list grouped
by uploads type.

Note that this also works on
:class:`lino_welfare.modlib.uploads.models.UploadsByClient` and their
subclasses for the different `_upload_area`.

        """
        UploadType = rt.modules.uploads.UploadType
        # Upload = rt.modules.uploads.Upload
        elems = []
        types = []

        for ut in UploadType.objects.filter(
                upload_area=self._upload_area):
            sar = ar.spawn(
                self, master_instance=obj,
                known_values=dict(type_id=ut.id))
            # logger.info("20140430 %s", sar.data_iterator.query)
            files = []
            for m in sar:
                text = self.format_row_in_slave_summary(ar, m)
                if text is None:
                    continue
                edit = ar.obj2html(
                    m,  text,  # _("Edit"),
                    # icon_name='application_form',
                    title=_("Edit metadata of the uploaded file."))
                if m.file.name:
                    show = ar.renderer.href_button(
                        settings.SITE.build_media_url(m.file.name),
                        _(" [show]"),  # fmt(m),
                        target='_blank',
                        icon_name='../xsite/link',
                        # icon_name='page_go',
                        # style="vertical-align:-30%;",
                        title=_("Open the uploaded file in a new browser window"))
                    # logger.info("20140430 %s", E.tostring(e))
                    files.append(E.span(edit, ' ', show))
                else:
                    files.append(edit)
            if ut.wanted and (
                    ut.max_number < 0 or len(files) < ut.max_number):
                files.append(sar.insert_button())
            if len(files) > 0:
                e = E.p(unicode(ut), ': ', *join_elems(files, ', '))
                types.append(e)
        # logger.info("20140430 %s", [E.tostring(e) for e in types])
        if len(types) == 0:
            elems.append(E.ul(E.li(ar.no_data_text)))
        else:
            elems.append(E.ul(*[E.li(e) for e in types]))
        return E.div(*elems)
Esempio n. 4
0
def buttons2pager(buttons, title=None):
    items = []
    if title:
        items.append(E.li(E.span(title)))
    for symbol, label, url in buttons:
        if url is None:
            items.append(E.li(E.span(symbol), class_="disabled"))
        else:
            items.append(E.li(E.a(symbol, href=url)))
    # Bootstrap version 2.x
    # return E.div(E.ul(*items), class_='pagination')
    return E.ul(*items, class_='pagination pagination-sm')
Esempio n. 5
0
    def get_slave_summary(self, obj, ar):
        # For every child, we want to display its relationship to
        # every parent of this household.
        sar = self.request(master_instance=obj)
        if sar.master_household is None:
            return E.div(ar.no_data_text)
        # obj is the Person for which we display the household

        def format_item(m):
            elems = [unicode(m.role), ': ']
            if m.person:
                elems += [obj.format_family_member(ar, m.person)]
                hl = self.find_links(ar, m.person, obj)
                if len(hl):
                    elems += [' ('] + hl + [')']
            else:
                elems += [obj.format_family_member(ar, m)]
            return elems
            
        items = []
        for m in sar.data_iterator:
            items.append(E.li(*format_item(m)))
        elems = []
        if len(items) > 0:
            elems = []
            elems.append(E.ul(*items))
        return E.div(*elems)
Esempio n. 6
0
    def about_html(cls):

        body = []

        body.append(settings.SITE.welcome_html())

        #~ print "20121112 startup_time", settings.SITE.startup_time.date()
        def dtfmt(dt):
            if isinstance(dt, float):
                dt = datetime.datetime.fromtimestamp(dt)
                #~ raise ValueError("Expected float, go %r" % dt)
            return unicode(_("%(date)s at %(time)s")) % dict(
                date=dd.fdf(dt.date()), time=dt.time())

        items = []
        times = []
        value = settings.SITE.startup_time
        label = _("Server uptime")
        body.append(E.p(unicode(label), ' : ', E.b(dtfmt(value))))
        body.append(E.p(unicode(_("Source timestamps:"))))
        for src in ("lino", "lino_welfare", 'django', 'atelier'):
            label = src
            value = codetime('%s.*' % src)
            if value is not None:
                times.append((label, value))

        def mycmp(a, b):
            return cmp(b[1], a[1])

        times.sort(mycmp)
        for label, value in times:
            items.append(E.li(unicode(label), ' : ', E.b(dtfmt(value))))
        body.append(E.ul(*items))
        return E.div(*body, class_='htmlText')
Esempio n. 7
0
 def collect_summary(prefix, fk_qs):
     parts = []
     for fld, qs in fk_qs:
         if qs.count() > 0:
             parts.append("%d %s" % (qs.count(), str(fld.model._meta.verbose_name_plural)))
     if len(parts) != 0:
         items.append(E.li(", ".join(parts), " ", E.b(prefix)))
Esempio n. 8
0
    def get_slave_summary(self, obj, ar):
        # For every child, we want to display its relationship to
        # every parent of this household.
        sar = self.request(master_instance=obj)
        if sar.master_household is None:
            return E.div(ar.no_data_text)
        # obj is the Person for which we display the household

        def format_item(m):
            elems = [unicode(m.role), ': ']
            if m.person:
                elems += [obj.format_family_member(ar, m.person)]
                hl = self.find_links(ar, m.person, obj)
                if len(hl):
                    elems += [' ('] + hl + [')']
            else:
                elems += [obj.format_family_member(ar, m)]
            return elems
            
        items = []
        for m in sar.data_iterator:
            items.append(E.li(*format_item(m)))
        elems = []
        if len(items) > 0:
            elems = []
            elems.append(E.ul(*items))
        return E.div(*elems)
Esempio n. 9
0
    def build_confirmation_message(self):
        self.analyze()
        items = []

        def collect_summary(prefix, fk_qs):
            parts = []
            for fld, qs in fk_qs:
                if qs.count() > 0:
                    parts.append(
                        "%d %s" %
                        (qs.count(), str(fld.model._meta.verbose_name_plural)))
            if len(parts) != 0:
                items.append(E.li(', '.join(parts), ' ', E.b(prefix)))

        collect_summary(_("will be deleted."), self.volatiles)
        collect_summary(_("will get reassigned."),
                        self.related + self.generic_related)
        items.append(E.li(_("%s will be deleted") % self.obj))
        msg = _("Are you sure you want to merge "
                "%(this)s into %(merge_to)s?") % dict(this=self.obj,
                                                      merge_to=self.merge_to)
        if len(items) != 0:
            # return E.div(E.p(msg), E.ul(*items), class_="htmlText")
            return rt.html_text(E.div(E.p(msg), E.ul(*items)))
        return msg
Esempio n. 10
0
    def build_confirmation_message(self):
        self.analyze()
        items = []

        def collect_summary(prefix, fk_qs):
            parts = []
            for fld, qs in fk_qs:
                if qs.count() > 0:
                    parts.append(
                        "%d %s" % (
                            qs.count(), str(
                                fld.model._meta.verbose_name_plural)))
            if len(parts) != 0:
                items.append(E.li(', '.join(parts), ' ', E.b(prefix)))

        collect_summary(_("will be deleted."), self.volatiles)
        collect_summary(_("will get reassigned."),
                        self.related + self.generic_related)
        items.append(E.li(_("%s will be deleted") % self.obj))
        msg = _("Are you sure you want to merge "
                "%(this)s into %(merge_to)s?") % dict(
                    this=self.obj, merge_to=self.merge_to)
        if len(items) != 0:
            # return E.div(E.p(msg), E.ul(*items), class_="htmlText")
            return rt.html_text(E.div(E.p(msg), E.ul(*items)))
        return msg
Esempio n. 11
0
    def about_html(cls):

        body = []

        body.append(settings.SITE.welcome_html())

        #~ print "20121112 startup_time", settings.SITE.startup_time.date()
        def dtfmt(dt):
            if isinstance(dt, float):
                dt = datetime.datetime.fromtimestamp(dt)
                #~ raise ValueError("Expected float, go %r" % dt)
            return unicode(_("%(date)s at %(time)s")) % dict(
                date=dd.fdf(dt.date()),
                time=dt.time())

        items = []
        times = []
        value = settings.SITE.startup_time
        label = _("Server uptime")
        body.append(E.p(unicode(label), ' : ', E.b(dtfmt(value))))
        body.append(E.p(unicode(_("Source timestamps:"))))
        for src in ("lino", "lino_welfare", 'django', 'atelier'):
            label = src
            value = codetime('%s.*' % src)
            if value is not None:
                times.append((label, value))

        def mycmp(a, b):
            return cmp(b[1], a[1])
        times.sort(mycmp)
        for label, value in times:
            items.append(E.li(unicode(label), ' : ', E.b(dtfmt(value))))
        body.append(E.ul(*items))
        return E.div(*body, class_='htmlText')
Esempio n. 12
0
    def get_slave_summary(self, obj, ar):
        """Displays a summary of all responses for a given partner using a
        bullet list grouped by poll.

        """
        if obj is None:
            return

        visible_polls = Poll.objects.filter(
            state__in=(PollStates.published,
                       PollStates.closed)).order_by('ref')

        qs = Response.objects.filter(partner=obj).order_by('date')
        polls_responses = {}
        for resp in qs:
            polls_responses.setdefault(resp.poll.pk, []).append(resp)

        items = []
        for poll in visible_polls:
            iar = self.insert_action.request_from(ar,
                                                  obj,
                                                  known_values=dict(poll=poll))
            elems = [str(poll), ' : ']
            responses = polls_responses.get(poll.pk, [])
            elems += join_elems(
                [ar.obj2html(r, dd.fds(r.date)) for r in responses], sep=', ')
            if poll.state == PollStates.published:
                elems += [' ', iar.ar2button()]
                #elems += [' ', iar.insert_button()]
            items.append(E.li(*elems))
        return E.div(E.ul(*items))
Esempio n. 13
0
    def get_slave_summary(self, obj, ar):
        """Displays a summary of all responses for a given partner using a
        bullet list grouped by poll.

        """
        if obj is None:
            return

        visible_polls = Poll.objects.filter(state__in=(PollStates.published, PollStates.closed)).order_by("ref")

        qs = Response.objects.filter(partner=obj).order_by("date")
        polls_responses = {}
        for resp in qs:
            polls_responses.setdefault(resp.poll.pk, []).append(resp)

        items = []
        for poll in visible_polls:
            iar = self.insert_action.request_from(ar, obj, known_values=dict(poll=poll))
            elems = [unicode(poll), " : "]
            responses = polls_responses.get(poll.pk, [])
            elems += join_elems([ar.obj2html(r, dd.fds(r.date)) for r in responses], sep=", ")
            if poll.state == PollStates.published:
                elems += [" ", iar.ar2button()]
                # elems += [' ', iar.insert_button()]
            items.append(E.li(*elems))
        return E.div(E.ul(*items))
Esempio n. 14
0
    def show_menu(self, ar, mnu, level=1):
        """
        Render the given menu as an HTML element.
        Used for writing test cases.
        """
        if not isinstance(mnu, Menu):
            assert isinstance(mnu, MenuItem)
            if mnu.bound_action:
                sr = mnu.bound_action.actor.request(
                    action=mnu.bound_action,
                    user=ar.user,
                    subst_user=ar.subst_user,
                    requesting_panel=ar.requesting_panel,
                    renderer=self,
                    **mnu.params)

                url = sr.get_request_url()
            else:
                url = mnu.href
            assert mnu.label is not None
            if url is None:
                return E.p()  # spacer
            return E.li(E.a(mnu.label, href=url, tabindex="-1"))

        items = [self.show_menu(ar, mi, level + 1) for mi in mnu.items]
        #~ print 20120901, items
        if level == 1:
            return E.ul(*items, class_='nav navbar-nav')
        if mnu.label is None:
            raise Exception("%s has no label" % mnu)
        if level == 2:
            cl = 'dropdown'
            menu_title = E.a(unicode(mnu.label),
                             E.b(' ', class_="caret"),
                             href="#",
                             class_='dropdown-toggle',
                             data_toggle="dropdown")
        elif level == 3:
            menu_title = E.a(unicode(mnu.label), href="#")
            cl = 'dropdown-submenu'
        else:
            raise Exception("Menu with more than three levels")
        return E.li(menu_title,
                    E.ul(*items, class_='dropdown-menu'),
                    class_=cl)
Esempio n. 15
0
 def as_list_item(self, ar):
     if settings.SITE.is_demo_site:
         p = "'{0}', '{1}'".format(self.username, '1234')
     else:
         p = "'{0}'".format(self.username)
     url = "javascript:Lino.show_login_window(null, {0})".format(p)
     return E.li(E.a(self.username, href=url), ' : ', str(self), ', ',
                 str(self.profile), ', ',
                 E.strong(settings.SITE.LANGUAGE_DICT.get(self.language)))
Esempio n. 16
0
 def collect_summary(prefix, fk_qs):
     parts = []
     for fld, qs in fk_qs:
         if qs.count() > 0:
             parts.append(
                 "%d %s" %
                 (qs.count(), str(fld.model._meta.verbose_name_plural)))
     if len(parts) != 0:
         items.append(E.li(', '.join(parts), ' ', E.b(prefix)))
Esempio n. 17
0
    def get_slave_summary(self, obj, ar):
        sar = self.request(master_instance=obj)
        links = []
        for lnk in sar:
            if lnk.child.id == obj.id:
                i = (lnk.type.as_child(obj), lnk.parent)
            else:
                i = (lnk.type.as_parent(obj), lnk.child)
            links.append(i)

        def by_age(a, b):
            return cmp(b[1].birth_date.as_date(), a[1].birth_date.as_date())

        try:
            links.sort(by_age)
        except AttributeError:
            # 'str' object has no attribute 'as_date'
            # possible when incomplete or empty birth_date
            pass

        items = []
        for type, other in links:
            items.append(E.li(
                unicode(type), _(" of "),
                obj.format_family_member(ar, other),
                " (%s)" % other.age()
            ))
        elems = []
        if len(items) > 0:
            elems += [_("%s is") % obj.first_name]
            elems.append(E.ul(*items))
        else:
            elems.append(_("No relationships."))

        actions = []

        def add_action(btn):
            if btn is None:
                return False
            actions.append(btn)
            return True

        for lt in addable_link_types:
            sar = ar.spawn(Links, known_values=dict(type=lt, parent=obj))
            if add_action(sar.insert_button(
                    lt.as_parent(obj), icon_name=None)):
                if not lt.symmetric:
                    actions.append('/')
                    sar = ar.spawn(
                        Links, known_values=dict(type=lt, child=obj))
                    add_action(sar.insert_button(
                        lt.as_child(obj), icon_name=None))
                actions.append(' ')

        elems += [E.br(), _("Create relationship as ")] + actions
        return E.div(*elems)
Esempio n. 18
0
 def as_list_item(self, ar):
     if settings.SITE.is_demo_site:
         p = "'{0}', '{1}'".format(self.username, '1234')
     else:
         p = "'{0}'".format(self.username)
     url = "javascript:Lino.show_login_window(null, {0})".format(p)
     return E.li(E.a(self.username, href=url), ' : ',
                 str(self), ', ',
                 str(self.profile), ', ',
                 E.strong(settings.SITE.LANGUAGE_DICT.get(self.language)))
Esempio n. 19
0
    def show_menu(self, ar, mnu, level=1):
        """
        Render the given menu as an HTML element.
        Used for writing test cases.
        """
        if not isinstance(mnu, Menu):
            assert isinstance(mnu, MenuItem)
            if mnu.bound_action:
                sr = mnu.bound_action.actor.request(
                    action=mnu.bound_action,
                    user=ar.user, subst_user=ar.subst_user,
                    requesting_panel=ar.requesting_panel,
                    renderer=self, **mnu.params)

                url = sr.get_request_url()
            else:
                url = mnu.href
            assert mnu.label is not None
            if url is None:
                return E.p()  # spacer
            return E.li(E.a(mnu.label, href=url, tabindex="-1"))

        items = [self.show_menu(ar, mi, level + 1) for mi in mnu.items]
        #~ print 20120901, items
        if level == 1:
            return E.ul(*items, class_='nav navbar-nav')
        if mnu.label is None:
            raise Exception("%s has no label" % mnu)
        if level == 2:
            cl = 'dropdown'
            menu_title = E.a(
                unicode(mnu.label), E.b(' ', class_="caret"), href="#",
                class_='dropdown-toggle', data_toggle="dropdown")
        elif level == 3:
            menu_title = E.a(unicode(mnu.label), href="#")
            cl = 'dropdown-submenu'
        else:
            raise Exception("Menu with more than three levels")
        return E.li(
            menu_title,
            E.ul(*items, class_='dropdown-menu'),
            class_=cl)
Esempio n. 20
0
    def get_slave_summary(self, obj, ar):
        sar = self.request(master_instance=obj)
        elems = []
        # n = sar.get_total_count()
        # if n == 0:
        #     elems += [_("Not member of any household."), E.br()]
        # else:

        items = []
        for m in sar.data_iterator:
            
            args = (unicode(m.role), _(" in "),
                    ar.obj2html(m.household))
            if m.primary:
                items.append(E.li(E.b("\u2611 ", *args)))
            else:
                btn = m.set_primary.as_button_elem(
                    ar, "\u2610 ", style="text-decoration:none;")
                items.append(E.li(btn, *args))
        if len(items) > 0:
            elems += [_("%s is") % obj]
            elems.append(E.ul(*items))
        if False:
            elems += [
                E.br(), ar.instance_action_button(obj.create_household)]
        else:
            elems += [E.br(), _("Create a household"), ' : ']
            Type = rt.modules.households.Type
            Person = dd.resolve_model(config.person_model)
            T = Person.get_default_table()
            ba = T.get_action_by_name('create_household')
            buttons = []
            for t in Type.objects.all():
                apv = dict(type=t, head=obj)
                sar = ar.spawn(ba,  # master_instance=obj,
                               selected_rows=[obj],
                               action_param_values=apv)
                buttons.append(ar.href_to_request(sar, unicode(t)))
            elems += join_elems(buttons, sep=' / ')
        return E.div(*elems)
Esempio n. 21
0
    def get_slave_summary(self, obj, ar):
        sar = self.request(master_instance=obj)
        elems = []
        # n = sar.get_total_count()
        # if n == 0:
        #     elems += [_("Not member of any household."), E.br()]
        # else:

        items = []
        for m in sar.data_iterator:
            
            args = (unicode(m.role), _(" in "),
                    ar.obj2html(m.household))
            if m.primary:
                items.append(E.li(E.b("\u2611 ", *args)))
            else:
                btn = m.set_primary.as_button_elem(
                    ar, "\u2610 ", style="text-decoration:none;")
                items.append(E.li(btn, *args))
        if len(items) > 0:
            elems += [_("%s is") % obj]
            elems.append(E.ul(*items))
        if False:
            elems += [
                E.br(), ar.instance_action_button(obj.create_household)]
        else:
            elems += [E.br(), _("Create a household"), ' : ']
            Type = rt.modules.households.Type
            Person = dd.resolve_model(config.person_model)
            T = Person.get_default_table()
            ba = T.get_action_by_name('create_household')
            buttons = []
            for t in Type.objects.all():
                apv = dict(type=t, head=obj)
                sar = ar.spawn(ba,  # master_instance=obj,
                               action_param_values=apv)
                buttons.append(ar.href_to_request(sar, unicode(t)))
            elems += join_elems(buttons, sep=' / ')
        return E.div(*elems)
Esempio n. 22
0
    def about_html(cls):

        body = []

        body.append(settings.SITE.welcome_html())

        if settings.SITE.languages:
            body.append(E.p(str(_("Languages")) + ": " + ', '.join([
                lng.django_code for lng in settings.SITE.languages])))

        # print "20121112 startup_time", settings.SITE.startup_time.date()
        def dtfmt(dt):
            if isinstance(dt, float):
                dt = datetime.datetime.fromtimestamp(dt)
                # raise ValueError("Expected float, go %r" % dt)
            return str(_("%(date)s at %(time)s")) % dict(
                date=dd.fds(dt.date()),
                time=settings.SITE.strftime(dt.time()))

        value = settings.SITE.startup_time
        label = _("Server uptime")
        body.append(E.p(
            str(label), ' : ', E.b(dtfmt(value)),
            ' ({})'.format(settings.TIME_ZONE)))
        if settings.SITE.is_demo_site:
            s = str(_("This is a Lino demo site."))
            body.append(E.p(s))
        if settings.SITE.the_demo_date:
            s = _("We are running with simulated date set to {0}.").format(
                dd.fdf(settings.SITE.the_demo_date))
            body.append(E.p(s))
            
        body.append(E.p(str(_("Source timestamps:"))))
        items = []
        times = []
        packages = set(['lino', 'django', 'atelier'])
        for p in settings.SITE.installed_plugins:
            packages.add(p.app_name.split('.')[0])
        for src in packages:
            label = src
            value = codetime('%s.*' % src)
            if value is not None:
                times.append((label, value))

        times.sort(key=lambda x: x[1])
        for label, value in times:
            items.append(E.li(str(label), ' : ', E.b(dtfmt(value))))
        body.append(E.ul(*items))
        # return E.div(*body, class_='htmlText')
        return rt.html_text(E.div(*body))
Esempio n. 23
0
        def add(title, flt):
            links = []
            sar = self.request(master_instance=obj, filter=flt)
            # logger.info("20141009 %s", sar.data_iterator.query)
            n = sar.get_total_count()
            if n:
                for i, ex in enumerate(sar):
                    txt = self.format_excerpt(ex)
                    if ex.build_time is not None:
                        txt += " (%s)" % naturaltime(ex.build_time)
                    links.append(ar.obj2html(ex, txt))
                    if i >= self.MORE_LIMIT:
                        # links.append(ar.href_to_request(sar, _("more")))
                        links.append('...')
                        break

                items.append(E.li(title, " : ", *join_elems(links, sep=', ')))
Esempio n. 24
0
    def about_html(cls):

        body = []

        body.append(settings.SITE.welcome_html())

        if settings.SITE.languages:
            body.append(
                E.p(str(_("Languages")) + ": " + ", ".join([lng.django_code for lng in settings.SITE.languages]))
            )

        # print "20121112 startup_time", settings.SITE.startup_time.date()
        def dtfmt(dt):
            if isinstance(dt, float):
                dt = datetime.datetime.fromtimestamp(dt)
                # raise ValueError("Expected float, go %r" % dt)
            return str(_("%(date)s at %(time)s")) % dict(date=dd.fds(dt.date()), time=settings.SITE.strftime(dt.time()))

        value = settings.SITE.startup_time
        label = _("Server uptime")
        body.append(E.p(str(label), " : ", E.b(dtfmt(value)), " ({})".format(settings.TIME_ZONE)))
        if settings.SITE.is_demo_site:
            s = str(_("This is a Lino demo site."))
            body.append(E.p(s))
        if settings.SITE.the_demo_date:
            s = _("We are running with simulated date set to {0}.").format(dd.fdf(settings.SITE.the_demo_date))
            body.append(E.p(s))

        body.append(E.p(str(_("Source timestamps:"))))
        items = []
        times = []
        packages = set(["lino", "django", "atelier"])
        for p in settings.SITE.installed_plugins:
            packages.add(p.app_name.split(".")[0])
        for src in packages:
            label = src
            value = codetime("%s.*" % src)
            if value is not None:
                times.append((label, value))

        times.sort(key=lambda x: x[1])
        for label, value in times:
            items.append(E.li(str(label), " : ", E.b(dtfmt(value))))
        body.append(E.ul(*items))
        # return E.div(*body, class_='htmlText')
        return rt.html_text(E.div(*body))
Esempio n. 25
0
        def add(title, flt):
            links = []
            sar = self.request(master_instance=obj, filter=flt)
            # logger.info("20141009 %s", sar.data_iterator.query)
            n = sar.get_total_count()
            if n:
                for i, ex in enumerate(sar):
                    txt = self.format_excerpt(ex)
                    if ex.build_time is not None:
                        txt += " (%s)" % naturaltime(ex.build_time)
                    links.append(ar.obj2html(ex, txt))
                    if i >= self.MORE_LIMIT:
                        # links.append(ar.href_to_request(sar, _("more")))
                        links.append('...')
                        break

                items.append(E.li(title, " : ", *join_elems(links, sep=', ')))
Esempio n. 26
0
    def about_html(cls):

        body = []

        body.append(settings.SITE.welcome_html())

        if settings.SITE.languages:
            body.append(E.p(str(_("Languages")) + ": " + ', '.join([
                lng.django_code for lng in settings.SITE.languages])))

        #~ print "20121112 startup_time", settings.SITE.startup_time.date()
        def dtfmt(dt):
            if isinstance(dt, float):
                dt = datetime.datetime.fromtimestamp(dt)
                #~ raise ValueError("Expected float, go %r" % dt)
            return str(_("%(date)s at %(time)s")) % dict(
                date=dd.fdf(dt.date()),
                time=dt.time())

        items = []
        times = []
        value = settings.SITE.startup_time
        label = _("Server uptime")
        body.append(E.p(str(label), ' : ', E.b(dtfmt(value))))
        if settings.SITE.is_demo_site:
            s = str(_("This is a Lino demo site."))
            body.append(E.p(s))
        if settings.SITE.the_demo_date:
            s = _("We are running with simulated date set to {0}.").format(
                dd.fdf(settings.SITE.the_demo_date))
            body.append(E.p(s))
        body.append(E.p(str(_("Source timestamps:"))))
        for src in ("lino", "lino_welfare", 'django', 'atelier'):
            label = src
            value = codetime('%s.*' % src)
            if value is not None:
                times.append((label, value))

        def mycmp(a, b):
            return cmp(b[1], a[1])
        times.sort(mycmp)
        for label, value in times:
            items.append(E.li(str(label), ' : ', E.b(dtfmt(value))))
        body.append(E.ul(*items))
        return E.div(*body, class_='htmlText')
Esempio n. 27
0
    def get_slave_summary(self, obj, ar):
        sar = self.request(master_instance=obj)
        elems = []
        # n = sar.get_total_count()
        # if n == 0:
        #     elems += [_("Not member of any household."), E.br()]
        # else:

        items = []
        for m in sar.data_iterator:
            items.append(E.li(
                unicode(m.role), _(" in "),
                # unicode(m.household.type), " ",
                ar.obj2html(m.household)))
        if len(items) > 0:
            elems += [_("%s is") % obj]
            elems.append(E.ul(*items))
        elems += [
            E.br(), ar.instance_action_button(obj.create_household)]
        return E.div(*elems)
Esempio n. 28
0
    def welcome(cls, self, ar):

        #~ MAXITEMS = 2
        u = ar.get_user()
        story = []

        if u.profile.authenticated:

            intro = [_("Hi, %(user)s!") % dict(user=u.first_name)]
            story.append(E.p(*intro))
            warnings = []

            #~ for T in (MySuggestedCoachings,cal.MyTasksToDo):
            for table, text in settings.SITE.get_todo_tables(ar):
                if table.get_view_permission(u.profile):
                    r = table.request(user=u)
                    #~ r = T.request(subst_user=u)
                    #~ r = ar.spawn(T)
                    if r.get_total_count() != 0:
                        warnings.append(E.li(
                            ar.href_to_request(r, text % r.get_total_count())))
                            #~ _("You have %d entries in ") % r.get_total_count(),
                            #~ ar.href_to_request(r,label)))

            #~ warnings.append(E.li("Test 1"))
            #~ warnings.append(E.li("Second test"))
            if len(warnings):
                #~ story.append(E.h3(_("Warnings")))
                story.append(E.h3(_("You have")))
                story.append(E.ul(*warnings))
            else:
                story.append(
                    E.p(_("Congratulatons: you have no warnings.")))
        #~ else:
            # story.append(E.p("Please log in"))
            #~ story.append(settings.SITE.get_guest_greeting())

        return E.div(*story, class_="htmlText", style="margin:5px")
Esempio n. 29
0
 def cbss_relations(self, ar):
     if ar is None:
         return ''
     cbss = dd.resolve_app('cbss')
     SLAVE = cbss.RetrieveTIGroupsRequestsByPerson
     elems = []
     sar = ar.spawn(
         SLAVE, master_instance=self,
         filter=models.Q(status__in=OK_STATES))
     btn = SLAVE.insert_action.request_from(ar).ar2button()
     n = sar.get_total_count()
     if n > 0:
         items = []
         SHOWN_TYPES = ('110', '120', '140', '141')
         obj = sar.data_iterator[n - 1]
         res = obj.Result(ar)
         for row in res:
             if row.type in SHOWN_TYPES:
                 chunks = []
                 if row.counter == 1:
                     chunks += [
                         'IT%s (' % row.type,
                         E.b(row.group),
                         ') ']
                 chunks += [str(row.since), ' ', row.info]
                 items.append(E.li(*chunks))
         if len(items) > 0:
             elems.append(E.ul(*items))
                 
         text = "%s %s" % (obj._meta.verbose_name, naturaltime(obj.sent))
         elems.append(ar.obj2html(obj, text))
     if btn is not None:
         elems += [' ', btn]
     if None in elems:
         raise Exception("20140513 None in %r" % elems)
     return E.div(*elems)
Esempio n. 30
0
 def as_list_item(self, ar):
     return E.li(str(self))
Esempio n. 31
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`LinksByHuman`.

        """
        # if obj.pk is None:
        #     return ''
        #     raise Exception("20150218")
        sar = self.request_from(ar, master_instance=obj)
        links = []
        for lnk in sar:
            if lnk.parent is None or lnk.child is None:
                pass
            else:
                if lnk.child_id == obj.id:
                    i = (lnk.type.as_child(obj), lnk.parent)
                else:
                    i = (lnk.type.as_parent(obj), lnk.child)
                links.append(i)

        def by_age(a, b):
            return cmp(b[1].birth_date.as_date(), a[1].birth_date.as_date())

        try:
            links.sort(by_age)
        # except AttributeError:
        except (AttributeError, ValueError):
            # AttributeError: 'str' object has no attribute 'as_date'
            # possible when empty birth_date
            # ValueError: day is out of range for month
            pass

        items = []
        for type, other in links:
            items.append(E.li(
                str(type), _(" of "),
                obj.format_family_member(ar, other),
                " (%s)" % other.age
            ))
        elems = []
        if len(items) > 0:
            elems += [_("%s is") % obj.first_name]
            elems.append(E.ul(*items))
        else:
            elems.append(_("No relationships."))

        # Buttons for creating relationships:
        sar = self.insert_action.request_from(ar)
        if sar.get_permission():
            actions = []
            for lt in self.addable_link_types:
                sar.known_values.update(type=lt, parent=obj)
                sar.known_values.pop('child', None)
                #sar = ar.spawn(self, known_values=dict(type=lt, parent=obj))
                btn = sar.ar2button(None, lt.as_parent(obj), icon_name=None)
                actions.append(btn)
                if not lt.symmetric:
                    actions.append('/')
                    sar.known_values.update(type=lt, child=obj)
                    sar.known_values.pop('parent', None)
                    btn = sar.ar2button(None, lt.as_child(obj), icon_name=None)
                    actions.append(btn)
                actions.append(' ')

            if len(actions) > 0:
                elems += [E.br(), _("Create relationship as ")] + actions
        return E.div(*elems)
Esempio n. 32
0
 def as_list_item(self, ar):
     return E.li(E.strong(self.username), ' : ', unicode(self), ', ',
                 unicode(self.profile), ', ',
                 E.strong(settings.SITE.LANGUAGE_DICT.get(self.language)))
Esempio n. 33
0
 def as_list_item(self, ar):
     return E.li(unicode(self))
Esempio n. 34
0
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`LinksByHuman`.

        """
        # if obj.pk is None:
        #     return ''
        #     raise Exception("20150218")
        sar = self.request_from(ar, master_instance=obj)
        links = []
        for lnk in sar:
            if lnk.parent is None or lnk.child is None:
                pass
            else:
                if lnk.child_id == obj.id:
                    i = (lnk.type.as_child(obj), lnk.parent)
                else:
                    i = (lnk.type.as_parent(obj), lnk.child)
                links.append(i)

        def by_age(a, b):
            return cmp(b[1].birth_date.as_date(), a[1].birth_date.as_date())

        try:
            links.sort(by_age)
        # except AttributeError:
        except (AttributeError, ValueError):
            # AttributeError: 'str' object has no attribute 'as_date'
            # possible when empty birth_date
            # ValueError: day is out of range for month
            pass

        items = []
        for type, other in links:
            items.append(
                E.li(unicode(type), _(" of "),
                     obj.format_family_member(ar, other), " (%s)" % other.age))
        elems = []
        if len(items) > 0:
            elems += [_("%s is") % obj.first_name]
            elems.append(E.ul(*items))
        else:
            elems.append(_("No relationships."))

        # Buttons for creating relationships:
        sar = self.insert_action.request_from(ar)
        if sar.get_permission():
            actions = []
            for lt in self.addable_link_types:
                sar.known_values.update(type=lt, parent=obj)
                sar.known_values.pop('child', None)
                #sar = ar.spawn(self, known_values=dict(type=lt, parent=obj))
                btn = sar.ar2button(None, lt.as_parent(obj), icon_name=None)
                actions.append(btn)
                if not lt.symmetric:
                    actions.append('/')
                    sar.known_values.update(type=lt, child=obj)
                    sar.known_values.pop('parent', None)
                    btn = sar.ar2button(None, lt.as_child(obj), icon_name=None)
                    actions.append(btn)
                actions.append(' ')

            if len(actions) > 0:
                elems += [E.br(), _("Create relationship as ")] + actions
        return E.div(*elems)
Esempio n. 35
0
 def as_list_item(self, ar):
     return E.li(unicode(self))
Esempio n. 36
0
 def as_list_item(self, ar):
     return E.li(str(self))
Esempio n. 37
0
 def as_list_item(self, ar):
     return E.li(E.strong(self.username), ' : ',
                 unicode(self), ', ',
                 unicode(self.profile), ', ',
                 E.strong(settings.SITE.LANGUAGE_DICT.get(self.language)))
Esempio n. 38
0
    def get_slave_summary(self, obj, ar):
        """Displays the uploads related to this controller as a list grouped
        by uploads type.

        Note that this also works on
        :class:`lino_welfare.modlib.uploads.models.UploadsByClient`
        and their subclasses for the different `_upload_area`.

        """
        UploadType = rt.modules.uploads.UploadType
        # Upload = rt.modules.uploads.Upload
        elems = []
        types = []

        perm = ar.get_user().profile.has_required_roles(self.required_roles)

        for ut in UploadType.objects.filter(upload_area=self._upload_area):
            sar = ar.spawn(self,
                           master_instance=obj,
                           known_values=dict(type_id=ut.id))
            # logger.info("20140430 %s", sar.data_iterator.query)
            files = []
            for m in sar:
                text = self.format_row_in_slave_summary(ar, m)
                if text is None:
                    continue
                edit = ar.obj2html(
                    m,
                    text,  # _("Edit"),
                    # icon_name='application_form',
                    title=_("Edit metadata of the uploaded file."))
                if m.file.name:
                    show = ar.renderer.href_button(
                        settings.SITE.build_media_url(m.file.name),
                        # u"\u21A7",  # DOWNWARDS ARROW FROM BAR (↧)
                        # u"\u21E8",
                        u"\u21f2",  # SOUTH EAST ARROW TO CORNER (⇲)
                        style="text-decoration:none;",
                        # _(" [show]"),  # fmt(m),
                        target='_blank',
                        # icon_name=settings.SITE.build_static_url(
                        #     'images/xsite/link'),
                        # icon_name='page_go',
                        # style="vertical-align:-30%;",
                        title=_(
                            "Open the uploaded file in a new browser window"))
                    # logger.info("20140430 %s", E.tostring(e))
                    files.append(E.span(edit, ' ', show))
                else:
                    files.append(edit)
            if perm and ut.wanted \
               and (ut.max_number < 0 or len(files) < ut.max_number):
                btn = self.insert_action.request_from(
                    sar, master_instance=obj,
                    known_values=dict(type_id=ut.id)).ar2button()
                if btn is not None:
                    files.append(btn)
            if len(files) > 0:
                e = E.p(unicode(ut), ': ', *join_elems(files, ', '))
                types.append(e)
        # logger.info("20140430 %s", [E.tostring(e) for e in types])
        if len(types) == 0:
            elems.append(E.ul(E.li(ar.no_data_text)))
        else:
            elems.append(E.ul(*[E.li(e) for e in types]))
        return E.div(*elems)
Esempio n. 39
0
    def get_slave_summary(self, obj, ar):
        """Displays the uploads related to this controller as a list grouped
        by uploads type.

        Note that this also works on
        :class:`lino_welfare.modlib.uploads.models.UploadsByClient`
        and their subclasses for the different `_upload_area`.

        """
        UploadType = rt.modules.uploads.UploadType
        # Upload = rt.modules.uploads.Upload
        elems = []
        types = []

        perm = ar.get_user().profile.has_required_roles(self.required_roles)

        for ut in UploadType.objects.filter(upload_area=self._upload_area):
            sar = ar.spawn(
                self, master_instance=obj,
                known_values=dict(type_id=ut.id))
            # logger.info("20140430 %s", sar.data_iterator.query)
            files = []
            for m in sar:
                text = self.format_row_in_slave_summary(ar, m)
                if text is None:
                    continue
                edit = ar.obj2html(
                    m,  text,  # _("Edit"),
                    # icon_name='application_form',
                    title=_("Edit metadata of the uploaded file."))
                if m.file.name:
                    show = ar.renderer.href_button(
                        settings.SITE.build_media_url(m.file.name),
                        # u"\u21A7",  # DOWNWARDS ARROW FROM BAR (↧)
                        # u"\u21E8",
                        u"\u21f2",  # SOUTH EAST ARROW TO CORNER (⇲)
                        style="text-decoration:none;",
                        # _(" [show]"),  # fmt(m),
                        target='_blank',
                        # icon_name=settings.SITE.build_static_url(
                        #     'images/xsite/link'),
                        # icon_name='page_go',
                        # style="vertical-align:-30%;",
                        title=_("Open the uploaded file in a new browser window"))
                    # logger.info("20140430 %s", E.tostring(e))
                    files.append(E.span(edit, ' ', show))
                else:
                    files.append(edit)
            if perm and ut.wanted \
               and (ut.max_number < 0 or len(files) < ut.max_number):
                btn = self.insert_action.request_from(
                    sar, master_instance=obj,
                    known_values=dict(type_id=ut.id)).ar2button()
                if btn is not None:
                    files.append(btn)
            if len(files) > 0:
                e = E.p(str(ut), ': ', *join_elems(files, ', '))
                types.append(e)
        # logger.info("20140430 %s", [E.tostring(e) for e in types])
        if len(types) == 0:
            elems.append(E.ul(E.li(ar.no_data_text)))
        else:
            elems.append(E.ul(*[E.li(e) for e in types]))
        return E.div(*elems)
Esempio n. 40
0
File: ui.py Progetto: khchine5/noi
    def get_slave_summary(self, obj, ar):
        """The :meth:`summary view <lino.core.actors.Actor.get_slave_summary>`
        for :class:`LinksByTicket`.

        """
        # if obj.pk is None:
        #     return ''
        #     raise Exception("20150218")
        sar = self.request_from(ar, master_instance=obj)
        links = []
        for lnk in sar:
            if lnk.parent is None or lnk.child is None:
                pass
            else:
                if lnk.child_id == obj.id:
                    i = (lnk.type.as_child(), lnk.parent)
                else:
                    i = (lnk.type.as_parent(), lnk.child)
                links.append(i)

        def by_age(a):
            return a[1].modified

        try:
            links.sort(key=by_age)
        # except AttributeError:
        except (AttributeError, ValueError):
            # AttributeError: 'str' object has no attribute 'as_date'
            # possible when empty birth_date
            # ValueError: day is out of range for month
            pass

        tbt = dict()  # tickets by lnktype
        for lnktype, other in links:
            lst = tbt.setdefault(lnktype, [])
            txt = "#%d" % other.id
            lst.append(ar.obj2html(other, txt, title=other.summary))

        items = []
        for lnktype, lst in tbt.items():
            items.append(E.li(unicode(lnktype), ": ", *join_elems(lst, ', ')))
        elems = []
        if len(items) > 0:
            # elems += join_elems(items)
            # elems.append(l(*items))
            elems.append(E.ul(*items))
        # else:
        #     elems.append(_("No dependencies."))

        # Buttons for creating relationships:

        sar = obj.spawn_triggered.request_from(ar)
        if ar.renderer.is_interactive and sar.get_permission():
            btn = sar.ar2button(obj)
            elems += [E.br(), btn]

        sar = self.insert_action.request_from(ar)
        if ar.renderer.is_interactive and sar.get_permission():
            actions = []
            for lt in LinkTypes.objects():
                actions.append(E.br())
                sar.known_values.update(type=lt, parent=obj)
                sar.known_values.pop('child', None)
                btn = sar.ar2button(None, lt.as_parent(), icon_name=None)
                if not lt.symmetric:
                    # actions.append('/')
                    sar.known_values.update(type=lt, child=obj)
                    sar.known_values.pop('parent', None)
                    btn2 = sar.ar2button(None, lt.as_child(), icon_name=None)
                    # actions.append(btn)
                    btn = E.span(btn, '/', btn2)
                actions.append(btn)
                # actions.append(' ')
            # actions = join_elems(actions, E.br)

            if len(actions) > 0:
                elems += [E.br(), _("Create dependency as ")] + actions
        return E.div(*elems)