예제 #1
0
    def __call__(self):

        response = current.response

        output = {}
        #output["title"] = response.title = current.deployment_settings.get_system_name()

        s3 = response.s3
        # Image Carousel
        s3.jquery_ready.append('''$('#myCarousel').carousel()''')

        # Latest 4 Events and Alerts
        from s3.s3resource import S3FieldSelector
        s3db = current.s3db
        layout = s3.render_posts
        list_id = "news_datalist"
        limit = 4
        list_fields = [
            "series_id",
            "location_id",
            "date",
            "body",
            "created_by",
            "created_by$organisation_id",
            "document.file",
            "event_post.event_id",
        ]

        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("series_id$name") == "Event")
        # Only show Future Events
        resource.add_filter(resource.table.date >= current.request.now)
        # Order with next Event first
        orderby = "date"
        output["events"] = latest_records(resource, layout, list_id, limit,
                                          list_fields, orderby)

        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("series_id$name") == "Alert")
        # Order with most recent Alert first
        orderby = "date desc"
        output["alerts"] = latest_records(resource, layout, list_id, limit,
                                          list_fields, orderby)

        self._view(THEME, "index.html")
        return output
예제 #2
0
    def __call__(self):
        """ Main entry point """

        # Authorization (user must be logged in)
        auth = current.auth
        permissions = auth.permission
        if not auth.user:
            permissions.fail()

        fmt = permissions.format

        if current.request.env.request_method == "POST" and fmt != "dl":
            return self.update()

        pe_id = auth.user.pe_id
        s3 = current.response.s3

        # Filter
        f = S3FieldSelector("pe_id") == pe_id
        s3.filter = f

        # List Fields
        current.s3db.configure(
            "pr_filter",
            list_fields=["title", "resource", "url", "query"],
            list_layout=self.render_filter,
            orderby="resource")

        # Page length
        s3.dl_pagelength = 10

        # Data list
        current.request.args = ["datalist.%s" % fmt]
        output = current.rest_controller("pr",
                                         "filter",
                                         list_ajaxurl=URL(f="index",
                                                          args="filters.dl"))

        # Title and view
        T = current.T
        if fmt != "dl":
            output["title"] = T("Saved Filters")
            self._view(THEME, "filters.html")

        # Script for inline-editing of filter title
        options = {
            "cssclass": "jeditable-input",
            "tooltip": str(T("Click to edit"))
        }
        script = '''$('.jeditable').editable('%s',%s)''' % \
                 (URL(args="filters"), json.dumps(options))
        s3.jquery_ready.append(script)
        return output
예제 #3
0
    def __call__(self):
        response = current.response
        s3 = response.s3
        s3db = current.s3db
        output = {}
        self._view(THEME, "index.html")
        
        # Organisations Data List
        resource = s3db.resource("org_organisation")
        
        datalist, numrows, ids = resource.datalist(list_id = "org_organisation_datalist",
                                                   #fields=list_fields,
                                                   #start=None,
                                                   limit=10,
                                                   #orderby=orderby,
                                                   layout = s3db.org_organisation_list_layout
                                                   )
        output["org_organisation_datalist"] = datalist.html()

        # News Feed Data List
        list_fields = ["series_id",
                       "location_id",
                       "date",
                       "body",
                       "created_by",
                       "created_by$organisation_id",
                       "document.file",
                       "event_post.event_id",
                       ]
        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("post.series_id") != None)
        datalist, numrows, ids = resource.datalist(list_id = "cms_post_datalist",
                                                   fields=list_fields,
                                                   #start=None,
                                                   limit=10,
                                                   #list_id=list_id,
                                                   #orderby=orderby,
                                                   layout = s3db.cms_post_list_layout
                                                   )
        output["cms_post_datalist"] = datalist.html()

        # Data Buttons
        # Description of available data
        from s3db.cms import S3CMS
        resource_content = S3CMS.resource_content
        for item in response.menu:
            item["cms"] = resource_content(module = item["c"], 
                                           resource = item["f"])

        return output
예제 #4
0
 def latest_4_posts(series_filter, layout):
     resource.add_filter(
         S3FieldSelector("series_id$name") == series_filter)
     list_fields = [
         "series_id",
         "location_id",
         "date",
         "body",
         "created_by",
         "created_by$organisation_id",
         "document.file",
         "event_post.event_id",
     ]
     orderby = resource.table.date
     resource.add_filter(resource.table.date >= current.request.now)
     datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                start=None,
                                                limit=4,
                                                listid="news_datalist",
                                                orderby=orderby,
                                                layout=layout)
     if numrows == 0:
         # Empty table or just no match?
         table = resource.table
         if "deleted" in table:
             available_records = current.db(table.deleted != True)
         else:
             available_records = current.db(table._id > 0)
         if available_records.select(table._id, limitby=(0, 1)).first():
             msg = DIV(S3CRUD.crud_string(resource.tablename,
                                          "msg_no_match"),
                       _class="empty")
         else:
             msg = DIV(S3CRUD.crud_string(resource.tablename,
                                          "msg_list_empty"),
                       _class="empty")
         data = msg
     else:
         # Render the list
         dl = datalist.html()
         data = dl
     return data
예제 #5
0
    def __call__(self):

        response = current.response
        
        output = {}
        #output["title"] = response.title = current.deployment_settings.get_system_name()

        s3 = response.s3
        # Image Carousel
        s3.jquery_ready.append('''$('#myCarousel').carousel()''')

        # Latest 4 Requests
        s3db = current.s3db
        list_id = "latest_reqs"
        layout = s3db.req_req_list_layout
        limit = 4
        resource = s3db.resource("req_req")
        s3db.req_customize_req_fields()
        list_fields = s3db.get_config("req_req", "list_fields")
        from s3.s3resource import S3FieldSelector
        resource.add_filter(S3FieldSelector("cancel") != True)
        # Order with most recent first
        orderby = "date desc"
        output["latest_reqs"] = latest_records(resource, layout, list_id, limit, list_fields, orderby)

        # Latest 4 Offers
        list_id = "latest_offers"
        layout = s3db.req_commit_list_layout
        #limit = 4

        resource = s3db.resource("req_commit")
        s3db.req_customize_commit_fields()
        list_fields = s3db.get_config("req_commit", "list_fields")
        resource.add_filter(S3FieldSelector("cancel") != True)
        # Order with most recent first
        #orderby = "date desc"
        output["latest_offers"] = latest_records(resource, layout, list_id, limit, list_fields, orderby)

        # What We Do
        table = s3db.cms_post
        ltable = s3db.cms_post_module
        query = (ltable.module == "default") & \
                (ltable.resource == "index") & \
                (ltable.post_id == table.id) & \
                (table.deleted != True)
        item = current.db(query).select(table.id,
                                        table.body,
                                        limitby=(0, 1)).first()
        if item:
            what_we_do = DIV(XML(item.body))
            if current.auth.s3_has_role("ADMIN"):
                if s3.crud.formstyle == "bootstrap":
                    _class = "btn"
                else:
                    _class = "action-btn"
                what_we_do.append(A(current.T("Edit"),
                                    _href=URL(c="cms", f="post",
                                              args=[item.id, "update"],
                                              vars={"module": "default",
                                                    "resource": "index",
                                                    }),
                                    _class="%s cms-edit" % _class))
        else:
            what_we_do = DIV()
            if current.auth.s3_has_role("ADMIN"):
                if s3.crud.formstyle == "bootstrap":
                    _class = "btn"
                else:
                    _class = "action-btn"
                what_we_do.append(A(current.T("Edit"),
                                    _href=URL(c="cms", f="post",
                                              args=["create"],
                                              vars={"module": "default",
                                                    "resource": "index",
                                                    }),
                                    _class="%s cms-edit" % _class))

        output["what_we_do"] = what_we_do

        self._view(THEME, "index.html")
        return output
예제 #6
0
    def __call__(self):
        response = current.response
        s3 = response.s3
        s3db = current.s3db
        output = {}
        self._view(THEME, "index.html")

        # Map
        # Enable Layers by default
        callback = '''S3.gis.show_map()
var layer,layers=S3.gis.maps.default_map.layers
for(var i=0,len=layers.length;i<len;i++){
 layer=layers[i]
 layer_name=layer.name
 if((layer_name=='Alerts')||(layer_name=='Incidents')||(layer_name=='Tasks')){layer.setVisibility(true)}}'''
        gis = current.gis
        #config = gis.get_config()
        #config.zoom = 8
        map = gis.show_map(
            width=600,
            height=600,
            callback=callback,
            catalogue_layers=True,
            collapsed=True,
            save=False,
        )
        output["map"] = map

        # Organisations Data List
        #resource = s3db.resource("org_organisation")

        #datalist, numrows, ids = resource.datalist(list_id = "org_organisation_datalist",
        #fields=list_fields,
        #start=None,
        #                                           limit=10,
        #orderby=orderby,
        #                                           layout = s3db.org_organisation_list_layout
        #                                           )
        #output["org_organisation_datalist"] = datalist.html()

        # News Feed Data List
        list_fields = [
            "series_id",
            "location_id",
            "date",
            "body",
            "created_by",
            "created_by$organisation_id",
            "document.file",
            "event_post.event_id",
        ]
        resource = s3db.resource("cms_post")
        resource.add_filter(
            S3FieldSelector("series_id$name").belongs(["Alert"]))
        #resource.add_filter(S3FieldSelector("post.series_id") != None)
        datalist, numrows, ids = resource.datalist(
            list_id="cms_post_datalist",
            fields=list_fields,
            #start=None,
            limit=5,
            #list_id=list_id,
            #orderby=orderby,
            layout=s3db.cms_post_list_layout)
        output["cms_post_datalist"] = datalist.html()

        # Incidents Data List
        resource = s3db.resource(
            "project_project")  # Temp: Uses relabelled project_project
        list_fields = [
            "name",
            "description",
            "location.location_id",
            "start_date",
            "organisation_id",
            "organisation_id$logo",
            "modified_by",
        ]
        datalist, numrows, ids = resource.datalist(
            list_id="project_project_datalist",
            fields=list_fields,
            #start=None,
            limit=5,
            #list_id=list_id,
            #orderby=orderby,
            layout=s3db.project_project_list_layout)
        output["project_project_datalist"] = datalist.html()

        # Tasks Data List
        resource = s3db.resource("project_task")
        list_fields = [
            "name",
            "description",
            "location_id",
            "date_due",
            "pe_id",
            "task_project.project_id",
            #"organisation_id$logo",
            "modified_by",
        ]
        datalist, numrows, ids = resource.datalist(
            list_id="project_task_datalist",
            fields=list_fields,
            #start=None,
            limit=5,
            #list_id=list_id,
            #orderby=orderby,
            layout=s3db.project_task_list_layout)
        output["project_task_datalist"] = datalist.html()

        # MCOP News Feed
        #s3.external_stylesheets.append("http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css")
        s3.scripts.append("http://www.google.com/jsapi?key=notsupplied-wizard")
        s3.scripts.append(
            "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js"
        )
        # feedCycleTime: milliseconds before feed is reloaded (5 minutes)
        s3.js_global.append("""
function LoadDynamicFeedControl(){
 var feeds=[{title:'News', url:'http://psmcop.org/?feed=rss2'}]
 var options={
  feedCycleTime:300000,
  numResults:5,
  stacked:true,
  horizontal:false,
 }
 new GFdynamicFeedControl(feeds,'feed-control',options);
}
google.load('feeds','1');
google.setOnLoadCallback(LoadDynamicFeedControl);
""")

        # Data Buttons
        # Description of available data
        from s3db.cms import S3CMS
        resource_content = S3CMS.resource_content
        for item in response.menu:
            item["cms"] = resource_content(module=item["c"],
                                           resource=item["f"])

        return output
예제 #7
0
    def __call__(self):

        response = current.response
        output = {}
        #output["title"] = response.title = current.deployment_settings.get_system_name()
        view = path.join(current.request.folder, "private", "templates", THEME,
                         "views", "index.html")
        try:
            # Pass view as file not str to work in compiled mode
            response.view = open(view, "rb")
        except IOError:
            from gluon.http import HTTP
            raise HTTP("404", "Unable to open Custom View: %s" % view)

        s3 = response.s3
        # Image Carousel
        s3.jquery_ready.append('''$('#myCarousel').carousel()''')

        if current.auth.is_logged_in():
            s3db = current.s3db
            # Latest 4 Events
            resource = s3db.resource("cms_post")
            resource.add_filter(S3FieldSelector("series_id$name") == "Event")
            list_fields = [
                "location_id",
                "date",
                "body",
                "created_by",
                "created_by$organisation_id",
                "document.file",
                "event_post.event_id",
            ]
            orderby = resource.get_config("list_orderby", ~resource.table.date)
            datalist, numrows, ids = resource.datalist(
                fields=list_fields,
                start=None,
                limit=4,
                listid="event_datalist",
                orderby=orderby,
                layout=render_cms_events)
            if numrows == 0:
                # Empty table or just no match?
                table = resource.table
                if "deleted" in table:
                    available_records = current.db(table.deleted != True)
                else:
                    available_records = current.db(table._id > 0)
                if available_records.select(table._id, limitby=(0, 1)).first():
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_no_match"),
                              _class="empty")
                else:
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_list_empty"),
                              _class="empty")
                data = msg
            else:
                # Render the list
                dl = datalist.html()
                data = dl
            output["events"] = data

            # Latest 4 Updates
            resource = s3db.resource("cms_post")
            list_fields = [
                "series_id",
                "location_id",
                "date",
                "body",
                "created_by",
                "created_by$organisation_id",
                "document.file",
                "event_post.event_id",
            ]
            orderby = resource.get_config("list_orderby", ~resource.table.date)
            datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                       start=None,
                                                       limit=4,
                                                       listid="news_datalist",
                                                       orderby=orderby,
                                                       layout=s3.render_posts)
            if numrows == 0:
                # Empty table or just no match?
                table = resource.table
                if "deleted" in table:
                    available_records = current.db(table.deleted != True)
                else:
                    available_records = current.db(table._id > 0)
                if available_records.select(table._id, limitby=(0, 1)).first():
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_no_match"),
                              _class="empty")
                else:
                    msg = DIV(S3CRUD.crud_string(resource.tablename,
                                                 "msg_list_empty"),
                              _class="empty")
                data = msg
            else:
                # Render the list
                dl = datalist.html()
                data = dl
            output["news"] = data

        return output
예제 #8
0
    def __call__(self):

        output = {}

        request = current.request
        s3 = current.response.s3

        # Check logged in and permissions
        auth = current.auth
        roles = current.session.s3.roles
        system_roles = auth.get_system_roles()
        AUTHENTICATED = system_roles.AUTHENTICATED

        # Login/Registration forms
        self_registration = current.deployment_settings.get_security_self_registration(
        )
        registered = False
        login_form = None
        login_div = None
        register_form = None
        register_div = None
        if AUTHENTICATED not in roles:
            # This user isn't yet logged-in
            T = current.T
            if request.cookies.has_key("registered"):
                # This browser has logged-in before
                registered = True

            if self_registration:
                # Provide a Registration box on front page
                register_form = auth.s3_registration_form()
                register_div = DIV(H3(T("Register")),
                                   P(XML(T("If you would like to help, then please %(sign_up_now)s") % \
                                            dict(sign_up_now=B(T("sign-up now"))))))

                if request.env.request_method == "POST":
                    post_script = \
'''$('#register_form').removeClass('hide')
$('#login_form').addClass('hide')'''
                else:
                    post_script = ""
                register_script = \
'''$('#register-btn').attr('href','#register')
$('#login-btn').attr('href','#login')
%s
$('#register-btn').click(function(){
 $('#register_form').removeClass('hide')
 $('#login_form').addClass('hide')
})
$('#login-btn').click(function(){
 $('#register_form').addClass('hide')
 $('#login_form').removeClass('hide')
})''' % post_script
                s3.jquery_ready.append(register_script)

            # Provide a login box on front page
            request.args = ["login"]
            auth.messages.submit_button = T("Login")
            login_form = auth()
            login_div = DIV(H3(T("Login")),
                            P(XML(T("Registered users can %(login)s to access the system") % \
                                  dict(login=B(T("login"))))))
        output["self_registration"] = self_registration
        output["registered"] = registered
        output["login_div"] = login_div
        output["login_form"] = login_form
        output["register_div"] = register_div
        output["register_form"] = register_form

        # Latest 4 Events and Requests
        s3db = current.s3db
        layout = s3.render_posts
        listid = "news_datalist"
        limit = 4
        list_fields = [
            "series_id",
            "location_id",
            "date",
            "body",
            "created_by",
            "created_by$organisation_id",
            "document.file",
            "event_post.event_id",
        ]

        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("series_id$name") == "Event")
        # Only show Future Events
        resource.add_filter(resource.table.date >= request.now)
        # Order with next Event first
        orderby = "date"
        output["events"] = latest_records(resource, layout, listid, limit,
                                          list_fields, orderby)

        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("series_id$name") == "Request")
        # Order with most recent Request first
        orderby = "date desc"
        output["requests"] = latest_records(resource, layout, listid, limit,
                                            list_fields, orderby)

        self._view(THEME, "index.html")
        return output
예제 #9
0
    def __call__(self):

        T = current.T
        db = current.db
        s3db = current.s3db
        request = current.request
        response = current.response
        s3 = response.s3

        output = {}
        output["title"] = response.title = current.deployment_settings.get_system_name()

        # Map
        auth = current.auth
        is_logged_in = auth.is_logged_in()
        callback = None
        if is_logged_in:
            # Show the User's Coalition's Polygon
            org_group_id = auth.user.org_group_id
            if org_group_id:
                # Lookup Coalition Name
                db = current.db
                table = s3db.org_group
                query = (table.id == org_group_id)
                row = db(query).select(table.name,
                                       limitby=(0, 1)).first()
                if row:
                    callback = '''S3.gis.show_map();
var layer,layers=S3.gis.maps.default_map.layers;
for(var i=0,len=layers.length;i<len;i++){
 layer=layers[i];
 if(layer.name=='%s'){layer.setVisibility(true)}}''' % row.name
        if not callback:
            # Show all Coalition Polygons
            callback = '''S3.gis.show_map();
var layer,layers=S3.gis.maps.default_map.layers;
for(var i=0,len=layers.length;i<len;i++){
 layer=layers[i];
 if(layer.name=='All Coalitions'){layer.setVisibility(true)}}
'''
        gis = current.gis
        config = gis.get_config()
        config.zoom = 8
        map = gis.show_map(width=770,
                           height=295,
                           callback=callback,
                           catalogue_layers=True,
                           collapsed=True,
                           save=False,
                           )
        output["map"] = map

        # Description of available data
        from s3db.cms import S3CMS
        for item in response.menu:
            item["cms"] = S3CMS.resource_content(module = item["c"], 
                                                 resource = item["f"])

        # Site Activity Log
        resource = s3db.resource("s3_audit")
        resource.add_filter(S3FieldSelector("~.method") != "delete")
        orderby = "s3_audit.timestmp desc"
        list_fields = ["id",
                       "method",
                       "user_id",
                       "tablename",
                       "record_id",
                       ]
        #current.deployment_settings.ui.customize_s3_audit()
        db.s3_audit.user_id.represent = s3_auth_user_represent_name
        list_id = "log"
        datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                   start=None,
                                                   limit=4,
                                                   list_id=list_id,
                                                   orderby=orderby,
                                                   layout=s3.render_log)

        # Placeholder
        filter_form = DIV(_class="filter_form")
        if numrows == 0:
            # Empty table or just no match?
            from s3.s3crud import S3CRUD
            table = resource.table
            if "deleted" in table:
                available_records = db(table.deleted != True)
            else:
                available_records = db(table._id > 0)
            if available_records.select(table._id,
                                        limitby=(0, 1)).first():
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_no_match"),
                          _class="empty")
            else:
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_list_empty"),
                          _class="empty")
            data = msg
        else:
            # Render the list
            ajaxurl = URL(c="default", f="audit", args="datalist_f.dl")
            popup_url = URL(c="default", f="audit", args="datalist.popup")
            dl = datalist.html(ajaxurl=ajaxurl,
                               pagesize=4,
                               popup_url=popup_url,
                               popup_title=T("Updates"),
                               )
            data = dl

            if is_logged_in and org_group_id:
                # Add a Filter
                filter_widgets = [S3OptionsFilter("user_id$org_group_id",
                                                  label = "",
                                                  # Can't just use "" as this is then omitted from rendering
                                                  options = {"*": T("All"),
                                                             org_group_id: T("My Community"),
                                                             },
                                                  multiple = False,
                                                  ),
                                  ]

                filter_submit_url = URL(c="default", f="index")
                filter_ajax_url = URL(c="default", f="audit", args=["filter.options"])
                filter_form = S3FilterForm(filter_widgets,
                                           filter_manager = False,
                                           formstyle = filter_formstyle,
                                           clear = False,
                                           submit = True,
                                           ajax = True,
                                           url = filter_submit_url,
                                           ajaxurl = filter_ajax_url,
                                           _class = "filter-form",
                                           _id = "%s-filter-form" % list_id
                                           )
                filter_form = filter_form.html(resource,
                                               request.get_vars,
                                               target=list_id,
                                               )

        output["updates"] = data
        output["filter_form"] = filter_form

        # Add JavaScript
        appname = request.application
        debug = s3.debug
        scripts_append = s3.scripts.append
        if debug:
            # Infinite Scroll doesn't make sense here, but currently required by dataLists.js
            scripts_append("/%s/static/scripts/jquery.infinitescroll.js" % appname)
            scripts_append("/%s/static/scripts/jquery.viewport.js" % appname)
            scripts_append("/%s/static/scripts/S3/s3.dataLists.js" % appname)
        else:
            scripts_append("/%s/static/scripts/S3/s3.dataLists.min.js" % appname)

        self._view(THEME, "index.html")
        return output
예제 #10
0
    def __call__(self):

        output = {}

        T = current.T
        request = current.request
        s3 = current.response.s3

        # Check logged in and permissions
        auth = current.auth
        roles = current.session.s3.roles
        system_roles = auth.get_system_roles()
        AUTHENTICATED = system_roles.AUTHENTICATED

        # Login/Registration forms
        self_registration = current.deployment_settings.get_security_self_registration(
        )
        registered = False
        login_form = None
        login_div = None
        register_form = None
        register_div = None
        if AUTHENTICATED not in roles:
            # This user isn't yet logged-in
            if request.cookies.has_key("registered"):
                # This browser has logged-in before
                registered = True

            if self_registration is True:
                # Provide a Registration box on front page
                register_form = auth.s3_registration_form()
                register_div = DIV(H3(T("Register")),
                                   P(XML(T("If you would like to help, then please %(sign_up_now)s") % \
                                            dict(sign_up_now=B(T("sign-up now"))))))

                if request.env.request_method == "POST":
                    post_script = \
'''$('#register_form').removeClass('hide')
$('#login_form').addClass('hide')'''
                else:
                    post_script = ""
                register_script = \
'''$('#register-btn').attr('href','#register')
$('#login-btn').attr('href','#login')
%s
$('#register-btn').click(function(){
 $('#register_form').removeClass('hide')
 $('#login_form').addClass('hide')
})
$('#login-btn').click(function(){
 $('#register_form').addClass('hide')
 $('#login_form').removeClass('hide')
})''' % post_script
                s3.jquery_ready.append(register_script)

            # Provide a login box on front page
            request.args = ["login"]
            auth.messages.submit_button = T("Login")
            login_form = auth()
            login_div = DIV(H3(T("Login")),
                            P(XML(T("Registered users can %(login)s to access the system") % \
                                  dict(login=B(T("login"))))))
        output["self_registration"] = self_registration
        output["registered"] = registered
        output["login_div"] = login_div
        output["login_form"] = login_form
        output["register_div"] = register_div
        output["register_form"] = register_form

        # Latest 4 Events and Requests
        from s3.s3resource import S3FieldSelector
        s3db = current.s3db
        layout = s3db.cms_render_posts
        list_id = "latest_events"
        limit = 4
        list_fields = [
            "series_id",
            "location_id",
            "date",
            "body",
            "created_by",
            "created_by$organisation_id",
            "document.file",
            "event_post.event_id",
        ]

        resource = s3db.resource("cms_post")
        resource.add_filter(S3FieldSelector("series_id$name") == "Event")
        # Only show Future Events
        resource.add_filter(resource.table.date >= request.now)
        # Order with next Event first
        orderby = "date"
        output["latest_events"] = latest_records(resource, layout, list_id,
                                                 limit, list_fields, orderby)

        list_id = "latest_reqs"
        resource = s3db.resource("req_req")
        s3db.req_customize_req_fields()
        list_fields = s3db.get_config("req_req", "list_fields")
        layout = s3db.req_render_reqs
        resource.add_filter(S3FieldSelector("cancel") != True)
        # Order with most recent Request first
        orderby = "date desc"
        output["latest_reqs"] = latest_records(resource, layout, list_id,
                                               limit, list_fields, orderby)

        # Site Activity Log
        from s3.s3utils import s3_auth_user_represent_name
        resource = s3db.resource("s3_audit")
        resource.add_filter(S3FieldSelector("~.method") != "delete")
        orderby = "s3_audit.timestmp desc"
        list_fields = [
            "id",
            "method",
            "user_id",
            "tablename",
            "record_id",
        ]
        #current.deployment_settings.ui.customize_s3_audit()
        db = current.db
        db.s3_audit.user_id.represent = s3_auth_user_represent_name
        list_id = "log"
        datalist, numrows, ids = resource.datalist(fields=list_fields,
                                                   start=None,
                                                   limit=4,
                                                   list_id=list_id,
                                                   orderby=orderby,
                                                   layout=s3.render_log)

        # Placeholder
        filter_form = DIV(_class="filter_form")
        if numrows == 0:
            # Empty table or just no match?
            from s3.s3crud import S3CRUD
            table = resource.table
            if "deleted" in table:
                available_records = db(table.deleted != True)
            else:
                available_records = db(table._id > 0)
            if available_records.select(table._id, limitby=(0, 1)).first():
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_no_match"),
                          _class="empty")
            else:
                msg = DIV(S3CRUD.crud_string(resource.tablename,
                                             "msg_list_empty"),
                          _class="empty")
            data = msg
        else:
            # Render the list
            ajaxurl = URL(c="default", f="audit", args="datalist_f.dl")
            popup_url = URL(c="default", f="audit", args="datalist.popup")
            dl = datalist.html(
                ajaxurl=ajaxurl,
                pagesize=4,
                popup_url=popup_url,
                popup_title=T("Updates"),
            )
            data = dl

            if auth.s3_logged_in() and auth.user.org_group_id:
                # Add a Filter
                from s3.s3filter import S3OptionsFilter, S3FilterForm
                filter_widgets = [
                    S3OptionsFilter(
                        "user_id$org_group_id",
                        label="",
                        # Can't just use "" as this is then omitted from rendering
                        options={
                            "*": T("All"),
                            org_group_id: T("My Community"),
                        },
                        multiple=False,
                    ),
                ]

                filter_submit_url = URL(c="default", f="index")
                filter_ajax_url = URL(c="default",
                                      f="audit",
                                      args=["filter.options"])
                filter_form = S3FilterForm(filter_widgets,
                                           filter_manager=False,
                                           formstyle=filter_formstyle,
                                           clear=False,
                                           submit=True,
                                           ajax=True,
                                           url=filter_submit_url,
                                           ajaxurl=filter_ajax_url,
                                           _class="filter-form",
                                           _id="%s-filter-form" % list_id)
                filter_form = filter_form.html(
                    resource,
                    request.get_vars,
                    target=list_id,
                )

        output["updates"] = data
        output["filter_form"] = filter_form

        # Add JavaScript
        appname = request.application
        debug = s3.debug
        scripts_append = s3.scripts.append
        if debug:
            # Infinite Scroll doesn't make sense here, but currently required by dataLists.js
            scripts_append("/%s/static/scripts/jquery.infinitescroll.js" %
                           appname)
            scripts_append("/%s/static/scripts/jquery.viewport.js" % appname)
            scripts_append("/%s/static/scripts/S3/s3.dataLists.js" % appname)
        else:
            scripts_append("/%s/static/scripts/S3/s3.dataLists.min.js" %
                           appname)

        self._view(THEME, "index.html")
        return output
예제 #11
0
    def search(self, form_type, results_expected, fields, row_count, **kwargs):
        '''
        Generic method to test the validity of search results.

        @param form_type: This can either be search.simple_form or
                          search.advanced_form

        @param results_expected: Are results expected?

        @param fields: See the `fields` function. 
                       For search.simple_form, an empty list [] can be pass. The field will be taken from s3resource.

        @param row_count: Expected row count
                       For search.simple_form, 
                               {"tablename":tablename, "key":key, "filters":[(field,value),...]} 
                                 can be pass to get the resource and eventually the DB row count.

        Keyword arguments:

        These let you specify the kinds of checks to perform on the resulting
        datatable. Here are some of the options:

        1. data - You can pass in your own function here that receives the data
        from the results table as an argument. Return true if your check is
        successful and false otherwise. This directly corresponds to the
        'dt_data' function.

        2. manual_check - You can pass in your own function here, and it'll
        receive this instance as an argument. This can be used for all other
        kinds of checks.

        3. match_row - You can use this to match a series of values to a row in
        the result data table. The first value must be the index of the row to
        match against.

        4. match_column - You can use this to match a series of values to a
        column in the result data table. The first value must be the index of
        the row to match against.
        '''

        current.auth.override = True
        if isinstance(row_count,
                      dict) and form_type == self.search.simple_form:
            key = row_count["key"]
            resource = current.s3db.resource(row_count["tablename"])
            simpleSearch = resource.search_method().simple[0]
            if len(fields) == 0:
                fields = ({"name": simpleSearch[0], "value": key}, )
            searchFields = simpleSearch[1].field
            for i in xrange(len(searchFields)):
                if i == 0:
                    query = (S3FieldSelector(searchFields[i]).like("%" + key +
                                                                   "%"))
                else:
                    query |= (S3FieldSelector(searchFields[i]).like("%" + key +
                                                                    "%"))

            filters = row_count.get("filters", None)
            if filters is not None:
                for filter in filters:
                    qfilter = (resource.table[filter[0]] == filter[1])
                    resource.add_filter(qfilter)

            resource.add_filter(query)
            row_count = resource.count()

        browser = self.browser

        clear_button = browser.find_elements_by_xpath("//a[text()='Clear']")
        if clear_button[0].is_displayed():
            clear_button[0].click()
        else:
            clear_button[1].click()

        try:
            if form_type == self.search.advanced_form:
                link = browser.find_element_by_xpath(
                    "//a[@class='action-lnk advanced-lnk']")
            elif form_type == self.search.simple_form:
                link = browser.find_element_by_xpath(
                    "//a[@class='action-lnk simple-lnk']")
        except NoSuchElementException:
            # There might be no link if one of the forms is the only option
            link = None

        if link and link.is_displayed():
            link.click()

        time.sleep(1)

        self.fill_fields(fields)

        if isinstance(row_count,
                      dict) and form_type == self.search.advanced_form:
            resource = current.s3db.resource(row_count["tablename"])
            search_list = resource.search_method().advanced
            for search in search_list:
                widget = search[1]
                if isinstance(widget, S3SearchOptionsWidget):
                    values = []
                    elem_list = browser.find_elements_by_name(
                        widget.attr._name)
                    for elem in elem_list:
                        if elem.get_attribute("checked"):
                            values.append(
                                int(s3_unicode(elem.get_attribute("value"))))
                    if len(values) > 0:
                        query = widget.query(resource, values)
                        resource.add_filter(query)

            filters = row_count.get("filters", None)
            if filters is not None:
                for filter in filters:
                    qfilter = (resource.table[filter[0]] == filter[1])
                    resource.add_filter(qfilter)

            row_count = resource.count()

        browser.find_element_by_name(
            ("simple_submit", "advanced_submit")[form_type]).click()

        time.sleep(1)

        if results_expected:
            self.assertFalse(
                browser.find_element_by_id("table-container").text ==
                "No Records Found", "No results found, when results expected.")
        else:
            return

        # We"re done entering and submitting data; now we need to check if the
        # results produced are valid.
        htmlRowCount = self.dt_row_cnt()[2]
        successMsg = "DB row count (" + str(
            row_count) + ") matches the HTML datatable row count (" + str(
                htmlRowCount) + ")."
        failMsg = "DB row count (" + str(
            row_count
        ) + ") does not match the HTML datatable row count (" + str(
            htmlRowCount) + ")."
        self.assertTrue(row_count == htmlRowCount, failMsg)
        self.reporter(successMsg)

        if "data" in kwargs.keys():
            self.assertTrue(bool(kwargs["data"](self.dt_data())),
                            "Data verification failed.")

        if "manual_check" in kwargs.keys():
            self.assertTrue(bool(kwargs["manual_check"](self)),
                            "Manual checks failed.")

        if "match_row" in kwargs.keys():
            data = self.dt_data(row_list=(kwargs["match_row"][0]))
            kwargs["match_row"] = kwargs["match_row"][1:]
            for a, b in zip(kwargs["match_row"], data):
                self.assertTrue(a == b, "Row match failed.")

        if "match_column" in kwargs.keys():
            column_index = kwargs["match_column"][0]
            kwargs["match_column"] = kwargs["match_column"][1:]
            shown_items = [
                dt_data_item(column=column_index, row=r)
                for r in xrange(1,
                                len(kwargs["match_column"]) + 1)
            ]
            for item in kwargs["match_column"]:
                self.assertTrue(item in shown_items)

        return self.dt_data()
예제 #12
0
파일: config.py 프로젝트: MDNishan/eden
def customize_org_organisation(**attr):
    """
        Customize org_organisation controller
        - Profile Page
    """

    s3db = current.s3db
    s3 = current.response.s3

    # Customise the cms_post table as that is used for the widgets
    customize_cms_post()

    # Represent used in rendering
    current.auth.settings.table_user.organisation_id.represent = s3db.org_organisation_represent

    # Load normal Model
    table = s3db.org_organisation

    alerts_widget = dict(
        label="Alerts",
        type="datalist",
        tablename="cms_post",
        context="organisation",
        filter=S3FieldSelector("series_id$name") == "Alert",
        icon="icon-alert",
        list_layout=render_profile_posts,
    )
    map_widget = dict(
        label="Location",
        type="map",
        context="organisation",
        icon="icon-map-marker",
    )
    incidents_widget = dict(
        label="Incidents",
        type="datalist",
        tablename="cms_post",
        context="organisation",
        filter=S3FieldSelector("series_id$name") == "Incident",
        icon="icon-warning-sign",
        list_layout=render_profile_posts,
    )
    assessments_widget = dict(
        label="Assessments",
        type="datalist",
        tablename="cms_post",
        context="organisation",
        filter=S3FieldSelector("series_id$name") == "Assessment",
        icon="icon-info-sign",
        list_layout=render_profile_posts,
    )
    activities_widget = dict(
        label="Activities",
        type="datalist",
        tablename="cms_post",
        context="organisation",
        filter=S3FieldSelector("series_id$name") == "Activity",
        icon="icon-activity",
        list_layout=render_profile_posts,
    )
    reports_widget = dict(
        label="Reports",
        type="datalist",
        tablename="cms_post",
        context="organisation",
        filter=S3FieldSelector("series_id$name") == "Report",
        icon="icon-report",
        list_layout=render_profile_posts,
    )
    comments_widget = dict(
        label="Comments",
        type="comments",
        icon="icon-comments-alt",
        colspan=2,
    )
    s3db.configure(
        "org_organisation",
        list_fields=[
            "id",
            "name",
            "logo",
        ],
        list_layout=render_organisations,
        profile_widgets=[
            alerts_widget,
            map_widget,
            incidents_widget,
            assessments_widget,
            activities_widget,
            reports_widget,
            #comments_widget,
        ],
    )

    ADD_ORGANISATION = T("New Stakeholder")
    s3.crud_strings["org_organisation"] = Storage(
        title_create=ADD_ORGANISATION,
        title_display=T("Stakeholder Details"),
        title_list=T("Stakeholders"),
        title_update=T("Edit Stakeholder"),
        title_search=T("Search Stakeholders"),
        subtitle_create=T("Add New Stakeholder"),
        label_list_button=T("List Stakeholders"),
        label_create_button=ADD_ORGANISATION,
        label_delete_button=T("Delete Stakeholder"),
        msg_record_created=T("Stakeholder added"),
        msg_record_modified=T("Stakeholder updated"),
        msg_record_deleted=T("Stakeholder deleted"),
        msg_list_empty=T("No Stakeholders currently registered"))

    crud_settings = s3.crud
    crud_settings.formstyle = "bootstrap"
    crud_settings.submit_button = T("Save changes")
    # Done already within Bootstrap formstyle (& anyway fails with this formstyle)
    #crud_settings.submit_style = "btn btn-primary"

    return attr
예제 #13
0
파일: config.py 프로젝트: MDNishan/eden
def customize_gis_location(**attr):
    """
        Customize gis_location controller
        - Profile Page
    """

    s3db = current.s3db
    s3 = current.response.s3

    # Customise the cms_post table as that is used for the widgets
    customize_cms_post()

    # Represent used in rendering
    current.auth.settings.table_user.organisation_id.represent = s3db.org_organisation_represent

    # Load normal Model
    table = s3db.gis_location

    alerts_widget = dict(
        label="Alerts",
        type="datalist",
        tablename="cms_post",
        context="location",
        filter=S3FieldSelector("series_id$name") == "Alert",
        icon="icon-alert",
        list_layout=render_profile_posts,
    )
    map_widget = dict(
        label="Location",
        type="map",
        context="location",
        icon="icon-map-marker",
    )
    incidents_widget = dict(
        label="Incidents",
        type="datalist",
        tablename="cms_post",
        context="location",
        filter=S3FieldSelector("series_id$name") == "Incident",
        icon="icon-warning-sign",
        list_layout=render_profile_posts,
    )
    assessments_widget = dict(
        label="Assessments",
        type="datalist",
        tablename="cms_post",
        context="location",
        filter=S3FieldSelector("series_id$name") == "Assessment",
        icon="icon-info-sign",
        list_layout=render_profile_posts,
    )
    activities_widget = dict(
        label="Activities",
        type="datalist",
        tablename="cms_post",
        context="location",
        filter=S3FieldSelector("series_id$name") == "Activity",
        icon="icon-activity",
        list_layout=render_profile_posts,
    )
    reports_widget = dict(
        label="Reports",
        type="datalist",
        tablename="cms_post",
        context="location",
        filter=S3FieldSelector("series_id$name") == "Report",
        icon="icon-report",
        list_layout=render_profile_posts,
    )
    comments_widget = dict(
        label="Comments",
        type="comments",
        icon="icon-comments-alt",
        colspan=2,
    )
    s3db.configure(
        "gis_location",
        list_layout=render_locations,
        profile_widgets=[
            alerts_widget,
            map_widget,
            incidents_widget,
            assessments_widget,
            activities_widget,
            reports_widget,
            #comments_widget,
        ],
    )

    crud_settings = s3.crud
    crud_settings.formstyle = "bootstrap"
    crud_settings.submit_button = T("Save changes")
    # Done already within Bootstrap formstyle (& anyway fails with this formstyle)
    #crud_settings.submit_style = "btn btn-primary"

    return attr
예제 #14
0
def email_inbox():
    """
        RESTful CRUD controller for the Email Inbox
        - all Inbound Email Messages are visible here

        @ToDo: Filter to those which have been unable to be automatically
               processed as being responses to Alerts
        @ToDo: Filter to those coming into the specific account used for
               Deployments
        @ToDo: Provide a mechanism (Action button?) to link a mail manually to
               an Alert
    """

    if not auth.s3_logged_in():
        session.error = T("Requires Login!")
        redirect(URL(c="default", f="user", args="login"))

    tablename = "msg_email"
    table = s3db.msg_email
    table.inbound.readable = False
    table.channel_id.readable = False
    table.to_address.readable = False

    from s3.s3resource import S3FieldSelector
    s3.filter = (S3FieldSelector("response.id") == None) & \
                (S3FieldSelector("inbound") == True)

    from s3.s3forms import S3SQLCustomForm, S3SQLInlineComponent
    crud_form = S3SQLCustomForm(
        "date",
        "subject",
        "from_address",
        "body",
        S3SQLInlineComponent(
            "attachment",
            name="document_id",
            label=T("Attachments"),
            fields=[
                "document_id",
            ],
        ),
    )

    s3db.configure(
        tablename,
        crud_form=crud_form,
        editable=False,
        insertable=False,
        list_fields=[
            "id",
            "date",
            "from_address",
            "subject",
            "body",
            (T("Attachments"), "attachment.document_id"),
        ],
    )

    # CRUD Strings
    s3.crud_strings[tablename] = Storage(
        title_list=T("View InBox"),
        title_update=T("Edit Message"),
        label_list_button=T("View InBox"),
        label_delete_button=T("Delete Message"),
        msg_record_modified=T("Message updated"),
        msg_record_deleted=T("Message deleted"),
        msg_list_empty=T("No Messages currently in InBox"))

    def prep(r):
        if r.id:
            s3db.msg_attachment.document_id.label = ""
        if r.component and r.component.alias == "select":
            if not r.method:
                r.method = "select"
            if r.method == "select":
                r.custom_action = s3db.deploy_response_select_mission
        return True

    s3.prep = prep

    def postp(r, output):
        if r.interactive:
            # Normal Action Buttons
            s3_action_buttons(r)
            # Custom Action Buttons
            s3.actions += [
                dict(label=str(T("Link to Mission")),
                     _class="action-btn link",
                     url=URL(f="email_inbox", args=["[id]", "select"])),
            ]

            if r.id:
                s3.rfooter = s3base.S3CRUD.crud_button(
                    T("Link to Mission"),
                    _href=URL(f="email_inbox", args=[r.id, "select"]),
                    _class="action-btn link",
                )
        return output

    s3.postp = postp

    return s3_rest_controller("msg", "email")