def _make_taglist(self): """Build a list of selected widget options to be displayed as a list of 'tags' below the widget.""" try: db = current.db classes = 'taglist' if self.sortable: classes += ' sortable' taglist = UL(_class=classes) if self.value: for v in self.value: the_row = db(db[self.linktable].id == v).select().first() fmt = db[self.linktable]._format format_string = fmt(the_row) if callable(fmt) \ else fmt % the_row listitem = LI(SPAN(format_string, _id=v, _class='label label-info'), _id=v, _class='tag') listitem.append( A(SPAN(_class='glyphicon glyphicon-remove'), _href='#', _class='tag tag_remover label label-warning')) taglist.append(listitem) else: pass except Exception: print(traceback.format_exc(5)) return taglist
def get_html(self): if self.stale_recommendations: self.card_title = "New problems to solve!" card_content = TAG[""](SPAN( "It has been more than a week since you last generated problem recommendations. Generate new ones and keep getting better by solving them." )) self.ctas = [ dict(btn_url=URL("problems", "recommendations"), btn_text="Generate recommendations", btn_class="recommendations-card-generate-recommendations") ] else: self.card_title = "StopStalk can recommend now!" card_content = TAG[""]( SPAN( "StopStalk will recommend you problems based on your past submissions." ), " ", SPAN("Click on the"), " ", B("'Find me problems'"), " ", SPAN( "button on the top and keep increasing your level gradually!" )) self.ctas = [ dict(btn_url=URL("problems", "recommendations"), btn_text="Find me problems", btn_class="recommendations-card-find-me-problems") ] card_html = BaseCard.get_html( self, **dict(card_title=self.card_title, card_content=card_content, cta_links=self.get_cta_html(), card_color_class="white", card_text_color_class="black-text")) return card_html
def pager(db): """ Return a row DIV for a pager. """ from gluon import current # Previous/current/next page. if current.request.args(0): current_page = int(current.request.args(0)) else: current_page = 1 prev_page = current_page - 1 next_page = current_page + 1 # List of LI. pages = [] # Previous/left. li_class = '' href = URL('poems', 'page', args=[str(prev_page)]) if prev_page < 1: li_class = 'disabled' href = '#' elif prev_page == 1: href = URL('poems', 'index') span = SPAN(xmlescape(u'\u4e0a'), **{'_aria-hidden': 'true'}) anchor = A(span, _href=href, **{'_aria-label': 'Previous'}) pages.append(LI(anchor, _class=li_class, _title='Previous Page')) # Chapter range links. for page in range(1, 10): li_class = '' href = URL('poems', 'page', args=[str(page)]) page_range = ['%d-%d' % (((page - 1) * 9) + 1, page * 9)] if page == 1: href = URL('poems', 'index') if page == current_page: li_class = 'active' page_range.append(SPAN('(current)', _class='sr-only')) anchor = A(page_range, _href=href) pages.append(LI(anchor, _class=li_class)) # Next/right. li_class = '' href = URL('poems', 'page', args=[str(next_page)]) if next_page > 9: li_class = 'disabled' href = '#' span = SPAN(xmlescape(u'\u4e0b'), **{'_aria-hidden': 'true'}) anchor = A(span, _href=href, **{'_aria-label': 'Next'}) pages.append(LI(anchor, _class=li_class, _title='Next Page')) # Together. return UL(pages, _class='pagination')
def widget(self): """ Place initial load container for controller to fill. """ # prepare classes for widget wrapper wclasses = self.get_classes(self.linktable, self.restricted, self.restrictor, self.lister, self.sortable) uvars = self.uvars uvars.update({self.fieldset[1]: self.value}) # create SPAN to wrap widget wrapper = SPAN(_id=self.wrappername, _class=wclasses) wrapper.append( LOAD("plugin_ajaxselect", "set_widget.load", args=self.uargs, vars=uvars, target=self.wrappername) ) return wrapper
def layout(item): """ Layout Method (Item Renderer) """ if item.enabled: if item.parent is not None: output = A( SPAN(item.label), _class="zocial %s" % item.opts.api, _href=item.url(), _title=item.opts.get("title", item.label), ) else: items = item.render_components() if items: output = DIV( items, _class="zocial-login", ) else: # Hide if empty output = None else: # Hide if disabled output = None return output
def _make_refresher(self, wrappername, linktable, uargs, uvars): ''' Return link to refresh this widget via ajax. The widget is always created, since its href attribute is used to pass several values to the client-side javascripts. If the widget is instantiated with the 'refresher' parameter set to False, then the link is hidden via CSS. ''' refresher_id = '{}_refresh_trigger'.format(linktable) # prepare to hide 'refresh' button via CSS if necessary rstyle = '' if self.refresher in (False, 'False'): rstyle = 'display:none' comp_url = URL('plugin_ajaxselect', 'get_values', args=self.uargs, vars=self.uvars) ajs = 'ajax("{url}", ["{n}"], "{wn}"); ' \ 'return false;'.format(url=comp_url, wn=self.wrappername, n=self.fieldset[1]) refresh_link = A(SPAN(_class='glyphicon glyphicon-refresh'), _onclick=ajs, _href=comp_url, _id=refresher_id, _class='refresh_trigger badge badge-info ', _style=rstyle) return refresh_link
def _make_adder(self, wrappername, linktable): '''Build link for adding a new entry to the linked table''' try: # attrs = {'_href': URL('plugin_ajaxselect', # 'linked_create_form.load', # args=self.uargs, vars=self.uvars)} content = LOAD('plugin_ajaxselect', 'linked_create_form.load', args=self.uargs, vars=self.uvars, ajax=True) adder = MODAL( SPAN(_class='glyphicon glyphicon-plus'), 'Add new {} item'.format(self.linktable), content, trigger_classes='add_trigger badge badge-success ', trigger_type='link', modal_classes='plugin_ajaxselect modal_adder', # attributes=attrs, id='{}_adder'.format(wrappername)) add_trigger = adder[0] add_modal = adder[1] return add_trigger, add_modal except Exception: print(traceback.format_exc(5))
def _make_linklist(self): """ Build a list of selected widget options to be displayed as a list of 'tags' below the widget. """ db = current.db xclasses = ' sortable' if self.sortable else '' ll = UL(_class='taglist editlist {}'.format(xclasses)) # append the currently selected items to the list if self.value: for v in listcheck(self.value): myrow = db(db[self.linktable].id == v).select().first() if myrow is None: continue try: fmt = db[self.linktable]._format formatted = fmt(myrow) if callable(fmt) else fmt % myrow except TypeError: formatted = myrow[1] linkargs = self.uargs[:] # new obj so vals don't pile up linkargs.append(v) ln = LI(SPAN(formatted, _class='badge badge-info'), _id=v, _class='editlink tag') myargs = self.uargs[:] myargs.append(v) elink = MODAL(SPAN(_class='glyphicon glyphicon-edit'), 'Edit {} item {}'.format(self.linktable, v), LOAD('plugin_ajaxselect', 'linked_edit_form.load', args=myargs, vars=self.uvars, ajax=True), trigger_classes='linklist_edit_trigger badge ' 'badge-warning ', trigger_type='link', modal_classes='plugin_ajaxselect ' 'modal_linklist_edit', id='{}_{}'.format(self.linktable, v)) ln.append(elink) ln.append( A(SPAN(_class='glyphicon glyphicon-remove'), _class='tag tag_remover ' 'label label-important')) ll.append(ln) return ll
def ICONLINK(title, text, icon): linktitle = '{}_icon'.format(title) link_classes = '{} icon-only icon-{}'.format(linktitle, icon) link = A(SPAN(text, _class='accessible'), _href='#', _class=link_classes, _id=linktitle) return link
def gen_links(row): diff = A( SPAN(_class="glyphicon glyphicon-random"), _href=URL('diff', args=[item.unique_id, row.id]), _class="btn btn-default", _title=T("Differences"), ) return CAT(diff)
def widget(self): """ Place initial load container for controller to fill. """ # prepare classes for widget wrapper wclasses = self.get_classes(self.linktable, self.restricted, self.restrictor, self.lister, self.sortable) uvars = self.uvars uvars.update({self.fieldset[1]: self.value}) # create SPAN to wrap widget wrapper = SPAN(_id=self.wrappername, _class=wclasses) wrapper.append( LOAD('plugin_ajaxselect', 'set_widget.load', args=self.uargs, vars=uvars, target=self.wrappername)) return wrapper
def problem_widget(name, link, link_class, link_title, disable_todo=False, anchor=True): """ Widget to display a problem in UI tables @param name (String): Problem name @param link (String): Problem link @param link_class (String): HTML class to determine solved/unsolved @param link_title (String): Link title corresponding to link_class @param disable_todo (Boolean): Show / Hide todo button @return (DIV) """ problem_div = SPAN() if anchor: problem_div.append( A(name, _href=URL("problems", "index", vars={ "pname": name, "plink": link }, extension=False), _class="problem-listing " + link_class, _title=link_title, _target="_blank", extension=False)) else: problem_div.append(SPAN(name, _class=link_class, _title=link_title)) if current.auth.is_logged_in() and disable_todo is False: problem_div.append( I(_class="add-to-todo-list fa fa-check-square-o tooltipped", _style="padding-left: 10px; display: none; cursor: pointer;", data={ "position": "right", "delay": "10", "tooltip": "Add problem to Todo List" })) return problem_div
def contact_represent(value, row=None): if isinstance(value, tuple) and len(value) == 3: if not any(value): return "" name, phone, email = value output = DIV(_class="contact-repr", ) if name: output.append(SPAN( name, _class="contact-name", )) if email or phone: details = DIV(_class="contact-details") if phone: details.append( DIV( ICON("phone"), SPAN(phone, _class="contact-phone"), _class="contact-info", )) if email: details.append( DIV( ICON("mail"), SPAN(A( email, _href="mailto:%s" % email, ), _class="contact-email"), _class="contact-info", )) output.append(details) return output else: return value if value else "-"
def BREADCUMBS(*args): # todo: fix and change breadcrumbs """ Args: *args: Returns: <span class="breadcrumb"> <span class="hide-on-small-and-down"> Fisrt</span> <span class="hide-on-med-and-up"> Last </span> </span> <span class="breadcrumb hide-on-med-and-down"> Mid 1</span> <span class="breadcrumb hide-on-med-and-down"> Mid 2</span> <span class="breadcrumb hide-on-med-and-down"> Mid ...</span> <span class="breadcrumb hide-on-small-and-down"> Last</span> """ l = list(*args) last = l.pop() first = l and l.pop(0) or None if first: current.response.write( SPAN(SPAN(A(first[0], _href=first[1]), _class="hide-on-small-and-down"), SPAN(last, _class="hide-on-med-and-up"), _class="breadcrumb")) for i in l: name, link = i current.response.write( SPAN(A(first[0], _href=first[1]), _class="breadcrumb hide-on-med-and-down")) current.response.write( SPAN(last, _class="breadcrumb hide-on-small-and-down")) else: current.response.write(SPAN(last, _class="breadcrumb"))
def _render_tag_div(self, label, controls, help): row = DIV(_class='col s12') label.tag = 'SPAN' row.append(DIV( DIV(label, controls[0], _class='btn'), DIV(INPUT(_class='file-path validate', _type='text'), _class='file-path-wrapper'), _class='file-field input-field' )) row.append(A(controls[3], _href=controls[1][1]['_href'])) row.append(DIV( P(LABEL(controls[1][3], SPAN(controls[1][4][0]))) )) return row
def get_html(self, **args): if len(args["cta_links"]) > 0: actions_div = DIV(*args["cta_links"], _class="card-action") else: actions_div = "" return DIV(DIV(DIV(SPAN(args["card_title"], _class="card-title"), args["card_content"], _class="card-content " + \ args["card_text_color_class"]), actions_div, _class="card stopstalk-dashboard-card " + \ args["card_color_class"]), _class="col s4")
def grand_button(nombre, link, icono, **kwargs): """ nombre: 1 a 3 palabras""" lista = nombre.split() spanlist = [] for i in lista: spanlist.append(SPAN(i.title())) spanlist.append(BR()) result = DIV(spanlist) if 'vars' in kwargs: url = URL(link, vars=kwargs['vars']) else: url = URL(link) boton = A(TABLE(I(_class='fa ' + str(icono) + ' fa-3x'), result), _class="btn-square-blue", _href=url) return boton
def postp(r, output): # Call standard postp if callable(standard_postp): output = standard_postp(r, output) if r.method == "datalist": if "showadd_btn" in output: from gluon import A, SPAN, URL from s3 import ICON output["showadd_btn"] = A(ICON("plus"), SPAN(T("New guide")), _class = "add-btn no-link s3_modal", _href = URL(c="doc", f="document", args = "create.popup", vars = {"refresh": "datalist"}, ), ) return output
def ICONLINK(user, icon, text, action=None, title="Click", theme_name="basic"): from gluon import current request = current.request bt = A(_class="icon-link", _onclick=action if user else "window.location = '%s'" % URL('default', 'user', args='login', vars=dict(_next=URL('article', 'show', args=request.args))), _style="cursor:pointer;", _title=title) bt.append( CAT( IMG(_src=URL('static', '%s/images/icons' % theme_name, args="%s.png" % icon), _width=16), SPAN(text, _style="line-height:16px;"))) return bt
def widget(cls, field, value, **attributes): """ Turn me on. lol! (or off) """ _id = str(field).replace('.', '_') attributes['_type'] = 'checkbox' return DIV(P(LABEL( 'Off', INPUT(_id=_id, _name=field.name, requires=field.requires, value=value, **attributes), SPAN(_class='lever'), 'On', _for=_id, ), _style='padding:20px'), _class='switch')
def get_html(self): submissions_data = self.get_data() card_content_table = TABLE(_class="bordered highlight") tbody = TBODY() for row in submissions_data: user_record = utilities.get_user_records([row[0]], "id", "id", True) tr = TR( TD( A(user_record.first_name + " " + user_record.last_name, _href=URL("user", "profile", args=user_record.stopstalk_handle, extension=False), _target="_blank"))) td = TD() for site in row[1]: if site == "total": continue else: td.append( SPAN(IMG(_src=current.get_static_url( "images/%s_small.png" % str(site).lower()), _class="parent-site-icon-very-small"), " " + str(row[1][site]), _style="padding-right: 10px;")) tr.append(td) tbody.append(tr) card_content_table.append(tbody) card_html = BaseCard.get_html( self, **dict(card_title=self.card_title, card_content=card_content_table, cta_links=self.get_cta_html(), card_color_class="white", card_text_color_class="black-text")) return card_html
def _(): # shortcuts # useful links to internal and external resources response.menu += [(SPAN('web2py', _style='color:yellow'), False, None, [ (T('This App'), False, URL('admin', 'default', 'design/%s' % app), [ (T('Controller'), False, URL('admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (T('View'), False, URL('admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (T('Layout'), False, URL('admin', 'default', 'edit/%s/views/layout.html' % app)), (T('Stylesheet'), False, URL('admin', 'default', 'edit/%s/static/css/web2py.css' % app)), (T('DB Model'), False, URL('admin', 'default', 'edit/%s/models/db.py' % app)), (T('Menu Model'), False, URL('admin', 'default', 'edit/%s/models/menu.py' % app)), (T('Database'), False, URL(app, 'appadmin', 'index')), (T('Errors'), False, URL('admin', 'default', 'errors/' + app)), (T('About'), False, URL('admin', 'default', 'about/' + app)), ]), ('web2py.com', False, 'http://www.web2py.com', [ (T('Download'), False, 'http://www.web2py.com/examples/default/download'), (T('Support'), False, 'http://www.web2py.com/examples/default/support'), (T('Demo'), False, 'http://web2py.com/demo_admin'), (T('Quick Examples'), False, 'http://web2py.com/examples/default/examples'), (T('FAQ'), False, 'http://web2py.com/AlterEgo'), (T('Videos'), False, 'http://www.web2py.com/examples/default/videos/'), (T('Free Applications'), False, 'http://web2py.com/appliances'), (T('Plugins'), False, 'http://web2py.com/plugins'), (T('Layouts'), False, 'http://web2py.com/layouts'), (T('Recipes'), False, 'http://web2pyslices.com/'), (T('Semantic'), False, 'http://web2py.com/semantic'), ]), ])]
def set_ordering(self): order_string = self._request.vars["orderby"] or ( self._request.args[0] + ".id") self.order_reverse = "~" in order_string order_string = order_string.strip("~") self.order_table, self.order_field = order_string.split(".") if self.order_reverse: self.orderby = ~self._db[self.order_table][self.order_field] else: self.orderby = self._db[self.order_table][self.order_field] if 'first_name' == self.order_field: self.orderby = self.orderby | self._db[ self.order_table]["last_name"] elif "last_name" == self.order_field: # if 2 people have the same last name, then sort by first name self.orderby = self.orderby | self._db[ self.order_table]["first_name"] for table_name in self._db.tables: for table_field in self._db[table_name].fields: table_field_is_order_field = ( table_name == self.order_table) & (self.order_field == table_field) self.order_links.setdefault(table_name, {}).setdefault( table_field, {} ).update( { # http://stackoverflow.com/questions/12905999/python-dict-how-to-create-key-or-append-an-element-to-key "url": URL(args=self._request.args, vars=dict( self._old_vars + { 'orderby': ("" if (not table_field_is_order_field or self.order_reverse) else "~") + "%s.%s" % (table_name, table_field) }.items())), # flipping order "arrow": SPAN(_class="text-info glyphicon glyphicon-arrow-" + ("down" if self.order_reverse else "up")) if table_field_is_order_field else "" })
def formstyle_materialize(form, fields, *args, **kwargs): """ divs only """ if not getattr(form, 'tag', None) == 'form': return DIV(form, fields, *args, **kwargs) form['_class'] = form['_class'] or 'col' form['_class'] = ' '.join(set(['col', 's12'] + form['_class'].split(' '))) table = DIV(_class="row") for id, label, controls, help in fields: _input_field = DIV(_class="input-field col s12") if help: _input_field.add_class('tooltipped') _input_field['_data-tooltip'] = help if getattr(controls, 'tag', None) == 'textarea': controls['_class'] += ' materialize-textarea' if controls['_type'] == 'file': _input_field['_class'] = 'file-field col s12 input-field' _input_field.append( DIV( SPAN(label[0]), controls, _class='btn')) _input_field.append( DIV( INPUT( _class='file-path validate', _readonly = '', _type='text'), _class='file-path-wrapper')) table.append(_input_field) continue if controls['_type'] == 'submit': controls.tag = 'button' controls.components.append(I('send', _class=('material-icons right'))) controls.components.append(controls['_value']) del controls['_value'] controls['_name'] = 'action' controls.add_class('btn right') _input_field.append(controls) _input_field.append(label) table.append(_input_field) return table
def represent_row(self, row): """ Represent a row @param row: the Row """ pentity = row.pr_pentity instance_type = pentity.instance_type item = object.__getattribute__(row, instance_type) if instance_type == "pr_person": if self.as_string: pe_str = current.T("private") else: pe_str = SPAN(current.T("private"), _class="free-hint") elif "name" in item: pe_str = s3_str(item["name"]) else: pe_str = "?" return pe_str
def get_html(self): problem_details = self.get_data() self.ctas = [ dict(btn_text="Write Editorial", btn_url=URL("problems", "editorials", args=problem_details["id"], vars=dict(write_editorial=True)), btn_class="last-solved-problem-write-editorial"), dict(btn_text="Suggest tags", btn_url=URL("problems", "index", vars=dict(problem_id=problem_details["id"], suggest_tag=True)), btn_class="last-solved-problem-suggest-tags"), dict(btn_text="Suggest difficulty", btn_url=URL("problems", "index", vars=dict(problem_id=problem_details["id"], suggest_difficulty=True)), btn_class="last-solved-problem-suggest-difficulty") ] card_content = SPAN( "You just solved ", utilities.problem_widget(problem_details["name"], problem_details["link"], "solved-problem", "Solved Problem", problem_details["id"]), ". You can write editorials on StopStalk and help the community.") card_html = BaseCard.get_html( self, **dict(card_title=self.card_title, card_content=card_content, cta_links=self.get_cta_html(), card_color_class="white", card_text_color_class="black-text")) return card_html
def drk_dvr_rheader(r, tabs=None): """ DVR custom resource headers """ if r.representation != "html": # Resource headers only used in interactive views return None from s3 import s3_rheader_resource, \ S3ResourceHeader, \ s3_fullname from .uioptions import get_ui_options tablename, record = s3_rheader_resource(r) if tablename != r.tablename: resource = current.s3db.resource(tablename, id=record.id) else: resource = r.resource rheader = None rheader_fields = [] if record: T = current.T record_id = record.id if tablename == "pr_person": # UI Options and ability to read cases from multiple orgs ui_opts = get_ui_options() ui_opts_get = ui_opts.get from .helpers import case_read_multiple_orgs multiple_orgs = case_read_multiple_orgs()[0] if not tabs: activity_tab_label = ui_opts_get("activity_tab_label") if activity_tab_label: ACTIVITIES = T(activity_tab_label) else: ACTIVITIES = T("Counseling Reasons") # Basic Case Documentation tabs = [(T("Basic Details"), None), (T("Contact Info"), "contacts"), (T("Family Members"), "group_membership/"), (ACTIVITIES, "case_activity"), ] # Optional Case Documentation if ui_opts_get("case_use_response_tab"): tabs.append((T("Actions"), "response_action")) if ui_opts_get("case_use_appointments"): tabs.append((T("Appointments"), "case_appointment")) if ui_opts_get("case_use_service_contacts"): tabs.append((T("Service Contacts"), "service_contact")) if ui_opts_get("case_use_photos_tab"): tabs.append((T("Photos"), "image")) # Uploads tabs.append((T("Documents"), "document/")) # Notes etc. if ui_opts_get("case_use_notes"): tabs.append((T("Notes"), "case_note")) # Get the record data lodging_opt = ui_opts_get("case_lodging") if lodging_opt == "site": lodging_sel = "dvr_case.site_id" lodging_col = "dvr_case.site_id" elif lodging_opt == "text": lodging_sel = "case_details.lodging" lodging_col = "dvr_case_details.lodging" else: lodging_sel = None lodging_col = None if ui_opts_get("case_use_flags"): flags_sel = "dvr_case_flag_case.flag_id" else: flags_sel = None if ui_opts_get("case_use_place_of_birth"): pob_sel = "person_details.place_of_birth" else: pob_sel = None if ui_opts_get("case_use_bamf"): bamf_sel = "bamf.value" else: bamf_sel = None case = resource.select(["first_name", "last_name", "dvr_case.status_id", "dvr_case.archived", "dvr_case.household_size", "dvr_case.organisation_id", "case_details.arrival_date", bamf_sel, "person_details.nationality", pob_sel, lodging_sel, flags_sel, ], represent = True, raw_data = True, ).rows if case: # Extract case data case = case[0] name = lambda person: s3_fullname(person, truncate=False) raw = case["_row"] case_status = lambda row: case["dvr_case.status_id"] archived = raw["dvr_case.archived"] organisation = lambda row: case["dvr_case.organisation_id"] arrival_date = lambda row: case["dvr_case_details.arrival_date"] household_size = lambda row: case["dvr_case.household_size"] nationality = lambda row: case["pr_person_details.nationality"] # Warn if nationality is lacking while mandatory if ui_opts_get("case_nationality_mandatory") and \ raw["pr_person_details.nationality"] is None: current.response.warning = T("Nationality lacking!") bamf = lambda row: case["pr_bamf_person_tag.value"] if pob_sel: place_of_birth = lambda row: case["pr_person_details.place_of_birth"] else: place_of_birth = None if lodging_col: lodging = (T("Lodging"), lambda row: case[lodging_col]) else: lodging = None if flags_sel: flags = lambda row: case["dvr_case_flag_case.flag_id"] else: flags = None else: # Target record exists, but doesn't match filters return None arrival_date_label = ui_opts_get("case_arrival_date_label") arrival_date_label = T(arrival_date_label) \ if arrival_date_label else T("Date of Entry") # Adaptive rheader-fields rheader_fields = [[None, (T("Nationality"), nationality), (T("Case Status"), case_status)], [None, None, None], [None, None, None], ] if ui_opts_get("case_use_pe_label"): rheader_fields[0][0] = (T("ID"), "pe_label") rheader_fields[1][0] = "date_of_birth" else: rheader_fields[0][0] = "date_of_birth" if pob_sel: pob_row = 1 if rheader_fields[1][0] is None else 2 rheader_fields[pob_row][0] = (T("Place of Birth"), place_of_birth) if bamf_sel: doe_row = 2 rheader_fields[1][1] = (T("BAMF-Az"), bamf) else: doe_row = 1 rheader_fields[doe_row][1] = (arrival_date_label, arrival_date) if lodging: rheader_fields[1][2] = lodging if ui_opts_get("case_show_total_consultations"): from .helpers import get_total_consultations total_consultations = (T("Number of Consultations"), get_total_consultations) if rheader_fields[1][2] is None: rheader_fields[1][2] = total_consultations else: rheader_fields[0].append(total_consultations) hhsize = (T("Size of Family"), household_size) if rheader_fields[1][0] is None: rheader_fields[1][0] = hhsize elif rheader_fields[2][0] is None: rheader_fields[2][0] = hhsize elif rheader_fields[1][2] is None: rheader_fields[1][2] = hhsize else: rheader_fields[2][2] = hhsize colspan = 5 if multiple_orgs: # Show organisation if user can see cases from multiple orgs rheader_fields.insert(0, [(T("Organisation"), organisation, colspan)]) if flags_sel: rheader_fields.append([(T("Flags"), flags, colspan)]) if ui_opts_get("case_header_protection_themes"): from .helpers import get_protection_themes rheader_fields.append([(T("Protection Need"), get_protection_themes, colspan, )]) if archived: # "Case Archived" hint hint = lambda record: SPAN(T("Invalid Case"), _class="invalid-case") rheader_fields.insert(0, [(None, hint)]) # Generate rheader XML rheader = S3ResourceHeader(rheader_fields, tabs, title=name)( r, table = resource.table, record = record, ) # Add profile picture from s3 import s3_avatar_represent rheader.insert(0, A(s3_avatar_represent(record_id, "pr_person", _class = "rheader-avatar", _width = 60, _height = 60, ), _href=URL(f = "person", args = [record_id, "image"], vars = r.get_vars, ), ) ) return rheader elif tablename == "dvr_case": if not tabs: tabs = [(T("Basic Details"), None), (T("Activities"), "case_activity"), ] rheader_fields = [["reference"], ["status_id"], ] rheader = S3ResourceHeader(rheader_fields, tabs)(r, table=resource.table, record=record, )
def render_table(submissions, duplicates=[]): """ Create the HTML table from submissions """ status_dict = { "AC": "Accepted", "WA": "Wrong Answer", "TLE": "Time Limit Exceeded", "MLE": "Memory Limit Exceeded", "RE": "Runtime Error", "CE": "Compile Error", "SK": "Skipped", "HCK": "Hacked", "OTH": "Others" } table = TABLE(_class="striped centered") table.append( THEAD( TR(TH("User Name"), TH("Site"), TH("Site Handle"), TH("Time of submission"), TH("Problem"), TH("Language"), TH("Status"), TH("Points"), TH("View Code")))) tbody = TBODY() for submission in submissions: tr = TR() append = tr.append span = SPAN() if submission.user_id: person_id = submission.user_id else: person_id = submission.custom_user_id # Check if the given custom_user is a duplicate # We need to do this because there might be a case # when a duplicate custom_user is created and then # his name or institute is changed for f in duplicates: if f[1] == person_id and f[0] != None: person_id = current.db.custom_friend(f[0]) break span = SPAN(_class="orange tooltipped", data={"position": "right", "delay": "50", "tooltip": "Custom User"}, _style="cursor: pointer; " + \ "float:right; " + \ "height:10px; " + \ "width:10px; " + \ "border-radius: 50%;") append( TD( DIV( span, A(person_id.first_name + " " + person_id.last_name, _href=URL("user", "profile", args=[person_id.stopstalk_handle], extension=False), _target="_blank")))) append(TD(submission.site)) append( TD( A(submission.site_handle, _href=get_link(submission.site, submission.site_handle), _target="_blank"))) append(TD(submission.time_stamp)) append( TD( A(submission.problem_name, _href=URL("problems", "index", vars={ "pname": submission.problem_name, "plink": submission.problem_link }, extension=False), _target="_blank"))) append(TD(submission.lang)) append( TD( IMG(_src=URL("static", "images/" + submission.status + ".jpg", extension=False), _title=status_dict[submission.status], _alt=status_dict[submission.status], _style="height: 25px; width: 25px;"))) append(TD(submission.points)) if submission.view_link: append( TD( A("View", _href=submission.view_link, _class="btn waves-light waves-effect", _style="background-color: #FF5722", _target="_blank"))) else: append(TD()) tbody.append(tr) table.append(tbody) return table
def materialize_form(form, fields): """ Change layout of SQLFORM forms """ form.add_class("form-horizontal center") main_div = DIV(_class="center") for field_id, label, controls, field_help in fields: curr_div = DIV(_class="row") input_field = None _controls = controls try: _name = controls.attributes["_name"] except: _name = "" try: _type = controls.attributes["_type"] except: _type = "string" try: _id = controls.attributes["_id"] except: _id = "" if isinstance(controls, INPUT): if _type == "file": # Layout for file type inputs input_field = DIV( DIV(SPAN("Upload"), INPUT(_type=_type, _id=_id), _class="btn"), DIV(INPUT(_type="text", _class="file-path", _placeholder=label.components[0]), _class="file-path-wrapper"), _class="col input-field file-field offset-s3 s6") if isinstance(controls, SPAN): # Mostly for ids which cannot be edited by user _controls = INPUT(_value=controls.components[0], _id=_id, _name=_name, _disabled="disabled") elif isinstance(controls, TEXTAREA): # Textarea inputs try: _controls = TEXTAREA(controls.components[0], _name=_name, _id=_id, _class="materialize-textarea text") except IndexError: _controls = TEXTAREA(_name=_name, _id=_id, _class="materialize-textarea text") elif isinstance(controls, SELECT): # Select inputs _controls = SELECT(OPTION(label, _value=""), _name=_name, _class="browser-default", *controls.components[1:]) # Note now label will be the first element # of Select input whose value would be "" label = "" elif isinstance(controls, A): # For the links in the bottom while updating tables like auth_user label = "" elif isinstance(controls, INPUT) is False: # If the values are readonly _controls = INPUT(_value=controls, _name=_name, _disabled="") if input_field is None: input_field = DIV(_controls, label, _class="input-field col offset-s3 s6") curr_div.append(input_field) main_div.append(curr_div) return main_div
def cms_post_list_layout(list_id, item_id, resource, rfields, record): """ dataList item renderer for Posts on the Bulletin Board. @param list_id: the HTML ID of the list @param item_id: the HTML ID of the item @param resource: the S3Resource to render @param rfields: the S3ResourceFields to render @param record: the record as dict """ record_id = record["cms_post.id"] #item_class = "thumbnail" T = current.T db = current.db s3db = current.s3db settings = current.deployment_settings permit = current.auth.s3_has_permission raw = record._row date = record["cms_post.date"] title = record["cms_post.title"] body = record["cms_post.body"] #series_id = raw["cms_post.series_id"] # Allow records to be truncated # (not yet working for HTML) body = DIV( body, _class="s3-truncate", ) #if series_id: # series = record["cms_post.series_id"] # translate = settings.get_L10n_translate_cms_series() # if translate: # series_title = T(series) # else: # series_title = series #else: # series_title = series = "" #status = record["cms_post.status_id"] author_id = raw["cms_post.created_by"] person = record["cms_post.created_by"] # @ToDo: Bulk lookup ltable = s3db.pr_person_user ptable = db.pr_person query = (ltable.user_id == author_id) & \ (ltable.pe_id == ptable.pe_id) row = db(query).select(ptable.id, limitby=(0, 1)).first() if row: person_id = row.id else: person_id = None if person: if person_id: # @ToDo: deployment_setting for controller to use? person_url = URL(c="hrm", f="person", args=[person_id]) else: person_url = "#" person = A( person, _href=person_url, ) table = db.cms_post # Toolbar if permit("update", table, record_id=record_id): edit_btn = A( ICON("edit"), SPAN( "edit", _class="show-for-sr", ), _href=URL(c="cms", f="post", args=[record_id, "update.popup"], vars={ "refresh": list_id, "record": record_id }), _class="s3_modal", #_title=T("Edit %(type)s") % dict(type=series_title), _title=T("Edit"), ) else: edit_btn = "" if permit("delete", table, record_id=record_id): delete_btn = A( ICON("delete"), SPAN( "delete", _class="show-for-sr", ), _class="dl-item-delete", _title=T("Delete"), ) else: delete_btn = "" # Bookmarks auth = current.auth user = auth.user if user: #and settings.get_cms_bookmarks(): # @ToDo: Bulk lookup (via list_fields?) ltable = s3db.cms_post_user query = (ltable.post_id == record_id) & \ (ltable.user_id == user.id) exists = db(query).select(ltable.id, limitby=(0, 1)).first() if exists: bookmark = A( ICON("bookmark"), SPAN( "remove bookmark", _class="show-for-sr", ), _class="bookmark", _title=T("Remove Bookmark"), ) else: bookmark = A( ICON("bookmark-empty"), SPAN( "bookmark", _class="show-for-sr", ), _class="bookmark", _title=T("Add Bookmark"), ) bookmark["_data-c"] = "cms" bookmark["_data-f"] = "post" bookmark["_data-i"] = record_id else: bookmark = "" # Dropdown of available documents documents = raw["doc_document.file"] if documents: if not isinstance(documents, list): documents = (documents, ) doc_list = UL( _class="dropdown-menu", _role="menu", ) retrieve = db.doc_document.file.retrieve for doc in documents: try: doc_name = retrieve(doc)[0] except (IOError, TypeError): doc_name = current.messages["NONE"] doc_url = URL(c="default", f="download", args=[doc]) doc_item = LI( A( ICON("file"), " ", doc_name, _href=doc_url, ), _role="menuitem", ) doc_list.append(doc_item) docs = DIV( A(ICON("paper-clip"), SPAN(_class="caret"), _class="btn dropdown-toggle", _href="#", **{"_data-toggle": "dropdown"}), doc_list, _class="btn-group attachments dropdown pull-right", ) else: docs = "" #divider = LI("|") #divider["_aria-hidden"] = "true" toolbar = UL( #LI(share_btn, # _class="item", # ), #LI(A(ICON("flag"), # @ToDo: Use flag-alt if not flagged & flag if already flagged (like for bookmarks) # SPAN("flag this", # _class = "show-for-sr", # ), # _href="#", # _title=T("Flag"), # ), # _class="item", # ), LI( bookmark, _class="item", ), #LI(A(I(_class="fa fa-users", # ), # SPAN("make public", # _class = "show-for-sr", # ), # _href="#", # _title=T("Make Public"), # ), # _class="item", # ), LI( edit_btn, _class="item", ), LI( delete_btn, _class="item", ), _class="controls", ) # Tags #if settings.get_cms_show_tags(): tag_list = UL(_class="left inline-list s3-tags", ) tag_list["_data-post_id"] = record_id tags = raw["cms_tag.name"] if tags: if not isinstance(tags, list): tags = [tags] for tag in tags: tag_list.append(LI(A( tag, _href="#", ), )) # Comments comment_list = UL(_class="card-post-comments") cappend = comment_list.append #if settings.get_cms_comments(): # Add existing comments (oldest 1st) # - should sort by default by ID which is equivalent to oldest first, # however they seem to come in in a random order (even if orderby set on the component) so need to be sorted manually here comments = raw["cms_comment.json_dump"] ncomments = 0 if comments: if not isinstance(comments, list): comments = [comments] comments = [json.loads(comment) for comment in comments] comments.sort(key=lambda c: c["created_on"]) for comment in comments: author = s3_auth_user_represent(comment["created_by"]) cdate = dateutil.parser.parse(comment["created_on"]) ctime = cdate.time().strftime("%H:%M") cdate = cdate.date().strftime("%b %d, %Y") comment = LI(TAG["ASIDE"](P(T("Updated %(date)s @ %(time)s by %(author)s") % \ dict(date = cdate, time = ctime, author = author, ), _class="meta", ), DIV(comment["body"], _class="desc", ), # @ToDo: Show this if more than x chars? #TAG["FOOTER"](P(A(T("More Info"), # _class="more", # ) # ), # _class="footer", # ), _class="card-post-comment", )) cappend(comment) ncomments += 1 if ncomments == 1: num_comments = "1 Comment" else: num_comments = T("%(num)s Comments") % dict(num=ncomments) if user: add_comment = A( T("Add Comment"), _class="add-comment", ) add_comment["_data-l"] = list_id add_comment["_data-i"] = record_id add_comment = P(add_comment) comment_input = LI( TAG["ASIDE"]( TEXTAREA( _class="desc", _placeholder=T("comment here"), ), TAG["FOOTER"](P(A( "Submit Comment", _class="submit", ), ), ), _class="card-post-comment", ), _class="comment-form hide", ) cappend(comment_input) else: add_comment = "" item = TAG["ASIDE"]( TAG["HEADER"]( UL( # post priority icon LI(_class="item icon", ), # post type title #LI(series_title, # _class="item primary", # ), # post status #LI(status, # _class="item secondary border status", # ), # post visibility # @ToDo: Read the visibility #LI(T("Public"), # _class="item secondary border visibility", # ), _class="status-bar-left"), toolbar, _class="status-bar", ), DIV( DIV( SPAN( "Updated ", # @ToDo: i18n TAG["TIME"](date), " by ", person, _class="meta-update", ), SPAN( num_comments, _class="meta-comments", ), _class="meta", ), H4( title, _class="title", ), DIV( body, _class="desc", ), _class="body", ), docs, TAG["FOOTER"]( DIV( tag_list, _class= "tags clearfix", # @ToDo: remove clearfix and style via CSS ), comment_list, add_comment, _class="footer", ), _class="card-post", _id=item_id, ) return item
def __call__(self): T = current.T db = current.db s3db = current.s3db s3 = current.response.s3 session_s3 = current.session.s3 output = {} # Recent Updates etable = s3db.event_event stable = s3db.event_sitrep query = (stable.deleted == False) fields = [ etable.name, stable.id, stable.date, stable.name, stable.summary, ] left = [etable.on(etable.id == stable.event_id)] language = session_s3.language if language != current.deployment_settings.get_L10n_default_language(): ntable = s3db.event_event_name left.append(ntable.on((ntable.event_id == etable.id) & \ (ntable.language == language))) fields.append(ntable.name_l10n) use_local_event_name = True else: use_local_event_name = False sitreps = db(query).select(left=left, limitby=(0, 3), orderby=~stable.date, *fields) len_sitreps = len(sitreps) if len_sitreps == 0: from s3 import S3CRUD recent_updates = DIV(S3CRUD.crud_string("event_sitrep", "msg_list_empty"), _class="empty") else: recent_updates = DIV() rappend = recent_updates.append count = 0 for s in sitreps: count += 1 if use_local_event_name: event_name = s["event_event_name.name_l10n"] or s[ "event_event.name"] else: event_name = s["event_event.name"] if not event_name: event_name = s["event_sitrep.name"] rappend( H3( A( event_name, _href=URL( c="event", f="sitrep", args=[s["event_sitrep.id"]], ), ))) rappend(P(XML(s["event_sitrep.summary"]))) if count != len_sitreps: rappend(HR()) output["recent_updates"] = recent_updates map_btn = A( T("MAP OF CURRENT NEEDS"), #_href = URL(c="default", # f="index", # args="dashboard", # ), _href=URL( c="req", f="need_line", args="map", ), _class="small primary button", ) create_btn = A( T("CREATE A NEED"), _href=URL( c="req", f="need", args="create", ), _class="small primary button", ) output["needs_btn"] = DIV( SPAN(map_btn), SPAN(create_btn), _class="button-group radius", ) output["about_btn"] = A( "%s >" % T("Read More"), _href=URL( c="default", f="about", ), ) # Resources section if current.deployment_settings.has_module("cms"): system_roles = current.auth.get_system_roles() ADMIN = system_roles.ADMIN in session_s3.roles table = s3db.cms_post ltable = s3db.cms_post_module module = "default" resource = "index" query = (ltable.module == module) & \ ((ltable.resource == None) | \ (ltable.resource == resource)) & \ (ltable.post_id == table.id) & \ (table.deleted != True) item = current.db(query).select(table.body, table.id, limitby=(0, 1)).first() if item: if ADMIN: item = DIV( XML(item.body), BR(), A(T("Edit"), _href=URL(c="cms", f="post", args=[item.id, "update"]), _class="action-btn")) else: item = DIV(XML(item.body)) elif ADMIN: if s3.crud.formstyle == "bootstrap": _class = "btn" else: _class = "action-btn" item = A(T("Edit"), _href=URL(c="cms", f="post", args="create", vars={ "module": module, "resource": resource }), _class="%s cms-edit" % _class) else: item = "" else: item = "" output["item"] = item # Inject D3 scripts from s3 import S3Report S3Report.inject_d3() # Inject charts-script appname = current.request.application scripts = s3.scripts if s3.debug: script = "/%s/static/scripts/S3/s3.ui.charts.js" % appname if script not in scripts: scripts.append(script) else: script = "/%s/static/scripts/S3/s3.ui.charts.min.js" % appname if script not in scripts: scripts.append(script) # Instantiate charts scriptopts = { # Standard SHARE theme color set: "colors": [ '#0C9CD0', # blue '#E03158', # red '#FBA629', # amber '#8ABC3F', # green '#AFB8BF', # grey ], } script = '''$('.homepage-chart').uiChart(%s)''' % json.dumps( scriptopts) s3.jquery_ready.append(script) # Add last update time of chart data last_update = HomepageStatistics.last_update() if last_update: output["last_stats_update"] = T("Updated on %(date)s") % { "date": last_update } else: output["last_stats_update"] = None self._view(THEME, "index.html") return output