desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'@todo: docstring'
def summary(self):
T = current.T append = self.result.append append((T('Yes'), self.yesp)) append((T('No'), self.nop)) return self.format()
'@todo: docstring'
def basicResults(self):
S3OptionAnalysis.basicResults(self) T = current.T if ('Yes' in self.listp): self.yesp = self.listp['Yes'] elif (self.cnt == 0): self.yesp = '' else: self.list['Yes'] = 0 self.yesp = T('0%') if ('No' in self.listp): self.nop = self.listp['No'] elif (sel...
'@todo: docstring'
def summary(self):
T = current.T append = self.result.append append((T('Yes'), self.yesp)) append((T('No'), self.nop)) append((T("Don't Know"), self.dkp)) return self.format()
'@todo: docstring'
def basicResults(self):
S3OptionAnalysis.basicResults(self) T = current.T if ('Yes' in self.listp): self.yesp = self.listp['Yes'] elif (self.cnt == 0): self.yesp = '' else: self.list['Yes'] = 0 self.yesp = T('0%') if ('No' in self.listp): self.nop = self.listp['No'] elif (sel...
'Used to modify the answer from its raw text format. Where necessary, this function will be overridden.'
def castRawAnswer(self, complete_id, answer):
valueList = json2list(answer) return valueList
'@todo: docstring'
def basicResults(self):
self.cnt = 0 self.list = {} for answer in self.valueList: if isinstance(answer, list): answerList = answer else: answerList = [answer] self.cnt += 1 for answer in answerList: if (answer in self.list): self.list[answer] += 1 ...
'@todo: docstring'
def drawChart(self, series_id, output='xml', data=None, label=None, xLabel=None, yLabel=None):
chartFile = self.getChartName(series_id) cached = S3Chart.getCachedFile(chartFile) if cached: return cached chart = S3Chart(path=chartFile) data = [] label = [] for (key, value) in self.list.items(): data.append(value) label.append(key) chart.survey_bar(self.qstnW...
'Convert the answer for the complete_id into a database record. This can have one of three type of return values. A single record: The actual location Multiple records: The set of location, on of which is the location None: No match is found on the database.'
def castRawAnswer(self, complete_id, answer):
records = self.qstnWidget.getLocationRecord(complete_id, answer) return records
'Returns a summary table'
def summary(self):
T = current.T append = self.result.append append((T('Known Locations'), self.kcnt)) append((T('Duplicate Locations'), self.dcnt)) append((T('Unknown Locations'), self.ucnt)) return self.format()
'Returns a table of basic results'
def count(self):
T = current.T append = self.result.append append((T('Total Locations'), len(self.valueList))) append((T('Unique Locations'), self.cnt)) return self.format()
'Calculate the basic results, which consists of a number of list related to the locations LISTS (dictionaries) All maps are keyed on the value used in the database lookup locationList - holding the number of times the value exists complete_id - a list of complete_id at this location duplicates - a list of duplicate ...
def basicResults(self):
self.locationList = {} self.duplicates = {} self.known = {} self.complete_id = {} for answer in self.valueList: if (answer != None): key = answer.key if (key in self.locationList): self.locationList[key] += 1 else: self.loca...
'Ensures that no button is set up @todo: use a class property rather than calling just to get a None'
def chartButton(self, series_id):
return None
'Calculate the number of occurrences of each value'
def uniqueCount(self):
_map = {} for answer in self.valueList: if (answer.key in _map): _map[answer.key] += 1 else: _map[answer.key] = 1 return _map
'@todo: docstring'
def __init__(self, type, question_id, answerList):
S3AbstractAnalysis.__init__(self, type, question_id, answerList) linkWidget = S3QuestionTypeLinkWidget(question_id) relation = linkWidget.get('Relation') type = linkWidget.get('Type') parent_qid = linkWidget.getParentQstnID() valueMap = {} for answer in self.answerList: complete_id =...
'@todo: docstring'
def summary(self):
return self.widget.summary()
'@todo: docstring'
def count(self):
return self.widget.count()
'@todo: docstring'
def chartButton(self, series_id):
return self.widget.chartButton(series_id)
'@todo: docstring'
def filter(self, filterType, groupedData):
return self.widget.filter(filterType, groupedData)
'@todo: docstring'
def drawChart(self, series_id, output='xml', data=None, label=None, xLabel=None, yLabel=None):
return self.widget.drawChart(data, series_id, label, xLabel, yLabel)
'@todo: docstring'
def __init__(self, type, question_id, answerList):
S3AbstractAnalysis.__init__(self, type, question_id, answerList) childWidget = S3QuestionTypeLinkWidget(question_id) trueType = childWidget.get('Type') for answer in self.answerList: if self.valid(answer): try: self.valueList.append(trueType.castRawAnswer(answer['comp...
'@todo: docstring'
def drawChart(self, series_id, output='xml', data=None, label=None, xLabel=None, yLabel=None):
return self.widget.drawChart(series_id, output, data, label, xLabel, yLabel)
'@todo: docstring'
def filter(self, filterType, groupedData):
return self.widget.filter(filterType, groupedData)
'FK representation'
@staticmethod def gis_country_code_represent(code):
if (not code): return current.messages['NONE'] return (current.gis.get_country(code, key_type='code') or current.messages.UNKNOWN_OPT)
'On Accept for GIS Locations (after DB I/O)'
@staticmethod def gis_location_onaccept(form):
auth = current.auth form_vars = form.vars id = form_vars.id if (form_vars.path and current.response.s3.bulk): db = current.db db((db.gis_location.id == id)).update(path=None) if ((not auth.override) and (not auth.rollback)): feature = json.dumps(dict(id=id, level=form_vars.ge...
'On Validation for GIS Locations (before DB I/O)'
@staticmethod def gis_location_onvalidation(form):
T = current.T db = current.db gis = current.gis auth = current.auth response = current.response settings = current.deployment_settings s3 = response.s3 form_vars = form.vars vars_get = form_vars.get level = vars_get('level', None) parent = vars_get('parent', None) lat = v...
'This callback will be called when importing location records it will look to see if the record being imported is a duplicate. @param item: An S3ImportItem object which includes all the details of the record being imported If the record is a duplicate then it will set the item method to update Rules for finding a dupli...
@staticmethod def gis_location_duplicate(item):
data = item.data name = data.get('name') if (not name): return level = data.get('level') if (not level): address = data.get('addr_street') if (not address): return table = item.table query = ((table.addr_street == address) & (table.deleted != True)...
'JSON search method for S3LocationAutocompleteWidget - adds hierarchy support @param r: the S3Request @param attr: request attributes'
@staticmethod def gis_search_ac(r, **attr):
output = None response = current.response resource = r.resource table = r.resource.table settings = current.deployment_settings resource.add_filter(response.s3.filter) resource.add_filter((table.end_date == None)) _vars = current.request.get_vars limit = int((_vars.limit or 0)) v...
'Provide the options for a Search widget - countries is a list of ISO2 codes - normally provided via settings.get_gis_countries()'
@staticmethod def gis_country_opts(countries):
db = current.db table = db.gis_location ttable = db.gis_location_tag query = (((ttable.tag == 'ISO2') & ttable.value.belongs(countries)) & (ttable.location_id == table.id)) opts = db(query).select(table.id, table.name, orderby=table.name) od = OrderedDict() for opt in opts: od[opt.id...
'Prepare the gis_hierarchy form'
@staticmethod def gis_hierarchy_form_setup():
T = current.T table = current.db.gis_hierarchy table.L1.label = T('Hierarchy Level 1 Name (e.g. State or Province)') table.L1.comment = DIV(_class='tooltip', _title=('%s|%s' % (T('Location Hierarchy Level 1 Name'), T('Term for the primary within-country ad...
'If strict, hierarchy names must not have gaps.'
@staticmethod def gis_hierarchy_onvalidation(form):
form_vars = form.vars if form_vars.strict_hierarchy: gis = current.gis hierarchy_level_keys = gis.hierarchy_level_keys level_names = [(form_vars[key] if (key in form_vars) else None) for key in hierarchy_level_keys] gaps = filter(None, map((lambda n: ((not level_names[n]) and lev...
'Prepare the gis_config form'
@staticmethod def gis_config_form_setup():
T = current.T table = current.db.gis_config label = T('Name') table.name.label = label table.name.represent = (lambda v: (v or '')) table.name.comment = DIV(_class='tooltip', _title=('%s|%s' % (label, T("If this configuration is displayed on the GIS config menu, giv...
'Set the pe_type'
@staticmethod def gis_config_onvalidation(form):
form_vars = form.vars if (form_vars.uuid == 'SITE_DEFAULT'): form_vars.pe_type = 9 elif ('pe_id' in form_vars): pe_id = form_vars.pe_id if pe_id: db = current.db s3db = current.s3db table = s3db.pr_pentity query = (table.pe_id == pe_id)...
'If this is the cached config, clear the cache. If this is this user\'s personal config, clear the config Check that there is only 1 default for each PE If this is an OU config, then add to GIS menu If this has a region location, protect that location from accidental editing (e.g. if it is used as a default location fo...
@staticmethod def gis_config_onaccept(form):
db = current.db auth = current.auth form_vars = form.vars config_id = form_vars.id pe_id = form_vars.get('pe_id', None) if pe_id: user = auth.user if (user and (user.pe_id == pe_id)): current.response.s3.gis.config = None if form_vars.pe_default: t...
'If the currently-active config was deleted, clear the cache'
@staticmethod def gis_config_ondelete(row):
s3 = current.response.s3 if (s3.gis.config and (s3.gis.config.id == row.id)): s3.gis.config = None
'Function which takes a list of k/v option tuples and adds an icon URL for S3SelectMenu()'
@staticmethod def gis_marker_options(options):
marker_ids = [] mappend = marker_ids.append for o in options: mappend(o[0]) mtable = current.s3db.gis_marker markers = current.db(mtable.id.belongs(marker_ids)).select(mtable.id, mtable.image, mtable.height, mtable.width) markers_lookup = {} base_url = ('/%s/static/img/markers/' % cu...
'Record the size of an Image upon Upload Don\'t wish to resize here as we\'d like to use full resolution for printed output'
@staticmethod def gis_marker_onvalidation(form):
form_vars = form.vars image = form_vars.image if (image is None): encoded_file = form_vars.get('imagecrop-data', None) if (not encoded_file): return import base64 import uuid (metadata, encoded_file) = encoded_file.split(',') (filename, datatype, e...
'Represent a Row @param row: The Row'
def represent_row(self, row):
represent = DIV(IMG(_src=URL(c='static', f='img', args=['markers', row.image]), _height=40)) return represent
'If this is the default base layer then remove this flag from all others in this config.'
@staticmethod def gis_layer_config_onaccept(form):
form_vars = form.vars base = form_vars.base if (base == 'False'): base = False enabled = form_vars.enabled if (enabled == 'False'): enabled = False if (base and enabled): db = current.db ctable = db.gis_config ltable = db.gis_layer_config query = (...
'Extract the style from a LocationSelectorWidget2 & create/update the style record'
@staticmethod def gis_style_postprocess(form):
colour = current.request.post_vars.colour if (not colour): return def rgb2hex(r, g, b): '\n Given an rgb or rgba sequence of 0-1 floats, return the hex string\n ...
'Ensure that only a single layer for each controller/function is set as Default'
@staticmethod def gis_layer_feature_onaccept(form):
id = form.vars.id vars = form.vars c = vars.get('controller', None) f = vars.get('function', None) default = vars.get('style_default', None) if (default and c and f and id): db = current.db table = db.gis_layer_feature query = (((table.controller == c) & (table.function =...
'custom_retrieve to override web2py DAL\'s standard retrieve, as that checks filenames for uuids, so doesn\'t work with pre-populated files in static'
@staticmethod def gis_cache2_retrieve(filename, path=None):
if (not path): path = current.db.gis_cache2.file.uploadfolder f = open(os.path.join(path, filename), 'rb') return (filename, f)
'Check we have either a URL or a file'
@staticmethod def gis_layer_file_onvalidation(form):
form_vars = form.vars doc = form_vars.file if (doc is None): return if ((not hasattr(doc, 'file')) and (not doc) and (not form_vars.url)): msg = current.T('Either file upload or URL required.') form.errors.file = msg form.errors.url = msg
'File representation'
@staticmethod def gis_layer_geojson_file_represent(file):
if file: try: filename = current.db.gis_layer_geojson.file.retrieve(file)[0] except IOError: return current.T('File not found') else: return A(filename, _href=URL(c='static', f='cache', args=['geojson', file])) else: return current.messag...
'If we have a file, then set the URL to point to it'
@staticmethod def gis_layer_geojson_onaccept(form):
id = form.vars.id table = current.s3db.gis_layer_geojson record = current.db((table.id == id)).select(table.id, table.file, limitby=(0, 1)).first() if (record and record.file): record.update_record(url=URL(c='static', f='cache', args=['geojson', record.file]), refresh=0) gis_layer_onaccept(f...
'File representation'
@staticmethod def gis_layer_kml_file_represent(file):
if file: try: filename = current.db.gis_layer_kml.file.retrieve(file)[0] except IOError: return current.T('File not found') else: return A(filename, _href=URL(c='static', f='cache', args=['kml', file])) else: return current.messages['NONE...
'If we have a file, then set the URL to point to it'
@staticmethod def gis_layer_kml_onaccept(form):
id = form.vars.id table = current.s3db.gis_layer_kml record = current.db((table.id == id)).select(table.id, table.file, limitby=(0, 1)).first() if (record and record.file): record.update_record(url=URL(c='static', f='cache', args=['kml', record.file]), refresh=0) gis_layer_onaccept(form)
'Convert the Uploaded Shapefile to GeoJSON for display on the map'
@staticmethod def gis_layer_shapefile_onaccept(form):
id = form.vars.id db = current.db tablename = ('gis_layer_shapefile_%s' % id) if (tablename in db): return try: from osgeo import ogr except ImportError: current.response.error = current.T('Python GDAL required for Shapefile support!') else: tab...
'@ToDo: Check if the file has changed & run the normal onaccept if-so'
@staticmethod def gis_layer_shapefile_onaccept_update(form):
S3MapModel.gis_layer_shapefile_onaccept(form)
'Custom method to create a Style for a Theme Layer - splits data into 5 quintiles - uses Colorbrewer to create a 5-class colorblind-safe printer-friendly Sequential scheme @ToDo: Divergent colour scheme option @ToDo: Select # of classes @ToDo: Select full range of colour schemes @ToDo: Alternate class breaks mechanisms...
@staticmethod def gis_theme_style(r, **attr):
classes = 5 nature = 'sequential' db = current.db table = db.gis_theme_data rows = db((table.layer_theme_id == r.id)).select(table.value) values = [float(row.value) for row in rows] q = [] qappend = q.append for i in range((classes - 1)): qappend(((1.0 / classes) * (i + 1))) ...
'If the Comments are a Style then create a gis_style record for this and blank the comment. Used for s3csv imports as we have no components & can\'t use an import_prep as we don\'t know the record_id'
@staticmethod def gis_poi_onaccept(form):
form_vars = form.vars comments = form_vars.get('comments') if (not comments): return value = comments.replace("'", '"') try: style = json.loads(value) except: return db = current.db s3db = current.s3db table = s3db.gis_poi_type poi_type = db((table.id == f...
'Update Style for the PoIs layer @ToDo: deployment_setting to add a new Feature Layer for new PoI types'
@staticmethod def gis_poi_type_onaccept(form):
db = current.db s3db = current.s3db ptable = s3db.gis_poi_type mtable = s3db.gis_marker query = ((ptable.deleted == False) & (mtable.id == ptable.marker_id)) rows = db(query).select(ptable.name, mtable.image) style = [] sappend = style.append for row in rows: marker = row['gi...
'Represent a (key, value) as hypertext link. @param k: the key @param v: the representation of the key @param row: the row with this key (unused here)'
@staticmethod def link(k, v, row=None):
if (k is None): return '-' settings = current.deployment_settings iheight = settings.get_gis_map_selector_height() popup = settings.get_gis_popup_location_link() return A(v, _style='cursor:pointer;cursor:hand', _onclick=("s3_viewMap(%i,%i,'%s');return false" % (k, iheight, popup)))
'Represent a coordinate (latitude or longitude) according to a format provided from deployment_settings.'
@staticmethod def lat_lon_format(coord):
degrees = abs(coord) minutes = ((degrees - int(degrees)) * 60) seconds = ((minutes - int(minutes)) * 60) (degrees, minutes) = (int(coord), int(minutes)) format = current.deployment_settings.get_L10n_lat_lon_format() formatted = format.replace('%d', ('%d' % degrees)).replace('%m', ('%d' % minutes...
'Custom lookup method for Location(GIS) rows.Parameters key and fields are not used, but are kept for API compatiblity reasons. @param values: the gis_location IDs'
def lookup_rows(self, key, values, fields=None):
db = current.db s3db = current.s3db ltable = s3db.gis_location count = len(values) sep = self.sep translate = self.translate fields = [ltable.id, ltable.name, ltable.level, ltable.path, ltable.L0, ltable.L1, ltable.L2, ltable.L3, ltable.L4, ltable.L5] if sep: gis_fields = fields ...
'Different Entry point for S3LocationSelector(intends to use represent_row) - Lookup L10n, path - then call represent_row'
def alt_represent_row(self, row):
sep = self.sep translate = self.translate self.paths = {} if (sep or translate): path = row.path if (not path): path = current.gis.update_location_tree(row) split_path = path.split('/') self.paths[row.id] = split_path location_ids = set(split_path) ...
'Represent a single Row - assumes that Path & Lx have been populated correctly by gis.update_location_tree() @param row: the gis_location Row'
def represent_row(self, row):
sep = self.sep translate = self.translate ids = self.paths.get(row.id) if translate: l10n = self.l10n loc = l10n.get(row.id) if loc: name = loc['name_l10n'] else: name = (row.name or '') else: name = (row.name or '') level = row.lev...
'Safe defaults if module is disabled'
def defaults(self):
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(sync_repository_id=(lambda **attr: dummy('repository_id')))
'Last pull synchronization date/time for this repository'
@staticmethod def sync_repository_last_pull_time(row):
try: repository_id = row['sync_repository.id'] except AttributeError: return '-' table = current.s3db.sync_task query = (table.repository_id == repository_id) task = current.db(query).select(orderby=(~ table.last_pull), limitby=(0, 1)).first() if (task and task.last_pull): ...
'Last push synchronization date/time for this repository'
@staticmethod def sync_repository_last_push_time(row):
try: repository_id = row['sync_repository.id'] except AttributeError: return '-' table = current.s3db.sync_task query = (table.repository_id == repository_id) task = current.db(query).select(orderby=(~ table.last_push), limitby=(0, 1)).first() if (task and task.last_push): ...
'Task representation @ToDo: Migrate to S3Represent'
@staticmethod def sync_task_represent(task_id):
s3db = current.s3db ttable = s3db.sync_task rtable = s3db.sync_repository query = ((ttable.id == task_id) & (rtable.id == ttable.repository_id)) db = current.db task = db(query).select(ttable.resource_name, rtable.name, limitby=(0, 1)).first() UNKNOWN_OPT = current.messages.UNKNOWN_OPT i...
'Cleanup after repository deletion @todo: use standard delete cascade'
@staticmethod def sync_repository_ondelete(row):
db = current.db s3db = current.s3db rtable = s3db.sync_repository db((rtable.id == row.id)).update(url=None) ttable = s3db.sync_task db((ttable.repository_id == row.id)).update(deleted=True) jtable = s3db.sync_job db((jtable.repository_id == row.id)).update(deleted=True) ltable = s3d...
'Send registration request to the peer'
@staticmethod def sync_repository_onaccept(form):
try: repository_id = form.vars.id except: return sync = current.sync if repository_id: rtable = current.s3db.sync_repository query = (rtable.id == repository_id) repository = current.db(query).select(limitby=(0, 1)).first() if (repository and repository.ur...
'Task record validation'
@staticmethod def sync_task_onvalidation(form):
repository_id = (form.vars.repository_id or current.request.post_vars.repository_id) resource_name = form.vars.resource_name if (repository_id and resource_name): ttable = current.s3db.sync_task query = (((ttable.repository_id == repository_id) & (ttable.resource_name == resource_name)) & (t...
'Reset last_push when adding/changing a filter'
@staticmethod def sync_resource_filter_onaccept(form):
db = current.db s3db = current.s3db ttable = s3db.sync_task ftable = s3db.sync_resource_filter if isinstance(form, Row): filter_id = form.id else: try: filter_id = form.vars.id except: return row = db((ftable.id == filter_id)).select(ftable.id,...
'Safe defaults for model-global names in case module is disabled - used by events module & legacy assess & impact modules'
def defaults(self):
ireport_id = S3ReusableField('ireport_id', 'integer', readable=False, writable=False) return Storage(irs_ireport_id=ireport_id)
'Incident Category Validation: Prevent Duplicates Done here rather than in .requires to maintain the dropdown.'
@staticmethod def irs_icategory_onvalidation(form):
db = current.db table = db.irs_icategory (category, error) = IS_NOT_ONE_OF(db, 'irs_icategory.code')(form.vars.code) if error: form.errors.code = error return False
'Represent an Incident Report via it\'s name'
@staticmethod def irs_ireport_represent(id, row=None):
if row: return row.name elif (not id): return current.messages['NONE'] db = current.db table = db.irs_ireport r = db((table.id == id)).select(table.name, limitby=(0, 1)).first() try: return r.name except: return current.messages.UNKNOWN_OPT
'Assign the appropriate vehicle & on-shift team to the incident @ToDo: Specialist teams @ToDo: Make more generic (currently Porto-specific)'
@staticmethod def ireport_onaccept(form):
settings = current.deployment_settings if (settings.has_module('fire') and settings.has_module('vehicle')): pass else: return db = current.db s3db = current.s3db vars = form.vars ireport = vars.id category = vars.category if (category == '1100'): types = ['VUC...
'Send a Dispatch notice from an Incident Report - this will be formatted as an OpenGeoSMS'
@staticmethod def irs_dispatch(r, **attr):
if ((r.representation == 'html') and (r.name == 'ireport') and r.id and (not r.component)): T = current.T msg = current.msg record = r.record id = record.id contact = '' if record.contact: contact = '\n%s: %s'(T('Contact'), record.contact) messa...
'Display the Incidents on a Simile Timeline http://www.simile-widgets.org/wiki/Reference_Documentation_for_Timeline @ToDo: Play button http://www.simile-widgets.org/wiki/Timeline_Moving_the_Timeline_via_Javascript'
@staticmethod def irs_timeline(r, **attr):
if ((r.representation == 'html') and (r.name == 'ireport')): T = current.T db = current.db s3db = current.s3db request = current.request response = current.response s3 = response.s3 itable = s3db.doc_image dtable = s3db.doc_document s3.scripts....
'Import Incident Reports from Ushahidi @ToDo: Deployment setting for Ushahidi instance URL'
@staticmethod def irs_ushahidi_import(r, **attr):
T = current.T auth = current.auth request = current.request response = current.response session = current.session system_roles = session.s3.system_roles ADMIN = system_roles.ADMIN if (not auth.s3_has_role(ADMIN)): auth.permission.fail() if ((r.representation == 'html') and (r...
'Populate the dropdown widget for responding to an Incident Report based on those vehicles which aren\'t already on-call'
@staticmethod def irs_vehicle_requires():
s3db = current.s3db table = s3db.asset_asset ltable = s3db.irs_ireport_vehicle asset_represent = s3db.asset_asset_id.represent query = (((table.type == s3db.asset_types['VEHICLE']) & (table.deleted == False)) & (((ltable.id == None) | (ltable.closed == True)) | (ltable.deleted == True))) left = ...
'Safe defaults for model-global names in case module is disabled'
def defaults(self):
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(deploy_mission_id=(lambda **attr: dummy('mission_id')))
'@todo: docstring?'
@staticmethod def add_button(r, widget_id=None, visible=True, **attr):
if current.auth.s3_has_permission('create', r.tablename): return A(S3Method.crud_string(r.tablename, 'label_create'), _href=r.url(method='create', id=0, vars={}), _class='action-btn') else: return ''
'@todo: docstring?'
@staticmethod def deploy_mission_name_represent(name):
table = current.s3db.deploy_mission mission = current.db((table.name == name)).select(table.id, limitby=(0, 1)).first() if (not mission): return name return A(name, _href=URL(c='deploy', f='mission', args=[mission.id, 'profile']))
'See if we can auto-populate the Date/Location/Event Type in imported records @param form: the form'
@staticmethod def deploy_mission_create_onaccept(form):
if (not current.response.s3.bulk): return db = current.db s3db = current.s3db table = s3db.deploy_mission record = db((table.id == form.vars.id)).select(table.id, table.name, table.location_id, table.event_type_id, limitby=(0, 1)).first() name = record.name if (' ' not in name): ...
'Create/update linked hrm_experience record for assignment @param form: the form'
@staticmethod def deploy_assignment_onaccept(form):
db = current.db s3db = current.s3db form_vars = form.vars assignment_id = form_vars.id fields = ('human_resource_id', 'mission_id', 'job_title', 'job_title_id', 'start_date', 'end_date') if any(((key not in form_vars) for key in fields)): atable = db.deploy_assignment query = (at...
'Remove linked hrm_experience record @param row: the link to be deleted @param tablename: the tablename (ignored)'
@staticmethod def deploy_assignment_experience_ondelete_cascade(row, tablename=None):
s3db = current.s3db table = s3db.deploy_assignment_experience link = current.db((table.id == row.id)).select(table.id, table.experience_id, limitby=(0, 1)).first() if (not link): return else: link.update_record(experience_id=None) s3db.resource('hrm_experience', id=link.experienc...
'Remove linked hrm_appraisal record @param row: the link to be deleted @param tablename: the tablename (ignored)'
@staticmethod def deploy_assignment_appraisal_ondelete_cascade(row, tablename=None):
s3db = current.s3db table = s3db.deploy_assignment_appraisal link = current.db((table.id == row.id)).select(table.id, table.appraisal_id, limitby=(0, 1)).first() if (not link): return else: link.update_record(appraisal_id=None) s3db.resource('hrm_appraisal', id=link.appraisal_id)...
'Add all Deployment Team members to the Recipients of the Alert - only runs if settings.deploy.manual_recipients is False'
@staticmethod def deploy_alert_onaccept(form):
db = current.db s3db = current.s3db alert_id = form.vars.id atable = s3db.deploy_application query = ((atable.active == True) & (atable.deleted == False)) rows = db(query).select(atable.human_resource_id) insert = s3db.deploy_alert_recipient.insert for row in rows: insert(alert_i...
'Custom Method to send an Alert'
@staticmethod def deploy_alert_send(r, **attr):
alert_id = r.id if ((r.representation != 'html') or (not alert_id) or r.component): raise HTTP(501, BADMETHOD) auth = current.auth authorised = auth.s3_has_permission('update', 'deploy_alert', record_id=alert_id) if (not authorised): r.unauthorised() record = r.record mission...
'Update the doc_id in all attachments (doc_document) to the hrm_human_resource the response is linked to. @param form: the form'
@staticmethod def deploy_response_update_onaccept(form):
form_vars = form.vars if ((not form_vars) or ('id' not in form_vars)): return db = current.db s3db = current.s3db if (('human_resource_id' not in form_vars) or ('message_id' not in form_vars)): rtable = s3db.deploy_response response = db((rtable.id == form_vars.id)).select(rt...
'Custom method for email inbox, provides a datatable with bulk-delete option @param r: the S3Request @param attr: the controller attributes'
def apply_method(self, r, **attr):
T = current.T s3db = current.s3db response = current.response s3 = response.s3 resource = self.resource if (r.http == 'POST'): deleted = 0 post_vars = r.post_vars if all([(n in post_vars) for n in ('delete', 'selected', 'mode')]): selected = post_vars.selected...
'Constructor'
def __init__(self, profile='deploy_mission'):
super(deploy_MissionProfileLayout, self).__init__(profile=profile) self.dcount = {} self.avgrat = {} self.deployed = set() self.appraisals = {} self.use_regions = current.deployment_settings.get_org_regions()
'Bulk lookups for cards @param resource: the resource @param records: the records as returned from S3Resource.select'
def prep(self, resource, records):
db = current.db s3db = current.s3db tablename = resource.tablename if (tablename == 'deploy_alert'): record_ids = set((record['_row']['deploy_alert.id'] for record in records)) htable = s3db.hrm_human_resource number_of_recipients = htable.id.count() rtable = s3db.deploy_...
'Render the card header @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'
def render_header(self, list_id, item_id, resource, rfields, record):
return None
'Render the card body @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'
def render_body(self, list_id, item_id, resource, rfields, record):
db = current.db s3db = current.s3db has_permission = current.auth.s3_has_permission table = resource.table tablename = resource.tablename T = current.T pkey = str(resource._id) raw = record['_row'] record_id = raw[pkey] contents = workflow = None if (tablename == 'deploy_aler...
'Render the body icon @param list_id: the list ID @param resource: the S3Resource'
def render_icon(self, list_id, resource):
tablename = resource.tablename if (tablename == 'deploy_alert'): icon = 'alert.png' elif (tablename == 'deploy_response'): icon = 'email.png' elif (tablename == 'deploy_assignment'): icon = 'member.png' else: return None return A(IMG(_src=URL(c='static', f='themes...
'Render the toolbox @param list_id: the HTML ID of the list @param resource: the S3Resource to render @param record: the record as dict'
def render_toolbox(self, list_id, resource, record):
table = resource.table tablename = resource.tablename record_id = record[str(resource._id)] open_url = update_url = None if (tablename == 'deploy_alert'): open_url = URL(f='alert', args=[record_id]) elif (tablename == 'deploy_response'): update_url = URL(f='response_message', arg...
'Render a data column. @param item_id: the HTML element ID of the item @param rfield: the S3ResourceField for the column @param record: the record (from S3Resource.select)'
def render_column(self, item_id, rfield, record):
colname = rfield.colname if (colname not in record): return None value = record[colname] value_id = ('%s-%s' % (item_id, colname.replace('.', '_'))) label = LABEL(('%s:' % rfield.label), _for=value_id, _class='profile-data-label') value = SPAN(value, _id=value_id, _class='profile-data-va...
'Represent the Active status of a Volunteer'
@staticmethod def vol_active_represent(opt):
if ('report' in current.request.args): return opt if opt: output = DIV(current.T('Yes'), _style='color:green') else: output = DIV(current.T('No'), _style='color:red') return output
'File representation'
@staticmethod def vol_award_file_represent(file):
if file: try: filename = current.db.vol_volunteer_award.file.retrieve(file)[0] except IOError: return current.T('File not found') else: return A(filename, _href=URL(c='default', f='download', args=[file])) else: return current.messages['N...
'Return safe defaults for model globals, this will be called instead of model() in case the model has been deactivated in deployment_settings.'
@staticmethod def defaults():
return dict(vol_cluster_id=S3ReusableField('vol_cluster_id', 'integer', readable=False, writable=False))
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(disease_disease_id=(lambda **attr: dummy('disease_id')), disease_symptom_id=(lambda **attr: dummy('symptom_id')))
'Disease import update detection @param item: the import item'
@staticmethod def disease_duplicate(item):
data = item.data code = data.get('code') name = data.get('name') table = item.table queries = [] if code: queries.append((table.code == code)) if name: queries.append((table.name == name)) if queries: query = reduce((lambda x, y: (x | y)), queries) else: ...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(disease_case_id=(lambda **attr: dummy('case_id')))
'Find the case record for a person for a disease @param person_id: the person record ID @param disease_id: the disease record ID'
@staticmethod def get_case(person_id, disease_id):
ctable = current.s3db.disease_case query = (((ctable.person_id == person_id) & (ctable.disease_id == disease_id)) & (ctable.deleted != True)) record = current.db(query).select(ctable.id, ctable.case_number, limitby=(0, 1)).first() return record
'Make sure that there\'s only one case per person and disease'
@classmethod def case_create_onvalidation(cls, form):
formvars = form.vars try: case_id = formvars.id person_id = formvars.person_id except AttributeError as e: return if ('disease_id' not in formvars): disease_id = current.s3db.disease_case.disease_id.default else: disease_id = formvars.disease_id record = c...
'Case import update detection @param item: the import item'
@staticmethod def case_duplicate(item):
data = item.data case_number = data.get('case_number') person_id = data.get('person_id') table = item.table if case_number: query = ((table.case_number == case_number) & (table.deleted != True)) else: disease_id = data.get('disease_id') if (person_id and disease_id): ...
'Propagate status updates of the case to high-risk contacts'
@staticmethod def case_onaccept(form):
formvars = form.vars try: record_id = formvars.id except AttributeError: return disease_propagate_case_status(record_id) return