desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Update detection for inv_inv_item @param item: the S3ImportItem'
@staticmethod def inv_item_duplicate(item):
table = item.table data = item.data site_id = data.get('site_id') item_id = data.get('item_id') pack_id = data.get('item_pack_id') owner_org_id = data.get('owner_org_id') supply_org_id = data.get('supply_org_id') pack_value = data.get('pack_value') currency = data.get('currency') ...
'Total value of a track item'
@staticmethod def inv_track_item_total_value(row):
if hasattr(row, 'inv_track_item'): row = row.inv_track_item try: v = (row.quantity * row.pack_value) return v except: return current.messages['NONE']
'Total volume of a track item'
@staticmethod def inv_track_item_total_volume(row, received=False):
if hasattr(row, 'inv_track_item'): row = row.inv_track_item try: table = current.s3db.supply_item item = current.db((table.id == row.item_id)).select(table.volume, limitby=(0, 1)).first() quantity = (row.quantity if (not received) else row.recv_quantity) if (not quantity)...
'Total weight of a track item'
@staticmethod def inv_track_item_total_weight(row, received=False):
if hasattr(row, 'inv_track_item'): row = row.inv_track_item try: table = current.s3db.supply_item item = current.db((table.id == row.item_id)).select(table.weight, limitby=(0, 1)).first() quantity = (row.quantity if (not received) else row.recv_quantity) if (not quantity)...
'Quantity still needed for a track item - used in Inv Send when an Item has come from a Request'
@staticmethod def inv_track_item_quantity_needed(row):
if hasattr(row, 'inv_track_item'): row = row.inv_track_item try: req_item_id = row.req_item_id except: req_item_id = None if (not req_item_id): return current.messages['NONE'] s3db = current.s3db ritable = s3db.req_req_item siptable = s3db.supply_item_pack ...
'Represent a Sent Shipment'
@staticmethod def inv_send_represent(id, row=None, show_link=True):
if row: id = row.id table = current.db.inv_send elif (not id): return current.messages['NONE'] else: db = current.db table = db.inv_send row = db((table.id == id)).select(table.date, table.send_ref, table.to_site_id, limitby=(0, 1)).first() try: se...
'When a inv send record is created then create the send_ref.'
@staticmethod def inv_send_onaccept(form):
db = current.db vars = form.vars id = vars.id type = vars.type if type: inv_track_item_onaccept = current.s3db.inv_track_item_onaccept site_id = vars.site_id itable = db.inv_inv_item tracktable = db.inv_track_item query = ((itable.site_id == site_id) & (itable...
'RESTful CRUD controller for inv_send'
@classmethod def inv_send_controller(cls):
T = current.T db = current.db s3db = current.s3db sendtable = s3db.inv_send tracktable = s3db.inv_track_item iitable = s3db.inv_inv_item request = current.request response = current.response s3 = response.s3 error_msg = T('You do not have permission for any f...
'Process a Shipment'
@staticmethod def inv_send_process():
request = current.request try: send_id = request.args[0] except: redirect(URL(f='send')) T = current.T auth = current.auth db = current.db s3db = current.s3db stable = db.inv_send session = current.session if (not auth.s3_has_permission('update', stable, record_id...
'Generate a PDF of a Waybill'
@staticmethod def inv_send_form(r, **attr):
db = current.db table = db.inv_send tracktable = db.inv_track_item table.date.readable = True record = db((table.id == r.id)).select(table.send_ref, limitby=(0, 1)).first() send_ref = record.send_ref tracktable.send_inv_item_id.readable = False tracktable.recv_inv_item_id.readable = Fals...
'Represent a Received Shipment'
@staticmethod def inv_recv_represent(id, row=None, show_link=True):
if row: id = row.id table = current.db.inv_recv elif (not id): return current.messages['NONE'] else: db = current.db table = db.inv_recv row = db((table.id == id)).select(table.date, table.recv_ref, table.from_site_id, table.organisation_id, limitby=(0, 1)).fi...
'When a inv recv record is created then create the recv_ref.'
@staticmethod def inv_recv_onaccept(form):
db = current.db rtable = db.inv_recv id = form.vars.id record = rtable[id] if (not record.recv_ref): code = current.s3db.supply_get_shipping_code(current.deployment_settings.get_inv_recv_shortname(), record.site_id, rtable.recv_ref) db((rtable.id == id)).update(recv_ref=code)
'Check that either organisation_id or to_site_id are filled according to the type'
@staticmethod def inv_send_onvalidation(form):
form_vars = form.vars if ((not form_vars.to_site_id) and (not form_vars.organisation_id)): error = (current.T('Please enter a %(site)s OR an Organization') % dict(site=current.deployment_settings.get_org_site_label())) errors = form.errors errors.to_site_id = error ...
'Check that either organisation_id or from_site_id are filled according to the type @ToDo: lookup the type values from s3cfg.py instead of hardcoding it'
@staticmethod def inv_recv_onvalidation(form):
form_vars = form.vars type = (form_vars.type and int(form_vars.type)) if ((type == 11) and (not form_vars.from_site_id)): form.errors.from_site_id = (current.T('Please enter a %(site)s') % dict(site=current.deployment_settings.get_org_site_label())) if ((type >= 32) and (not form_vars.o...
'Generate a PDF of a GRN (Goods Received Note)'
@staticmethod def inv_recv_form(r, **attr):
T = current.T db = current.db table = db.inv_recv track_table = db.inv_track_item table.date.readable = True table.site_id.readable = True track_table.recv_quantity.readable = True table.site_id.label = (T('By %(site)s') % dict(site=T(current.deployment_settings.get_inv_facility_label...
'Generate a PDF of a Donation certificate'
@staticmethod def inv_recv_donation_cert(r, **attr):
T = current.T db = current.db table = db.inv_recv table.date.readable = True table.type.readable = False field = table.site_id field.readable = True field.label = (T('By %(site)s') % dict(site=T(current.deployment_settings.get_inv_facility_label()))) field.represent = current.s3db...
'Represent for the Tall Out number, if show_link is True then it will generate a link to the pdf'
@staticmethod def inv_send_ref_represent(value, show_link=True):
if value: if show_link: db = current.db table = db.inv_send row = db((table.send_ref == value)).select(table.id, limitby=(0, 1)).first() if row: return A(value, _href=URL(c='inv', f='send', args=[row.id, 'form'])) else: ...
'Represent for the Goods Received Note if show_link is True then it will generate a link to the pdf'
@staticmethod def inv_recv_ref_represent(value, show_link=True):
if value: if show_link: db = current.db table = db.inv_recv recv_row = db((table.recv_ref == value)).select(table.id, limitby=(0, 1)).first() return A(value, _href=URL(c='inv', f='recv', args=[recv_row.id, 'form'])) else: return B(value) ...
'When a track item record is being created with a tracking number then the tracking number needs to be unique within the organisation. If the inv. item is coming out of a warehouse then the inv. item details need to be copied across (org, expiry etc) If the inv. item is being received then their might be a selected bin...
@staticmethod def inv_track_item_onvalidate(form):
form_vars = form.vars send_inv_item_id = form_vars.send_inv_item_id if send_inv_item_id: db = current.db itable = db.inv_inv_item query = (itable.id == send_inv_item_id) record = db(query).select(limitby=(0, 1)).first() form_vars.item_id = record.item_id form_...
'Check that we have sufficient inv_item in stock to build the kits'
@staticmethod def inv_kitting_onvalidate(form):
form_vars = form.vars item_id = form_vars.item_id item_pack_id = form_vars.item_pack_id quantity = form_vars.quantity site_id = form_vars.site_id db = current.db s3db = current.s3db ktable = s3db.supply_kit_item ptable = db.supply_item_pack iitable = s3db.inv_inv_item query =...
'Adjust the Inventory stocks reduce the components & increase the kits - picks items which have an earlier expiry_date where they have them, earlier purchase_data otherwise Provide a pick list to ensure that the right stock items are used to build the kits: inv_kitting_item'
@staticmethod def inv_kitting_onaccept(form):
form_vars = form.vars kitting_id = form_vars.id item_id = form_vars.item_id item_pack_id = form_vars.item_pack_id quantity = form_vars.quantity site_id = form_vars.site_id db = current.db s3db = current.s3db ktable = s3db.supply_kit_item ptable = db.supply_item_pack iitable =...
'When a track item record is created and it is linked to an inv_item then the inv_item quantity will be reduced.'
@staticmethod def inv_track_item_onaccept(form):
db = current.db s3db = current.s3db tracktable = db.inv_track_item inv_item_table = db.inv_inv_item stable = db.inv_send rtable = db.inv_recv siptable = db.supply_item_pack supply_item_add = s3db.supply_item_add form_vars = form.vars id = form_vars.id record = form.record ...
'A track item can only be deleted if the status is Preparing When a track item record is deleted and it is linked to an inv_item then the inv_item quantity will be reduced.'
@staticmethod def inv_track_item_deleting(id):
db = current.db s3db = current.s3db tracktable = db.inv_track_item inv_item_table = db.inv_inv_item ritable = s3db.req_req_item siptable = db.supply_item_pack record = tracktable[id] if (record.status != 1): return False if record.req_item_id: req_id = record.req_item...
'Display the Incidents on a Simile Timeline http://www.simile-widgets.org/wiki/Reference_Documentation_for_Timeline @ToDo: Play button http://www.simile-widgets.org/wiki/Timeline_Moving_the_Timeline_via_Javascript'
@staticmethod def inv_timeline(r, **attr):
if ((r.representation == 'html') and ((r.name == 'recv') or (r.name == 'send'))): T = current.T request = current.request response = current.response s3 = response.s3 s3.scripts.append(('/%s/static/scripts/simile/timeline/timeline-api.js' % request.application)) if s3...
'Make unadjusted quantities show up in bold'
@staticmethod def qnty_adj_repr(value):
if (value is None): return B(value) else: return value
'When an adjustment record is created and it is of type inventory then an adj_item record for each inv_inv_item in the site will be created. If needed, extra adj_item records can be created later.'
@staticmethod def inv_adj_onaccept(form):
id = form.vars.id db = current.db inv_item_table = db.inv_inv_item adjitemtable = db.inv_adj_item adjtable = db.inv_adj adj_rec = adjtable[id] if (adj_rec.category == 1): site_id = form.vars.site_id query = (((inv_item_table.site_id == site_id) & (inv_item_table.quantity > 0)...
'Represent an Inventory Adjustment'
@staticmethod def inv_adj_represent(id, row=None, show_link=True):
if row: table = current.db.inv_adj elif (not id): return current.messages['NONE'] else: db = current.db table = db.inv_adj row = db((table.id == id)).select(table.adjustment_date, table.adjuster_id, limitby=(0, 1)).first() try: repr = ('%s - %s' % (t...
'Represent an Inventory Adjustment Item'
@staticmethod def inv_adj_item_represent(id, row=None, show_link=True):
if row: table = current.db.inv_adj_item elif (not id): return current.messages['NONE'] else: db = current.db table = db.inv_adj_item row = db((table.id == id)).select(table.item_id, table.old_quantity, table.new_quantity, table.item_pack_id, limitby=(0, 1)).first() ...
'Constructor'
def __init__(self):
super(inv_InvItemRepresent, self).__init__(lookup='inv_inv_item')
'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 itable = s3db.inv_inv_item stable = s3db.supply_item left = stable.on((stable.id == itable.item_id)) if (len(values) == 1): query = (key == values[0]) else: query = key.belongs(values) rows = current.db(query).select(itable.id, stable.name, stable.um, itab...
'Represent a row @param row: the Row'
def represent_row(self, row):
itable = current.s3db.inv_inv_item iitem = row.inv_inv_item sitem = row.supply_item stringify = (lambda string: (string if string else '')) ctn = stringify(iitem.item_source_no) org = itable.owner_org_id.represent(iitem.owner_org_id) bin = stringify(iitem.bin) expires = iitem.expiry_date...
'Safe defaults if the module is disabled'
def defaults(self):
document_id = S3ReusableField('document_id', 'integer', readable=False, writable=False) return dict(doc_document_id=document_id)
'File representation'
@staticmethod def doc_file_represent(file):
if file: try: filename = current.db.doc_document.file.retrieve(file)[0] except IOError: return current.T('File not found') else: return A(filename, _href=URL(c='default', f='download', args=[file])) else: return current.messages['NONE']
'Import item de-duplication'
@staticmethod def document_duplicate(item):
data = item.data query = None file = data.get('file') if file: table = item.table query = (table.file == file) else: url = data.get('url') if url: table = item.table query = (table.url == url) if query: duplicate = current.db(query)...
'Form validation for both, documents and images'
@staticmethod def document_onvalidation(form, document=True):
form_vars = form.vars doc = form_vars.file if (doc is None): return if (not document): encoded_file = form_vars.get('imagecrop-data', None) if encoded_file: import base64 import uuid (metadata, encoded_file) = encoded_file.split(',') ...
'Build a full-text index'
@staticmethod def document_onaccept(form):
form_vars = form.vars doc = form_vars.file table = current.db.doc_document document = json.dumps(dict(filename=doc, name=table.file.retrieve(doc)[0], id=form_vars.id)) current.s3task.async('document_create_index', args=[document])
'Remove the full-text index'
@staticmethod def document_ondelete(row):
db = current.db table = db.doc_document record = db((table.id == row.id)).select(table.file, limitby=(0, 1)).first() document = json.dumps(dict(filename=record.file, id=row.id)) current.s3task.async('document_delete_index', args=[document])
'Represent a (key, value) as hypertext link. @param k: the key (doc_document.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: filename = row['doc_document.file'] url = row['doc_document.url'] except AttributeError: return v else: if filename: url = URL(c='default', f='download', args=filename) return A(v, _href=url) ...
'Return safe defaults in case the model has been deactivated.'
@staticmethod def defaults():
dummy = S3ReusableField('dummy_id', 'integer', readable=False, writable=False) return dict(doc_sitrep_id=(lambda **attr: dummy('sitrep_id')))
'Takes a filename and returns a category based on the file type. Categories: word, excel, powerpoint, flash, pdf, image, video, audio, archive, other.'
@staticmethod def doc_filetype(filename):
parts = os.path.splitext(filename) if (len(parts) < 2): return 'other' else: ext = parts[1][1:].lower() if (ext in ('png', 'jpg', 'jpeg', 'gif')): return 'image' elif (ext in ('avi', 'mp4', 'm4v', 'ogv', 'wmv', 'mpg', 'mpeg')): return 'video' e...
'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(budget_budget_id=(lambda **attr: dummy('budget_id')), budget_location_id=(lambda **attr: dummy('location_id')), budget_staff_id=(lambda **attr: dummy('staff_id')))
'Calculate totals for the budget'
@staticmethod def budget_budget_onaccept(form):
try: budget_entity_id = form.vars.budget_entity_id except: return budget_budget_totals(budget_entity_id) return
'Staff type has been updated => update totals of all budgets with this staff type'
@staticmethod def budget_staff_onaccept(form):
try: record_id = form.vars.id except: return linktable = current.s3db.budget_budget_staff budget_entity_id = linktable.budget_entity_id query = (linktable.staff_id == record_id) rows = current.db(query).select(budget_entity_id, groupby=budget_entity_id) for row in rows: ...
'Location has been updated => update totals of all budgets with staff at this location'
@staticmethod def budget_location_onaccept(form):
try: record_id = form.vars.id except: return linktable = current.s3db.budget_budget_staff budget_entity_id = linktable.budget_entity_id query = (linktable.location_id == record_id) rows = current.db(query).select(budget_entity_id, groupby=budget_entity_id) for row in rows: ...
'Budget staff has been updated => update totals of the budget'
@staticmethod def budget_budget_staff_onaccept(form):
try: record_id = form.vars.id except: return table = current.s3db.budget_budget_staff row = current.db((table.id == record_id)).select(table.budget_entity_id, limitby=(0, 1)).first() if row: budget_budget_totals(row.budget_entity_id) return
'Budget staff has been deleted => update totals of the budget'
@staticmethod def budget_budget_staff_ondelete(row):
db = current.db linktable = current.s3db.budget_budget_staff try: record_id = row.id except: return link = db((linktable.id == record_id)).select(linktable.deleted_fk, limitby=(0, 1)).first() if link: deleted_fk = json.loads(link.deleted_fk) budget_entity_id = del...
'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(budget_kit_id=(lambda **attr: dummy('kit_id')), budget_item_id=(lambda **attr: dummy('item_id')))
'Calculate totals for the kit'
@staticmethod def budget_kit_onaccept(form):
try: kit_id = form.vars.id except: return budget_kit_totals(kit_id) return
'Calculate totals for all kits and bundles with this item'
@staticmethod def budget_item_onaccept(form):
db = current.db s3db = current.s3db try: item_id = form.vars.id except: return linktable = s3db.budget_kit_item kit_id = linktable.kit_id rows = db((linktable.item_id == item_id)).select(kit_id, groupby=kit_id) kit_ids = set() for row in rows: kit_id = row.kit...
'Kit item has been updated => update totals of the kit'
@staticmethod def budget_kit_item_onaccept(form):
try: record_id = form.vars.id except: return table = current.s3db.budget_kit_item row = current.db((table.id == record_id)).select(table.kit_id, limitby=(0, 1)).first() if row: budget_kit_totals(row.kit_id) return
'Kit item has been deleted => update totals of the kit'
@staticmethod def budget_kit_item_ondelete(row):
db = current.db linktable = current.s3db.budget_kit_item try: record_id = row.id except: return link = db((linktable.id == record_id)).select(linktable.deleted_fk, limitby=(0, 1)).first() if link: deleted_fk = json.loads(link.deleted_fk) kit_id = deleted_fk.get('k...
'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(budget_bundle_id=(lambda **attr: dummy('bundle_id')))
'Calculate totals for the bundle'
@staticmethod def budget_bundle_onaccept(form):
try: bundle_id = form.vars.id except: return budget_bundle_totals(bundle_id) return
'Bundle item has been updated => update totals of the bundle'
@staticmethod def budget_bundle_item_onaccept(form):
try: record_id = form.vars.id except: return table = current.s3db.budget_bundle_item row = current.db((table.id == record_id)).select(table.bundle_id, limitby=(0, 1)).first() if row: budget_bundle_totals(row.bundle_id) return
'Bundle item has been deleted => update totals of the bundle'
@staticmethod def budget_bundle_item_ondelete(row):
db = current.db linktable = current.s3db.budget_bundle_item try: record_id = row.id except: return link = db((linktable.id == record_id)).select(linktable.deleted_fk, limitby=(0, 1)).first() if link: deleted_fk = json.loads(link.deleted_fk) bundle_id = deleted_fk....
'Bundle kit has been updated => update totals of the bundle'
@staticmethod def budget_bundle_kit_onaccept(form):
try: record_id = form.vars.id except: return table = current.s3db.budget_bundle_kit row = current.db((table.id == record_id)).select(table.bundle_id, limitby=(0, 1)).first() if row: budget_bundle_totals(row.bundle_id) return
'Bundle kit has been deleted => update totals of the bundle'
@staticmethod def budget_bundle_kit_ondelete(row):
db = current.db linktable = current.s3db.budget_bundle_kit try: record_id = row.id except: return link = db((linktable.id == record_id)).select(linktable.deleted_fk, limitby=(0, 1)).first() if link: deleted_fk = json.loads(link.deleted_fk) bundle_id = deleted_fk.g...
'Budget bundle has been updated => update totals of the budget'
@staticmethod def budget_budget_bundle_onaccept(form):
try: record_id = form.vars.id except: return table = current.s3db.budget_budget_bundle row = current.db((table.id == record_id)).select(table.budget_entity_id, limitby=(0, 1)).first() if row: budget_budget_totals(row.budget_entity_id) return
'Budget bundle has been deleted => update totals of the budget'
@staticmethod def budget_budget_bundle_ondelete(row):
db = current.db linktable = current.s3db.budget_budget_bundle try: record_id = row.id except: return link = db((linktable.id == record_id)).select(linktable.deleted_fk, limitby=(0, 1)).first() if link: deleted_fk = json.loads(link.deleted_fk) budget_entity_id = de...
'Safe defaults for model-global names in case module is disabled'
def defaults(self):
return {}
'Import item de-duplication @todo: additionally have an onaccept sanitizing overlapping allocations? (may be too simple, though)'
@staticmethod def budget_allocation_duplicate(item):
data = item.data budget_entity_id = data.get('budget_entity_id') cost_item_id = data.get('cost_item_id') if (budget_entity_id and cost_item_id): table = item.table start_date = data.get('start_date') end_date = data.get('end_date') query = (((table.budget_entity_id == bud...
'Handle Updates of entries to reset the hidden start_date'
@staticmethod def budget_monitoring_onaccept(form):
db = current.db table = current.s3db.budget_monitoring record_id = form.vars.id record = db((table.id == record_id)).select(table.budget_entity_id, table.start_date, table.end_date, limitby=(0, 1)).first() if (not record): s3_debug("Cannot find Budget Monitoring record (no ...
'Don\'t allow total Planned to exceed Total Budget'
@staticmethod def budget_monitoring_onvalidation(form):
db = current.db s3db = current.s3db mtable = s3db.budget_monitoring record_id = form.record_id record = db((mtable.id == record_id)).select(mtable.budget_entity_id, limitby=(0, 1)).first() if (not record): s3_debug("Cannot find Budget Monitoring record (no record for...
'Virtual Field to show the percentage used of the Budget'
@staticmethod def budget_monitoring_percentage(row):
if hasattr(row, 'budget_monitoring'): row = row.budget_monitoring if hasattr(row, 'planned'): planned = row.planned if (planned == 0.0): return current.messages['NONE'] else: planned = None if hasattr(row, 'value'): actual = row.value else: ...
'Constructor'
def __init__(self, show_link=False):
super(budget_CostItemRepresent, self).__init__(lookup='budget_cost_item', key='cost_item_id', show_link=show_link) s3db = current.s3db self.represent = {'asset_id': s3db.asset_AssetRepresent(show_link=False), 'site_id': s3db.org_SiteRepresent(show_link=False), 'human_resource_id': s3db.hrm_HumanResourceRepr...
'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 = {'event_asset': ['incident_id', 'asset_id'], 'event_site': ['incident_id', 'site_id'], 'event_human_resource': ['incident_id', 'human_resource_id']} etable = s3db.budget_cost_item rows = db(key.belongs(values)).select(key, etable.instance_type) ...
'Represent a row @param row: the Row'
def represent_row(self, row):
s3db = current.s3db cost_item = row.budget_cost_item instance_type = cost_item.instance_type item = object.__getattribute__(row, instance_type) if (instance_type == 'event_asset'): table = s3db.event_asset repr_str = ('%s - %s' % (table.incident_id.represent(item.incident_id), ...
'Update body presence log'
@staticmethod def body_onaccept(form):
db = current.db table = db.dvi_body body = db((table.id == form.vars.id)).select(table.uuid, table.location_id, table.track_id, table.date_of_recovery, limitby=(0, 1)).first() if (body and body.location_id): tracker = S3Tracker() tracker(record=body).set_location(body.location_id, timest...
'Constructor'
def __init__(self):
settings = current.deployment_settings log_level = settings.get_log_level() if (log_level is None): self.critical = self.error = self.warning = self.info = self.debug = self.ignore self.log_level = 100 else: try: level = getattr(logging, log_level.upper()) exc...
'Set up current.log'
@classmethod def setup(cls):
if hasattr(current, 'log'): return current.log = cls() return
'Configure output handlers'
def configure_logger(self):
if hasattr(current, 'log'): return settings = current.deployment_settings console = settings.get_log_console() logfile = settings.get_log_logfile() if ((not console) and (not logfile)): self.critical = self.error = self.warning = self.info = self.debug = self.ignore return ...
'Dummy to ignore messages below minimum severity level'
@staticmethod def ignore(message, value=None):
return
'Return a recording facility for log messages'
@staticmethod def recorder():
return S3LogRecorder()
'Log a message @param severity: the severity of the message @param message: the message @param value: message suffix (optional)'
@staticmethod def _log(severity, message, value=None):
logger = logging.getLogger(__name__) logger.propagate = False msg = (('%s: %s' % (message, value)) if value else message) extra = {'caller': 'S3LOG'} if current.deployment_settings.get_log_caller_info(): caller = logger.findCaller() if caller: extra = {'caller': ('(%s ...
'Log a critical message (highest severity level), called via current.log.critical() @param message: the message @param value: message suffix (optional)'
@classmethod def _critical(cls, message, value=None):
cls._log(logging.CRITICAL, message, value=value)
'Log an error message, called via current.log.error() @param message: the message @param value: message suffix (optional)'
@classmethod def _error(cls, message, value=None):
cls._log(logging.ERROR, message, value=value)
'Log a warning message, called via current.log.warning() @param message: the message @param value: message suffix (optional)'
@classmethod def _warning(cls, message, value=None):
cls._log(logging.WARNING, message, value=value)
'Log an general info message, called via current.log.info() @param message: the message @param value: message suffix (optional)'
@classmethod def _info(cls, message, value=None):
cls._log(logging.INFO, message, value=value)
'Log a detailed debug message (lowest severity level), called via current.log.debug() @param message: the message @param value: message suffix (optional)'
@classmethod def _debug(cls, message, value=None):
cls._log(logging.DEBUG, message, value=value)
'Start recording S3Log messages'
def listen(self):
if (self.handler is not None): return strbuf = self.strbuf if (strbuf is None): try: from cStringIO import StringIO except: from StringIO import StringIO strbuf = StringIO() handler = logging.StreamHandler(strbuf) logger = logging.getLogger(__n...
'Read out recorded S3Log messages'
def read(self):
strbuf = self.strbuf if (strbuf is None): return '' handler = self.handler if (handler is not None): handler.flush() return strbuf.getvalue()
'Stop recording S3Log messages (and return the messages)'
def stop(self):
handler = self.handler if (handler is not None): logger = logging.getLogger(__name__) logger.removeHandler(handler) handler.close() self.handler = None strbuf = self.strbuf if (strbuf is not None): return strbuf.getvalue() else: return ''
'Clear the messages buffer'
def clear(self):
if (self.handler is not None): on = True self.stop() else: on = False strbuf = self.strbuf if (strbuf is not None): strbuf.close() self.strbuf = None if on: self.listen()
'Allow adding validation on each payload key by defining `validate_{key_name}`'
def validate(self, options):
for (key, value) in options.items(): validate_method = getattr(self, ('validate_%s' % key), None) if validate_method: validate_method(value)
'api_key : google api key url: url of gcm service. proxy: can be string "http://host:port" or dict {\'https\':\'host:port\'} timeout: timeout for every HTTP request, see \'requests\' documentation for possible values.'
def __init__(self, api_key, proxy=None, timeout=None, debug=False):
self.api_key = api_key self.url = GCM_URL if isinstance(proxy, str): protocol = self.url.split(':')[0] self.proxy = {protocol: proxy} else: self.proxy = proxy self.timeout = timeout self.debug = debug self.retry_after = None if self.debug: GCM.enable_loggi...
'Helper for quickly adding a StreamHandler to the logger. Useful for debugging. :param handler: :param level: :return: the handler after adding it'
@staticmethod def enable_logging(level=logging.DEBUG, handler=None):
if (not handler): if (GCM.logging_handler is None): GCM.logging_handler = logging.StreamHandler() GCM.logging_handler.setFormatter(logging.Formatter('[%(asctime)s - %(levelname)s - %(filename)s:%(lineno)s - %(funcName)s()] %(message)s')) handler = GCM.log...
'Construct the dictionary mapping of parameters. Encodes the dictionary into JSON if for json requests. :return constructed dict or JSON payload :raises GCMInvalidTtlException: if time_to_live is invalid'
@staticmethod def construct_payload(**kwargs):
is_json = kwargs.pop('is_json', True) if is_json: if (('topic' not in kwargs) and ('registration_ids' not in kwargs)): raise GCMMissingRegistrationException('Missing registration_ids or topic') elif (('topic' in kwargs) and ('registration_ids' in kwargs)): raise ...
'Makes a HTTP request to GCM servers with the constructed payload :param data: return value from construct_payload method :param session: requests.Session object to use for request (optional) :raises GCMMalformedJsonException: if malformed JSON request found :raises GCMAuthenticationException: if there was a problem wi...
def make_request(self, data, is_json=True, session=None):
headers = {'Authorization': ('key=%s' % self.api_key)} if is_json: headers['Content-Type'] = 'application/json' else: headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8' GCM.log('Request URL: {0}', self.url) GCM.log('Request headers: {0}', headers)...
'Makes a plaintext request to GCM servers :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc'
def plaintext_request(self, **kwargs):
if ('registration_id' not in kwargs): raise GCMMissingRegistrationException('Missing registration_id') elif (not kwargs['registration_id']): raise GCMMissingRegistrationException('Empty registration_id') kwargs['is_json'] = False retries = kwargs.pop('retries', 5) session = kwa...
'Makes a JSON request to GCM servers :param kwargs: dict mapping of key-value pairs of parameters :return dict of response body from Google including multicast_id, success, failure, canonical_ids, etc'
def json_request(self, **kwargs):
if ('registration_ids' not in kwargs): raise GCMMissingRegistrationException('Missing registration_ids') elif (not kwargs['registration_ids']): raise GCMMissingRegistrationException('Empty registration_ids') args = dict(**kwargs) retries = args.pop('retries', 5) session = args....
'Publish Topic Messaging to GCM servers Ref: https://developers.google.com/cloud-messaging/topic-messaging :param kwargs: dict mapping of key-value pairs of parameters :return message_id :raises GCMInvalidInputException: if the topic is empty'
def send_topic_message(self, **kwargs):
if ('topic' not in kwargs): raise GCMInvalidInputException('Topic name missing!') elif (not kwargs['topic']): raise GCMInvalidInputException('Topic name cannot be empty!') retries = kwargs.pop('retries', 5) session = kwargs.pop('session', None) payload = self.constr...
'Tests for Send-Receive - Receive Workflow'
def test_inv003_send_receive_items(self):
user = 'admin' method = 'search' send_data = [('site_id', 'Timor-Leste Red Cross Society (CVTL) National Warehouse (Warehouse)'), ('type', 'Internal Shipment'), ('to_site_id', 'Lospalos Warehouse (Warehouse)'), ('sender_id', 'Beatriz de Carvalho'), ('recipient_id', 'Lilia...
'Test to send a shipment and confirm that it is receive outside of the system'
def test_inv021_send_and_confirm(self):
user = 'admin' method = 'search' send_data = [('site_id', 'Timor-Leste Red Cross Society (CVTL) National Warehouse (Warehouse)'), ('type', 'Internal Shipment'), ('to_site_id', 'Lori (Facility)'), ('sender_id', 'Beatriz de Carvalho')] item_data = [[('send_inv_item_id', 'B...
'@case: warehouse_01 @description: Search Warehouse - Simple Search'
def test_warehouse_01_search_name(self):
w = current.s3db['inv_warehouse'] key = 'na' dbRowCount = current.db(((w.deleted != 'T') & w.name.like((('%' + key) + '%')))).count() self.search(self.search.advanced_form, True, ({'id': 'warehouse_search_simple', 'value': key},), dbRowCount, manual_check=functools.partial(_kwsearch, keyword=key, items=...
'@case: warehouse_02 @description: Search Warehouse - Advanced Search by Organization'
def test_warehouse_02_search_by_Organization(self):
w = current.s3db['inv_warehouse'] o = current.s3db['org_organisation'] key = 'Timor-Leste Red Cross Society (Cruz Vermelha de Timor-Leste)' dbRowCount = current.db((((w.deleted != 'T') & (w.organisation_id == o.id)) & (o.name == key))).count() self.search(self.search.advanced_fo...
'@case: warehouse_03 @description: Search Warehouse - Advanced Search by District'
def test_warehouse_03_search_by_District(self):
w = current.s3db['inv_warehouse'] l = current.s3db['gis_location'] key = 'Viqueque' dbRowCount = current.db((((w.deleted != 'T') & (w.location_id == l.id)) & (l.L2 == key))).count() self.search(self.search.advanced_form, True, ({'name': 'warehouse_search_location', 'label': key, 'value': True},), db...
'@case: INV005 @description: Create an Item @TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE @Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing'
def test_inv005_create_item(self):
print '\n' self.login(account='admin', nexturl='asset/item/create') self.browser.find_element_by_id('supply_item_um').clear() self.create('supply_item', [('name', 'Soup'), ('um', 'litre'), ('item_category_id', 'Standard > Food'), ('model', 'Tomato'), ('year', '2012'), ('comments', 'This is a...
'Create a Warehouse @param items: Warehouse(s) to create from the data @TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE @Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing'
def test_inv004_create_warehouse(self, items=[0]):
tablename = 'inv_warehouse' url = 'inv/warehouse/create' account = 'admin' data = [[('name', 'Bucharest RFAAT Central Warehouse (Test)'), ('code', '12345679'), ('organisation_id', 'International Federation of Red Cross and Red Crescent Societies'), ('comments', 'This ...
'@case: INV @description: Functions which runs specific workflows for Inventory tes @TestDoc: https://docs.google.com/spreadsheet/ccc?key=0AmB3hMcgB-3idG1XNGhhRG9QWF81dUlKLXpJaFlCMFE @Test Wiki: http://eden.sahanafoundation.org/wiki/DeveloperGuidelines/Testing'
def send(self, user, data):
print '\n' '\n Helper method to add a inv_send record by the given user\n ' self.login(account=user, nexturl='inv/send/create') table = 'inv_send' result = self.create(table, data) s3_debu...
'Helper method to add a track item to the inv_send with the given send_id by the given user'
def track_send_item(self, user, send_id, data, removed=True):
time.sleep(2) self.login(account=user, nexturl=('inv/send/%s/track_item' % send_id)) try: add_btn = self.browser.find_element_by_id('show-add-btn') if add_btn.is_displayed(): add_btn.click() except: pass table = 'inv_track_item' result = self.create(table, dat...