desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
return {}
'Onaccept routine for case event types: - only one type can be the default @param form: the FORM'
@staticmethod def case_event_type_onaccept(form):
form_vars = form.vars try: record_id = form_vars.id except AttributeError: record_id = None if (not record_id): return if (('is_default' in form_vars) and form_vars.is_default): table = current.s3db.dvr_case_event_type db = current.db db((table.id != r...
'Actions after creation of a case event: - update last_seen_on in the corresponding cases - close appointments if configured to do so @param form: the FORM'
@staticmethod def case_event_create_onaccept(form):
formvars = form.vars try: record_id = formvars.id except AttributeError: record_id = None if (not record_id): return db = current.db s3db = current.s3db close_appointments = current.deployment_settings.get_dvr_case_events_close_appointments() case_id = formvars.ge...
'Actions after deleting a case event: - update last_seen_on in the corresponding cases @param row: the deleted Row'
@staticmethod def case_event_ondelete(row):
table = current.s3db.dvr_case_event row = current.db((table.id == row.id)).select(table.deleted_fk, limitby=(0, 1)).first() if (row and row.deleted_fk): try: deleted_fk = json.loads(row.deleted_fk) except (ValueError, TypeError): person_id = None else: ...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
return {}
'File representation'
@staticmethod def report_represent(value):
if value: try: filename = current.db.dvr_site_activity.report.retrieve(value)[0] except IOError: return current.T('File not found') else: return A(filename, _href=URL(c='default', f='download', args=[value])) else: return current.messages...
'Constructor @param show_link: show representation as clickable link'
def __init__(self, show_link=False):
super(dvr_ActivityRepresent, self).__init__(lookup='dvr_activity', show_link=show_link)
'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=[]):
table = current.s3db.dvr_activity count = len(values) if (count == 1): query = (key == values[0]) else: query = key.belongs(values) rows = current.db(query).select(table.id, table.name, table.start_date, table.end_date, table.service_id, table.facilitator, limitby=(0, count)) sel...
'Represent a row @param row: the Row'
def represent_row(self, row):
if row.name: title = row.name else: table = current.s3db.dvr_activity title = table.service_id.represent(row.service_id) template = '%(title)s' data = {'title': title, 'start': '-', 'end': '-'} start_date = row.start_date end_date = row.end_date if (start_date or end_...
'Represent a (key, value) as hypertext link @param k: the key (dvr_activity.id) @param v: the representation of the key @param row: the row with this key (unused here)'
def link(self, k, v, row=None):
url = URL(c='dvr', f='activity', args=[k], extension='') return A(v, _href=url)
'Constructor @param show_link: show representation as clickable link @param fmt: string format template for person record'
def __init__(self, show_link=False, fmt=None):
super(dvr_CaseActivityRepresent, self).__init__(lookup='dvr_case_activity', show_link=show_link) if fmt: self.fmt = fmt else: self.fmt = '%(first_name)s %(last_name)s'
'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=[]):
table = self.table count = len(values) if (count == 1): query = (key == values[0]) else: query = key.belongs(values) ptable = current.s3db.pr_person left = ptable.on((ptable.id == table.person_id)) rows = current.db(query).select(table.id, ptable.id, ptable.pe_label, ptable.f...
'Represent a row @param row: the Row'
def represent_row(self, row):
beneficiary = row.pr_person repr_str = (self.fmt % beneficiary) return repr_str
'Represent a (key, value) as hypertext link @param k: the key (dvr_case_activity.id) @param v: the representation of the key @param row: the row with this key'
def link(self, k, v, row=None):
beneficiary = row.pr_person url = URL(c='dvr', f='person', args=[beneficiary.id, 'case_activity', k], extension='') return A(v, _href=url)
'Main entry point for REST interface. @param r: the S3Request instance @param attr: controller parameters'
def apply_method(self, r, **attr):
permitted = self._permitted('update') if (not permitted): r.unauthorised() if (r.representation in ('html', 'iframe')): if (r.http in ('GET', 'POST')): output = self.bulk_update_status(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) else: r...
'Method to bulk-update status of allowance payments @param r: the S3Request instance @param attr: controller parameters'
def bulk_update_status(self, r, **attr):
T = current.T s3db = current.s3db settings = current.deployment_settings response = current.response output = {'title': T('Update Allowance Status')} status_opts = dict(s3db.dvr_allowance_status_opts) del status_opts[2] formfields = [s3_date('from_date', label=T('Planned From'),...
'Update form validation @param form: the FORM'
def validate(self, form):
T = current.T formvars = form.vars errors = form.errors if (str(formvars.current_status) == '2'): errors.current_status = T('Bulk update from this status not allowed') if (str(formvars.new_status) == '2'): errors.new_status = T('Bulk update to this statu...
'Main entry point for REST interface. @param r: the S3Request instance @param attr: controller parameters'
def apply_method(self, r, **attr):
if (not self.permitted()): current.auth.permission.fail() output = {} representation = r.representation if (representation == 'html'): if (r.http in ('GET', 'POST')): output = self.registration_form(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) ...
'Render and process the registration form @param r: the S3Request instance @param attr: controller parameters'
def registration_form(self, r, **attr):
T = current.T s3db = current.s3db response = current.response settings = current.deployment_settings s3 = response.s3 output = {} error = None http = r.http request_vars = r.get_vars check = True label = None if (http == 'POST'): request_vars = r.post_vars ...
'Helper function to check permissions @return: True if permitted to use this method, else False'
def permitted(self):
return self._permitted('create')
'Get a case event type for an event code @param code: the type code (using default event type if None) @return: the dvr_case_event_type Row, or None if not found'
def get_event_type(self, code=None):
event_types = self.get_event_types() event_type = None if (code is None): event_type = event_types.get('_default') else: code = s3_str(code) for value in event_types.values(): if (value.code == code): event_type = value break return...
'Validate the event registration form @param form: the FORM'
def validate(self, form):
T = current.T formvars = form.vars pe_label = formvars.get('label').strip() person = self.get_person(pe_label) if (person is None): form.errors['label'] = T('No person found with this ID number') permitted = False else: person_id = person.id form...
'Helper function to process the form @param r: the S3Request @param form: the FORM @param event_type: the event_type (Row)'
def accept(self, r, form, event_type=None):
T = current.T response = current.response formvars = form.vars person_id = formvars.person_id success = False if (not formvars.get('permitted')): response.error = T('Event registration not permitted') elif person_id: event_type_id = (event_type.id if event_type else ...
'Ajax response method, expects a JSON input like: {l: the PE label (from the input field), c: boolean to indicate whether to just check the PE label or to register payments t: the event type code @param r: the S3Request instance @param attr: controller parameters @return: JSON response, structure: {l: the actual PE lab...
def registration_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 message = None warning = None permitted = False flags = [] pe_label = data.get('l'...
'Helper function to extend the form @param person: the person (Row) @param formfields: list of form fields (Field) @param data: the form data (dict) @param hidden: hidden form fields (dict) @param permitted: whether the action is permitted @return: tuple (widget_id, submit_label)'
def get_form_data(self, person, formfields, data, hidden, permitted=False):
T = current.T if person: details = dvr_get_household_size(person.id, dob=person.date_of_birth) else: details = '' formfields.extend([Field('details', label=T('Family'), writable=False)]) data['details'] = details widget_id = 'case-event-form' submit = current.T('Register') ...
'Helper function to construct the event type header @param event_type: the event type (Row) @returns: dict of view items'
def get_header(self, event_type=None):
T = current.T output = {} if event_type: event_type_name = T(event_type.name) name_class = 'event-type-name' else: event_type_name = T('Please select an event type') name_class = 'event-type-name placeholder' event_type_header = DIV(H4(SPAN(T(event_type...
'Register a case event @param person_id: the person record ID @param type:id: the event type record ID'
@staticmethod def register_event(person_id, type_id):
s3db = current.s3db ctable = s3db.dvr_case etable = s3db.dvr_case_event query = ((ctable.person_id == person_id) & (ctable.deleted != True)) case = current.db(query).select(ctable.id, limitby=(0, 1)).first() if case: case_id = case.id else: case_id = None r = S3Request('d...
'Lazy getter for case event types @return: a dict {id: Row} for dvr_case_event_type, with an additional key "_default" for the default event type'
def get_event_types(self):
if (not hasattr(self, 'event_types')): event_types = {} table = current.s3db.dvr_case_event_type query = ((table.is_inactive == False) & (table.deleted == False)) excluded = current.deployment_settings.get_dvr_event_registration_exclude_codes() if excluded: for co...
'Check minimum intervals between consecutive registrations of the same event type @param person_id: the person record ID @param type_id: check only this event type (rather than all types) @return: a dict with blocked event types {type_id: (error_message, blocked_until_datetime)}'
def check_intervals(self, person_id, type_id=None):
T = current.T db = current.db s3db = current.s3db now = current.request.utcnow day_start = now.replace(hour=0, minute=0, second=0, microsecond=0) next_day = (day_start + datetime.timedelta(days=1)) output = {} table = s3db.dvr_case_event event_type_id = table.type_id event_types ...
'Get the person record for a PE Label (or ID code), search only for persons with an open DVR case. @param pe_label: the PE label (or a scanned ID code as string)'
@classmethod def get_person(cls, pe_label):
s3db = current.s3db person = None fields = ['id', 'pe_id', 'pe_label', 'first_name', 'middle_name', 'last_name', 'date_of_birth', 'gender'] data = cls.parse_code(pe_label) def person_(label): ' Helper function to find a person by pe_label ' query = ((((FS('...
'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 output = SPAN(details, _...
'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 minimum intervals for event registration and return all currently blocked events @param person_id: the person record ID @param type_id: check only this event type (rather than all) @return: a dict of blocked event types: {type_id: (reason, blocked_until)}'
def get_blocked_events(self, person_id, type_id=None):
check_intervals = self.check_intervals if (check_intervals and callable(check_intervals)): blocked = check_intervals(person_id, type_id=type_id) else: blocked = {} return blocked
'Parse a scanned ID code (QR Code) @param code: the scanned ID code (string) @return: a dict {"label": the PE label, "first_name": optional first name, "last_name": optional last name, "date_of_birth": optional date of birth,'
@staticmethod def parse_code(code):
data = {'label': code} pattern = current.deployment_settings.get_dvr_id_code_pattern() if (pattern and code): import re pattern = re.compile(pattern) m = pattern.match(code) if m: data.update(m.groupdict()) return data
'Renders the button to launch the Zxing barcode scanner app @param event_code: the current event code @return: the Zxing launch button'
@staticmethod def get_zxing_launch_button(event_code):
T = current.T template = 'zxing://scan/?ret=%s&SCAN_FORMATS=Code 128,UPC_A,EAN_13' scan_vars = {'label': '{CODE}', 'scanner': 'zxing', 'event': '{EVENT}'} tmp = URL(args=['register'], vars=scan_vars, host=True) tmp = str(tmp).replace('&', '%26') if event_code: scan_vars['event'] = eve...
'Helper function to inject static JS and instantiate the eventRegistration 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.dvr.js' % appname) else: script = ('/%s/static/scripts/S3/s3.dvr.min.js' % appname) scripts.append(script) scripts = s3.jquery_ready script...
'Helper function to check permissions @return: True if permitted to use this method, else False'
def permitted(self):
return self._permitted('update')
'Get a case event type for an event code @param code: the type code (using default event type if None) @return: the dvr_case_event_type Row, or None if not found'
def get_event_type(self, code=None):
return Storage(id=None, code='PAYMENT')
'Helper function to process the form @param r: the S3Request @param form: the FORM @param event_type: the event_type (Row)'
def accept(self, r, form, event_type=None):
T = current.T response = current.response formvars = form.vars person_id = formvars.person_id success = False if (not formvars.get('permitted')): response.error = T('Payment registration not permitted') elif person_id: payments = r.post_vars.get('actions') if...
'Ajax response method, expects a JSON input like: {l: the PE label (from the input field), c: boolean to indicate whether to just check the PE label or to register payments d: the payment data (raw data, which payments to update) @param r: the S3Request instance @param attr: controller parameters @return: JSON response...
def registration_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 = {} alert = None error = None warning = None message = None permitted = False flags = [] pe_label = data.get('l'...
'Helper function to extend the form @param person: the person (Row) @param formfields: list of form fields (Field) @param data: the form data (dict) @param hidden: hidden form fields (dict) @param permitted: whether the action is permitted @return: tuple (widget_id, submit_label)'
def get_form_data(self, person, formfields, data, hidden, permitted=False):
T = current.T if (person and permitted): payments = self.get_payment_data(person.id) else: payments = [] date = S3DateTime.datetime_represent(current.request.utcnow, utc=True) formfields.extend([Field('details', label=T('Pending Payments'), writable=False, represent=self.payment_d...
'Helper function to construct the event type header @param event_type: the event type (Row) @returns: dict of view items'
def get_header(self, event_type=None):
event_type_header = DIV(H4(SPAN(current.T('Allowance Payment'), _class='event-type-name')), _class='event-type-header') output = {'event_type': event_type_header, 'event_type_selector': ''} return output
'Helper function to extract currently pending allowance payments for the person_id. @param person_id: the person record ID @return: a list of dicts [{i: record_id, d: date, c: currency, a: amount,'
def get_payment_data(self, person_id):
query = (((FS('person_id') == person_id) & (FS('status') == 1)) & (FS('date') <= current.request.utcnow.date())) resource = current.s3db.resource('dvr_allowance', filter=query) data = resource.select(['id', 'date', 'currency', 'amount'], orderby='dvr_allowance.date', represent=True) payments = [] ap...
'Helper function to register payments @param person_id: the person record ID @param payments: the payments as sent from form @param date: the payment date (default utcnow) @param comments: comments for the payments @return: tuple (updated, failed), number of records'
def register_payments(self, person_id, payments, date=None, comments=None):
if isinstance(payments, basestring): try: payments = json.loads(payments) except (ValueError, TypeError): payments = [] if (not date): date = current.request.utcnow data = {'status': 2, 'paid_on': date} if comments: data['comments'] = comments ...
'Representation method for the payment details field @param data: the payment data (from get_payment_data)'
def payment_data_represent(self, data):
if data: output = TABLE(_class='payment-details') for payment in data: details = TR(TD(payment['d'], _class='payment-date'), TD(payment['c'], _class='payment-currency'), TD(payment['a'], _class='payment-amount')) output.append(details) else: output = current.T('No...
'@param component: the Component in which to create records @param types: a list of types to pick from: Staff, Volunteers, Deployables @param next_tab: the component/method to redirect to after assigning'
def __init__(self, component, next_tab='case', types=None):
self.component = component self.next_tab = next_tab self.types = types
'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!') ...
'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(cms_post_id=(lambda **attr: dummy('post_id')), cms_tag_id=(lambda **attr: dummy('tag_id')))
'Cascade values down to all component Posts'
@staticmethod def cms_series_onaccept(form):
form_vars = form.vars db = current.db table = db.cms_post query = (table.series_id == form_vars.id) db(query).update(avatar=form_vars.avatar, replies=form_vars.replies, roles_permitted=form_vars.roles_permitted)
'CMS Post Import - Update Detection (primarily for non-blog contents such as homepage, module index pages, summary pages, or online documentation): - same name and series => same post @param item: the import item @todo: if no name present => use cms_post_module component to identify updates (also requires deduplication...
@staticmethod def cms_post_duplicate(item):
data = item.data name = data.get('name') series_id = data.get('series_id') if (not name): return table = item.table query = ((table.name == name) & (table.series_id == series_id)) duplicate = current.db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id...
'- Set person_id from created_by if not already set - Handle the case where the page is for a Module home page, Resource Summary page or Map Layer'
@staticmethod def cms_post_onaccept(form):
db = current.db s3db = current.s3db post_id = form.vars.id get_vars = current.request.get_vars module = get_vars.get('module', None) if module: table = db.cms_post_module query = (table.module == module) resource = get_vars.get('resource', None) if resource: ...
'Add a Tag to a Post S3Method for interactive requests - designed to be called as an afterTagAdded callback to tag-it.js'
@staticmethod def cms_add_tag(r, **attr):
post_id = r.id if ((not post_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db ttable = db.cms_tag ltable = db.cms_tag_post exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, ttable.deleted_fk, limitby=(0, 1)).first(...
'Remove a Tag from a Post S3Method for interactive requests - designed to be called as an afterTagRemoved callback to tag-it.js'
@staticmethod def cms_remove_tag(r, **attr):
post_id = r.id if ((not post_id) or (len(r.args) < 3)): raise HTTP(405, current.ERROR.BAD_METHOD) tag = r.args[2] db = current.db ttable = db.cms_tag exists = db((ttable.name == tag)).select(ttable.id, ttable.deleted, limitby=(0, 1)).first() if exists: tag_id = exists.id ...
'Bookmark a Post S3Method for interactive requests'
@staticmethod def cms_add_bookmark(r, **attr):
post_id = r.id user = current.auth.user user_id = (user and user.id) if ((not post_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) db = current.db ltable = db.cms_post_user query = ((ltable.post_id == post_id) & (ltable.user_id == user_id)) exists = db(query).sel...
'Remove a Bookmark for a Post S3Method for interactive requests'
@staticmethod def cms_remove_bookmark(r, **attr):
post_id = r.id user = current.auth.user user_id = (user and user.id) if ((not post_id) or (not user_id)): raise HTTP(405, current.ERROR.BAD_METHOD) db = current.db ltable = db.cms_post_user query = ((ltable.post_id == post_id) & (ltable.user_id == user_id)) exists = db(query).sel...
'Entry point to apply cms method to S3Requests - produces a full page with a Richtext widget @param r: the S3Request @param attr: dictionary of parameters for the method handler @return: output object to send to the view'
def apply_method(self, r, **attr):
r.error(405, current.ERROR.BAD_METHOD)
'Render a Rich Text widget suitable for use in a page such as S3Summary @param method: the widget method @param r: the S3Request @param attr: controller attributes @ToDo: Support comments'
def widget(self, r, method='cms', widget_id=None, **attr):
if (not current.deployment_settings.has_module('cms')): return '' return self.resource_content(r.controller, r.function, r.id, widget_id)
'Render resource-related CMS contents @param module: the module prefix @param resource: the resource name (without prefix) @param record: the record ID (optional) @param widget_id: the DOM node ID for the CMS widget @param hide_if_empty: return an empty string when there is no contents rather than a blank DIV'
@staticmethod def resource_content(module, resource, record=None, widget_id=None, hide_if_empty=False):
db = current.db table = current.s3db.cms_post ltable = db.cms_post_module query = (((((ltable.module == module) & (ltable.resource == resource)) & (ltable.record == record)) & (ltable.post_id == table.id)) & (table.deleted != True)) _item = db(query).select(table.id, table.body, limitby=(0, 1)).firs...
'Entry point for REST API @param r: the S3Request @param attr: controller arguments'
def apply_method(self, r, **attr):
if (r.name == 'post'): if (r.representation == 'html'): output = self.html(r, **attr) return output raise HTTP(405, current.ERROR.BAD_METHOD)
'Extract the Data'
def _extract(self, days, r, **attr):
resource = r.resource resource.add_filter(((FS('date') > days[0].replace(hour=0, minute=0, second=0, microsecond=0)) & (FS('date') < days[(-1)].replace(hour=23, minute=59, second=59)))) fields = ['body', 'date', 'location_id', 'post_module.module', 'post_module.resource', 'post_module.record'] data = re...
'HTML Representation'
def html(self, r, **attr):
T = current.T now = current.request.now timedelta = datetime.timedelta days = ((now - timedelta(days=1)), now, (now + timedelta(days=1)), (now + timedelta(days=2)), (now + timedelta(days=3)), (now + timedelta(days=4)), (now + timedelta(days=5))) posts = self._extract(days, r, **attr) item = TABL...
'Format a calendar entry'
@staticmethod def post_layout(post):
title = post['cms_post.body'] record_id = post['cms_post_module.record'] if record_id: title = A(title, _href=URL(c=str(post['cms_post_module.module']), f=str(post['cms_post_module.resource']), args=record_id), _target='_blank') location = post['cms_post.location_id'] return DIV(title, BR(),...
'Entry point for REST API @param r: the S3Request @param attr: controller arguments'
def apply_method(self, r, **attr):
if (r.representation == 'json'): table = current.s3db.cms_tag tags = current.db((table.deleted == False)).select(table.name) tag_list = [tag.name for tag in tags] output = json.dumps(tag_list, separators=SEPARATORS) current.response.headers['Content-Type'] = 'application/json...
'Safe defaults for model-global names in case module is disabled'
def defaults(self):
return {}
'If a logo was uploaded then create the extra versions. Process injected fields'
@staticmethod def org_organisation_onaccept(form):
newfilename = form.vars.logo_newfilename if newfilename: s3db = current.s3db image = form.request_vars.logo s3db.pr_image_modify(image.file, newfilename, image.filename, size=(None, 60)) s3db.pr_image_modify(image.file, newfilename, image.filename, size=(None, 60), to_format='bmp...
'If an Org is deleted then remove Logo'
@staticmethod def org_organisation_ondelete(row):
db = current.db table = db.org_organisation deleted_row = db((table.id == row.id)).select(table.logo, limitby=(0, 1)).first() if (deleted_row and deleted_row.logo): current.s3db.pr_image_delete_all(deleted_row.logo)
'Update the realm entity of the organisation after changing the organisation type (otherwise type-dependent realm rules won\'t ever take effect since the org_organisation record is written before the org_organisation_organisation_type) @param form: the Form'
@staticmethod def org_organisation_organisation_type_onaccept(form):
try: record_id = form.vars.id except AttributeError: return table = current.s3db.org_organisation_organisation_type row = current.db((table.id == record_id)).select(table.organisation_id, limitby=(0, 1)).first() if row: current.auth.set_realm_entity('org_organisation', row.or...
'Update the realm entity of the organisation after removing an organisation type (otherwise type-dependent realm rules won\'t take effect) @param form: the Row'
@staticmethod def org_organisation_organisation_type_ondelete(row):
try: record_id = row.id except AttributeError: return table = current.s3db.org_organisation_organisation_type row = current.db((table.id == record_id)).select(table.deleted_fk, limitby=(0, 1)).first() if (row and row.deleted_fk): try: deleted_fk = json.loads(row.d...
'Check for defaults provided by project/organisation.xsl'
@staticmethod def org_organisation_organisation_type_xml_post_parse(element, record):
org_type_default = element.xpath('data[@field="_organisation_type_id"]') if org_type_default: org_type_default = org_type_default[0].text db = current.db table = db.org_organisation_type row = None if (org_type_default == 'Donor'): row = db((table.name == 'Bil...
'JSON search method for S3OrganisationAutocompleteWidget - searches name & acronym for both this organisation & the parent of branches @param r: the S3Request @param attr: request attributes'
@staticmethod def org_search_ac(r, **attr):
_vars = current.request.get_vars value = (_vars.term or _vars.value or _vars.q or None) value = s3_unicode(value).lower().strip() if (not value): output = current.xml.json_message(False, 400, 'Missing option! Require value') raise HTTP(400, body=output) response = current.re...
'Prevent an Organisation from being a Branch of itself - this is for interactive forms, imports are caught in .xsl'
@staticmethod def org_branch_onvalidation(form):
request_vars = form.request_vars if (request_vars and request_vars.branch_id and request_vars.organisation_id and (int(request_vars.branch_id) == int(request_vars.organisation_id))): error = current.T('Cannot make an Organization a branch of itself!') form.errors['branch_id'...
'Remove any duplicate memberships and update affiliations'
@staticmethod def org_branch_onaccept(form):
_id = form.vars.id db = current.db s3db = current.s3db inherit = ['region_id', 'country'] otable = s3db.org_organisation ltable = db.org_organisation_branch btable = db.org_organisation.with_alias('org_branch_organisation') ifields = ([otable[fn] for fn in inherit] + [btable[fn] for fn i...
'Update affiliations'
@staticmethod def org_branch_ondelete(row):
db = current.db table = db.org_organisation_branch record = db((table.id == row.id)).select(table.branch_id, table.deleted, table.deleted_fk, limitby=(0, 1)).first() if record: org_update_affiliations('org_organisation_branch', record)
'Remove any duplicate memberships and update affiliations'
@staticmethod def group_membership_onaccept(form):
if hasattr(form, 'vars'): _id = form.vars.id elif (isinstance(form, Row) and ('id' in form)): _id = form.id else: return db = current.db mtable = db.org_group_membership if _id: record = db((mtable.id == _id)).select(limitby=(0, 1)).first() else: retur...
'Update affiliations'
@staticmethod def org_group_team_onaccept(form):
from pr import OU if hasattr(form, 'vars'): _id = form.vars.id elif (isinstance(form, Row) and ('id' in form)): _id = form.id else: return if (not _id): return db = current.db table = db.org_group_team record = db((table.id == _id)).select(table.group_id, ...
'Import item de-duplication'
@staticmethod def org_sector_duplicate(item):
data = item.data abrv = data.get('abrv') name = data.get('name') table = item.table if abrv: query = (table.abrv.lower() == s3_unicode(abrv).lower()) elif name: query = (table.name.lower() == s3_unicode(name).lower()) else: return duplicate = current.db(query).sel...
'If no abrv is set then set it from the name'
@staticmethod def org_sector_onaccept(form):
_id = form.vars.id db = current.db table = db.org_sector record = db((table.id == _id)).select(table.abrv, table.name, limitby=(0, 1)).first() if (not record.abrv): db((table.id == _id)).update(abrv=record.name[:64])
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return {'org_service_id': (lambda name='service_id', **attr: dummy(name, **attr))}
'Update the root_service'
@staticmethod def org_service_onaccept(form):
org_service_root_service(form.vars['id'])
'Import item de-duplication'
@staticmethod def org_service_location_deduplicate(item):
table = item.table data = item.data organisation_id = data.organisation_id if organisation_id: query = (table.organisation_id == organisation_id) site_id = data.site_id location_id = data.location_id location = data.location if site_id: query &= (table...
'Update affiliations. @ToDo: ondelete function needed too'
@staticmethod def org_team_onaccept(form):
if hasattr(form, 'vars'): _id = form.vars.id elif (isinstance(form, Row) and ('id' in form)): _id = form.id else: return if (not _id): return db = current.db table = db.org_organisation_team record = db((table.id == _id)).select(table.group_id, table.organisat...
'Create the code from the name'
@staticmethod def org_site_onaccept(form):
name = form.vars.name if (not name): return code_len = current.deployment_settings.get_org_site_code_len() temp_code = name[:code_len].upper() db = current.db site_table = db.org_site query = (site_table.code == temp_code) row = db(query).select(site_table.id, limitby=(0, 1)).fir...
'Update realm entity in all related HRs @todo: clean up records which RESTRICT the site_id'
@staticmethod def org_site_ondelete_cascade(form):
site_id = form.site_id htable = current.s3db.hrm_human_resource query = (htable.site_id == site_id) db = current.db rows = db(query).select(htable.id) db(query).update(site_id=None) current.auth.set_realm_entity(htable, rows, force_update=True)
'Called by org_site_onaccept'
@staticmethod def getCodeList(code, wildcard_posn=[]):
temp_code = '' for posn in range(len(code)): if (posn in wildcard_posn): temp_code += '%' else: temp_code += code[posn] db = current.db site_table = db.org_site query = site_table.code.like(temp_code) rows = db(query).select(site_table.id, site_table.code)...
'Called by org_site_onaccept'
@staticmethod def returnUniqueCode(code, wildcard_posn=[], code_list=[]):
replacement_char = '1234567890ZQJXKVBWPYGUMCFLDHSIRNOATE' rep_posn = ([0] * len(wildcard_posn)) finished = False while (not finished): temp_code = '' r = 0 for posn in range(len(code)): if (posn in wildcard_posn): temp_code += replacement_char[rep_posn...
'JSON lookup method for S3AddPersonWidget2'
@staticmethod def site_contact_person(r, **attr):
site_id = r.id if (not site_id): output = current.xml.json_message(False, 400, 'No id provided!') raise HTTP(400, body=output) db = current.db s3db = current.s3db ltable = s3db.hrm_human_resource_site htable = db.hrm_human_resource query = (((ltable.site_id == site_id) ...
'JSON search method for S3SiteAutocompleteWidget @param r: the S3Request @param attr: request attributes'
@staticmethod def site_search_ac(r, **attr):
response = current.response resource = r.resource settings = current.deployment_settings resource.add_filter(response.s3.filter) _vars = current.request.get_vars value = (_vars.term or _vars.value or _vars.q or None) value = s3_unicode(value).lower().strip() if (not value): outpu...
'Update Affiliation, record ownership and component ownership'
@staticmethod def org_facility_onaccept(form):
form_vars = form.vars if (('main_facility' in form_vars) and form_vars.main_facility): record_id = form_vars.id if record_id: db = current.db table = current.s3db.org_facility organisation_id = form_vars.organisation_id if (not organisation_id): ...
'Import item de-duplication'
@staticmethod def org_facility_duplicate(item):
data = item.data name = data.get('name') org = data.get('organisation_id') table = item.table query = (table.name.lower() == s3_unicode(name).lower()) if org: query = (query & ((table.organisation_id == org) | (table.organisation_id == None))) duplicate = current.db(query).select(tab...
'Produce a static GeoJSON[P] feed of Facility data Designed to be run on a schedule to serve a high-volume website'
@staticmethod def org_facility_geojson(jsonp=True, decimals=4):
from shapely.geometry import Point from ..geojson import dumps db = current.db s3db = current.s3db stable = s3db.org_facility ltable = db.org_site_facility_type ttable = db.org_facility_type gtable = db.gis_location ntable = s3db.req_site_needs formatter = ('.%sf' % decimals) ...
'* Update Affiliation and Realms * Process injected fields'
@staticmethod def org_office_onaccept(form):
form_vars = form.vars org_update_affiliations('org_office', form_vars) if current.deployment_settings.get_org_summary(): db = current.db id = form_vars.id table = current.s3db.org_office_summary query = (table.office_id == id) existing = db(query).select(table.id, lim...
'Custom lookup method for organisation rows, does a left join with the parent organisation. Parameters key and fields are not used, but are kept for API compatibility reasons. @param values: the organisation IDs'
def custom_lookup_rows(self, key, values, fields=[]):
s3db = current.s3db otable = s3db.org_organisation fields = [otable.id, otable.name, otable.acronym] show_parent = self.parent if show_parent: btable = s3db.org_organisation_branch ptable = otable.with_alias('org_parent_organisation') fields.append(ptable.name) left =...
'Represent a single Row @param row: the org_organisation Row'
def represent_row(self, row):
show_parent = self.parent if self.translate: name = (row['org_organisation_name.name_l10n'] or row['org_organisation.name']) acronym = (row['org_organisation_name.acronym_l10n'] or row['org_organisation.acronym']) if show_parent: parent = (row['org_parent_organisation_name.na...
'Custom orderby logic for datatables @ToDo: Support for self.translate = True need to handle the inevitable NULL values which vary in order by DB, although perhaps DB handling doesn\'t matter here.'
def dt_orderby(self, field, direction, orderby, left):
otable = current.s3db.org_organisation left.add(otable.on((field == otable.id))) if self.parent: rotable = otable.with_alias('org_root_organisation') left.add(rotable.on((otable.root_organisation == rotable.id))) orderby.extend([('org_root_organisation.name%s' % direction), ('org_org...
'Represent multiple values as dict {value: representation} @param values: list of values @param rows: the referenced rows (if values are foreign keys) @param show_link: render each representation as link @param include_blank: Also include a blank value @return: a dict {value: representation}'
def bulk(self, values, rows=None, list_type=False, show_link=True, include_blank=True):
show_link = (show_link and self.show_link) if (show_link and (not rows)): rows = self.custom_lookup_rows(None, values) self._setup() if (rows and self.table): values = [row['org_site.site_id'] for row in rows] else: values = ([values] if (type(values) is not list) else values...
'Custom lookup method for site rows, does a left join with any instance_types found. Parameters key and fields are not used, but are kept for API compatibility reasons. @param values: the site IDs'
def custom_lookup_rows(self, key, values, fields=[]):
db = current.db s3db = current.s3db stable = s3db.org_site count = len(values) if (count == 1): value = values[0] query = (stable.site_id == value) limitby = (0, 1) else: query = stable.site_id.belongs(values) limitby = (0, count) if self.show_link: ...
'Represent a (key, value) as hypertext link. @param k: the key (site_id) @param v: the representation of the key @param row: the row with this key'
def link(self, k, v, row=None):
if row: try: instance_type = row['org_site.instance_type'] id = row[instance_type].id except (AttributeError, KeyError): return v else: (c, f) = instance_type.split('_', 1) return A(v, _href=URL(c=c, f=f, args=[id], extension='')) ...
'Represent a single Row @param row: the org_site Row'
def represent_row(self, row):
if self.translate: _row = self.l10n.get(row['org_site.site_id']) if _row: name = _row['name_l10n'] else: name = row['org_site.name'] else: name = row['org_site.name'] if (not name): return self.default if self.show_type: instance_ty...
'Entry point for the REST API @param r: the S3Request @param attr: controller parameters'
def apply_method(self, r, **attr):
output = {} representation = r.representation if (representation == 'html'): if (r.http == 'GET'): output = self.check_in_form(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) elif (representation == 'json'): if (r.http == 'POST'): outpu...
'Render the check-in page @param r: the S3Request @param attr: controller parameters'
def check_in_form(self, r, **attr):
T = current.T response = current.response settings = current.deployment_settings output = {'title': T('Check-in')} request_vars = r.get_vars label = request_vars.get('label') person = None pe_label = None if (label is not None): person = self.get_person(label) if (per...