def organisation(): """ Function to handle pagination for the org list on the homepage """ from s3.s3utils import S3DataTable resource = s3db.resource("org_organisation") totalrows = resource.count() table = resource.table list_fields = ["id", "name"] limit = int(request.get_vars["iDisplayLength"] ) if request.extension == "aadata" else 1 rfields = resource.resolve_selectors(list_fields)[0] (orderby, filter) = S3DataTable.getControlData(rfields, request.vars) resource.add_filter(filter) filteredrows = resource.count() if isinstance(orderby, bool): orderby = table.name rows = resource.select( list_fields, orderby=orderby, start=0, limit=limit, ) data = resource.extract( rows, list_fields, represent=True, ) dt = S3DataTable(rfields, data) dt.defaultActionButtons(resource) s3.no_formats = True if request.extension == "html": items = dt.html( totalrows, filteredrows, "org_list_1", dt_displayLength=10, dt_ajax_url=URL( c="default", f="organisation", extension="aadata", vars={"id": "org_list_1"}, ), ) elif request.extension.lower() == "aadata": limit = resource.count() if "sEcho" in request.vars: echo = int(request.vars.sEcho) else: echo = None items = dt.json(totalrows, filteredrows, "org_list_1", echo) else: raise HTTP(501, s3mgr.ERROR.BAD_FORMAT) return items
def testSqlTableJSON(self): """ render to a JSON Object """ dt = S3DataTable(self.rfields, self.data) actual = dt.json("list_1", 1, 14, 14) # @todo: Need to add a test for the format returned #print actual dt = S3DataTable(self.rfields, self.data, start=3, limit=5) actual = dt.json("list_1", 1, 14, 14)
def testSqlTableHTML(self): """ render to an HTML TABLE """ dt = S3DataTable(self.rfields, self.data) actual = dt.html(14, 14) # @todo: Need to add a test for the format returned #print actual dt = S3DataTable(self.rfields, self.data, start=3, limit=5) actual = dt.html(14, 14)
def get_resource_flowable(self, resource, doc): # get a list of fields, if the list_fields attribute is provided # then use that to extract the fields that are required, otherwise # use the list of readable fields. from s3.s3utils import S3DataTable if not self.list_fields: self.list_fields = [] fields = resource.readable_fields() for field in fields: if field.type == "id": continue if self.pdf_hide_comments and field.name == "comments": continue self.list_fields.append(field.name) rfields = resource.resolve_selectors(self.list_fields)[0] (orderby, filter) = S3DataTable.getControlData(rfields, current.request.vars) resource.add_filter(filter) current.manager.ROWSPERPAGE = None # needed to get all the data rows = resource._select(self.list_fields, orderby=orderby) data = resource._extract(rows, self.list_fields, represent=True) # Now generate the PDF table pdf_table = S3PDFTable( doc, rfields, data, groupby=self.pdf_groupby, autogrow=self.table_autogrow, body_height=doc.body_height ).build() return pdf_table
def organisation(): """ Function to handle pagination for the org list on the homepage """ from s3.s3utils import S3DataTable resource = s3db.resource("org_organisation") totalrows = resource.count() table = resource.table list_fields = ["id", "name"] limit = int(request.get_vars["iDisplayLength"]) if request.extension == "aaData" else 1 rfields = resource.resolve_selectors(list_fields)[0] (orderby, filter) = S3DataTable.getControlData(rfields, request.vars) resource.add_filter(filter) filteredrows = resource.count() if isinstance(orderby, bool): orderby = table.name rows = resource.select(list_fields, orderby=orderby, start=0, limit=limit, ) data = resource.extract(rows, list_fields, represent=True, ) dt = S3DataTable(rfields, data) dt.defaultActionButtons(resource) s3.no_formats = True if request.extension == "html": items = dt.html(totalrows, filteredrows, "org_list_1", dt_displayLength=10, dt_ajax_url=URL(c="default", f="organisation", extension="aaData", vars={"id": "org_list_1"}, ), ) elif request.extension.lower() == "aadata": limit = resource.count() if "sEcho" in request.vars: echo = int(request.vars.sEcho) else: echo = None items = dt.json(totalrows, filteredrows, "supply_list_1", echo) else: raise HTTP(501, s3mgr.ERROR.BAD_FORMAT) return items
def extractResource(self, resource, list_fields, report_groupby): """ Extract the items from the resource @param resource: the resource @param list_fields: fields to include in list views @param report_groupby: a Field object of the field to group the records by """ from s3.s3utils import S3DataTable s3 = current.response.s3 # Use the title_list CRUD string for the title name = "title_list" tablename = resource.tablename crud_strings = s3.crud_strings.get(tablename, s3.crud_strings) not_found = s3.crud_strings.get(name, current.request.function) title = str(crud_strings.get(name, not_found)) rfields = resource.resolve_selectors(list_fields)[0] types = [] for f in rfields: if f.show: if f.field: types.append(f.field.type) else: # Virtual Field types.append("string") lfields = [] heading = {} for field in rfields: selector = "%s.%s" % (field.tname, field.fname) lfields.append(selector) heading[selector] = (field.label) (orderby, filter) = S3DataTable.getControlData(rfields, current.request.vars) resource.add_filter(filter) current.manager.ROWSPERPAGE = None # needed to get all the data rows = resource.select( list_fields, orderby=orderby, ) items = resource.extract( rows, list_fields, represent=True, ) return (title, types, lfields, heading, items)
def extractResource(self, resource, list_fields, report_groupby): """ Extract the items from the resource @param resource: the resource @param list_fields: fields to include in list views @param report_groupby: a Field object of the field to group the records by """ from s3.s3utils import S3DataTable s3 = current.response.s3 # Use the title_list CRUD string for the title name = "title_list" tablename = resource.tablename crud_strings = s3.crud_strings.get(tablename, s3.crud_strings) not_found = s3.crud_strings.get(name, current.request.function) title = str(crud_strings.get(name, not_found)) rfields = resource.resolve_selectors(list_fields)[0] types = [] for f in rfields: if f.show: if f.field: types.append(f.field.type) else: # Virtual Field types.append("string") lfields = [] heading = {} for field in rfields: if field.show: selector = "%s.%s" % (field.tname, field.fname) lfields.append(selector) heading[selector] = (field.label) (orderby, filter) = S3DataTable.getControlData(rfields, current.request.vars) resource.add_filter(filter) current.manager.ROWSPERPAGE = None # needed to get all the data rows = resource.select(list_fields, orderby=orderby, ) items = resource.extract(rows, list_fields, represent=True, ) return (title, types, lfields, heading, items)
def testInitOrderby(self): """ test to check that the orderby property is set up correctly from different types of input. """ table = self.resource.table dt = S3DataTable(self.rfields, self.data) expected = [[1, "asc"]] actual = dt.orderby self.assertEqual(expected, actual, "1) %s not equal to %s" % (expected, actual)) dt = S3DataTable(self.rfields, self.data, orderby=table.name) expected = [[3, "asc"]] actual = dt.orderby self.assertEqual(expected, actual, "2) %s not equal to %s" % (expected, actual)) dt = S3DataTable(self.rfields, self.data, orderby=~table.name) expected = [[3, "desc"]] actual = dt.orderby self.assertEqual(expected, actual, "3) %s not equal to %s" % (expected, actual)) dt = S3DataTable(self.rfields, self.data, orderby=table.office_type_id | table.name) expected = [[4, "asc"], [3, "asc"]] actual = dt.orderby self.assertEqual(expected, actual, "4) %s not equal to %s" % (expected, actual)) dt = S3DataTable(self.rfields, self.data, orderby=~table.office_type_id | table.name) expected = [[4, "desc"], [3, "asc"]] actual = dt.orderby self.assertEqual(expected, actual, "5) %s not equal to %s" % (expected, actual)) otable = current.s3db.org_organisation dt = S3DataTable(self.rfields, self.data, orderby=otable.name | ~table.office_type_id | table.name) expected = [[1, "asc"], [4, "desc"], [3, "asc"]] actual = dt.orderby self.assertEqual(expected, actual, "6) %s not equal to %s" % (expected, actual))
def get_resource_flowable(self, resource, doc): """ Get a list of fields, if the list_fields attribute is provided then use that to extract the fields that are required, otherwise use the list of readable fields. """ from s3.s3utils import S3DataTable if not self.list_fields: self.list_fields = [] fields = resource.readable_fields() for field in fields: if field.type == "id": continue if self.pdf_hide_comments and field.name == "comments": continue self.list_fields.append(field.name) rfields = resource.resolve_selectors(self.list_fields)[0] (orderby, filter) = S3DataTable.getControlData(rfields, current.request.vars) resource.add_filter(filter) current.manager.ROWSPERPAGE = None # needed to get all the data rows = resource.select( self.list_fields, orderby=orderby, ) data = resource.extract( rows, self.list_fields, represent=True, ) # Now generate the PDF table pdf_table = S3PDFTable( doc, rfields, data, groupby=self.pdf_groupby, autogrow=self.table_autogrow, body_height=doc.body_height, ).build() return pdf_table
def reportDataTable(request): """ Helper function to return the dataTable that uses the selected filter options """ from s3.s3utils import S3DataTable doctable = s3db.doc_source_entity #----------------------------------------------------------------- # Set up custom represents #----------------------------------------------------------------- def location_repr(id): """ Return the location name (commune) wrapped in a span """ if not id: repr_text = current.messages.NONE else: db = current.db table = db.gis_location row = db(table.id == id).select(table.name, limitby=(0, 1)).first() if not row: repr_text = current.messages.UNKNOWN_OPT repr_text = row.name return SPAN(repr_text, _class="communeCell") def submitted_repr(id): """ Return the initial of the first name and the complete last name """ if not id: repr_text = current.messages.NONE else: db = current.db table = db.pr_person row = db(table.id == id).select(table.first_name, table.last_name, limitby=(0, 1)).first() if row: repr_text = "%s. %s" % (row.first_name[0], row.last_name) else: repr_text = current.messages.UNKNOWN_OPT return repr_text def approved_repr(id): """ Return the initials of the first and the last name """ if not id: repr_text = T("Approval pending") else: db = current.db table = db.pr_person row = db(table.id == id).select(table.first_name, table.last_name, limitby=(0, 1)).first() if row: repr_text = T("Approved by %(first_initial)s.%(last_initial)s") % \ dict(first_initial = row.first_name[0], last_initial = row.last_name[0]) else: repr_text = current.messages.UNKNOWN_OPT return repr_text def action_repr(id): """ Return the initials of the first and the last name """ if not id: repr_text = current.messages.NONE else: repr_text = A(T("Review"), _class = "reviewButton", _href = "#reports?id=%s" % id ) repr_text.append(A(T("Close"), _class = "closeReviewButton", _href = "#reports" )) return repr_text doctable.location_id.represent = location_repr doctable.created_by.represent = submitted_repr doctable.modified_by.represent = approved_repr doctable.id.represent = action_repr filter_request = request.post_vars filter = reportFilter(filter_request) resource = s3db.resource("doc_source_entity") resource.add_filter(filter) filteredrows = resource.count() ############################################################# # Note if list_fields is changed here then it also needs # to be changed in index, where the table is initialised ############################################################# list_fields = [(T("Action"), "id"), (T("Date"), "date"), (T("Commune Name"), "location_id"), "location_id$L3", "status", (T("Type"), "source_type_id"), (T("Submitted by"), "created_by"), (T("Status"), "modified_by"), ] rows = resource.select(list_fields, orderby=~doctable.date, start=0, limit=filteredrows, ) data = resource.extract(rows, list_fields, represent=True, ) type_totals = {} for item in data: status = item["doc_source_entity.status"] if status in type_totals: type_totals[status] += 1 else: type_totals[status] = 1 rfields = resource.resolve_selectors(list_fields)[0] dt = S3DataTable(rfields, data) dt.defaultActionButtons(resource) if request.extension == "html": report = dt.html(#filteredrows, #filteredrows, "report", dt_pagination = "false", dt_bFilter = "false", dt_sDom = "t", dt_group = [3, 4], dt_group_totals = [type_totals], dt_ajax_url = URL(c="vulnerability", f="report", extension="aaData", vars={"id": "report"}, ), dt_action_col = -1, dt_shrink_groups = "accordion" ) else: report = dt.json("report", int(request.vars.sEcho), filteredrows, filteredrows, dt_group_totals=[type_totals], ) return str(report)
def index(): """ Module Home Page: Map """ # This module uses it's own Theme settings.base.theme = "Vulnerability" # Additional scripts append = s3.scripts.append append("/%s/static/scripts/yepnope.1.5.4-min.js" % appname) if s3.debug: append("/%s/static/scripts/jquery.ui.selectmenu.js" % appname) append("/%s/static/scripts/TypeHelpers.js" % appname) append("/%s/static/scripts/S3/s3.vulnerability.js" % appname) append("/%s/static/scripts/S3/s3.dataTables.js" % appname) append("/%s/static/scripts/jquery.dataTables.js" % appname) append("/%s/static/scripts/jquery.dataTables.fnSetFilteringDelay.js" % appname) else: append("/%s/static/scripts/S3/s3.vulnerability.min.js" % appname) append("/%s/static/scripts/S3/dataTables.min.js" % appname) js_global = [] append = js_global.append # Get the L0 hdata & summary vdata hdata, vdata = l0() # Get the default location to open the map bounds = None root_org = auth.root_org() start = False if root_org: otable = s3db.org_organisation ttable = s3db.gis_location_tag gtable = s3db.gis_location query = (otable.id == root_org) & \ (ttable.tag == "ISO2") & \ (ttable.value == otable.country) r = db(query).select(ttable.location_id, limitby=(0, 1)).first() if r and r.location_id in countries: start = True append('''start=%s''' % r.location_id) # Add the child L1 summary vdata l1(r.location_id, vdata) if not start: append('''start=""''') dumps = json.dumps script = ''' hdata=%s vdata=%s ''' % (dumps(hdata), dumps(vdata)) append(script) # Get the list of indicators itable = s3db.vulnerability_indicator query = (itable.deleted == False) rows = db(query).select(itable.name, itable.description, itable.parameter_id, orderby=itable.name) indicators = OrderedDict() for row in rows: indicators[row.parameter_id] = dict(n=row.name, d=row.description) append('''idata=%s''' % json.dumps(indicators)) s3.js_global.append("".join(js_global)) from s3.s3utils import S3DataTable resource = s3db.resource("doc_source_entity") list_fields = ["id", "date", "location_id", "location_id$L3", "status", "source_type_id", "created_by", "modified_by", ] rfields = resource.resolve_selectors(list_fields)[0] dt = S3DataTable(rfields, []) report = dt.html(#filteredrows, #filteredrows, "report", dt_pagination="false", dt_bFilter="false", dt_sDom="t", dt_group=[4,3], dt_group_totals=[], dt_ajax_url=URL(c="vulnerability", f="report", extension="aaData", vars={"id": "report"}, ), dt_action_col = -1, dt_shrink_groups = "accordion" ) s3.report = report response.view = "vulnerability/map.html" return dict()
def reportDataTable(request): """ Helper function to return the dataTable that uses the selected filter options """ from s3.s3utils import S3DataTable sgtable = s3db.stats_group #----------------------------------------------------------------- # Set up custom represents #----------------------------------------------------------------- def location_repr(id): """ Return the location name (commune) wrapped in a span """ if not id: repr_text = current.messages.NONE else: table = db.gis_location row = db(table.id == id).select(table.name, limitby=(0, 1)).first() if not row: repr_text = current.messages.UNKNOWN_OPT repr_text = row.name return SPAN(repr_text, _class="communeCell") def submitted_repr(id): """ Return the initial of the first name and the complete last name """ if not id: repr_text = current.messages.NONE else: table = db.pr_person row = db(table.id == id).select(table.first_name, table.last_name, limitby=(0, 1)).first() if row: repr_text = "%s. %s" % (row.first_name[0], row.last_name) else: repr_text = current.messages.UNKNOWN_OPT return repr_text def approved_repr(id): """ Return the initials of the first and the last name """ if not id: repr_text = T("Approval pending") else: table = db.pr_person row = db(table.id == id).select(table.first_name, table.last_name, limitby=(0, 1)).first() if row: repr_text = T("Approved by %(first_initial)s.%(last_initial)s") % \ dict(first_initial = row.first_name[0], last_initial = row.last_name[0]) else: repr_text = current.messages.UNKNOWN_OPT return repr_text def action_repr(id): """ Return the action button for this row """ if not id: repr_text = current.messages.NONE else: row = s3db.stats_group[id] if row.approved_by: repr_text = A(T("View"), _id=id, _class="viewButton", _href="javascript:viewReportDetails(%s);" % id) else: repr_text = A(T("Review"), _id=id, _class="reviewButton", _href="javascript:showReportDetails(%s);" % id) repr_text.append( A(T("Close"), _class="closeReviewButton", _href="javascript:hideReportDetails(%s);" % id)) return repr_text sgtable.location_id.represent = location_repr sgtable.created_by.represent = submitted_repr sgtable.approved_by.represent = approved_repr sgtable.id.represent = action_repr filter_request = request.post_vars filter = reportFilter(filter_request) # Ensure that we also get the records awaiting for approval resource = s3db.resource("stats_group", unapproved=True) resource.add_filter(filter) filteredrows = resource.count() ############################################################# # Note if list_fields is changed here then it also needs # to be changed in index, where the table is initialised ############################################################# list_fields = [ (T("Action"), "id"), (T("Date"), "date"), (T("Commune Name"), "location_id"), "location_id$L3", "group", (T("Type"), "group_type_id"), (T("Submitted by"), "created_by"), (T("Status"), "approved_by"), ] if filteredrows > 0: rows = resource.select( list_fields, orderby=~sgtable.date, start=0, limit=filteredrows, ) data = resource.extract( rows, list_fields, represent=True, ) # The types are fixed and will always be displayed (even if empty) type_totals = {"Approval pending": 0, "VCA Report": 0, "Report": 0} # Calculate the report group totals location_totals = {} for item in data: # Collect the type totals group = item["stats_group.group"] if not group: group = "Report" type_totals[group] += 1 # Collect the L3 sub totals loc_code = "%s_%s" % (group, item["gis_location.L3"]) if loc_code in location_totals: location_totals[loc_code] += 1 else: location_totals[loc_code] = 1 rfields = resource.resolve_selectors(list_fields)[0] dt = S3DataTable(rfields, data) dt.defaultActionButtons(resource) if request.extension == "html": level_1_titles = [ ["Approval pending", T("Approval pending")], ["VCA Report", T("VCA Report")], ["Report", T("Report")], ] if request.extension == "html": report = dt.html(filteredrows, filteredrows, "report", dt_pagination="false", dt_bFilter="false", dt_sDom="t", dt_group=[3, 4], dt_group_totals=[type_totals, location_totals], dt_group_titles=[level_1_titles], dt_ajax_url=URL( c="vulnerability", f="report", extension="aadata", vars={"id": "report"}, ), dt_action_col=-1, dt_group_space="true", dt_shrink_groups="accordion") reportCount = T("%(count)s Entries Found") % dict(count=filteredrows) report.append( INPUT(_type="hidden", _id="reportCount", _name="config", _value=reportCount)) else: report = "" if filteredrows > 0: report = dt.json( "report", int(request.vars.sEcho), filteredrows, filteredrows, dt_group_totals=[type_totals], ) return str(report)
def index(): """ Module Home Page: Map """ # This module uses it's own Theme settings.base.theme = "Vulnerability" # Additional scripts append = s3.scripts.append append("/%s/static/scripts/yepnope.1.5.4-min.js" % appname) if s3.debug: append("/%s/static/scripts/jquery.ui.selectmenu.js" % appname) append("/%s/static/scripts/jquery.ui.progressbar.js" % appname) append("/%s/static/scripts/TypeHelpers.js" % appname) append("/%s/static/scripts/S3/s3.vulnerability.js" % appname) append("/%s/static/scripts/S3/s3.dataTables.js" % appname) append("/%s/static/scripts/jquery.dataTables.js" % appname) append("/%s/static/scripts/jquery.dataTables.fnSetFilteringDelay.js" % appname) else: append("/%s/static/scripts/S3/s3.vulnerability.min.js" % appname) append("/%s/static/scripts/S3/s3.dataTables.min.js" % appname) js_global = [] append = js_global.append # i18n i18n = "\n".join(( "S3.i18n.gis_requires_login='******'" % T("Requires Login"), "S3.i18n.no_matching_result='%s'" % T("No matching result"), "S3.i18n.no_entries_found='%s'" % T("No Entries Found"), "S3.i18n.loading_report_details='%s'" % T("Loading report details"), "S3.i18n.choose='%s'" % T("Choose"), "S3.i18n.population='%s'" % T("Population"), "S3.i18n.reported='%s'" % T("Reported"), "S3.i18n.country='%s'" % T("Country"), "S3.i18n.country_in='%s'" % T("Country in"), "S3.i18n.show_more='%s'" % T("Show more"), "S3.i18n.show_less='%s'" % T("Show less"), "S3.i18n.submit_data='%s'" % T("Submit Data"), "S3.i18n.analysis='%s'" % T("Analysis"), "S3.i18n.reports='%s'" % T("Reports"), "S3.i18n.all_reports='%s'" % T("All reports"), "S3.i18n.my_reports='%s'" % T("My reports"), "S3.i18n.approval_request_submitted='%s'" % T("Approval request submitted"), "S3.i18n.thankyou_for_your_approval='%s'" % T("Thank you for your approval"), "S3.i18n.reject_request_submitted='%s'" % T("Reject request submitted"), "S3.i18n.submission_has_been_declined='%s'" % T("Thank you, the submission%(br)shas been declined") % dict(br="<br />"), "S3.i18n.last_data_collected_on='%s'" % T("Last Data Collected on"), "S3.i18n.by='%s'" % T("by"), "S3.i18n.in_='%s'" % T("in"), "S3.i18n.in_this='%s'" % T("in this"), "S3.i18n.of='%s'" % T("of"), "S3.i18n.out_of='%s'" % T("out of"), "S3.i18n.review='%s'" % T("Review"), "S3.i18n.go_to_the='%s'" % T("Go to the"), "S3.i18n.select_data_type='%s'" % T("Select data type"), "S3.i18n.about_to_submit_indicator_ratings='%s'" % T("You are about to submit indicator ratings for"), "S3.i18n.poor='%s'" % T("poor"), "S3.i18n.fair='%s'" % T("fair"), "S3.i18n.moderate='%s'" % T("moderate"), "S3.i18n.strong='%s'" % T("strong"), "S3.i18n.data_quality='%s'" % T("Data Quality"), "S3.i18n.of_total_data_reported='%s'" % T("of total data reported"), )) append(i18n) # Get the L0 hdata & summary vdata hdata, vdata = l0() # Get the default location to open the map bounds = None root_org = auth.root_org() start = False if root_org: otable = s3db.org_organisation ttable = s3db.gis_location_tag gtable = s3db.gis_location query = (otable.id == root_org) & \ (ttable.tag == "ISO2") & \ (ttable.value == otable.country) r = db(query).select(ttable.location_id, limitby=(0, 1)).first() if r and r.location_id in countries: start = True append('''\nstart=%s''' % r.location_id) # Add the child L1 summary vdata l1(r.location_id, vdata) if not start: append('''\nstart=""''') dumps = json.dumps script = ''' hdata=%s vdata=%s ''' % (dumps(hdata), dumps(vdata)) append(script) # Get the list of indicators itable = s3db.vulnerability_indicator query = (itable.deleted == False) rows = db(query).select(itable.name, itable.description, itable.parameter_id, orderby=itable.posn) indicators = OrderedDict() for row in rows: indicators[row.parameter_id] = dict(n=row.name, d=row.description) append('''idata=%s''' % json.dumps(indicators)) s3.js_global.append("".join(js_global)) # Reports from s3.s3utils import S3DataTable resource = s3db.resource("stats_group") list_fields = [ "id", "date", "location_id", "location_id$L3", "group", "group_type_id", "created_by", "approved_by", ] rfields = resource.resolve_selectors(list_fields)[0] filteredrows = resource.count() dt = S3DataTable(rfields, []) level_1_titles = [ ["Approval pending", T("Approval pending")], ["VCA Report", T("VCA Report")], ["Report", T("Report")], ] report = dt.html(filteredrows, filteredrows, "report", dt_pagination="false", dt_bFilter="false", dt_sDom="t", dt_group=[4, 3], dt_group_totals=[level_1_titles], dt_ajax_url=URL( c="vulnerability", f="report", extension="aadata", vars={"id": "report"}, ), dt_action_col=-1, dt_group_space="true", dt_shrink_groups="accordion") s3.report = report response.view = "vulnerability/map.html" return dict(indicators=indicators)