def render_trending_table(caption, problems, column_name, user_id):
    """
        Create trending table from the rows
    """
    T = current.T

    table = TABLE(_class="bordered centered")
    thead = THEAD(
        TR(TH(T("Problem")), TH(T("Recent Submissions")), TH(column_name)))
    table.append(thead)
    tbody = TBODY()

    for problem in problems:
        tr = TR()
        link_class = get_link_class(problem[0], user_id)
        link_title = (" ".join(link_class.split("-"))).capitalize()

        tr.append(
            TD(
                problem_widget(problem[1]["name"], problem[0], link_class,
                               link_title)))
        tr.append(TD(problem[1]["total_submissions"]))
        tr.append(TD(len(problem[1]["users"]) + \
                     len(problem[1]["custom_users"])))
        tbody.append(tr)

    table.append(tbody)
    table = DIV(H5(caption, _class="center"), HR(), table)

    return table
Example #2
0
File: poems.py Project: ichem/ddj
def _thumb(row, cls, title=None):
    """ Return a column DIV thumbnail. """
    caption = DIV(H3(row.chapter.title),
                  H4('Chapter %i' % row.chapter.number),
                  H5(row.published.strftime(date_format)),
                  H3(row.intro_hanzi),
                  H4(row.intro_en),
                  _class='caption',
                  _role='button',
                  _title=title)
    anchor = A(caption,
               _class='ddj-thumbnail',
               _href=URL('poems', 'chapter', args=[row.chapter.number]))
    thumbnail = DIV(anchor, _class='thumbnail')
    return DIV(thumbnail, _class=cls)
Example #3
0
File: poems.py Project: ichem/ddj
def chapter(poem, db, uhdb):
    """ Return a bootstrap row for a poem row. """
    if not poem:
        raise Exception('No such poem')
    qry = ((db.verse.book == 1) & (db.verse.chapter == poem.chapter))
    verse = db(qry).select().first()
    title = H3(poem.chapter.title)
    subtitle = H4('Chapter %i' % poem.chapter.number)
    published = H5(poem.published.strftime(date_format))
    stanzas = verse.en.split('\r\n\r\n')
    content = []
    for stanza in stanzas:
        content.append(P(XML(stanza.replace('\r\n', '<br />'))))
    link = P(A(I('Go to the study version'),
               _href=URL('studies', 'chapter', args=[poem.chapter.number]),
               _style='color:inherit;',
               _title='Study version'),
             _style='font-size:0.9em;padding-top:1em')
    content.append(P(link))
    column = DIV(title, subtitle, published, *content, _class=poem_class)
    return DIV(column,
               _class='row',
               _style='font-size:1.12em;white-space:nowrap;')
Example #4
0
    def pdf(self, r, **attr):
        """
            Generate the PDF

            Args:
                r: the S3Request instance
                attr: controller attributes
        """

        T = current.T

        db = current.db
        s3db = current.s3db

        # Look up the report organisation
        logo = None
        org_id, org_label = self.get_report_organisation(r)
        if org_id:
            # Look up the root organisation's logo
            otable = s3db.org_organisation
            rotable = otable.with_alias("root_organisation")
            join = rotable.on(rotable.id == otable.root_organisation)
            field = rotable.logo
            row = db(otable.id == org_id).select(
                field,
                join=join,
                limitby=(0, 1),
            ).first()
            if row and row.logo:
                if field.uploadfolder:
                    path = field.uploadfolder
                else:
                    path = os.path.join(current.request.folder, 'uploads')
                logo = os.path.join(path, row.logo)

        # Look up the report programme
        prog_id, prog_label = self.get_report_programme(r)

        # Extract the HR records
        data, pictures = self.extract(r.resource)

        # Construct the header
        title = T("Official Volunteer List")
        header = TABLE(_class="no-grid", )
        trow = TR()
        if logo:
            trow.append(
                TD(
                    IMG(_src=logo, _width="80"),
                    _rowspan=3 if prog_id else 2,
                ))
        trow.append(TD(H4(title), _colspan=3))
        header.append(trow)
        if org_id:
            header.append(TR(TD(H5(org_label), _colspan=3)))
        if prog_id:
            header.append(TR(TD(prog_label, _colspan=3)))
        header.append(TR(TD()))

        # Should we show the branch column?
        branches = set(row["_row"]["hrm_human_resource.organisation_id"]
                       for row in data.rows)
        if org_id:
            show_branch = len(branches) > 1
            org_repr = s3db.org_OrganisationRepresent(
                show_link=False,
                parent=False,
                acronym=True,
            )
        else:
            show_branch = True
            org_repr = r.table.organisation_id.represent
        org_repr.bulk(list(branches))

        # Construct the table header
        labels = TR(
            TH(T("Picture")),
            TH(T("Name")),
            TH(T("Last Name")),
            TH(T("National ID")),
            TH(T("Volunteer ID")),
            TH(T("Signature")),
        )
        if not prog_id:
            labels.insert(1, TH(T("Program")))
        if show_branch:
            labels.insert(1, TH(T("Branch")))

        # Build the table
        body = TABLE(labels, _class="repeat-header shrink-to-fit")

        # Add the data rows
        for row in data.rows:

            raw = row._row

            # Picture
            picture = pictures.get(raw["pr_person.pe_id"])
            if picture:
                picture = IMG(
                    _src=picture,
                    _width=80,
                )
            else:
                picture = ""

            # Name
            name = s3_format_fullname(
                fname=raw["pr_person.first_name"],
                mname=raw["pr_person.middle_name"],
                lname="",
                truncate=False,
            )

            # Build the row
            trow = TR(
                TD(picture),
                TD(name),
                TD(row["pr_person.last_name"]),
                TD(row["pr_national_id_identity.value"]),
                TD(row["hrm_human_resource.code"]),
                TD(),
            )
            if not prog_id:
                trow.insert(1, TD(row["hrm_programme_hours.programme_id"]))
            if show_branch:
                trow.insert(
                    1, TD(org_repr(raw["hrm_human_resource.organisation_id"])))
            body.append(trow)

        footer = DIV()

        from s3.codecs.pdf import EdenDocTemplate, S3RL_PDF

        doc = EdenDocTemplate(title=title)
        printable_width = doc.printable_width

        get_html_flowable = S3RL_PDF().get_html_flowable

        header_flowable = get_html_flowable(header, printable_width)
        body_flowable = get_html_flowable(body, printable_width)
        footer_flowable = get_html_flowable(footer, printable_width)

        # Build the PDF
        doc.build(
            header_flowable,
            body_flowable,
            footer_flowable,
        )
        filename = "siglist.pdf"

        # Return the generated PDF
        response = current.response
        response.headers["Content-Type"] = contenttype(".pdf")
        disposition = "attachment; filename=\"%s\"" % filename
        response.headers["Content-disposition"] = disposition

        return doc.output.getvalue()
Example #5
0
File: cwa.py Project: sahana/eden
    def formatted(self, retry=False):
        """
            Formatted version of this report

            @param retry: add retry-action for sending to CWA

            @returns: a FORM containing
                      - the QR-code
                      - human-readable report details
                      - actions to download PDF, or retry sending to CWA
        """

        T = current.T
        table = current.s3db.disease_case_diagnostics

        # Personal Details
        data_repr = TABLE()
        data = self.data
        if not any(k in data for k in ("fn", "ln", "dob")):
            data_repr.append(
                TR(
                    TD(T("Person Tested")),
                    TD(T("anonymous"), _class="cwa-data"),
                ))
        else:
            labels = {
                "fn": T("First Name"),
                "ln": T("Last Name"),
                "dob": T("Date of Birth"),
            }
            for k in ("ln", "fn", "dob"):
                value = data[k]
                if k == "dob":
                    value = self.to_local_dtfmt(value)
                data_repr.append(
                    TR(
                        TD(labels.get(k)),
                        TD(value, _class="cwa-data"),
                    ))

        # Test Station, date and result
        field = table.site_id
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.site_id),
                        _class="cwa-data",
                    ),
                ))
        field = table.probe_date
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.probe_date),
                        _class="cwa-data",
                    ),
                ))
        field = table.result
        if field.represent:
            data_repr.append(
                TR(
                    TD(field.label),
                    TD(
                        field.represent(self.result),
                        _class="cwa-data",
                    ),
                ))

        # Details
        details = DIV(
            H5(T("Details")),
            data_repr,
            _class="cwa-details",
        )

        # QR Code
        title = T("Code for %(app)s") % CWA
        qrcode = DIV(
            s3_qrcode_represent(self.get_link(), show_value=False),
            DIV(title, _class="cwa-qrcode-title"),
            _class="cwa-qrcode",
        )
        if retry:
            qrcode.add_class("hide")

        # Form buttons
        buttons = [
            BUTTON(
                T("Download PDF"),
                _class="tiny primary button cwa-pdf",
                _type="button",
            ),
        ]
        if retry:
            buttons[0].add_class("hide")
            buttons.append(
                BUTTON(
                    T("Retry sending to %(app)s") % CWA,
                    _class="tiny alert button cwa-retry",
                    _type="button",
                ))

        # Generate form key
        formurl = URL(
            c="disease",
            f="case_diagnostics",
            args=[self.result_id],
        )
        formkey = uuid.uuid4().hex

        # Store form key in session
        session = current.session
        keyname = "_formkey[testresult/%s]" % self.result_id
        session[keyname] = session.get(keyname, [])[-9:] + [formkey]

        form = FORM(
            DIV(
                DIV(
                    details,
                    qrcode,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            DIV(
                DIV(
                    buttons,
                    _class="small-12 columns",
                ),
                _class="row form-row",
            ),
            hidden={
                "formurl": formurl,
                "cwadata": json.dumps(self.data),
                "_formkey": formkey,
            },
        )

        return form
Example #6
0
    def comment_internal(self):
        is_author = False
        if self.session.auth and self.session.auth.user:
            is_author = True if self.session.auth.user.id == self.context.article.author else False
            self.db.Comments.article_id.default = self.context.article.id
            self.db.Comments.user_id.default = self.session.auth.user.id
            self.db.Comments.commenttime.default = self.request.now
            self.db.Comments.comment_text.label = self.T("Post your comment")
            from plugin_ckeditor import CKEditor
            ckeditor = CKEditor()
            self.db.Comments.comment_text.widget = ckeditor.basicwidget
            form = SQLFORM(self.db.Comments, formstyle='divs')
            if form.process(
                    message_onsuccess=self.T('Comment included')).accepted:
                self.new_article_event(
                    'new_article_comment',
                    self.session.auth.user,
                    data={
                        'event_text':
                        form.vars.comment_text,
                        'event_link':
                        "%s/%s#comment_%s" %
                        (self.context.article.id, self.context.article.slug,
                         form.vars.id)
                    })
        else:
            form = A(
                self.T("Login to post comments"),
                _class="button",
                _href=self.CURL(
                    'default',
                    'user',
                    args='login',
                    vars=dict(_next=self.CURL('article',
                                              'show',
                                              args=[
                                                  self.context.article.id,
                                                  self.context.article.slug
                                              ]))))

        comments = self.db(
            self.db.Comments.article_id == self.context.article.id).select(
                orderby=self.db.Comments.created_on)

        if comments and is_author:
            edit_in_place = ckeditor.bulk_edit_in_place(
                ["comment_%(id)s" % comment for comment in comments],
                URL('editcomment'))
        elif comments and self.session.auth and self.session.auth.user:
            usercomments = comments.find(
                lambda row: row.user_id == self.session.auth.user.id)
            if usercomments:
                edit_in_place = ckeditor.bulk_edit_in_place(
                    ["comment_%(id)s" % comment for comment in usercomments],
                    URL('editcomment'))
            else:
                edit_in_place = ('', '')
        else:
            edit_in_place = ('', '')

        return DIV(H4(
            IMG(_src=URL('static',
                         '%s/images/icons' % self.context.theme_name,
                         args='board.24.png')), self.T("Comments")),
                   UL(
                       *[
                           LI(H5(
                               A(self.T("%s %s" %
                                        (comment.nickname or comment.user_id,
                                         self.db.pdate(comment.commenttime))),
                                 _href=self.CURL('person',
                                                 'show',
                                                 args=comment.nickname
                                                 or comment.user_id))),
                              DIV(
                                  XML(comment.comment_text), **{
                                      '_class': 'editable commentitem',
                                      '_data-object': 'comment',
                                      '_data-id': comment.id,
                                      '_id': "comment_%s" % comment.id
                                  }),
                              _class="comment_li") for comment in comments
                       ], **dict(_class="comment_ul")),
                   edit_in_place[1],
                   form,
                   _class="internal-comments article-box")