desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Update the illness status of the case from last monitoring entry'
@staticmethod def monitoring_onaccept(form):
formvars = form.vars try: record_id = formvars.id except AttributeError: return db = current.db s3db = current.s3db ctable = s3db.disease_case mtable = s3db.disease_case_monitoring case_id = None if ('case_id' not in formvars): query = (mtable.id == record_id)...
'Constructor'
def __init__(self):
super(disease_CaseRepresent, self).__init__(lookup='disease_case')
'Custom rows lookup @param key: the key Field @param values: the values @param fields: unused (retained for API compatibility)'
def lookup_rows(self, key, values, fields=[]):
s3db = current.s3db table = self.table ptable = s3db.pr_person dtable = s3db.disease_disease left = [ptable.on((ptable.id == table.person_id)), dtable.on((dtable.id == table.disease_id))] if (len(values) == 1): query = (key == values[0]) else: query = key.belongs(values) ...
'Represent a row @param row: the Row'
def represent_row(self, row):
try: case_number = row[self.tablename].case_number except AttributeError: return row.case_number disease_name = None try: disease = row['disease_disease'] except AttributeError: pass else: for field in ('acronym', 'short_name', 'name'): if (fie...
'@todo: docstring'
@staticmethod def exposure_onaccept(form):
formvars = form.vars try: record_id = formvars.id except AttributeError: return db = current.db s3db = current.s3db if ('case_id' not in formvars): etable = s3db.disease_exposure row = db((etable.id == record_id)).select(etable.case_id, limitby=(0, 1)).first() ...
'This will delete all the disease_stats_aggregate records and then rebuild them by triggering off a request for each disease_stats_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 disease_stats_rebuild_all_aggregates():
db = current.db ttable = db.scheduler_task rtable = db.scheduler_run wtable = db.scheduler_worker query = (((ttable.task_name == 'disease_stats_update_aggregates') & (rtable.task_id == ttable.id)) & (rtable.status == 'RUNNING')) rows = db(query).select(rtable.id, rtable.task_id, rtable.worker_na...
'This will calculate the disease_stats_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 onaccept/onapprove. @ToDo: onapprove/onaccept wrapper function. This will get the raw data from disease_stats_data and generate a...
@staticmethod def disease_stats_update_aggregates(records=None, all=False):
if (not records): return if isinstance(records, basestring): from_json = True from dateutil.parser import parse records = json.loads(records) elif isinstance(records[0]['date'], (datetime.date, datetime.datetime)): from_json = False else: from_json = True ...
'Calculates the disease_stats_aggregate for a specific parameter at a specific location over the range of dates. @param location_id: location to aggregate at @param children: locations to aggregate from @param parameter_id: arameter to aggregate @param dates: dates to aggregate for (as JSON string)'
@staticmethod def disease_stats_update_location_aggregates(location_id, children, parameter_id, dates):
db = current.db atable = current.s3db.disease_stats_aggregate ifield = atable.id lfield = atable.location_id pfield = atable.parameter_id dfield = atable.date children = json.loads(children) query = (((pfield == parameter_id) & (atable.deleted != True)) & lfield.belongs(children)) ro...
'Generate an identifier for a new form'
@staticmethod def generate_identifier():
db = current.db table = db.cap_alert r = db().select(table.id, limitby=(0, 1), orderby=(~ table.id)).first() _time = datetime.datetime.strftime(datetime.datetime.utcnow(), '%Y.%m.%d') if r: next_id = (int(r.id) + 1) else: next_id = 1 settings = current.deployment_settings ...
'Generate a sender for a new form'
@staticmethod def generate_sender():
try: user_email = current.auth.user.email except AttributeError: return '' return ('%s' % user_email)
'Generate a source for CAP alert'
@staticmethod def generate_source():
return ('%s@%s' % (current.xml.domain, current.deployment_settings.get_base_public_url()))
'Default Sender name for the alert Sendername is the name of the organisation if user is associated else None'
@staticmethod def cap_sendername():
db = current.db utable = db.auth_user otable = current.s3db.org_organisation query = (((utable.id == current.auth.user.id) & (utable.organisation_id == otable.id)) & (otable.deleted != True)) row = db(query).select(otable.name, limitby=(0, 1)).first() if row: return row.name return c...
'Represent an alert template concisely'
@staticmethod def cap_template_represent(id, row=None):
if row: id = row.id elif (not id): return current.messages['NONE'] else: db = current.db table = db.cap_alert row = db((table.id == id)).select(table.is_template, table.template_title, limitby=(0, 1)).first() try: if row.is_template: return row...
'Auto-approve Templates'
@staticmethod def cap_alert_create_onaccept(form):
db = current.db form_vars = form.vars table = current.s3db.cap_alert if form_vars.get('is_template'): user = current.auth.user if user: db((table.id == form_vars.id)).update(approved_by=user.id)
'Custom Form Validation: multi-field level'
@staticmethod def cap_alert_onvalidation(form):
form_vars_get = form.vars.get if (not form_vars_get('is_template')): if (not form_vars_get('scope')): form.errors['scope'] = current.T("'Scope' field is mandatory for actual alerts!") if (form_vars_get('scope') == 'Private'): request = current.request ...
'Custom Form Validation'
@staticmethod def cap_warning_priority_onvalidation(form):
form_vars = form.vars table = current.s3db.cap_warning_priority query = (((((table.event_type_id == form_vars.event_type_id) & (table.urgency == form_vars.urgency)) & (table.severity == form_vars.severity)) & (table.certainty == form_vars.certainty)) & (table.deleted != True)) row = current.db(query).se...
'After DB I/O'
@staticmethod def cap_info_onaccept(form):
if ('vars' in form): form_vars = form.vars elif ('id' in form): form_vars = form elif hasattr(form, 'vars'): form_vars = form.vars else: form_vars = form info_id = form_vars.id if (not info_id): return db = current.db atable = db.cap_alert itab...
'Custom Form Validation: used for import from CSV'
@staticmethod def cap_info_onvalidation(form):
form_record = form.record if (form_record and (form_record.is_template == False)): form_vars = form.vars if (not form_vars.get('urgency')): form.errors['urgency'] = current.T("'Urgency' field is mandatory") if (not form_vars.get('severity')): form.errors[...
'Update the approved_on field when alert gets approved'
@staticmethod def cap_alert_approve(record=None):
if (not record): return alert_id = record['id'] if alert_id: db = current.db approved_on = record['approved_on'] table = db.cap_alert query = (table.id == alert_id) utcnow = current.request.utcnow db(query).update(approved_on=utcnow, sent=utcnow) ...
'Link alert_id to cap_info_parameter table'
@staticmethod def cap_info_parameter_onaccept(form):
form_vars = form.vars info_id = form_vars.get('info_id', None) if (not info_id): return db = current.db itable = db.cap_info irow = db((itable.id == info_id)).select(itable.alert_id, limitby=(0, 1)).first() alert_id = irow.alert_id if alert_id: db((db.cap_info_parameter.i...
'Custom Form Validation'
@staticmethod def cap_info_parameter_onvalidation(form):
form_vars = form.vars parameter_name = form_vars.get('name') parameter_value = form_vars.get('value') if ((parameter_name and (not parameter_value)) or (parameter_value and (not parameter_name))): form.errors['name'] = current.T('Name-Value Pair is incomplete.')
'Link alert_id for CAP XML import'
@staticmethod def cap_area_onaccept(form):
form_vars = form.vars if form_vars.get('event_type_id'): return db = current.db alert_id = form_vars.get('alert_id', None) if (not alert_id): info_id = form_vars.get('info_id', None) if info_id: itable = db.cap_info item = db((itable.id == info_id)).se...
'- Link alert_id for non-template area - for external alerts (from import feed or rss), make sure the locations are only imported if we set polygons to be imported'
@staticmethod def cap_area_location_onaccept(form):
form_vars = form.vars area_id = form_vars.get('area_id', None) if (not area_id): return db = current.db alert_id = form_vars.get('alert_id', None) if (not alert_id): atable = db.cap_area row = db((atable.id == area_id)).select(atable.alert_id, limitby=(0, 1)).first() ...
'Link location if area_tag has SAME code Link alert_id for non-template area'
@staticmethod def cap_area_tag_onaccept(form):
form_vars = form.vars area_id = form_vars.get('area_id', None) if (not area_id): return db = current.db atable = db.cap_area arow = db((atable.id == area_id)).select(atable.alert_id, limitby=(0, 1)).first() alert_id = arow.alert_id if alert_id: db((db.cap_area_tag.id == f...
'Link alert_id for CAP XML import'
@staticmethod def cap_resource_onaccept(form):
form_vars = form.vars info_id = form_vars.get('info_id', None) if info_id: db = current.db itable = db.cap_info item = db((itable.id == info_id)).select(itable.alert_id, limitby=(0, 1)).first() alert_id = item.alert_id if alert_id: db((db.cap_resource.id =...
'For Image Upload NB not using document_onvalidation here because we are extracting other values from the file like size and mime type'
@staticmethod def cap_resource_onvalidation(form):
form_vars = form.vars image = form_vars.image if (image is None): encoded_file = form_vars.get('imagecrop-data', None) if encoded_file: import base64 import uuid import cStringIO (metadata, encoded_file) = encoded_file.split(',') (f...
'Apply method. @param r: the S3Request @param attr: controller options for this request'
@staticmethod def apply_method(r, **attr):
authorised = current.auth.s3_has_permission('create', 'cap_alert') if (not authorised): r.unauthorised() if (r.representation == 'html'): T = current.T response = current.response title = T('Import from Feed URL') fields = [Field('url', label=T('URL'), requir...
'Apply method. @param r: the S3Request @param attr: controller options for this request'
def apply_method(self, r, **attr):
if (not r.record): r.error(404, current.ERROR.BAD_RECORD) alert_id = r.id authorised = current.auth.s3_has_permission('update', 'cap_alert', record_id=alert_id) if (not authorised): r.unauthorised() T = current.T s3db = current.s3db response = current.response itable = s3...
'Apply method @param r: the S3Request @param attr: controller options for this request'
def apply_method(self, r, **attr):
output = {} if (r.http == 'POST'): if (r.method == 'clone'): output = clone(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) else: r.error(405, current.ERROR.BAD_METHOD) return output
'Custom lookup method for Area(CAP) rows.Parameters key and fields are not used, but are kept for API compatibility reasons. @param values: the cap_area IDs'
def lookup_rows(self, key, values, fields=None):
db = current.db s3db = current.s3db artable = s3db.cap_area count = len(values) if (count == 1): query = (artable.id == values[0]) else: query = artable.id.belongs(values) fields = [artable.id, artable.name] if self.translate: ltable = s3db.cap_area_name f...
'Represent a single Row @param row: the cap_area Row'
def represent_row(self, row):
if self.translate: name = (row['cap_area_name.name_l10n'] or row['cap_area.name']) else: name = row['cap_area.name'] if (not name): return self.default return s3_str(name)
'Widget builder @param f: the calling function'
def __call__(self, f):
def widget(r, **attr): components = f(r, **attr) components = [c for c in components if (c is not None)] title = self.title if title: label = self.label value = self.value T = current.T if (label and value): title_ = DIV...
'Component builder @param label: name for the component label @param value: value for the component @param represent: representation used for the value @param uppercase: whether to display label in upper case @param strong: whether to display with strong color @param hide_empty: whether to hide empty records @param hea...
@staticmethod def component(label, value, represent=None, uppercase=False, strong=False, hide_empty=True, headline=False, resource_segment=False):
if ((not value) and hide_empty): return None else: if isinstance(value, list): nvalue = [] for value_ in value: if value_: if (resource_segment and represent): nvalue.append(represent(value_)) ...
'Return safe defaults for model globals, this will be called instead of model() in case the model has been deactivated in deployment_settings. You don\'t need this function in case your model is mandatory anyway.'
@staticmethod def defaults():
return dict(skeleton_example_id=S3ReusableField('skeleton_example_id', 'integer', readable=False, writable=False))
'Form validation'
@staticmethod def skeleton_example_onvalidation(form):
db = current.db table = db.skeleton_example query = (table.id == form.vars.id) record = db(query).select(table.name, limitby=(0, 1)).first() return
'FK representation'
@staticmethod def fire_station_represent(id, row=None):
if row: return row.name elif (not id): return current.messages['NONE'] db = current.db table = db.fire_station r = db((table.id == id)).select(table.name, limitby=(0, 1)).first() try: return r.name except: return current.messages.UNKNOWN_OPT
'Represent a Shift by Start and End times'
@staticmethod def fire_shift_represent(id, row=None):
if row: pass elif (not id): return current.messages['NONE'] else: db = current.db table = db.fire_shift row = db((table.id == id)).select(table.start_time, table.end_time, limitby=(0, 1)).first() try: return ('%s - %s' % (row.start_time, row.end_time...
'Return a query for hrm_human_resource filtering for entries which are linked to a current shift'
@staticmethod def fire_staff_on_duty(station_id=None):
db = current.db staff = db.hrm_human_resource roster = db.fire_shift_staff query = ((staff.id == roster.human_resource_id) & (roster.deleted != True)) if (station_id is not None): query &= (roster.station_id == station_id) return query
'Custom method to provide a report on Vehicle Deployment Times - this is one of the main tools currently used to manage an Incident'
@staticmethod def vehicle_report(r, **attr):
rheader = attr.get('rheader', None) if rheader: rheader = rheader(r) station_id = r.id if station_id: s3db = current.s3db dtable = s3db.irs_ireport_vehicle vtable = s3db.vehicle_vehicle stable = s3db.fire_station_vehicle query = (((stable.station_id == sta...
'JSON search method for S3AutocompleteWidget @param r: the S3Request @param attr: request attributes'
@staticmethod def pe_search_ac(r, **attr):
get_vars = current.request.get_vars value = (get_vars.term or get_vars.value or get_vars.q or None) if (not value): output = current.xml.json_message(False, 400, 'No search term specified') raise HTTP(400, body=output) value = s3_unicode(value).lower() limit = int((get_vars....
'Represent an entity role @param role_id: the pr_role record ID'
@staticmethod def pr_role_represent(role_id):
db = current.db table = db.pr_role role = db((table.id == role_id)).select(table.role, table.pe_id, limitby=(0, 1)).first() try: entity = current.s3db.pr_pentity_represent(role.pe_id) return ('%s: %s' % (entity, role.role)) except: return current.messages.UNKNOWN_OPT
'Clear descendant paths if role type has changed @param form: the CRUD form'
@staticmethod def pr_role_onvalidation(form):
form_vars = form.vars if (not form_vars): return if ('role_type' in form_vars): role_id = form.record_id if (not role_id): return role_type = form_vars.role_type db = current.db rtable = db.pr_role role = db((rtable.id == role_id)).select(r...
'Update organisation affiliations for org_site instances.'
@staticmethod def pr_pentity_onaccept(form):
db = current.db s3db = current.s3db ptable = s3db.pr_pentity pe_id = form.vars.pe_id pe = db((ptable.pe_id == pe_id)).select(ptable.instance_type, limitby=(0, 1)).first() if pe: itable = s3db.table(pe.instance_type, None) if (itable and ('site_id' in itable.fields) and ('organisa...
'Remove duplicate affiliations and clear descendant paths (to trigger lazy rebuild) @param form: the CRUD form'
@staticmethod def pr_affiliation_onaccept(form):
form_vars = form.vars role_id = form_vars['role_id'] pe_id = form_vars['pe_id'] record_id = form_vars['id'] if (role_id and pe_id and record_id): db = current.db atable = db.pr_affiliation query = (((atable.id != record_id) & (atable.role_id == role_id)) & (atable.pe_id == pe...
'Clear descendant paths, also called indirectly via ondelete-CASCADE when a role gets deleted. @param row: the deleted Row'
@staticmethod def pr_affiliation_ondelete(row):
if (row and row.id): db = current.db atable = db.pr_affiliation query = (atable.id == row.id) record = db(query).select(atable.deleted_fk, limitby=(0, 1)).first() else: return if (record and record.deleted_fk): data = json.loads(record.deleted_fk) pe_i...
'Virtual Field to display the Age of a person @param row: a Row containing the person record'
@classmethod def pr_person_age(cls, row):
age = cls.pr_age(row) if ((age is None) or (age < 0)): return current.messages['NONE'] else: return age
'Virtual Field to allow Reporting by Age Group @param row: a Row containing the person record @ToDo: This formula might need to be different for different Orgs or Usecases @ToDo: If we need to be able to Filter based on these then we should create a \'Named Range\' widget for an S3DateTimeFilter field'
@classmethod def pr_person_age_group(cls, row):
age = cls.pr_age(row) if ((age is None) or (age < 0)): return current.messages['NONE'] else: return current.deployment_settings.get_pr_age_group(age)
'Compute the age of a person @param row: a Row containing the person record @return: age in years (integer)'
@staticmethod def pr_age(row):
if hasattr(row, 'pr_person'): row = row.pr_person if hasattr(row, 'date_of_birth'): dob = row.date_of_birth elif hasattr(row, 'id'): table = current.s3db.pr_person person = current.db((table.id == row.id)).select(table.date_of_birth, limitby=(0, 1)).first() dob = (per...
'Onaccept callback Update any User record associated with this person'
@staticmethod def pr_person_onaccept(form):
db = current.db s3db = current.s3db form_vars = form.vars person_id = form_vars.id ptable = s3db.pr_person ltable = s3db.pr_person_user utable = current.auth.settings.table_user query = (((ptable.id == person_id) & (ltable.pe_id == ptable.pe_id)) & (utable.id == ltable.user_id)) user...
'Import item deduplication'
@staticmethod def person_duplicate(item):
db = current.db data = item.data pe_label = data.get('pe_label') if pe_label: table = item.table query = (table.pe_label == pe_label) duplicate = db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.method = ...
'JSON search method for S3PersonAutocompleteWidget and S3AddPersonWidget2 - full name search'
@staticmethod def pr_search_ac(r, **attr):
response = current.response resource = r.resource resource.add_filter(response.s3.filter) _vars = current.request.get_vars value = (_vars.term or _vars.value or _vars.q or None) if (not value): output = current.xml.json_message(False, 400, 'No value provided!') raise HTTP(4...
'JSON lookup method for S3AddPersonWidget2'
@staticmethod def pr_person_lookup(r, **attr):
id = r.id if (not id): output = current.xml.json_message(False, 400, 'No id provided!') raise HTTP(400, body=output) db = current.db s3db = current.s3db settings = current.deployment_settings request_dob = settings.get_pr_request_dob() request_gender = settings.get_pr_r...
'JSON lookup method for S3AddPersonWidget2'
@staticmethod def pr_person_check_duplicates(r, **attr):
settings = current.deployment_settings post_vars = current.request.post_vars dob = post_vars.get('dob', None) if dob: (dob, error) = s3_validate(current.s3db.pr_person, 'date_of_birth', dob) if (not error): dob = dob.isoformat() else: dob = None gender...
'Verify that a person isn\'t added to a group more than once @param form: the FORM'
@staticmethod def group_membership_onvalidation(form):
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 person_id = form_vars.get('person_id') group_id = form_vars.get('group_id') db = current.db s3db = current.s3d...
'Remove any duplicate memberships and update affiliations @param form: the FORM'
@staticmethod def group_membership_onaccept(form):
if hasattr(form, 'vars'): record_id = form.vars.id elif (isinstance(form, Row) and ('id' in form)): record_id = form.id else: return if (not record_id): return db = current.db settings = current.deployment_settings table = db.pr_group_membership gtable = d...
'Set the realm entity of Group Membership records to the same as that of the person'
@staticmethod def group_membership_realm_entity(table, row):
db = current.db s3db = current.s3db gtable = s3db.pr_group group = db((gtable.id == row.group_id)).select(gtable.realm_entity, limitby=(0, 1)).first() try: return group.realm_entity except: return None
'Updates the Base Location to be the same as the Address If the base location hasn\'t yet been set or if this is specifically requested'
@staticmethod def pr_address_onaccept(form):
form_vars = form.vars location_id = form_vars.get('location_id') if (not location_id): return try: record_id = form_vars['id'] except: return db = current.db s3db = current.s3db atable = db.pr_address pe_id = db((atable.id == record_id)).select(atable.pe_id, l...
'Contact form validation'
@staticmethod def pr_contact_onvalidation(form):
form_vars = form.vars contact_method = form_vars.contact_method if ((not contact_method) and ('id' in form_vars)): ctable = current.s3db.pr_contact record = current.db((ctable._id == form_vars.id)).select(ctable.contact_method, limitby=(0, 1)).first() if record: contact_m...
'Representation'
@staticmethod def pr_image_represent(image, size=None):
if (not image): return current.messages['NONE'] url_full = URL(c='default', f='download', args=image) if (size is None): size = (None, 60) image = pr_image_library_represent(image, size=size) url_small = URL(c='default', f='download', args=image) return DIV(A(IMG(_src=url_small, ...
'If this is the profile image then remove this flag from all others for this person.'
@staticmethod def pr_image_onaccept(form):
form_vars = form.vars id = form_vars.id profile = form_vars.profile url = form_vars.url newfilename = form_vars.image_newfilename if (profile == 'False'): profile = False if newfilename: _image = form.request_vars.image pr_image_modify(_image.file, newfilename, _image...
'Image form validation'
@staticmethod def pr_image_onvalidation(form):
form_vars = form.vars image = form_vars.image url = form_vars.url if (not hasattr(image, 'file')): id = current.request.post_vars.id if id: db = current.db table = db.pr_image record = db((table.id == id)).select(table.image, limitby=(0, 1)).first() ...
'If a PR Image is deleted, delete the thumbnails too'
@staticmethod def pr_image_ondelete(row):
db = current.db table = db.pr_image row = db((table.id == row.id)).select(table.image, limitby=(0, 1)).first() current.s3db.pr_image_delete_all(row.image)
'Presence record validation'
@staticmethod def presence_onvalidation(form):
db = current.db table = db.pr_presence s3db = current.s3db popts = s3db.pr_presence_opts shelter_table = s3db.cr_shelter location = form.vars.location_id shelter = form.vars.shelter_id if (shelter and (shelter_table is not None)): set = db((shelter_table.id == shelter)) r...
'Update the presence log of a person entity - mandatory to be called as onaccept routine at any modification of pr_presence records'
@staticmethod def presence_onaccept(form):
db = current.db table = db.pr_presence popts = current.s3db.pr_presence_opts if isinstance(form, (int, long, str)): id = form elif hasattr(form, 'vars'): id = form.vars.id else: id = form.id presence = db((table.id == id)).select(table.ALL, limitby=(0, 1)).first() ...
'Update missing status for person'
@staticmethod def note_onaccept(form):
db = current.db s3db = current.s3db pe_table = s3db.pr_pentity ntable = db.pr_note ptable = s3db.pr_person if isinstance(form, (int, long, str)): _id = form elif hasattr(form, 'vars'): _id = form.vars.id else: _id = form.id note = ntable[_id] if (not note)...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
return {}
'Used by s3_avatar_represent()'
@staticmethod def pr_image_size(image_name, size):
db = current.db table = db.pr_image_library image = db((table.new_name == image_name)).select(table.actual_height, table.actual_width, limitby=(0, 1)).first() if image: return (image.actual_width, image.actual_height) else: return size
'Method to delete all the images that belong to the original file.'
@staticmethod def pr_image_delete_all(original_image_name):
if current.deployment_settings.get_security_archive_not_delete(): return db = current.db table = db.pr_image_library set = db((table.original_name == original_image_name)) set.delete_uploaded_files() set.delete()
'Ensure that JSON can be loaded by json.loads()'
@staticmethod def pr_filter_onvalidation(form):
query = form.vars.get('query', None) if query: query = query.replace("'", '"') try: json.loads(query) except ValueError as e: form.errors.query = ('%s: %s' % (current.T('Query invalid'), e)) form.vars.query = query
'Constructor @param show_link: whether to add a URL to representations @param multiple: web2py list-type (all values will be lists) @param translate: translate all representations (using T)'
def __init__(self, show_link=False, multiple=False, translate=True):
self.fields = ['pe_id', 'role'] super(pr_RoleRepresent, self).__init__(lookup='pr_role', fields=self.fields, show_link=show_link, translate=translate, multiple=multiple)
'Represent a Row @param row: the Row'
def represent_row(self, row):
entity = current.s3db.pr_pentity_represent(row.pe_id) return ('%s: %s' % (entity, row.role))
'Lookup all rows referenced by values. @param key: the key Field @param values: the values @param fields: the fields to retrieve'
def lookup_rows(self, key, values, fields=[]):
if (not fields): table = self.table fields = [table[f] for f in self.fields] rows = self._lookup_rows(key, values, fields=fields) pe_ids = [row.pe_id for row in rows] current.s3db.pr_pentity_represent.bulk(pe_ids) return rows
'Constructor @param show_label: show the ID tag label for persons @param default_label: the default for the ID tag label @param show_type: show the instance_type @param multiple: assume a value list by default'
def __init__(self, show_label=True, default_label='[No ID Tag]', show_type=True, multiple=False, show_link=False, linkto=None):
self.show_label = show_label self.default_label = default_label self.show_type = show_type super(pr_PersonEntityRepresent, self).__init__(lookup='pr_pentity', key='pe_id', multiple=multiple, show_link=show_link, linkto=linkto)
'Represent a (key, value) as hypertext link. - Typically, k is a foreign key value, and v the representation of the referenced record, and the link shall open a read view of the referenced record. - The linkto-parameter expects a URL (as string) with "[id]" as placeholder for the key. @param k: the key @param v: the re...
def link(self, k, v, row=None):
if (not k): return v if (self.linkto == URL(c='pr', f='pentity', args=['[id]'])): k = s3_unicode(k) db = current.db petable = db.pr_pentity pe_record = db((petable._id == k)).select(petable.instance_type, limitby=(0, 1)).first() if (not pe_record): ret...
'Custom rows lookup function @param key: the key field @param values: the values to look up @param fields: unused (retained for API compatibility)'
def lookup_rows(self, key, values, fields=[]):
db = current.db s3db = current.s3db instance_fields = {'pr_person': ['first_name', 'middle_name', 'last_name']} etable = s3db.pr_pentity rows = db(key.belongs(values)).select(key, etable.pe_label, etable.instance_type) self.queries += 1 keyname = key.name types = {} for row in rows: ...
'Represent a row @param row: the Row'
def represent_row(self, row):
pentity = row.pr_pentity instance_type = pentity.instance_type show_label = self.show_label if show_label: label = (pentity.pe_label if pentity.pe_label else self.default_label) else: label = '' item = object.__getattribute__(row, instance_type) if (instance_type == 'pr_perso...
'Constructor'
def __init__(self):
super(pr_GroupRepresent, self).__init__('pr_group', fields=['name']) self.show_org_groups = current.deployment_settings.get_org_group_team_represent() self.org_groups = {}
'Custom rows lookup @param key: the key Field @param values: the values @param fields: unused (retained for API compatibility)'
def lookup_rows(self, key, values, fields=[]):
db = current.db table = self.table count = len(values) if (count == 1): query = (key == values[0]) else: query = key.belongs(values) rows = db(query).select(table.id, table.name, limitby=(0, count)) self.queries += 1 if self.show_org_groups: s3db = current.s3db ...
'Represent a row @param row: the Row'
def represent_row(self, row):
representation = ('%s' % row.name) if self.show_org_groups: names = self.org_groups.get(row.id) if names: representation = ('%s (%s)' % (representation, ', '.join(names))) return representation
'Show a Contact with appropriate hyperlinks if Facebook or Twitter @param: see super'
def __init__(self, show_link=True):
super(pr_ContactRepresent, self).__init__(lookup='pr_contact', fields=['contact_method', 'value'], show_link=show_link)
'Represent a (key, value) as hypertext link. - Typically, k is a foreign key value, and v the representation of the referenced record, and the link shall open a read view of the referenced record. - The linkto-parameter expects a URL (as string) with "[id]" as placeholder for the key. @param k: the key @param v: the re...
def link(self, k, v, row=None):
if (not k): return v if v.startswith('http'): return A(v, _href=v) contact_method = row.contact_method if (contact_method == 'TWITTER'): url = ('http://twitter.com/%s' % v) return A(v, _href=url) elif (contact_method == 'FACEBOOK'): url = ('http://%s' % v) ...
'Represent a row @param row: the Row'
def represent_row(self, row):
value = row['pr_contact.value'] if (not value): return self.default return s3_str(value)
'Entry point for REST API @param r: the S3Request @param attr: controller parameters for the request'
def apply_method(self, r, **attr):
if (r.http != 'GET'): r.error(405, current.ERROR.BAD_METHOD) record = r.record if (not record): r.error(404, current.ERROR.BAD_RECORD) allow_create = current.auth.s3_has_permission('update', 'pr_person', record_id=record.id) widget_id = 'pr-contacts' pe_id = record.pe_id cont...
'Action buttons for contact rows'
@staticmethod def action_buttons(table, record_id):
T = current.T has_permission = current.auth.s3_has_permission if has_permission('update', table, record_id=record_id): edit_btn = A(T('Edit'), _class='edit-btn action-btn fright') else: edit_btn = SPAN() if has_permission('delete', table, record_id=record_id): delete_bt...
'Contact Information Subform @param r: the S3Request @param pe_id: the pe_id @param allow_create: allow adding of new contacts @param method: the request method ("contacts", "private_contacts" or "public_contacts")'
def contacts(self, r, pe_id, allow_create=False, method='contacts'):
T = current.T s3db = current.s3db tablename = 'pr_contact' resource = s3db.resource(tablename, filter=(FS('pe_id') == pe_id)) if (method != 'contacts'): if (method == 'private_contacts'): access = (FS('access') == 1) else: access = (FS('access') == 2) ...
'Emergency Contact Information SubForm @param pe_id: the pe_id @param allow_create: allow adding of new contacts @todo: make inline-editable this one too'
def emergency(self, pe_id, allow_create=False):
if (not current.deployment_settings.get_pr_show_emergency_contacts()): return None T = current.T s3db = current.s3db resource = s3db.resource('pr_contact_emergency', filter=(FS('pe_id') == pe_id)) table = resource.table fields = [f for f in ('name', 'relationship', 'address', 'phone', 'c...
'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):
header = DIV(ICON('icon'), SPAN(record['pr_contact_emergency.name'], _class='card-title'), _class='card-header') toolbox = self.render_toolbox(list_id, resource, record) if toolbox: header.append(toolbox) return header
'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):
body = DIV(_class='media') append = body.append fields = ('pr_contact_emergency.relationship', 'pr_contact_emergency.phone', 'pr_contact_emergency.address', 'pr_contact_emergency.comments') render_column = self.render_column for rfield in rfields: if (rfield.colname in fields): c...
'Render a column of the record @param list_id: the HTML ID of the list @param rfield: the S3ResourceField @param record: the record as dict'
def render_column(self, item_id, rfield, record):
value = record[rfield.colname] if value: if (rfield.ftype == 'text'): _class = 'card_manylines' else: _class = 'card_1_line' return P(ICON(self.ICONS.get(rfield.fname, 'icon')), SPAN(value), _class=_class) else: return None
'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)] toolbox = DIV(_class='edit-bar fright') update_url = URL(c='pr', f='contact_emergency', args=[record_id, 'update.popup'], vars={'refresh': list_id, 'record': record_id, 'profile': self.profile}) has_pe...
'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):
raw = record._row fullname = s3_format_fullname(raw['pr_person.first_name'], raw['pr_person.middle_name'], raw['pr_person.last_name']) header = DIV(ICON('icon'), SPAN(fullname, _class='card-title'), _class='card-header') toolbox = self.render_toolbox(list_id, resource, record) if toolbox: he...
'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):
body = DIV(_class='media') append = body.append fields = ('pr_person_details.nationality', 'pr_person.date_of_birth', 'pr_person.gender', 'pr_physical_description.blood_type') render_column = self.render_column for rfield in rfields: if (rfield.colname in fields): column = render...
'Render a column of the record @param list_id: the HTML ID of the list @param rfield: the S3ResourceField @param record: the record as dict'
def render_column(self, item_id, rfield, record):
value = record._row[rfield.colname] if value: if (rfield.ftype == 'text'): _class = 'card_manylines' else: _class = 'card_1_line' if (rfield.colname == 'pr_person.gender'): gender = record._row[rfield.colname] if (gender == 2): ...
'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):
record_id = record[str(resource._id)] toolbox = DIV(_class='edit-bar fright') if current.auth.s3_has_permission('update', resource.table, record_id=record_id): controller = current.request.controller if (controller not in ('deploy', 'hrm', 'member', 'vol')): controller = 'pr' ...
'Constructor @param search_fields: tuple|list of field selectors'
def __init__(self, search_fields=None):
if (search_fields is None): self.search_fields = ('first_name', 'middle_name', 'last_name') else: self.search_fields = search_fields
'Entry point for REST controller @param r: the S3Request @param attr: controller parameters for the request'
def apply_method(self, r, **attr):
response = current.response settings = current.deployment_settings resource = r.resource resource.add_filter(response.s3.filter) get_vars = r.get_vars value = (get_vars.term or get_vars.value or get_vars.q or None) if (not value): r.error(400, 'No value provided!') value = ...
'FK representation'
@staticmethod def delphi_group_represent(id, row=None):
if (not row): db = current.db table = db.delphi_group row = db((table.id == id)).select(table.id, table.name, limitby=(0, 1)).first() elif (not id): return current.messages['NONE'] try: return A(row.name, _href=URL(c='delphi', f='group', args=[row.id])) except: ...
'FK representation @ToDo: Migrate to S3Represent'
@staticmethod def delphi_problem_represent(id, row=None, show_link=False, solutions=True):
if (not row): db = current.db table = db.delphi_problem row = db((table.id == id)).select(table.id, table.name, limitby=(0, 1)).first() elif (not id): return current.messages['NONE'] try: if show_link: if solutions: url = URL(c='delphi', f=...
'Used by Discuss() (& summary())'
def user(self):
return current.s3db.auth_user[self.user_id]
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(dc_template_id=(lambda **attr: dummy('template_id')))