Beispiel #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.s3query import FS
        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(FS("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(FS("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
Beispiel #2
0
    def testAutomaticInterval(self):
        """ Test automatic determination of interval start and end """

        assertEqual = self.assertEqual
        assertTrue = self.assertTrue
        is_now = self.is_now

        s3db = current.s3db
        resource = s3db.resource("tp_test_events")

        event_start = resource.resolve_selector("event_start")
        event_end = resource.resolve_selector("event_end")

        tp = S3TimePlot()

        query = FS("event_type") == "STARTEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(tp.resource, event_start, event_end)
        # falls back to first start date
        assertEqual(ef.start, tp_datetime(2011, 1, 3, 0, 0, 0))
        assertTrue(is_now(ef.end))

        query = FS("event_type") == "NOSTART"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(tp.resource, event_start, event_end)
        # falls back to first end date minus 1 day
        assertEqual(ef.start, tp_datetime(2012, 2, 12, 0, 0, 0))
        assertTrue(is_now(ef.end))

        query = FS("event_type") == "NOEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(tp.resource, event_start, event_end)
        # falls back to first start date
        assertEqual(ef.start, tp_datetime(2012, 7, 21, 0, 0, 0))
        assertTrue(is_now(ef.end))

        tp.resource = s3db.resource("tp_test_events")
        ef = tp.create_event_frame(tp.resource, event_start, event_end)
        # falls back to first start date
        assertEqual(ef.start, tp_datetime(2011, 1, 3, 0, 0, 0))
        assertTrue(is_now(ef.end))
Beispiel #3
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 = FS("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
Beispiel #4
0
def person_search():
    """
        Person REST controller
        - limited to just search_ac for use in Autocompletes
        - allows differential access permissions
    """

    # Filter to just deployables (RDRT Members)
    s3.filter = FS("application.active") == True

    s3.prep = lambda r: r.method == "search_ac"

    return s3_rest_controller("pr", "person")
Beispiel #5
0
def human_resource():
    """
        RESTful CRUD Controller
    """

    # Tweak settings for RDRT
    settings.hrm.staff_experience = True
    settings.hrm.use_skills = True
    settings.search.filter_manager = True

    # Add deploy_alert_recipient as component so that we filter by it
    s3db.add_components("hrm_human_resource",
                        deploy_alert_recipient="human_resource_id")

    q = FS("application.active") == True
    output = s3db.hrm_human_resource_controller(extra_filter=q)
    return output
Beispiel #6
0
def human_resource():
    """
        RESTful CRUD Controller
    """

    # Tweak settings for RDRT
    # @ToDo: These should really be in customise_ in IFRC template
    settings.hrm.staff_experience = True
    settings.hrm.use_skills = True
    settings.search.filter_manager = True

    # Add deploy_alert_recipient as component so that we can filter by it
    s3db.add_components("hrm_human_resource",
                        deploy_alert_recipient = "human_resource_id",
                        )

    # Filter to just Deployables
    q = FS("application.active") != None
    output = s3db.hrm_human_resource_controller(extra_filter = q)
    return output
Beispiel #7
0
    def __call__(self):

        response = current.response
        output = {}
        s3 = response.s3

        from s3.s3query import FS
        s3db = current.s3db
        layout = s3.render_posts
        list_id = "news_datalist"
        limit = 10
        list_fields = ["series_id", "date", "title", "body"]

        resource = s3db.resource("cms_post")
        resource.add_filter(FS("series_id$name") == "Haberler")
        # Order with next Event first
        orderby = "date DESC"
        output["news"] = latest_records(resource, layout, list_id, limit,
                                        list_fields, orderby)

        self._view(THEME, "index.html")
        return output
Beispiel #8
0
    def testAutomaticSlotLength(self):
        """ Test automatic determination of reasonable aggregation time slot """

        s3db = current.s3db
        dt = datetime.datetime
        resource = s3db.resource("tp_test_events")

        event_start = resource.resolve_selector("event_start")
        event_end = resource.resolve_selector("event_end")

        tp = S3TimePlot()

        end = "2011-03-01"
        query = FS("event_type") == "STARTEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(event_start, event_end, end=end)
        # falls back to first start date
        self.assertEqual(ef.start, dt(2011, 1, 3, 0, 0, 0))
        self.assertEqual(ef.end, dt(2011, 3, 1, 0, 0, 0))
        # ~8 weeks => reasonable intervall length: weeks
        self.assertEqual(ef.slots, "weeks")

        end = "2013-01-01"
        query = FS("event_type") == "NOSTART"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(event_start, event_end, end=end)
        # falls back to first end date minus 1 day
        self.assertEqual(ef.start, dt(2012, 2, 12, 0, 0, 0))
        self.assertEqual(ef.end, dt(2013, 1, 1, 0, 0))
        # ~11 months => reasonable intervall length: months
        self.assertEqual(ef.slots, "months")

        end = "2016-06-01"
        query = FS("event_type") == "NOEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(event_start, event_end, end=end)
        # falls back to first start date
        self.assertEqual(ef.start, dt(2012, 7, 21, 0, 0, 0))
        self.assertEqual(ef.end, dt(2016, 6, 1, 0, 0))
        # ~4 years => reasonable intervall length: 3 months
        self.assertEqual(ef.slots, "3 months")

        end = "2011-01-15"
        tp.resource = s3db.resource("tp_test_events")
        ef = tp.create_event_frame(event_start, event_end, end=end)
        # falls back to first start date
        self.assertEqual(ef.start, dt(2011, 1, 3, 0, 0, 0))
        self.assertEqual(ef.end, dt(2011, 1, 15, 0, 0))
        # ~12 days => reasonable intervall length: days
        self.assertEqual(ef.slots, "days")

        # Check with manual slot length
        end = "2016-06-01"
        query = FS("event_type") == "NOEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(event_start,
                                   event_end,
                                   end=end,
                                   slots="years")
        # falls back to first start date
        self.assertEqual(ef.start, dt(2012, 7, 21, 0, 0, 0))
        self.assertEqual(ef.end, dt(2016, 6, 1, 0, 0))
        self.assertEqual(ef.slots, "years")

        # Check with manual start date
        start = "2011-02-15"
        end = "2011-03-01"
        query = FS("event_type") == "STARTEND"
        tp.resource = s3db.resource("tp_test_events", filter=query)
        ef = tp.create_event_frame(event_start,
                                   event_end,
                                   start=start,
                                   end=end)
        # falls back to first start date
        self.assertEqual(ef.start, dt(2011, 2, 15, 0, 0, 0))
        self.assertEqual(ef.end, dt(2011, 3, 1, 0, 0, 0))
        # ~14 days => reasonable intervall length: days
        self.assertEqual(ef.slots, "days")
Beispiel #9
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.s3query import FS
    s3.filter = (FS("response.id") == None) & \
                (FS("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):
        # Decode subject and sender fields
        decode = current.msg.decode_email
        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
            represent = lambda string: decode(string)
        elif not r.method and r.representation in ("html", "aadata"):
            # Use custom data table method to allow bulk deletion
            r.method = "inbox"
            r.custom_action = s3db.deploy_Inbox()
            represent = lambda string: s3base.s3_datatable_truncate(decode(string))
        table = r.resource.table
        table.subject.represent = represent
        table.from_address.represent = represent
        return True
    s3.prep = prep

    def postp(r, output):
        if r.interactive and r.record and not r.component:
            # Custom CRUD button for linking the message to mission
            authorised = auth.s3_has_permission("create", "deploy_response")
            if authorised:
                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")
Beispiel #10
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 = req_req_list_layout
        limit = 4
        resource = s3db.resource("req_req")
        req_customise_req_fields()
        list_fields = s3db.get_config("req_req", "list_fields")
        from s3.s3query import FS
        resource.add_filter(FS("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 = req_commit_list_layout
        #limit = 4

        resource = s3db.resource("req_commit")
        req_customise_commit_fields()
        list_fields = s3db.get_config("req_commit", "list_fields")
        resource.add_filter(FS("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
Beispiel #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 = (FS(searchFields[i]).like("%" + key + "%"))
                else:
                    query |= (FS(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()
Beispiel #12
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.s3query import FS
        s3db = current.s3db
        layout = s3db.cms_post_list_layout
        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(FS("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_customise_req_fields()
        list_fields = s3db.get_config("req_req", "list_fields")
        layout = s3db.req_req_list_layout
        resource.add_filter(FS("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(FS("~.method") != "delete")
        orderby = "s3_audit.timestmp desc"
        list_fields = [
            "id",
            "method",
            "user_id",
            "tablename",
            "record_id",
        ]
        #current.deployment_settings.ui.customise_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
Beispiel #13
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(FS("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,
                list_id="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,
                                                       list_id="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
Beispiel #14
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

        # Alerts Data List
        resource = s3db.resource("cms_post")
        # Only show Alerts
        #resource.add_filter(FS("series_id$name").belongs(["Alert"]))
        #resource.add_filter(FS("post.series_id") != None)
        # Only show Open Alerts
        resource.add_filter(FS("expired") == False)
        # Only show Alerts which are linked to Open Incidents
        resource.add_filter(FS("incident.closed") == False)
        list_id = "cms_post_datalist"
        list_fields = [  #"series_id",
            "location_id",
            "date",
            "body",
            "created_by",
            "created_by$organisation_id",
            "document.file",
            "event_post.event_id",
        ]
        # Order with most recent Alert first
        orderby = "cms_post.date desc"
        datalist, numrows, ids = resource.datalist(
            fields=list_fields,
            #start = None,
            limit=5,
            list_id=list_id,
            orderby=orderby,
            layout=s3db.cms_post_list_layout)
        ajax_url = URL(c="cms",
                       f="post",
                       args="datalist.dl",
                       vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl=ajax_url, pagesize=5)

        # Incidents Data List
        resource = s3db.resource("event_incident")
        # Only show Open Incidents
        resource.add_filter(FS("closed") == False)
        list_id = "event_incident_datalist"
        list_fields = [
            "name",
            "location_id",
            "zero_hour",
            "modified_by",
            "organisation_id",
            "comments",
        ]
        # Order with most recent Incident first
        orderby = "event_incident.zero_hour desc"
        datalist, numrows, ids = resource.datalist(
            fields=list_fields,
            #start = None,
            limit=5,
            list_id=list_id,
            orderby=orderby,
            layout=s3db.event_incident_list_layout)
        ajax_url = URL(c="event",
                       f="incident",
                       args="datalist.dl",
                       vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl=ajax_url, pagesize=5)

        # Tasks Data List
        resource = s3db.resource("project_task")
        # Only show Active Tasks
        active_statuses = s3db.project_task_active_statuses
        resource.add_filter(FS("status").belongs(active_statuses))
        # Only show Tasks which are linked to Open Incidents
        resource.add_filter(FS("incident.incident_id$closed") == False)
        list_id = "project_task_datalist"
        list_fields = [
            "name",
            "description",
            "comments",
            "location_id",
            "priority",
            "status",
            "date_due",
            "pe_id",
            "task_project.project_id",
            #"organisation_id$logo",
            "modified_by",
            "source_url"
        ]
        # Order with most urgent Task first
        orderby = "project_task.date_due asc"
        datalist, numrows, ids = resource.datalist(
            fields=list_fields,
            #start = None,
            limit=5,
            list_id=list_id,
            orderby=orderby,
            layout=s3db.project_task_list_layout)
        ajax_url = URL(c="project",
                       f="task",
                       args="datalist.dl",
                       vars={"list_id": list_id})
        output[list_id] = datalist.html(ajaxurl=ajax_url, pagesize=5)

        # MCOP RSS 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
Beispiel #15
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
                table = s3db.org_group
                row = db(table.id == org_group_id).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(FS("~.method") != "delete")
        orderby = "s3_audit.timestmp desc"
        list_fields = [
            "id",
            "method",
            "user_id",
            "tablename",
            "record_id",
        ]
        #current.deployment_settings.ui.customise_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"),
                        },
                        cols=2,
                        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