def _get_label(rfields, field, tablename, key): """ Get the label for a field @param rfields: the list fields map @param key: the configuration key """ DEFAULT = "" if field in rfields: rfield = rfields[field] else: return DEFAULT # @todo: cleanup this: get_config = lambda key, default, tablename=tablename: \ current.s3db.get_config(tablename, key, default) list_fields = get_config("list_fields", None) fields = get_config(key, list_fields) if fields: for f in fields: if isinstance(f, (tuple, list)) and f[1] == rfield.selector: return f[0] if rfield: if rfield.ftype == "id": return current.T("Records") return rfield.label else: return DEFAULT
def rheader(r, **attr): """ S3SyncLog resource header """ if r.id is None: return DIV(current.T("Showing latest entries first")) else: return None
def layout(item): name = current.T("Cumbria County Council") current_user = current.auth.user if current_user: user_org_id = current_user.organisation_id if user_org_id: otable = current.s3db.org_organisation query = (otable.id == user_org_id) & \ (otable.deleted == False) row = current.db(query).select(otable.name, limitby = (0, 1), ).first() if row: name = row.name logo = IMG(_src = "/%s/static/themes/CCC/img/logo_small.png" % current.request.application, _alt = name, _width = 140, ) # Note: render using current.menu.org.render()[0] + current.menu.org.render()[1] return (name, logo)
def _custom(self, r, widget, **attr): """ Generate a Custom widget @param r: the S3Request instance @param widget: the widget definition as dict @param attr: controller attributes for the request """ label = widget.get("label", "") # Activate if-required #if label and isinstance(label, basestring): if label: label = current.T(label) icon = widget.get("icon", "") if icon: icon = ICON(icon) _class = self._lookup_class(r, widget) contents = widget["fn"](r, **attr) # Render the widget output = DIV(H4(icon, label, _class="profile-sub-header"), DIV(contents, _class="card-holder"), _class=_class) return output
def _comments(r, widget, **attr): """ Generate a Comments widget @param r: the S3Request instance @param widget: the widget as a tuple: (label, type, icon) @param attr: controller attributes for the request @ToDo: Configurable to use either Disqus or internal Comments """ label = widget.get("label", "") if label: label = current.T(label) icon = widget.get("icon", "") if icon: icon = TAG[""](I(_class=icon), " ") _class = self._lookup_class(r, widget) # Render the widget output = DIV(H4(icon, label, _class="profile-sub-header"), DIV(_class="thumbnail"), _class=_class) return output
def _comments(self, r, widget, **attr): """ Generate a Comments widget @param r: the S3Request instance @param widget: the widget definition as dict @param attr: controller attributes for the request @ToDo: Configurable to use either Disqus or internal Comments """ label = widget.get("label", "") # Activate if-required #if label and isinstance(label, basestring): if label: label = current.T(label) icon = widget.get("icon", "") if icon: icon = ICON(icon) _class = self._lookup_class(r, widget) comments = "@ToDo" # Render the widget output = DIV(H4(icon, label, _class="profile-sub-header"), DIV(comments, _class="card-holder"), _class=_class) return output
def get_inv_send_types(self): """ Shipment types which are just for Send """ return self.inv.get("send_type", { 21: current.T("Distribution"), })
def get_report_programme(r): """ Identify the report programme @param r: the S3Request @returns: a tuple (programme_id, label) """ programme_id, label = None, None # Introspect the programme filter progfilter = r.get_vars.get("person_id$hours.programme_id__belongs") or \ r.get_vars.get("~.person_id$hours.programme_id__belongs") if progfilter: prog_ids = progfilter.split(",") if len(prog_ids) == 1: try: programme_id = long(prog_ids[0]) except (ValueError, TypeError): pass if programme_id: table = current.s3db.hrm_programme_hours field = table.programme_id label = current.T("Program: %(programme)s") % \ {"programme": field.represent(programme_id)} return programme_id, label
def get_archived_radio_buttons(self, state, _class='pull-right'): """ state is expected to be 'current' or 'archive' """ from gluon import current if state == 'current': value = True current_class = 'btn-primary' else: value = False current_class = 'btn-default' input_current = INPUT(value=value, _type='radio', _name='show_archive', _value='current', _onchange="this.form.submit();", _id='radio_current') if state == 'archive': value = True archive_class = 'btn-primary' else: value = False archive_class = 'btn-default' input_archive = INPUT(_type='radio', _name='show_archive', _value='archive', _id='radio_archive', _onchange="this.form.submit();", value=value) current_text = current.T('Current') archived_text = current.T('Archive') current = LABEL(current_text, input_current, _class='btn btn-sm ' + current_class) archived = LABEL(archived_text, input_archive, _class='btn btn-sm ' + archive_class) return FORM(DIV(current, archived, _class='btn-group', **{'_data-toggle': 'buttons'}), _class=_class)
def menu_auth(cls, **attr): """ Auth Menu """ auth = current.auth logged_in = auth.is_logged_in() if not logged_in: request = current.request login_next = URL(args=request.args, vars=request.vars) if request.controller == "default" and \ request.function == "user" and \ "_next" in request.get_vars: login_next = request.get_vars["_next"] self_registration = current.deployment_settings.get_security_registration_visible() if self_registration == "index": register = MM("Register", c="default", f="index", m="register", vars=dict(_next=login_next), check=self_registration) else: register = MM("Register", m="register", vars=dict(_next=login_next), check=self_registration) menu_auth = MM("Login", c="default", f="user", m="login", _id="auth_menu_login", vars=dict(_next=login_next), **attr)( MM("Login", m="login", vars=dict(_next=login_next)), register, MM("Lost Password", m="retrieve_password") ) else: # Logged-in menu_auth = MM(auth.user.email, c="default", f="user", translate=False, link=False, _id="auth_menu_email", **attr)( MM("Logout", m="logout", _id="auth_menu_logout"), #MM("User Profile", m="profile"), MM("Personal Profile", c="default", f="person", m="update"), #MM("Contact Details", c="pr", f="person", # args="contact", # vars={"person.pe_id" : auth.user.pe_id}), #MM("Subscriptions", c="pr", f="person", # args="pe_subscription", # vars={"person.pe_id" : auth.user.pe_id}), MM("Change Password", m="change_password"), SEP(), MM({"name": current.T("Rapid Data Entry"), "id": "rapid_toggle", "value": current.session.s3.rapid_data_entry is True, }, f="rapid", ), ) return menu_auth
def rDetailsButton(self,rid): return A( I(_class='icon-th-large icon-white'), _class='btn btn-inverse btn-mini', _title=current.T('Edit details records'), _onclick="return detailsEDialogShow('%s', %d);" % (self._rDetailsURL, rid), #_onmouseover="return detailsSDialogShow('%s', %d);" % (self._rActionURL, rid) )
def rCheckControl(self, rid): return INPUT( _type="checkbox", _class='row-checkbox', _title=current.T('Select this record'), _id="rowcheck_%s" % rid, _onclick="checkControlOthers();" )
def get_inv_shipment_types(self): """ Shipment types which are common to both Send & Receive """ return self.inv.get("shipment_type", { 0: current.messages.NONE, 11: current.T("Internal Shipment"), })
def __call__(self): auth = current.auth ADMIN = auth.get_system_roles().ADMIN if auth.s3_has_role(ADMIN): T = current.T form = FORM(H3(T("Check transferability for all current cases")), INPUT(_class="tiny primary button", _type="submit", _value=T("Update now"), ), P("(%s)" % T("This process can take a couple of minutes")), ) if form.accepts(current.request.post_vars, current.session): # Get default site default_site = current.deployment_settings.get_org_default_site() # Update transferability result = update_transferability(site_id=default_site) if result: msg = current.T("%(number)s transferable cases found") % {"number": result} current.session.confirmation = msg else: msg = current.T("No transferable cases found") current.session.warning = msg # Forward to list of transferable cases redirect(URL(c = "dvr", f = "person", vars = {"closed": "0", "dvr_case.transferable__belongs": "True", "show_family_transferable": "1", }, )) self._view(THEME, "transferability.html") return {"form": form} else: auth.permission.fail()
def dvr(): """ DVR / Disaster Victim Registry """ due_followups = current.s3db.dvr_due_followups() or "0" follow_up_label = "%s (%s)" % ( current.T("Due Follow-ups"), due_followups, ) ADMIN = current.auth.get_system_roles().ADMIN return M(c="dvr")( M("Current Cases", c=("dvr", "pr"), f="person", vars={"closed": "0"})( M("Create", m="create"), #M("All Cases", vars = {}), ), M("Reports", link=False)(M( "Check-in overdue", c=("dvr", "pr"), f="person", vars={ "closed": "0", "overdue": "1" }, ), ), M("Activities", f="case_activity")( M( "Emergencies", vars={"~.emergency": "True"}, ), M(follow_up_label, f="due_followups"), M("All Activities"), M("Report", m="report"), ), M("Appointments", f="case_appointment")(M("Bulk Status Update", m="manage"), ), M("Allowances", f="allowance")(), M("Archive", link=False)( M( "Closed Cases", f="person", vars={"closed": "1"}, ), M( "Invalid Cases", f="person", vars={"archived": "1"}, ), ), M("Administration", restrict=ADMIN)( M("Flags", f="case_flag"), M("Case Status", f="case_status"), ), )
def report_options_validation(form): """ Report options form validation @param form: the form """ if form.vars.rows == form.vars.cols: form.errors.cols = current.T("Duplicate label selected")
def apply_method(self, r, **attr): """ Entry point for REST API @param r: the S3Request instance @param attr: controller parameters @return: output data (JSON) """ resource = self.resource rules = resource.get_config("anonymize") if not rules: r.error(405, "Anonymizing not configured for resource") record_ids = current.session.s3.get("anonymize_record_ids") if not record_ids: r.error(400, "No target record(s) specified") table = resource.table # Check permission for each record has_permission = current.auth.s3_has_permission for record_id in record_ids: if not has_permission("update", table, record_id=record_id) or \ not has_permission("delete", table, record_id=record_id): r.unauthorised() output = {} if r.representation == "html": if r.http == "GET": # Show form anonymise_btn = S3AnonymizeBulkWidget.widget( r, record_ids=record_ids, _class="action-btn anonymize-btn", ) current.response.view = "simple.html" output = { "item": anonymise_btn, "title": current.T("Anonymize Records"), } elif r.http == "POST": # Process form output = self.anonymize(r, table, record_ids) del current.session.s3["anonymize_record_ids"] next_url = resource.get_config("anonymize_next") if next_url: redirect(next_url) else: r.error(405, current.ERROR.BAD_METHOD) else: r.error(415, current.ERROR.BAD_FORMAT) return output
def __init__( self, field_name, other, error_message=current.T( 'enter a value (or check the "confirm empty field" checkbox)')): mylogger.debug(message='__init__') self.other = other self.field_name = field_name self.error_message = error_message
def __init__(self): self.cancel = None # Page to go to upon 'Cancel'...defaults to List View for Resource self.empty = False self.new_id = None self.method = None self.pages = [{"page": "basic", # visible to developers via r.get_vars, can be used by prep/customise "label": current.T("Basic info"), # visible to users via header }, ]
def widget(cls, field, value, **attributes): _id = '%s_%s' % (field._tablename, field.name) _name = field.name if field.type == 'list:integer': _class = 'integer' else: _class = 'string' requires = field.requires if isinstance(field.requires, (IS_NOT_EMPTY, IS_LIST_OF)) else None items = [LI(INPUT(_id=_id, _class=_class, _name=_name, value=v, hideerror=True, requires=requires)) \ for v in value or ['']] buttons = UL() buttons.append( TAG.BUTTON(TAG.I(_class="icon-plus", _style="margin-right:10px;"), current.T("add new"), _class="btn", _id=_id + '_add')) script = SCRIPT(""" // from http://refactormycode.com/codes/694-expanding-input-list-using-jquery (function(){ jQuery.fn.grow_input = function() { return this.each(function() { var ul = this; jQuery(ul).find(":text").after('<a href="javascript:void(0)>+</a>').keypress(function (e) { return (e.which == 13) ? pe(ul) : true; }).next().click(function(){ pe(ul) }); jQuery('#%(id)s_add').click(function(){ pe(ul); return false; }); }); }; function pe(ul) { var new_line = ml(ul); rel(ul); new_line.appendTo(ul); new_line.find(":text").focus(); return false; } function ml(ul) { var line = jQuery(ul).find("li:first").clone(true); line.find(':text').val(''); return line; } function rel(ul) { jQuery(ul).find("li").each(function() { var trimmed = jQuery.trim(jQuery(this.firstChild).val()); if (trimmed=='') jQuery(this).remove(); else jQuery(this.firstChild).val(trimmed); }); } })(); jQuery(document).ready(function(){jQuery('#%(id)s_grow_input').grow_input();}); """ % dict(id=_id)) attributes['_id'] = _id + '_grow_input' return TAG[''](UL(*items, **attributes), buttons, script)
def vol(): """ VOL / Volunteer Management """ pending_label = current.T("Pending Requests") if current.auth.s3_has_role("COORDINATOR"): from s3 import FS query = (FS("end_date") >= current.request.utcnow) & \ (FS("status") == "REQ") resource = current.s3db.resource( "hrm_delegation", filter=query, ) num_pending_requests = resource.count() if num_pending_requests: pending_label = "%s (%s)" % (pending_label, num_pending_requests) return M(c=("vol", "hrm"))( M("Volunteers", c="vol", f="person")( M("Create", m="create", t="pr_person"), M( "Currently Deployed", vars={"deployed_now": 1}, ), M( "Archive", vars={"active": "0"}, restrict="COORDINATOR", ), ), M("Deployments", c="hrm", f="delegation")( M( pending_label, vars={"workflow": "p"}, translate=False, ), M( "Processed Requests", vars={"workflow": "d"}, ), M( "Archive", vars={"workflow": "o"}, ), M("Organizer", m="organize", restrict="HRMANAGER"), ), M("Statistics", link=False)(M("Deployments", c="hrm", f="delegation", m="report"), ), M("Administration", link=False, restrict="ADMIN")( M("Occupation Types", c="pr", f="occupation_type"), M("Skills / Resources", c="hrm", f="skill"), #M("Competency Levels", c="hrm", f="competency_rating"), ))
def customize_deploy_mission(**attr): """ Customize deploy/mission controller """ code = current.s3db.deploy_mission.code code.readable = True code.writable = True code.label = current.T("M-Code") return attr
def buttonsAjax(buttons): ret = '' if buttons: for button in buttons: ret += (' ' if not ret else ' ') + \ str(A(current.T(button[0]),_class='button',_onClick=\ XML("ajaxCall('%s','%s','%s');" % \ (button[1], button[2], button[3])))) return ret
def __init__(self, caption=current.T('Preview'), close=current.T("Close"), id=None, width=70, height=70, source=None, target='', url=None, reload=False): import uuid self.caption = caption self.close = close self.id = id or str(uuid.uuid4()) self.width = width self.height = height self.source = source self.update = 'location.reload();' if reload else '' if url: self.update = "jQuery.ajax({url:\'%s\',success:function(data){jQuery('#%s').html(data);}});" % ( url, target)
def xml(self): return '<div id="%(id)s" style="display:none"><div style="display_order:fixed;top:0%%;left:0%%;width:100%%;height:100%%;background-color:black;z-index:1001;-moz-opacity:0.8;opacity:.80;opacity:0.8;"></div><div id="popup_ivinh" style="display_order:fixed;top:%(top)s%%;left:%(left)s%%;width:%(width)s%%;height:%(height)s%%;padding:16px;border:2px solid black;background-color:white;opacity:1.0;z-index:1002;overflow:auto;-moz-border-radius: 10px; -webkit-border-radius: 10px;"><span id="title" style="font-weight:bold">%(title)s</span><span style="float:right"><a id="close" href="#" onclick="%(update)s jQuery(\'#%(id)s\').hide();return false;">%(close)s</a></span><div id="popup_content" style="width:100%%;height:90%%;" id="c%(id)s"><iframe id="popup_modal_content%(id)s" style="width:100%%;height:100%%;border:0">%(loading)s</iframe></div></div></div><a href="#" onclick="jQuery(\'#popup_modal_content%(id)s\').attr(\'src\',\'%(source)s\');jQuery(\'#%(id)s\').fadeIn(); return false" id="plugin_wiki_open_attachments%(id)s"">%(title)s</a>' % dict( title=self.caption, source=self.source, close=self.close, id=self.id, left=(100 - self.width) / 2, top=(100 - self.height) / 2, width=self.width, height=self.height, loading=current.T('loading...'), update=self.update)
def rheader(self, r): """ Show the current date in the output @param r: the S3Request @returns: the page header (rheader) """ from s3 import S3DateTime today = S3DateTime.datetime_represent(r.utcnow, utc=True) return P("%s: %s" % (current.T("Date"), today))
def tExportButton(self): export_links = [] if not self._db(self._query).isempty(): for k, v in sorted(self.exportClasses.items()): if not v: continue label = v[1] if hasattr(v, "__getitem__") else k link = self.__url2(vars=dict( order=current.request.vars.order or '', _export_type=k, keywords=current.request.vars.keywords or '') ) export_links.append(A(current.T(label), _href=link)) else: pass return DIV( BUTTON( SPAN( I(_class='icon-download icon-white'), current.T('Export') ), _class="btn btn-mini btn-inverse", _title=current.T('Export data to file'), ), BUTTON( SPAN( _class="caret" ), **{ '_class':'btn btn-mini btn-inverse dropdown-toggle', '_data-toggle':'dropdown' } ), UL( _class="dropdown-menu", *[LI(l) for l in export_links] ), _class="btn-group" )
def s3_represent_facilities(db, site_ids, link=True): table = db.org_site sites = db(table._id.belongs(site_ids)).select(table._id, table.instance_type) if not sites: return [] instance_ids = Storage() instance_types = [] for site in sites: site_id = site[table._id.name] instance_type = site.instance_type if instance_type not in instance_types: instance_types.append(instance_type) instance_ids[instance_type] = [site_id] else: instance_ids[instance_type].append(site_id) results = [] for instance_type in instance_types: table = db[instance_type] site_ids = instance_ids[instance_type] query = table.site_id.belongs(site_ids) if instance_type == "org_office": records = db(query).select(table.id, table.site_id, table.type, table.name) else: records = db(query).select(table.id, table.site_id, table.name) for record in records: if instance_type == "org_office" and record.type == 5: instance_type_nice = current.T("Warehouse") else: represent = db.org_site.instance_type.represent instance_type_nice = represent(instance_type) site_str = "%s (%s)" % (record.name, instance_type_nice) if link: c, f = instance_type.split("_") site_str = A(site_str, _href=URL(c=c, f=f, args=[record.id], extension="")) results.append((record.site_id, site_str)) return results
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 _report(self, r, widget, **attr): """ Generate a Report widget @param r: the S3Request instance @param widget: the widget as a tuple: (label, type, icon) @param attr: controller attributes for the request """ widget_get = widget.get # Parse context context = widget_get("context", None) tablename = widget_get("tablename", None) resource, context = self._resolve_context(r, tablename, context) # Widget filter option widget_filter = widget_get("filter", None) if widget_filter: resource.add_filter(widget_filter) # Use the widget-index to create a unique ID widget_id = "profile-report-%s-%s" % (tablename, widget["index"]) # Define the Pivot Table report = S3Report() report.resource = resource ajaxurl = widget_get("ajaxurl", None) contents = report.widget(r, widget_id=widget_id, ajaxurl=ajaxurl, **attr) # Card holder label and icon label = widget_get("label", "") if label and isinstance(label, basestring): label = current.T(label) icon = widget_get("icon", "") if icon: icon = ICON(icon) _class = self._lookup_class(r, widget) # Render the widget output = DIV(H4(icon, label, _class="profile-sub-header"), DIV(contents, _class="card-holder"), _class=_class) return output