desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'On-accept routine for dc_template: - Create & link a Dynamic Table to use to store the Questions'
@staticmethod def dc_template_create_onaccept(form):
form_vars = form.vars try: template_id = form_vars.id except AttributeError: return mobile_data = current.deployment_settings.get_dc_mobile_data() table_id = current.s3db.s3_table.insert(title=form_vars.get('name'), mobile_data=mobile_data) db = current.db db.s3_field.insert(...
'On-accept routine for dc_question: - Create & link a Dynamic Field to use to store the Question'
@staticmethod def dc_question_onaccept(form):
try: question_id = form.vars.id except AttributeError: return db = current.db qtable = db.dc_question question = db((qtable.id == question_id)).select(qtable.id, qtable.template_id, qtable.field_id, qtable.name, qtable.comments, qtable.field_type, qtable.options, qtable.require_not_e...
'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_response_id=(lambda **attr: dummy('response_id')), dc_target_id=(lambda **attr: dummy('target_id')))
'Safe defaults for model-global names in case module is disabled'
def defaults(self):
dummy = S3ReusableField('dummy', 'string', readable=False, writable=False) return dict(req_req_id=(lambda **attr: dummy('req_id')), req_req_ref=(lambda **attr: dummy('req_ref')))
'Function to be called from REST prep functions - main module & components (sites & events)'
@staticmethod def req_create_form_mods():
T = current.T db = current.db s3 = current.response.s3 settings = current.deployment_settings table = db.req_req table.req_ref.readable = False table.commit_status.readable = table.commit_status.writable = False table.transit_status.readable = table.transit_status.writable = False ta...
'Function to be called from REST prep functions - to add req_item & req_skill components as inline forms'
@staticmethod def req_inline_form(type, method):
T = current.T s3db = current.s3db table = s3db.req_req s3 = current.response.s3 postprocess = s3.req_req_postprocess if (type == 1): itable = s3db.req_req_item itable.item_id.widget = None jquery_ready = s3.jquery_ready jquery_ready.append("\n$.filterOptionsS3({\n...
'Function to be called from REST prep functions - main module & components (sites)'
@staticmethod def req_prep(r):
if ((not r.component) or (r.component.name == 'req')): default_type = current.db.req_req.type.default if default_type: T = current.T req_submit_button = {1: T('Save and add Items'), 3: T('Save and add People'), 9: T('Save')} current.response.s3.c...
'Represent a Request'
@staticmethod def req_represent(id, row=None, show_link=True, pdf=False):
if row: table = current.db.req_req elif (not id): return current.messages['NONE'] else: id = int(id) if id: db = current.db table = db.req_req row = db((table.id == id)).select(table.date, table.req_ref, table.site_id, limitby=(0, 1)).first...
'Represet the Commitment Status of the Request'
@staticmethod def req_commit_status_represent(opt):
if (opt == REQ_STATUS_COMPLETE): return SPAN(current.T('Complete'), _class='req_status_complete') else: return current.s3db.req_status_opts.get(opt, current.messages.UNKNOWN_OPT)
'Represent for the Request Reference if show_link is True then it will generate a link to the record if pdf is True then it will generate a link to the PDF'
@staticmethod def req_ref_represent(value, show_link=True, pdf=False):
if value: if show_link: db = current.db table = db.req_req req_row = db((table.req_ref == value)).select(table.id, limitby=(0, 1)).first() if req_row: if pdf: args = [req_row.id, 'form'] else: ...
'Generate a PDF of a Request Form'
@staticmethod def req_form(r, **attr):
db = current.db table = db.req_req record = db((table.id == r.id)).select(limitby=(0, 1)).first() if (record.type == 1): pdf_componentname = 'req_item' list_fields = ['item_id', 'item_pack_id', 'quantity', 'quantity_commit', 'quantity_transit', 'quantity_fulfil'] elif (record.type ==...
'Custom Method to copy an existing Request - creates a req with req_item records'
@staticmethod def req_copy_all(r, **attr):
db = current.db s3db = current.s3db table = s3db.req_req settings = current.deployment_settings now = current.request.now record = r.record req_id = record.id if settings.get_req_use_req_number(): code = s3db.supply_get_shipping_code(settings.get_req_shortname(), record.site_id, ...
'Custom Method to commit to a Request - creates a commit with commit_items for each req_item or commit_skills for each req_skill'
@staticmethod def req_commit_all(r, **attr):
T = current.T db = current.db s3db = current.s3db table = s3db.req_commit record = r.record req_id = record.id query = ((table.req_id == req_id) & (table.deleted == False)) exists = db(query).select(table.id, limitby=(0, 1)) if exists: redirect(URL(f='req', args=[r.id, 'commi...
''
@staticmethod def req_priority_represent(id):
src = URL(c='static', f='img', args=['priority', ('priority_%d.gif' % (id or 4))]) return DIV(IMG(_src=src))
'Hide the Update Quantity Status Fields from Request create forms'
@staticmethod def req_hide_quantities(table):
if (not current.deployment_settings.get_req_item_quantities_writable()): table.quantity_commit.writable = table.quantity_commit.readable = False table.quantity_transit.writable = table.quantity_transit.readable = False table.quantity_fulfil.writable = table.quantity_fulfil.readable = False
'Add a set of Tabs for a Site\'s Request Tasks @ToDo: Roll these up like inv_tabs in inv.py'
@staticmethod def req_tabs(r, match=True):
settings = current.deployment_settings if settings.get_org_site_inv_req_tabs(): permit = current.auth.s3_has_permission if (settings.has_module('req') and permit('read', 'req_req', c='req')): T = current.T tabs = [(T('Requests'), 'req')] if (match and permit('...
'After DB I/O'
@staticmethod def req_onaccept(form):
db = current.db s3db = current.s3db request = current.request settings = current.deployment_settings tablename = 'req_req' table = s3db.req_req form_vars = form.vars id = form_vars.id if form_vars.get('is_template', None): is_template = True f = 'req_template' els...
'Cleanup any scheduled tasks'
@staticmethod def req_req_ondelete(row):
db = current.db table = db.scheduler_task query = ((table.function_name == 'req_add_from_template') & (table.args == ('[%s]' % row.id))) db(query).delete()
'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(req_item_id=(lambda **attr: dummy('req_item_id')))
'Represent a Request Item @ToDo: Migrate to S3Represent'
@staticmethod def req_item_represent(id, row=None):
if row: id = row.id elif (not id): return current.messages['NONE'] db = current.db ritable = db.req_req_item sitable = db.supply_item query = ((ritable.id == id) & (ritable.item_id == sitable.id)) record = db(query).select(sitable.name, limitby=(0, 1)).first() if record: ...
'call the generic quantity represent'
@staticmethod def req_qnty_commit_represent(quantity, show_link=True):
return S3RequestItemModel.req_quantity_represent(quantity, 'commit', show_link)
'call the generic quantity represent'
@staticmethod def req_qnty_transit_represent(quantity, show_link=True):
return S3RequestItemModel.req_quantity_represent(quantity, 'transit', show_link)
'call the generic quantity represent'
@staticmethod def req_qnty_fulfil_represent(quantity, show_link=True):
return S3RequestItemModel.req_quantity_represent(quantity, 'fulfil', show_link)
'@ToDo: There should be better control of this feature - currently this only works with req_items which are being matched by commit / send / recv'
@staticmethod def req_quantity_represent(quantity, type, show_link=True):
if (quantity and show_link and (not current.deployment_settings.get_req_item_quantities_writable())): return TAG[''](quantity, A(DIV(_class=('quantity %s ajax_more collapsed' % type)), _href='#')) else: return quantity
'This callback will be called when importing records. It will look to see if the record being imported is a duplicate. @param item: An S3ImportItem object which includes all the details of the record being imported If the record is a duplicate then it will set the item method to update Rules for finding a duplicate: - ...
@staticmethod def req_item_duplicate(item):
db = current.db itable = item.table rtable = db.req_req stable = db.supply_item req_id = None item_id = None for ref in item.references: if (ref.entry.tablename == 'req_req'): if (ref.entry.id != None): req_id = ref.entry.id else: ...
'Used in controllers/req.py commit()'
@staticmethod def req_skill_represent(id):
if (not id): return current.messages['NONE'] db = current.db rstable = db.req_req_skill hstable = db.hrm_skill query = ((rstable.id == id) & (rstable.skill_id == hstable.id)) record = db(query).select(hstable.name, limitby=(0, 1)).first() try: return record.name except: ...
'Deduplication method for req_organisation_needs: replace existing records rather than updating them @param item: the S3ImportItem'
@staticmethod def organisation_needs_deduplicate(item):
data = item.data organisation_id = data.get('organisation_id') if organisation_id: from s3 import FS query = (FS('organisation_id') == organisation_id) resource = current.s3db.resource('req_organisation_needs', filter=query) resource.delete(cascade=True)
'Represent a Commit @ToDo: Migrate to S3Represent'
@staticmethod def commit_represent(id, row=None):
if row: table = current.db.req_commit elif (not id): return current.messages['NONE'] else: db = current.db table = db.req_commit row = db((table.id == id)).select(table.type, table.date, table.organisation_id, table.site_id, limitby=(0, 1)).first() if (row.type ==...
'Copy the request_type to the commitment'
@staticmethod def commit_onvalidation(form):
req_id = s3_get_last_record_id('req_req') if req_id: rtable = current.s3db.req_req query = (rtable.id == req_id) req_record = current.db(query).select(rtable.type, limitby=(0, 1)).first() if req_record: form.vars.type = req_record.type
'Update Status of Request & components'
@staticmethod def commit_onaccept(form):
db = current.db s3db = current.s3db form_vars = form.vars id = form_vars.id if (not id): return ctable = s3db.req_commit site_id = form_vars.get('site_id', None) if site_id: stable = s3db.org_site site = db((stable.site_id == site_id)).select(stable.location_id, l...
'Update Status of Request & components'
@staticmethod def commit_ondelete(row):
db = current.db s3db = current.s3db id = row.id ctable = s3db.req_commit fks = db((ctable.id == id)).select(ctable.deleted_fk, limitby=(0, 1)).first().deleted_fk req_id = json.loads(fks)['req_id'] rtable = s3db.req_req req = db((rtable.id == req_id)).select(rtable.id, rtable.type, rtable...
'Update the Commit Status for the Request Item & Request'
@staticmethod def commit_item_onaccept(form):
db = current.db req_item_id = form.vars.req_item_id ritable = db.req_req_item req = db((ritable.id == req_item_id)).select(ritable.req_id, limitby=(0, 1)).first() if (not req): return req_id = req.req_id query = ((ritable.req_id == req_id) & (ritable.deleted == False)) ritems = d...
'Create a Shipment containing all items in a Commitment'
@staticmethod def req_send_commit():
try: commit_id = current.request.args[0] except: redirect(URL(c='req', f='commit')) db = current.db s3db = current.s3db req_table = db.req_req rim_table = db.req_req_item com_table = db.req_commit cim_table = db.req_commit_item send_table = s3db.inv_send tracktabl...
'Not working'
@staticmethod def commit_person_onaccept(form):
db = current.db s3db = current.s3db table = db.req_commit_person rstable = s3db.req_req_skill req_skill_id = 0 if form: req_skill_id = form.vars.get('req_skill_id', None) if (not req_skill_id): commit_skill_id = s3_get_last_record_id('req_commit_skill') r_commit_skill...
'Update the Commit Status for the Request Skill & Request'
@staticmethod def commit_skill_onaccept(form):
req_skill_id = form.vars.req_skill_id db = current.db rstable = db.req_req_skill req = db((rstable.id == req_skill_id)).select(rstable.req_id, limitby=(0, 1)).first() if (not req): return req_id = req.req_id query = ((rstable.req_id == req_id) & (rstable.deleted == False)) rskill...
'Apply method. @param r: the S3Request @param attr: controller options for this request'
def apply_method(self, r, **attr):
req_type = r.record.type if (req_type == 1): return self.inv_match(r, **attr) elif (req_type == 3): return self.skills_match(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD)
'Match a Request\'s Items with a Site\'s Inventory'
@staticmethod def inv_match(r, **attr):
T = current.T db = current.db s3db = current.s3db response = current.response s3 = response.s3 output = dict(title=T('Check Request'), rheader=req_rheader(r, check_page=True), subtitle=T('Requested Items')) table = s3db.req_req_item query = ((table.req_id == r.id) & (table.deleted ...
'Match a Request\'s Skills with an Organisation\'s HRs @ToDo: Optionally Filter by Site (Volunteers don\'t currently link to a Site) @ToDo: Check Availability - when the Volunteer has said they will work - where the Volunteer has said they will work - don\'t commit the same time slot twice'
@staticmethod def skills_match(r, **attr):
T = current.T db = current.db s3db = current.s3db response = current.response s3 = response.s3 output = dict(title=T('Check Request'), rheader=req_rheader(r, check_page=True), subtitle=T('Requested Skills')) table = s3db.req_req_skill query = ((table.req_id == r.id) & (table.delete...
'Safe defaults if module is disabled'
def defaults(self):
return dict(stats_source_superlink=S3ReusableField('source_id', 'integer', readable=False, writable=False)())
'This will delete all the stats_demographic_aggregate records and then rebuild them by triggering off a request for each stats_demographic_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 stats_demographic_rebuild_all_aggregates():
db = current.db ttable = db.scheduler_task rtable = db.scheduler_run wtable = db.scheduler_worker query = (((ttable.task_name == 'stats_demographic_update_aggregates') & (rtable.task_id == ttable.id)) & (rtable.status == 'RUNNING')) rows = db(query).select(rtable.id, rtable.task_id, rtable.worke...
'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 stats_demographic_aggregated_period(data_date=None):
date = datetime.date 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 stats_demographic_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 vulnerability approve_report() controller. @ToDo: onapprove/onaccept wrapper f...
@staticmethod def stats_demographic_update_aggregates(records=None):
if (not records): return from dateutil.rrule import rrule, YEARLY db = current.db s3db = current.s3db dtable = s3db.stats_demographic_data atable = db.stats_demographic_aggregate gtable = db.gis_location param_total_dict = {} param_location_dict = {} location_dict = {} ...
'Calculates the stats_demographic_aggregate for a specific parameter at a specific location. @param location_id: the location record ID @param parameter_id: the parameter record ID @param total_id: the parameter record ID for the percentage calculation @param start_date: the start date of the time period (as string) @p...
@staticmethod def stats_demographic_update_location_aggregate(location_level, location_id, parameter_id, total_id, start_date, end_date):
db = current.db dtable = current.s3db.stats_demographic_data atable = db.stats_demographic_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) & (dtable.deleted != True)...
'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['stats_source.source_id'] for row in rows] else: values = ([values] if (type(values) is not list) else ...
'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.stats_source qty = len(values) if (qty == 1): query = (stable.id == values[0]) limitby = (0, 1) else: query = stable.id.belongs(values) limitby = (0, qty) if self.show_link: rows = db(query).select(stab...
'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: url = row['doc_document.url'] except AttributeError: return v else: if url: return A(v, _href=url, _target='blank') return v
'Represent a single Row @param row: the org_site Row'
def represent_row(self, row):
name = row['stats_source.name'] if (not name): return self.default return s3_str(name)
'Update Affiliation, record ownership and component ownership'
@staticmethod def hms_hospital_onaccept(form):
current.s3db.org_update_affiliations('hms_hospital', form.vars)
'Bed Capacity Validation'
@staticmethod def hms_bed_capacity_onvalidation(form):
db = current.db htable = db.hms_hospital ctable = db.hms_bed_capacity hospital_id = ctable.hospital_id.update bed_type = form.vars.bed_type query = ((ctable.hospital_id == hospital_id) & (ctable.bed_type == bed_type)) row = db(query).select(ctable.id, limitby=(0, 1)).first() if (row and ...
'Updates the number of total/available beds of a hospital'
@staticmethod def hms_bed_capacity_onaccept(form):
if isinstance(form, Row): formvars = form else: formvars = form.vars db = current.db ctable = db.hms_bed_capacity htable = db.hms_hospital query = ((ctable.id == formvars.id) & (htable.id == ctable.hospital_id)) hospital = db(query).select(htable.id, limitby=(0, 1)) if ho...
'Update Affiliation, record ownership and component ownership'
@staticmethod def police_station_onaccept(form):
current.s3db.org_update_affiliations('police_station', form.vars)
'Update Affiliation, record ownership and component ownership'
@staticmethod def edu_school_onaccept(form):
current.s3db.org_update_affiliations('edu_school', form.vars)
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return {'po_area_id': (lambda **attr: dummy('area_id'))}
'Onaccept actions for po_area'
@classmethod def area_onaccept(cls, form):
try: record_id = form.vars.id except AttributeError: return cls.area_update_affiliations(record_id)
'Ondelete actions for po_area'
@classmethod def area_ondelete(cls, row):
try: record_id = row.id except AttributeError: return cls.area_update_affiliations(record_id)
'Update affiliations for an area @param record: the area record'
@staticmethod def area_update_affiliations(record_id):
ROLE = 'Areas' db = current.db s3db = current.s3db table = s3db.po_area row = db((table.id == record_id)).select(table.pe_id, table.deleted, table.deleted_fk, table.organisation_id, limitby=(0, 1)).first() if (not row): return area_pe_id = row.pe_id if (not area_pe_id): r...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return {'po_household_id': (lambda **attr: dummy('household_id'))}
'Determine where to go next after creating a new household'
@staticmethod def household_create_next(r):
post_vars = r.post_vars next_vars = S3Method._remove_filters(r.get_vars) next_vars.pop('w', None) follow_up = (('followup' in post_vars) and post_vars['followup']) if (r.function == 'area'): if follow_up: return URL(f='household', args=['[id]', 'person'], vars=next_vars) ...
'Onaccept-routine for households'
@staticmethod def household_onaccept(form):
formvars = form.vars try: record_id = formvars.id except AttributeError: return s3db = current.s3db htable = s3db.po_household ftable = s3db.po_household_followup left = ftable.on(((ftable.household_id == htable.id) & (ftable.deleted != True))) row = current.db((htable.id...
'Constructor @param show_link: whether to add a URL to representations'
def __init__(self, show_link=True):
super(po_HouseholdRepresent, self).__init__(lookup='po_household', show_link=show_link) self.location_represent = current.s3db.gis_LocationRepresent(address_only=True, show_link=False)
'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) rows = current.db(query).select(table.id, table.location_id, limitby=(0, count)) self.queries += 1 location_id = str(table.location_id) location_ids = [row...
'Represent a row @param row: the Row'
def represent_row(self, row):
return self.location_represent(row.location_id)
'Whether the member has paid within 12 months of start_date anniversary @ToDo: Formula should come from the deployment_template'
@staticmethod def member_membership_paid(row):
T = current.T try: start_date = row['member_membership.start_date'] except AttributeError: start_date = None try: paid_date = row['member_membership.membership_paid'] except AttributeError: paid_date = None if start_date: PAID = T('paid') OVERDUE =...
'On-accept for Member records'
@staticmethod def member_onaccept(form):
db = current.db s3db = current.s3db auth = current.auth settings = current.deployment_settings utable = current.auth.settings.table_user ptable = s3db.pr_person ltable = s3db.pr_person_user mtable = db.member_membership _id = form.vars.id if _id: query = (mtable.id == _id...
'Virtual Field to return the current location of a Trackable @ToDo: Bulk @ToDo: Also show Timestamp of when seen there'
@staticmethod def sit_location(row, tablename):
s3db = current.s3db tracker = S3Tracker()(s3db[tablename], row[tablename].id) location = tracker.get_location(as_rows=True).first() return s3db.gis_location_represent(None, row=location)
'Update the overall status from the Gutting/Mold status'
@staticmethod def assess_building_onvalidation(form):
vars = form.vars status = ((vars.status and int(vars.status)) or None) if (status < 3): status_gutting = ((vars.status_gutting and int(vars.status_gutting)) or None) status_mold = ((vars.status_mold and int(vars.status_mold)) or None) if ((status_gutting in (3, 4)) or (status_mold in...
'Resource Header'
@staticmethod def assess_building_rheader(r):
if ((r.representation != 'html') or (r.method == 'import') or (not r.record)): return None rheader = TABLE(A(T('Print Work Order'), _href=URL(args=[r.record.id, 'form']), _class='action-btn')) return rheader
'Generate a PDF of a Work Order @ToDo: Move this to Template?'
@staticmethod def assess_building_form(r, **attr):
db = current.db table = db.assess_building gtable = db.gis_location query = (table.id == r.id) left = gtable.on((gtable.id == table.location_id)) record = db(query).select(left=left, limitby=(0, 1)).first() location = record.gis_location record = record.assess_building address = loca...
''
@staticmethod def climate_price_create_onvalidation(form):
vars = form.request_vars db = current.db table = db.climate_prices query = ((table.category == vars['category']) & (table.parameter_id == vars['parameter_id'])) price = db(query).select(table.id, limitby=(0, 1)).first() if (price is not None): form.errors['nrs_per_datum'] = ['There is...
'Calculate Price'
@staticmethod def climate_purchase_onaccept(form):
import ClimateDataPortal vars = form.vars id = vars.id db = current.db ptable = db.climate_purchase purchase = db((ptable.id == id)).select(ptable.paid, limitby=(0, 1)).first() if (purchase and (purchase.paid == True)): pass else: parameter_id = vars.parameter_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(cr_shelter_id=(lambda **attr: dummy('shelter_id')))
'After DB I/O'
@staticmethod def cr_shelter_onaccept(form):
form_vars = form.vars current.s3db.org_update_affiliations('cr_shelter', form_vars) if current.deployment_settings.get_cr_shelter_population_dynamic(): cr_update_shelter_population(form_vars.id) return
''
@staticmethod def cr_shelter_service_multirepresent(shelter_service_ids):
if (not shelter_service_ids): return current.messages['NONE'] db = current.db table = db.cr_shelter_service if isinstance(shelter_service_ids, (list, tuple)): query = table.id.belongs(shelter_service_ids) shelter_services = db(query).select(table.name) return ', '.join...
'Virtual Field to show the status of the unit by available capacity - used to colour features on the map 0: Full 1: Partial 2: Empty 3: Not Available'
@staticmethod def cr_shelter_unit_status(row):
if hasattr(row, 'cr_shelter_unit'): row = row.cr_shelter_unit if hasattr(row, 'status'): status = row.status else: status = None if (status == 2): return 3 if hasattr(row, 'available_capacity_day'): actual = row.available_capacity_day else: actual ...
'Safe defaults for names in case the module is disabled'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return {'cr_shelter_flag_id': (lambda **attr: dummy('flag_id'))}
'Shelter Flag form validation: - if create_task=True, then task_description is required'
@staticmethod def shelter_flag_onvalidation(form):
T = current.T formvars = form.vars create_task = formvars.get('create_task') task_description = formvars.get('task_description') if (create_task and (not task_description)): form.errors['task_description'] = T('Task Description required')
'Shelter inspection flag onaccept: - auto-create task if/as configured'
@staticmethod def shelter_inspection_flag_onaccept(form):
settings = current.deployment_settings if (not settings.get_cr_shelter_inspection_tasks()): return formvars = form.vars try: record_id = formvars.id except AttributeError: return db = current.db s3db = current.s3db table = s3db.cr_shelter_inspection_flag ftabl...
'Ondelete-cascade method for inspection task links: - close the linked task if there are no other unresolved flags linked to it'
@staticmethod def shelter_inspection_task_ondelete_cascade(row, tablename=None):
db = current.db s3db = current.s3db ltable = s3db.cr_shelter_inspection_task query = (ltable.id == row.id) link = db(query).select(ltable.id, ltable.task_id, limitby=(0, 1)).first() task_id = link.task_id ftable = s3db.cr_shelter_inspection_flag ttable = s3db.project_task query = (((...
'Check if the housing unit belongs to the requested shelter'
@staticmethod def cr_shelter_registration_onvalidation(form):
request = current.request controller = request.controller if (controller == 'dvr'): return unit_id = None if (type(form) is Row): form_vars = form else: form_vars = form.vars if (controller == 'evr'): shelter_id = form_vars.shelter_id unit_id = form_va...
'Registration onaccept: track status changes, update shelter population @param form: the FORM (also accepts Row)'
@classmethod def shelter_registration_onaccept(cls, form):
try: if (type(form) is Row): formvars = form else: formvars = form.vars registration_id = formvars.id except AttributeError: unit_id = None else: unit_id = formvars.get('shelter_unit_id') if registration_id: s3db = current.s...
'Update the shelter population, onaccept @param form: the FORM @param tablename: the table name @param unit_id: the shelter unit ID (to warn if full)'
@staticmethod def shelter_population_onaccept(form, tablename=None, unit_id=None):
db = current.db s3db = current.s3db if (not tablename): return table = s3db[tablename] try: if (type(form) is Row): record_id = form.id else: record_id = form.vars.id except AttributeError: return if (tablename == 'cr_shelter_unit'): ...
'Entry point for REST API @param r: the S3Request @param attr: controller arguments'
def apply_method(self, r, **attr):
try: person_id = int(r.get_vars['person_id']) except: raise HTTP(400, current.messages.BAD_REQUEST) self.settings = current.response.s3.crud sqlform = self._config('crud_form') self.sqlform = (sqlform if sqlform else S3SQLDefaultForm()) self.data = None table = current.s3db.c...
'Constructor @param show_link: represent as link to the shelter inspection'
def __init__(self, show_link=False):
super(ShelterInspectionFlagRepresent, self).__init__(lookup='cr_shelter_inspection_flag', show_link=show_link)
'Link inspection flag representations to the inspection record @param k: the inspection flag ID @param v: the representation @param row: the row from lookup_rows'
def link(self, k, v, row=None):
if row: inspection_id = row.cr_shelter_inspection.id if inspection_id: return A(v, _href=URL(c='cr', f='shelter_inspection', args=[inspection_id])) return v
'Represent a Row @param row: the Row'
def represent_row(self, row):
details = {'unit': row.cr_shelter_unit.name, 'date': row.cr_shelter_inspection.date, 'flag': row.cr_shelter_flag.name} return ('%(unit)s (%(date)s): %(flag)s' % details)
'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=[]):
s3db = current.s3db table = self.table ftable = s3db.cr_shelter_flag itable = s3db.cr_shelter_inspection utable = s3db.cr_shelter_unit left = (ftable.on((ftable.id == table.flag_id)), itable.on((itable.id == table.inspection_id)), utable.on((utable.id == itable.shelter_unit_id))) count = len...
'Constructor @param show_link: represent as link to the shelter inspection'
def __init__(self, show_link=False):
super(ShelterInspectionRepresent, self).__init__(lookup='cr_shelter_inspection', show_link=show_link)
'Link inspection flag representations to the inspection record @param k: the inspection flag ID @param v: the representation @param row: the row from lookup_rows'
def link(self, k, v, row=None):
if row: inspection_id = row.cr_shelter_inspection.id if inspection_id: return A(v, _href=URL(c='cr', f='shelter_inspection', args=[inspection_id])) return v
'Represent a Row @param row: the Row'
def represent_row(self, row):
details = {'unit': row.cr_shelter_unit.name, 'date': row.cr_shelter_inspection.date} return ('%(date)s: %(unit)s' % details)
'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=[]):
s3db = current.s3db table = self.table utable = s3db.cr_shelter_unit left = utable.on((utable.id == table.shelter_unit_id)) count = len(values) if (count == 1): query = (table.id == values[0]) else: query = table.id.belongs(values) limitby = (0, count) rows = current....
'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.inspection_form(r, **attr) else: r.error(405, current.ERROR.BAD_METHOD) ...
'@todo: docstring'
def permitted(self):
return True
'Generate the form @param r: the S3Request instance @param attr: controller parameters'
def inspection_form(self, r, **attr):
T = current.T db = current.db s3db = current.s3db settings = current.deployment_settings response = current.response output = {} record = r.record if record: utable = s3db.cr_shelter_unit dbset = db((utable.shelter_id == record.id)) else: dbset = db shelte...
'Ajax-registration of shelter inspection @param r: the S3Request instance @param attr: controller parameters'
def inspection_ajax(self, r, **attr):
T = current.T db = current.db s3db = current.s3db s = r.body s.seek(0) try: data = json.load(s) except (ValueError, TypeError): r.error(400, current.ERROR.BAD_REQUEST) shelter_unit_id = data.get('u') if shelter_unit_id: error = False comments = data.ge...
'Helper function to inject static JS and instantiate the shelterInspection 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.shelter_inspection.js' % appname) else: script = ('/%s/static/scripts/S3/s3.shelter_inspection.min.js' % appname) scripts.append(script) script...
'Update Affiliation, record ownership and component ownership'
@staticmethod def inv_warehouse_onaccept(form):
current.s3db.org_update_affiliations('inv_warehouse', form.vars)
'Total value of an inventory item'
@staticmethod def inv_item_total_value(row):
if hasattr(row, 'inv_inv_item'): row = row.inv_inv_item try: v = (row.quantity * row.pack_value) return v except (AttributeError, TypeError): return current.messages['NONE']
'When a inv_inv_item record is created with a source number, then the source number needs to be unique within the organisation.'
@staticmethod def inv_inv_item_onvalidate(form):
item_source_no = form.vars.item_source_no if (not item_source_no): return if hasattr(form, 'record'): record = form.record if (record and record.item_source_no and (record.item_source_no == item_source_no)): return db = current.db s3db = current.s3db itable = ...
'Check that the required_total can be removed from the inv_record if there is insufficient stock then set up the total to being what is in stock otherwise set it to be the required total. If the update flag is true then remove it from stock. The current total is what has already been removed for this transaction.'
@staticmethod def inv_remove(inv_rec, required_total, required_pack_value=1, current_track_total=0, update=True):
db = current.db inv_item_table = db.inv_inv_item siptable = db.supply_item_pack inv_p_qnty = db((siptable.id == inv_rec.item_pack_id)).select(siptable.quantity, limitby=(0, 1)).first().quantity inv_qnty = (inv_rec.quantity * inv_p_qnty) cur_qnty = (current_track_total * inv_p_qnty) req_qnty ...
'Used in site REST controllers to Filter out items which are already in this inventory'
@staticmethod def inv_prep(r):
if r.component: if (r.component.name == 'inv_item'): db = current.db table = db.inv_inv_item query = ((table.site_id == r.record.site_id) & (table.deleted == False)) inv_item_rows = db(query).select(table.item_id) item_ids = [row.item_id for row in...