desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Custom widget for label input, providing a clear-button (for ease of use on mobile devices where no ESC exists) @param field: the Field @param value: the current value @param attributes: HTML attributes NB: expects Foundation theme'
@staticmethod def label_input(field, value, **attributes):
from gluon.sqlhtml import StringWidget default = {'value': (((value is not None) and str(value)) or '')} attr = StringWidget._attributes(field, default, **attributes) placeholder = current.T('Enter or scan ID') attr['_placeholder'] = placeholder postfix = ICON('fa fa-close') widg...
'Perform ajax actions, accepts a JSON object as input: {m: the method (check|check-in|check-out) l: the PE label @param r: the S3Request @param attr: controller parameters'
def submit_ajax(self, r, **attr):
T = current.T s = r.body s.seek(0) try: data = json.load(s) except (ValueError, TypeError): r.error(400, current.ERROR.BAD_REQUEST) output = {} error = None alert = None alert_type = 'success' label = data.get('l') person = self.get_person(label) if (perso...
'Convert person details and current check-in status into a JSON-serializable dict for Ajax-actions @param person: the person record @param status: the status dict (from status())'
@classmethod def ajax_data(cls, person, status):
T = current.T person_details = cls.person_details(person) output = {'d': s3_str(person_details), 'i': (True if status.get('check_in_allowed') else False), 'o': (True if status.get('check_out_allowed') else False), 's': status.get('status')} profile_picture = cls.profile_picture(person) if profile_pi...
'Get the person record for the label @param label: the PE label'
def get_person(self, label):
s3db = current.s3db person = None fields = ['id', 'pe_id', 'pe_label', 'first_name', 'middle_name', 'last_name', 'date_of_birth', 'gender', 'location_id'] query = (FS('pe_label') == label) presource = s3db.resource('pr_person', filter=query) rows = presource.select(fields, start=0, limit=1, as_r...
'Check the check-in/out status for a person at this site, invokes the check_in_status hook for the site resource to obtain current status information. @param r: the S3Request @param site_id: the site ID @param person: the person record @return: a dict like: {valid: True|False, whether the person record is valid for che...
@staticmethod def status(r, person):
result = {'valid': True, 'status': None, 'info': None, 'check_in_allowed': True, 'check_out_allowed': True, 'error': None} check_in_status = current.s3db.get_config(r.tablename, 'check_in_status') if check_in_status: status = check_in_status(r.record, person) else: status = None if i...
'Format the person details @param person: the person record (Row)'
@staticmethod def person_details(person):
T = current.T settings = current.deployment_settings name = s3_fullname(person) dob = person.date_of_birth if dob: dob = S3DateTime.date_represent(dob) details = ('%s (%s %s)' % (name, T('Date of Birth'), dob)) else: details = name return SPAN(details, _cl...
'Get the profile picture URL for a person @param person: the person record (Row) @return: the profile picture URL (relative URL), or None if no profile picture is available for that person'
@staticmethod def profile_picture(person):
try: pe_id = person.pe_id except AttributeError: return None table = current.s3db.pr_image query = (((table.pe_id == pe_id) & (table.profile == True)) & (table.deleted != True)) row = current.db(query).select(table.image, limitby=(0, 1)).first() if row: return URL(c='defa...
'Check-in the person at this site, invokes the site_check_in hook for the site resource @param r: the S3Request @param person: the person record'
def check_in(self, r, person):
s3db = current.s3db ptable = s3db.pr_person from s3.s3track import S3Trackable person_id = person.id record = r.record tracker = S3Trackable(ptable, record_id=person_id) tracker.set_location(record.location_id) site_check_in = s3db.get_config(r.tablename, 'site_check_in') if site_che...
'Check-out the person from this site, invokes the site_check_out hook for the site resource @param r: the S3Request @param person: the person record'
def check_out(self, r, person):
s3db = current.s3db ptable = s3db.pr_person from s3.s3track import S3Trackable person_id = person.id record = r.record tracker = S3Trackable(ptable, record_id=person_id) tracker.set_location(person.location_id) site_check_out = s3db.get_config(r.tablename, 'site_check_out') if site_c...
'Helper function to inject static JS and instantiate the client-side widget @param widget_id: the node ID where to instantiate the widget @param options: dict of widget options (JSON-serializable)'
@staticmethod def inject_js(widget_id, options):
s3 = current.response.s3 appname = current.request.application scripts = s3.scripts if s3.debug: script = ('/%s/static/scripts/S3/s3.ui.sitecheckin.js' % appname) else: script = ('/%s/static/scripts/S3/s3.ui.sitecheckin.min.js' % appname) scripts.append(script) scripts = s3.j...
'Main method, to be set for the "deduplicate" hook @param item: the S3ImportItem'
@classmethod def duplicate(cls, item):
try: duplicate_id = cls.identify(item) except ValueError: error = ('Ambiguous data, try specifying parent organisation: %s' % item.data.get('name')) item.accepted = False item.error = error if (item.element is not None): item.element.set(curr...
'Get the record ID that corresponds to the given import item or UUID @param item: the import item @param uid: the UUID @return: the record ID if successfully identified, or None if there is no record for that item yet @raise ValueError: if there are multiple matches in the DB'
@classmethod def identify(cls, item=None, uid=None):
if item.id: return item.id if (uid is not None): table = (item.table if item else current.s3db.org_organisation) row = current.db((table.uuid == uid)).select(table.id, limitby=(0, 1)).first() if row: return row.id name_matches = cls.name_match(item) if (not na...
'Find all name matches for the given import item @param item: the import item @return: a dict {id: name, parent: parent_id} of records which match the import item by name, or alternatively by local name if enabled and no direct name match'
@classmethod def name_match(cls, item):
matches = {} name = item.data.get('name') if (not name): return matches db = current.db s3db = current.s3db table = item.table lower_name = s3_unicode(name).lower() query = ((table.name.lower() == lower_name) & (table.deleted == False)) rows = db(query).select(table.id, table...
'Find the parent for the given import item @param item: the import item @return: a tuple (id, uid, item) for the parent'
@classmethod def parent(cls, item):
parent_id = parent_uid = parent_item = None is_key = (lambda fk, name: ((fk == name) or (isinstance(fk, (tuple, list)) and (fk[1] == name)))) all_items = item.job.items for (uid, link_item) in all_items.items(): if (link_item.tablename == 'org_organisation_branch'): references = link...
'@param component: the Component in which to create records'
def __init__(self, component, types=None):
self.component = component
'Apply method. @param r: the S3Request @param attr: controller options for this request'
def apply_method(self, r, **attr):
component = self.component components = r.resource.components for c in components: if (c == component): component = components[c] break try: if component.link: component = component.link except: current.log.error('Invalid Component!') ...
'Apply method. @param r: the S3Request @param attr: controller options for this request'
def apply_method(self, r, **attr):
if (r.http == 'GET'): if (r.representation == 'html'): T = current.T output = dict(title=T('Branch Organisational Capacity Assessment')) current.response.view = 'org/capacity_report.html' if attr.get('rheader'): rheader = attr['rheader...
'Method to read the data @param r: the S3Request'
@staticmethod def _extract(r):
resource = r.resource resource.load() rows = resource._rows if (not len(rows)): return None db = current.db s3db = current.s3db itable = s3db.org_capacity_indicator indicators = db((itable.deleted == False)).select(itable.id, itable.number, itable.section, itable.name, orderby=it...
'Method to output as XLS @ToDo: Finish & use HTML2XLS method in XLS codec to be DRY & reusable'
@staticmethod def _xls(data):
try: import xlwt except ImportError: if (current.auth.permission.format in S3Request.INTERACTIVE_FORMATS): current.session.error = S3XLS.ERROR.XLWT_ERROR redirect(URL(extension='')) else: error = S3XLS.ERROR.XLWT_ERROR current.log.error(err...
'Return the parameter_id of the resilience indicator'
@staticmethod def vulnerability_resilience_id():
if (S3VulnerabilityModel.resilience_pid is None): db = current.db table = db.vulnerability_aggregated_indicator row = db((table.uuid == 'Resilience')).select(table.parameter_id, limitby=(0, 1)).first() try: S3VulnerabilityModel.resilience_pid = row.parameter_id ex...
'Return a list of the parameter_id\'s that are to be used when calculating the resilience indicator'
@staticmethod def vulnerability_pids():
if (S3VulnerabilityModel.indicator_pids is None): db = current.db table = db.vulnerability_indicator rows = db((table.deleted == False)).select(table.parameter_id) S3VulnerabilityModel.indicator_pids = [i.parameter_id for i in rows] return S3VulnerabilityModel.indicator_pids
'Calculates the resilience held in the vulnerability_data table for a specific location and time period. This is run async within vulnerability_update_aggregates Where appropriate add test cases to modules/unit_tests/s3db/vulnerability.py'
@staticmethod def vulnerability_resilience(location_id, resilience_pid, indicator_pids, date_period_start, date_period_end, use_location):
location_level = 'L3' db = current.db s3db = current.s3db vtable = s3db.vulnerability_data atable = db.vulnerability_aggregate query = (((vtable.deleted != True) & (vtable.approved_by != None)) & vtable.parameter_id.belongs(indicator_pids)) ward_count = 1 if use_location: query &...
'This will delete all the vulnerability_aggregate records and then rebuild them by triggering off a request for each vulnerability_data record. This function is normally only run during prepop or postpop so we don\'t need to worry about the aggregate data being unavailable for any length of time'
@staticmethod def vulnerability_rebuild_all_aggregates():
db = current.db ttable = db.scheduler_task rtable = db.scheduler_run wtable = db.scheduler_worker query = (((ttable.task_name == 'vulnerability_update_aggregates') & (rtable.task_id == ttable.id)) & (rtable.status == 'RUNNING')) rows = db(query).select(rtable.id, rtable.task_id, rtable.worker_na...
'This will return the start and end dates of the aggregated time period. Currently the time period is annually so it will return the start and end of the current year.'
@staticmethod def vulnerability_aggregated_period(data_date=None):
if (data_date is None): data_date = date.today() year = data_date.year soap = date(year, 1, 1) eoap = date(year, 12, 31) return (soap, eoap)
'This will calculate the vulnerability_aggregates for the specified records. Either all (when rebuild_all is invoked) or for the individual parameter(s) at the specified location(s) when run onapprove - which currently happens inside the approve_report() controller. This will get the raw data from vulnerability_data an...
@staticmethod def vulnerability_update_aggregates(records=None):
if (not records): return import datetime from dateutil.rrule import rrule, YEARLY db = current.db s3db = current.s3db dtable = s3db.vulnerability_data atable = db.vulnerability_aggregate gtable = db.gis_location param_location_dict = {} location_dict = {} vulnerabilit...
'Calculates the vulnerability_aggregate for a specific parameter at a specific location and time. @param location_id: the location record ID @param parameter_id: the parameter record ID @param start_date: the start date of the time period (as string) @param end_date: the end date of the time period (as string)'
@staticmethod def vulnerability_update_location_aggregate(location_id, parameter_id, start_date, end_date):
location_level = 'L3' db = current.db dtable = current.s3db.vulnerability_data atable = db.vulnerability_aggregate child_locations = current.gis.get_children(location_id, location_level) child_ids = [row.id for row in child_locations] query = ((((dtable.parameter_id == parameter_id) & (dtabl...
'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 Storage(hazard_id=S3ReusableField('hazard_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 {'work_job_id': (lambda **attr: dummy('job_id'))}
'Validation callback for work assignments: - a worker can only be assigned once to the same job @param form: the FORM'
@staticmethod def assignment_onvalidation(form):
db = current.db s3db = current.s3db table = s3db.work_assignment form_vars = form.vars if ('id' in form_vars): record_id = form_vars.id elif hasattr(form, 'record_id'): record_id = form.record_id else: record_id = None try: job_id = form_vars.job_id ex...
'Onaccept callback for work assignments @param form: the FORM'
@classmethod def assignment_onaccept(cls, form):
try: formvars = form.vars except AttributeError: return db = current.db atable = current.s3db.work_assignment if ('job_id' not in formvars): if ('id' not in formvars): return record_id = formvars.id row = db((atable.id == record_id)).select(atable....
'Ondelete callback for work assignments @param row: the Row'
@classmethod def assignment_ondelete(cls, row):
try: record_id = row.id except AttributeError: return db = current.db atable = current.s3db.work_assignment row = db((atable.id == record_id)).select(atable.deleted_fk, limitby=(0, 1)).first() if (row and row.deleted_fk): data = json.loads(row.deleted_fk) job_id =...
'Update the number of workers assigned to a job @param job_id: the job record id'
@staticmethod def update_workers_assigned(job_id):
if (not job_id): return db = current.db s3db = current.s3db jtable = s3db.work_job atable = s3db.work_assignment query = ((atable.job_id == job_id) & (atable.deleted != True)) count = atable.id.count() row = db(query).select(count, limitby=(0, 1)).first() if (not row): ...
'Page-render entry point for REST interface. @param r: the S3Request instance @param attr: controller attributes'
def apply_method(self, r, **attr):
output = {} if (r.http == 'POST'): if (r.representation == 'json'): method = r.method if (method == 'signup'): output = self.signup(r, **attr) elif (method == 'cancel'): output = self.cancel(r, **attr) else: ...
'Sign up the current user for this a job @param r: the S3Request instance @param attr: controller attributes'
def signup(self, r, **attr):
s3db = current.s3db job_id = self.record_id if (not job_id): r.error(404, current.ERROR.BAD_RECORD) atable = s3db.work_assignment auth = current.auth person_id = auth.s3_logged_in_person() if ((not person_id) or (not auth.s3_has_permission('create', atable))): auth.permission...
'Cancel a job assignment of the current user @param r: the S3Request instance @param attr: controller attributes'
def cancel(self, r, **attr):
s3db = current.s3db job_id = self.record_id if (not job_id): r.error(404, current.ERROR.BAD_RECORD) atable = s3db.work_assignment auth = current.auth person_id = auth.s3_logged_in_person() if ((not person_id) or (not auth.s3_has_permission('delete', atable))): auth.permission...
'Constructor'
def __init__(self, profile='work_job'):
super(work_JobListLayout, self).__init__(profile=profile) self.current_assignments = set()
'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):
T = current.T toolbox = self.render_toolbox(list_id, resource, record) if (not toolbox): toolbox = '' place = record['work_job.site_id'] date = record['work_job.start_date'] hours_planned = record['work_job.duration'] job_type = record['work_job.job_type_id'] header = DIV(SPAN(pl...
'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):
T = current.T title = record['work_job.name'] details = record['work_job.details'] status = record['work_job.status'] priority = record['work_job.priority'] last_modified = record['work_job.modified_on'] date_line = DIV(LABEL(T('Status'), _class='dl-inline-label'), SPAN(status, _class='dl-in...
'Render the card footer (including card action button) @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_footer(self, list_id, item_id, resource, rfields, record):
T = current.T raw = record['_row'] button = '' actionable = False status = raw['work_job.status'] if (status == 'STARTED'): button_text = T('Job has started') elif (status == 'COMPLETED'): button_text = T('Job has been completed') elif (status == 'CANCELLED...
'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):
T = current.T record_id = record['_row']['work_job.id'] has_permission = current.auth.s3_has_permission table = current.db.work_job if has_permission('update', table, record_id=record_id): edit_btn = A(ICON('edit'), _href=URL(c='work', f='job', args=[record_id, 'update.popup'], vars={'refres...
'Return safe defaults in case the model has been deactivated.'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(event_event_id=(lambda **attr: dummy('event_id')), event_type_id=(lambda **attr: dummy('event_type_id')))
'Bookmark an Event S3Method for interactive requests'
@staticmethod def event_add_bookmark(r, **attr):
event_id = r.id user = current.auth.user user_id = (user and user.id) if ((not event_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) db = current.db s3db = current.s3db ltable = s3db.event_bookmark query = ((ltable.event_id == event_id) & (ltable.user_id == user_...
'Remove a Bookmark for an Event S3Method for interactive requests'
@staticmethod def event_remove_bookmark(r, **attr):
event_id = r.id user = current.auth.user user_id = (user and user.id) if ((not event_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) s3db = current.s3db ltable = s3db.event_bookmark query = ((ltable.event_id == event_id) & (ltable.user_id == user_id)) exists = cu...
'Add a Tag to an Event S3Method for interactive requests - designed to be called as an afterTagAdded callback to tag-it.js'
@staticmethod def event_add_tag(r, **attr):
event_id = r.id if ((not event_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db s3db = current.s3db ttable = s3db.cms_tag ltable = s3db.event_tag exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, ttable.deleted...
'Remove a Tag from an Event S3Method for interactive requests - designed to be called as an afterTagRemoved callback to tag-it.js'
@staticmethod def event_remove_tag(r, **attr):
event_id = r.id if ((not event_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db s3db = current.s3db ttable = s3db.cms_tag exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, limitby=(0, 1)).first() if exists: ...
'Virtual field for event_event - returns the year of this entry used for report. Requires "start_date" to be in extra_fields @param row: the Row @ToDo: Extend this to show multiple years if open for multiple?'
@staticmethod def event_event_year(row):
try: thisdate = row['event_event.start_date'] except AttributeError: return current.messages['NONE'] if (not thisdate): return current.messages['NONE'] return thisdate.year
'When an Event is updated, check for closure'
@staticmethod def event_update_onaccept(form):
form_vars = form.vars if form_vars.closed: event = form_vars.id s3 = current.session.s3 if (s3.event == event): s3.event = None db = current.db ltable = current.s3db.event_post table = db.cms_post rows = db((ltable.event_id == event)).select(lt...
'Return safe defaults in case the model has been deactivated.'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(event_incident_id=(lambda **attr: dummy('incident_id')))
'When an Incident is instantiated, populate defaults'
@staticmethod def incident_create_onaccept(form):
form_vars = form.vars closed = form_vars.get('closed', False) incident = form_vars.get('id') if (incident and (not closed)): current.session.s3.incident = incident event = form_vars.get('event_id') if (event and (not closed)): current.session.s3.event = event s3db = current.s...
'When an Incident is updated - set correct event_id for all relevant components - check for closure'
@staticmethod def incident_update_onaccept(form):
db = current.db s3db = current.s3db form_vars = form.vars incident_id = form_vars.id closed = form_vars.get('closed') event_id = form_vars.get('event_id', False) if ((event_id is False) or (closed is None)): itable = s3db.event_incident record = db((itable.id == incident_id))...
'Add a Tag to an Incident S3Method for interactive requests - designed to be called as an afterTagAdded callback to tag-it.js'
@staticmethod def incident_add_tag(r, **attr):
incident_id = r.id if ((not incident_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db s3db = current.s3db ttable = s3db.cms_tag ltable = s3db.event_tag exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, ttable.d...
'Remove a Tag from an Incident S3Method for interactive requests - designed to be called as an afterTagRemoved callback to tag-it.js'
@staticmethod def incident_remove_tag(r, **attr):
incident_id = r.id if ((not incident_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db s3db = current.s3db ttable = s3db.cms_tag exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, limitby=(0, 1)).first() if exist...
'Bookmark an Incident S3Method for interactive requests'
@staticmethod def incident_add_bookmark(r, **attr):
incident_id = r.id user = current.auth.user user_id = (user and user.id) if ((not incident_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) db = current.db s3db = current.s3db ltable = s3db.event_bookmark query = ((ltable.incident_id == incident_id) & (ltable.user...
'Remove a Bookmark for an Incident S3Method for interactive requests'
@staticmethod def incident_remove_bookmark(r, **attr):
incident_id = r.id user = current.auth.user user_id = (user and user.id) if ((not incident_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) s3db = current.s3db ltable = s3db.event_bookmark query = ((ltable.incident_id == incident_id) & (ltable.user_id == user_id)) ...
'Return safe defaults in case the model has been deactivated.'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(event_incident_type_id=(lambda **attr: dummy('incident_type_id')))
'It is not valid to re-import a template that already has a status of Active or higher'
@staticmethod def template_onvalidate(form):
template_id = form.vars.id table = current.s3db.survey_template row = current.db((table.id == template_id)).select(table.status, limitby=(0, 1)).first() if ((row is not None) and (row.status > 1)): return False return True
'Adds a question to the template corresponding to template_id'
@staticmethod def add_question(template_id, name, code, notes, qtype, posn, metadata={}):
db = current.db s3db = current.s3db qtable = s3db.survey_question query = ((qtable.name == name) & (qtable.code == code)) record = db(query).select(qtable.id, limitby=(0, 1)).first() if record: qstn_id = record.id else: qstn_id = qtable.insert(name=name, code=code, notes=note...
'All of the standard questions will now be generated competion_qstn: who completed the assessment date_qstn: when it was completed (date) time_qstn: when it was completed (time) location_detail: json of the location question May consist of any of the following: L0, L1, L2, L3, L4, Lat, Lon for json entry a question wil...
@staticmethod def template_onaccept(form):
form_vars = form.vars if form_vars.id: template_id = form_vars.id else: return add_question = S3SurveyTemplateModel.add_question if (form_vars.competion_qstn != None): name = form_vars.competion_qstn code = 'STD-WHO' notes = 'Who completed the assessm...
'Return the question name, for locations in the gis hierarchy the localised name will be returned @todo: add the full name if it is a grid question BUT not displayed as part of a grid, e.g. "Currently known Displaced", rather than just "Displaced" see controller... template_read() for an example not in the grid'
@staticmethod def qstn_name_represent(value):
if ((value == 'L0') or (value == 'L1') or (value == 'L2') or (value == 'L3') or (value == 'L4')): return current.gis.get_location_hierarchy(value) else: return value
'Any text with the metadata that is imported will be held in single quotes, rather than double quotes and so these need to be escaped to double quotes to make it valid JSON'
@staticmethod def question_onvalidate(form):
metadata = form.vars.metadata if (metadata != None): from xml.sax.saxutils import unescape metadata = unescape(metadata, {"'": '"'}) return True
'All of the question metadata will be stored in the metadata field in a JSON format. They will then be inserted into the survey_question_metadata table pair will be a record on that table.'
@staticmethod def question_onaccept(form):
form_vars = form.vars if (form_vars.metadata is None): return if form_vars.id: record = current.s3db.survey_question[form_vars.id] else: return if (form_vars.metadata and (form_vars.metadata != '')): survey_updateMetaData(record, form_vars.type, form_vars.metadata)
'If a grid question is added to the the list then all of the grid children will need to be added as well'
@staticmethod def question_list_onaccept(form):
qstntable = current.s3db.survey_question try: form_vars = form.vars question_id = form_vars.question_id template_id = form_vars.template_id section_id = form_vars.section_id posn = form_vars.posn except AttributeError: return record = qstntable[question_id...
'If this is the formatter rules for the Background Information section then add the standard questions to the layout'
@staticmethod def formatter_onaccept(form):
s3db = current.s3db section_id = form.vars.section_id stable = s3db.survey_section section_name = stable[section_id].name if (section_name == 'Background Information'): col1 = [] ttable = s3db.survey_template template = ttable[form.vars.template_id] if (template.co...
'Ensure that the template status is set to Active'
@staticmethod def series_onaccept(form):
if form.vars.template_id: template_id = form.vars.template_id else: return table = current.s3db.survey_template current.db((table.id == template_id)).update(status=2)
'Custom Method to build a Summary of a series'
@staticmethod def seriesSummary(r, **attr):
s3db = current.s3db response = current.response s3 = response.s3 posn_offset = 11 rheader = attr.get('rheader', None) if rheader: rheader = rheader(r) output = dict(rheader=rheader) else: output = {} if ((r.env.request_method == 'POST') or ('mode' in r.vars)): ...
'Create a Name for a Chart'
@staticmethod def getChartName():
import hashlib rvars = current.request.vars end_part = ('%s_%s' % (rvars.numericQuestion, rvars.labelQuestion)) h = hashlib.sha256() h.update(end_part) encoded_part = h.hexdigest() chart_name = ('survey_series_%s_%s' % (rvars.series, encoded_part)) return chart_name
'Helper function to download a Chart'
@staticmethod def seriesChartDownload(r, **attr):
from gluon.contenttype import contenttype filename = ('%s_chart.png' % r.record.name) response = current.response response.headers['Content-Type'] = contenttype('.png') response.headers['Content-disposition'] = ('attachment; filename="%s"' % filename) chart_file = S3SurveySeriesModel.getChart...
'Allows the user to select one string question and multiple numeric questions. The string question is used to group the numeric data, with the result displayed as a bar chart. For example: The string question can be Geographic area, and the numeric questions could be people injured and families displaced. Then the resu...
@staticmethod def seriesGraph(r, **attr):
T = current.T response = current.response s3 = current.response.s3 output = {} rvars = r.vars if ('viewing' in rvars): (dummy, series_id) = rvars.viewing.split('.') elif ('series' in rvars): series_id = rvars.series else: series_id = r.id chart_file = S3Survey...
'Helper function to create/draw Chart'
@staticmethod def drawChart(output, series_id, numeric_question_list, label_question, outputFormat=None):
T = current.T get_answers = survey_getAllAnswersForQuestionInSeries gqstn = survey_getQuestionFromName(label_question, series_id) gqstn_id = gqstn['qstn_id'] ganswers = get_answers(gqstn_id, series_id) data_list = [] legend_labels = [] for numeric_question in numeric_question_list: ...
'Helper function to show a map with markers on the places where assessments are carried out'
@staticmethod def seriesMap(r, **attr):
import math T = current.T response = current.response s3 = response.s3 gis = current.gis rheader = attr.get('rheader', None) if rheader: rheader = rheader(r) output = dict(rheader=rheader) else: output = {} crud_strings = s3.crud_strings['survey_series'] v...
'function to extract the answer for the question code passed in from the list of answers. This is in a CSV format created by the XSL stylesheet or by the function saveAnswers()'
@staticmethod def extractAnswerFromAnswerList(answer_list, question_code):
start = answer_list.find(question_code) if (start == (-1)): return None start = ((start + len(question_code)) + 3) end = answer_list.find('"', start) answer = answer_list[start:end] return answer
''
@staticmethod def complete_onvalidate(form):
T = current.T form_vars = form.vars if (('series_id' not in form_vars) or (form_vars.series_id is None)): form.errors.series_id = T('Series details missing') return False if (('answer_list' not in form_vars) or (form_vars.answer_list is None)): form.errors.answer_list = T('...
'All of the answers will be stored in the answer_list in the format "code","answer" They will then be inserted into the survey_answer table each item will be a record on that table. This will also extract the default location question as defined by the template and store this in the location field'
@staticmethod def complete_onaccept(form):
complete_id = form.vars.id if complete_id: S3SurveyCompleteModel.completeOnAccept(complete_id)
'Helper function for complete_onaccept'
@staticmethod def completeOnAccept(complete_id):
db = current.db s3db = current.s3db rtable = s3db.survey_complete record = db((rtable.id == complete_id)).select(rtable.id, rtable.series_id, rtable.answer_list, limitby=(0, 1)).first() series_id = record.series_id purge_prefix = ('survey_series_%s' % series_id) S3Chart.purgeCache(purge_pref...
'Private function used to save the answer_list stored in survey_complete into answer records held in survey_answer'
@staticmethod def importAnswers(complete_id, question_list):
import csv import os strio = StringIO() strio.write(question_list) strio.seek(0) answer = [] append = answer.append reader = csv.reader(strio) for row in reader: if (row != None): row.insert(0, complete_id) append(row) from tempfile import Temporar...
'Private function used to save the locations to gis.location'
@staticmethod def importLocations(location_dict):
import csv import os last_loc_widget = None code_list = ['STD-L0', 'STD-L1', 'STD-L2', 'STD-L3', 'STD-L4'] heading_list = ['Country', 'ADM1_NAME', 'ADM2_NAME', 'ADM3_NAME', 'ADM4_NAME'] answer = [] headings = [] aappend = answer.append happend = headings.append for (position, loc...
'Rules for finding a duplicate: - Look for a record with the same name, answer_list'
@staticmethod def survey_complete_duplicate(item):
answers = item.data.get('answer_list') table = item.table query = (table.answer_list == answers) try: duplicate = current.db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.method = item.METHOD.UPDATE except: r...
'Some question types may require additional processing'
@staticmethod def answer_onaccept(form):
form_vars = form.vars if (form_vars.complete_id and form_vars.question_id): atable = current.s3db.survey_answer complete_id = form_vars.complete_id question_id = form_vars.question_id value = form_vars.value widget_obj = survey_getWidgetFromQuestion(question_id) n...
'Rules for finding a duplicate: - Look for a record with the same complete_id and question_id'
@staticmethod def survey_answer_duplicate(item):
data = item.data qid = data.get('question_id') rid = data.get('complete_id') table = item.table query = ((table.question_id == qid) & (table.complete_id == rid)) duplicate = current.db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.m...
'If the translation spreadsheet has been uploaded then it needs to be processed. The translation strings need to be extracted from the spreadsheet and inserted into the language file.'
@staticmethod def translate_onaccept(form):
if ('file' in form.vars): try: import xlrd except ImportError: print >>sys.stderr, 'ERROR: xlrd & xlwt modules are needed for importing spreadsheets' return None from gluon.languages import read_dict, write_dict T = curre...
'Entry point for REST API @param r: the S3Request @param attr: controller arguments'
def apply_method(self, r, **attr):
if (r.representation != 'xls'): r.error(415, current.ERROR.BAD_FORMAT) template_id = r.id template = r.record if (not template): r.error(405, current.ERROR.BAD_METHOD) T = current.T try: import xlwt except ImportError: r.error(501, T('xlwt not installed,...
'Entry point for REST API @param r: the S3Request @param attr: controller arguments'
def apply_method(self, r, **attr):
if (r.representation != 'xls'): r.error(415, current.error.BAD_FORMAT) series_id = self.record_id if (series_id is None): r.error(405, current.error.BAD_METHOD) s3db = current.s3db T = current.T try: import xlwt except ImportError: r.error(501, T('xlwt not ...
'Constructor'
def __init__(self):
self.startPosn = [0, 0] self.endPosn = [0, 0] self.contains = [] self.temp = [] self.widgetList = [] self.growToWidth = 0 self.growToHeight = 0
'@todo: docstring'
def growTo(self, width=None, height=None):
if (width != None): self.growToWidth = width if (height != None): self.growToHeight = height
'@todo: docstring'
def growBy(self, width=None, height=None):
if (width != None): self.growToWidth = (self.endPosn[1] + width) if (height != None): self.growToHeight = (self.endPosn[0] + height)
'@todo: docstring'
def setPosn(self, start, end):
if ((self.startPosn[0] == 0) or (start[0] < self.startPosn[0])): self.startPosn[0] = start[0] if ((self.startPosn[1] == 0) or (start[1] > self.startPosn[1])): self.startPosn[1] = start[1] if (end[0] > self.endPosn[0]): self.endPosn[0] = end[0] if (end[1] > self.endPosn[1]): ...
'@todo: docstring'
def slideHorizontally(self, colAdjust):
self.startPosn[1] += colAdjust self.endPosn[1] += colAdjust for block in self.contains: block.slideHorizontally(colAdjust)
'@todo: docstring'
def setWidgets(self, widgets):
rowList = {} colList = {} for widget in widgets: startCol = widget.startPosn[1] startRow = widget.startPosn[0] if (startCol in colList): colList[startCol] += 1 else: colList[startCol] = 1 if (startRow in rowList): rowList[startRow] ...
'@todo: docstring'
def widthShortfall(self):
return (self.growToWidth - self.endPosn[1])
'@todo: docstring'
def heightShortfall(self):
return (self.growToHeight - self.endPosn[0])
'@todo: docstring'
def addBlock(self, start, end, widgets=[]):
lb = survey_LayoutBlocks() lb.setPosn(start, end) lb.setWidgets(widgets) length = len(self.contains) temp = [] if ((length > 0) and (self.contains[(length - 1)].startPosn == start)): lb.contains.append(self.contains.pop()) for element in self.temp: if ((element.startPosn[0] <...
'@todo: docstring'
def addTempBlock(self, start, end, widgets):
lb = survey_LayoutBlocks() lb.setPosn(start, end) lb.setWidgets(widgets) self.temp.append(lb)
'@todo: docstring'
def __repr__(self):
indent = '' data = self.display(indent) return data
'@todo: docstring'
def display(self, indent):
widgets = '' for widget in self.widgetList: widgets += ('%s ' % widget.question.code) data = ('%s%s, %s grow to [%s, %s]- %s\n' % (indent, self.startPosn, self.endPosn, self.growToHeight, self.growToWidth, widgets)) indent = (indent + ' ') for lb in self.contains:...
'Method to align the widgets up with each other. This means that blocks that are adjacent to each other will be spaced to ensure that they have the same height. And blocks on top of each other will have the same width.'
def align(self):
formWidth = self.endPosn[1] self.realign(formWidth)
'Recursive method to ensure all widgets line up @todo: parameter description'
def realign(self, formWidth):
rowList = {} for block in self.contains: startRow = block.startPosn[0] endRow = block.endPosn[0] if (startRow in rowList): rowList[startRow].add(block) continue else: overlap = False for storedBlock in rowList.values(): ...
'@todo: docstring'
def alignBlock(self, block, blkCnt):
if (block.action == 'rows'): widthShortfall = block.widthShortfall() self.alignRow(block, widthShortfall) else: heightShortfall = block.heightShortfall() widthShortfall = block.widthShortfall() self.alignCol(block, heightShortfall, widthShortfall)
'Method to align the widgets laid out in a single row. The horizontal spacing will be fixed. Identify all widgets that can grow horizontally and let them do so. If their are multiple widgets that can grow then they will all grow by the same amount. Any space that is left over will be added to a margin between the widge...
def alignRow(self, block, widthShortfall):
canGrowCount = 0 for widget in block.widgetList: if widget.canGrowHorizontal(): canGrowCount += 1 if (canGrowCount > 0): growBy = (widthShortfall / canGrowCount) if (growBy > 0): for widget in block.widgetList: if widget.canGrowHorizontal(): ...
'Method to align the widgets laid out different rows @todo: parameter description'
def alignCol(self, block, heightShortfall, widthShortfall):
for widget in block.widgetList: widgetWidth = (block.startPosn[1] + widget.getMatrixSize()[1]) widthShortfall = (block.growToWidth - widgetWidth) if (widthShortfall == 0): continue if widget.canGrowHorizontal(): widget.growHorizontal(widthShortfall) el...
'Constructor'
def __init__(self):
self.matrix = {} self.lastRow = 0 self.lastCol = 0 self.fixedWidthRepr = False self.fixedWidthReprLen = 1