示例#1
0
    def customise_project_activity_resource(r, tablename):

        from s3 import S3OptionsFilter
        filter_widgets = [S3OptionsFilter("activity_activity_type.activity_type_id",
                                          label = T("Type"),
                                          ),
                          S3OptionsFilter("project_id",
                                          represent = "%(name)s",
                                          ),
                          ]

        report_fields = [(T("Project"), "project_id"),
                         (T("Activity"), "name"),
                         (T("Activity Type"), "activity_type.name"),
                         (T("Sector"), "project_id$sector.name"),
                         (T("Time Estimated"), "time_estimated"),
                         (T("Time Actual"), "time_actual"),
                         ]

        report_options = Storage(rows = report_fields,
                                 cols = report_fields,
                                 fact = report_fields,
                                 defaults = Storage(rows = "activity.project_id",
                                                    cols = "activity.name",
                                                    fact = "sum(activity.time_actual)",
                                                    totals = True,
                                                    )
                                 )

        current.s3db.configure(tablename,
                               filter_widgets = filter_widgets,
                               report_options = report_options,
                               )
示例#2
0
文件: config.py 项目: thuyxd/Turkey
        def custom_prep(r):
            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
            else:
                result = True

            s3db = current.s3db
            from s3 import S3TextFilter, S3OptionsFilter, S3LocationFilter
            filter_widgets = [
                S3TextFilter(
                    [
                        "reference",
                        "person_id$first_name",
                        "person_id$middle_name",
                        "person_id$last_name",
                    ],
                    label=T("Search"),
                ),
            ]
            filter_widgets.append(S3OptionsFilter("person_id$gender"))
            if is_admin:
                filter_widgets.append(S3OptionsFilter("organisation_id"))

            s3db.configure("dvr_case", filter_widgets=filter_widgets)

            return result
示例#3
0
    def customise_org_facility_resource(r, tablename):

        from s3 import S3LocationFilter, S3OptionsFilter, S3TextFilter

        filter_widgets = [
            S3TextFilter(
                ["name"],
                label=T("Search"),
                comment=T(
                    "Search by facility name. You can use * as wildcard."),
            ),
            S3OptionsFilter("site_facility_type.facility_type_id", ),
            S3OptionsFilter("organisation_id", ),
            S3LocationFilter("location_id", ),
        ]

        s3db = current.s3db

        s3db.configure(
            tablename,
            filter_widgets=filter_widgets,
        )

        # Customize fields
        table = s3db.org_facility

        # Main facility flag visible and in custom crud form
        field = table.main_facility
        field.readable = field.writable = True
        crud_form = s3db.get_config(tablename, "crud_form")
        crud_form.insert(-2, "main_facility")

        # "Obsolete" labeled as "inactive"
        field = table.obsolete
        field.label = T("Inactive")
示例#4
0
    def customise_org_facility_resource(r, tablename):

        s3db = current.s3db

        # Custom filter widgets
        from s3 import S3LocationFilter, S3OptionsFilter, S3TextFilter
        filter_widgets = [
            S3TextFilter(
                ["name"],
                label=T("Search"),
                comment=T(
                    "Search by facility name. You can use * as wildcard."),
            ),
            S3OptionsFilter("site_facility_type.facility_type_id", ),
            S3OptionsFilter("organisation_id", ),
            S3LocationFilter("location_id", ),
        ]

        # Custom list fields
        list_fields = [
            "name",
            "site_facility_type.facility_type_id",
            "organisation_id",
            "location_id",
            "opening_times",
            "contact",
            "phone1",
            "phone2",
            "email",
            #"website",
            "obsolete",
            #"comments",
        ]

        s3db.configure(
            tablename,
            filter_widgets=filter_widgets,
            list_fields=list_fields,
        )

        # Customise fields
        table = s3db.org_facility

        # Main facility flag visible and in custom crud form
        field = table.main_facility
        field.readable = field.writable = True
        crud_form = s3db.get_config(tablename, "crud_form")
        crud_form.insert(-2, "main_facility")

        # "Obsolete" labeled as "inactive"
        field = table.obsolete
        field.label = T("Inactive")
        field.represent = lambda opt: T("Inactive") \
                                      if opt else current.messages["NONE"]
        field.readable = field.writable = True

        # Not using facility code
        field = table.code
        field.readable = field.writable = False
示例#5
0
    def __call__(self):
        """ Main entry point, configuration """

        T = current.T
        s3db = current.s3db
        settings = current.deployment_settings
        gis = current.gis

        # Must be logged in
        auth = current.auth
        if not auth.s3_logged_in():
            auth.permission.fail()

        # Available resources
        resources = [
            dict(resource="cap_alert", url="cap/alert", label=T("Updates")),
        ]

        # Filter widgets
        # @note: subscription manager has no resource context, so
        #        must configure fixed options or lookup resources
        #        for filter widgets which need it.
        filters = [
            S3OptionsFilter(
                "category",
                label=T("Category"),
                options=s3db.cap_info_category_opts,
                represent="%(name)s",
                resource="cap_info",
                _name="category-filter",
            ),
            S3LocationFilter(
                "location_id",
                label=T("Location(s)"),
                levels=("L0", ),
                resource="cap_area_location",
                options=gis.get_countries().keys(),
                _name="location-filter",
            ),
            S3OptionsFilter(
                "language",
                label=T("Language"),
                options=settings.get_cap_languages(),
                represent="%(name)s",
                resource="cap_info",
                _name="language-filter",
            ),
        ]

        # Title and view
        title = T("Notification Settings")
        self._view(THEME, "subscriptions.html")

        # Form
        form = self._manage_subscriptions(resources, filters)

        return dict(title=title, form=form)
示例#6
0
    def customise_org_organisation_resource(r, tablename):

        s3db = current.s3db

        # Simplify form
        table = s3db.org_organisation
        field = table.year
        field.readable = field.writable = False
        field = table.country
        field.readable = field.writable = False

        if not current.auth.is_logged_in():
            field = table.logo
            field.readable = field.writable = False
            # User can create records since we need this during registration,
            # but we don't want to let the user do this from the list view
            s3db.configure(
                "org_organisation",
                listadd=False,
            )

        # Custom filters to match the information provided
        from s3 import S3LocationFilter, S3OptionsFilter, S3TextFilter
        filter_widgets = [
            S3TextFilter(
                [
                    "name",
                    "acronym",
                    #"website",
                    #"comments",
                ],
                label=T("Search"),
                comment=
                T("Search by organization name or acronym. You can use * as wildcard."
                  ),
            ),
            S3OptionsFilter("sector_organisation.sector_id", ),
            S3OptionsFilter(
                "organisation_organisation_type.organisation_type_id",
                label=T("Type"),
            ),
            S3LocationFilter(
                "organisation_location.location_id",
                label=T("Areas Served"),
                levels=("L1", "L2", "L3", "L4"),
                #hidden = True,
            ),
        ]

        s3db.configure(
            "org_organisation",
            filter_widgets=filter_widgets,
        )
示例#7
0
文件: requests.py 项目: sahana/eden
def recv_filter_widgets():
    """
        Filter widgets for incoming shipments

        @returns: list of filter widgets
    """

    T = current.T

    from s3 import S3DateFilter, \
                   S3OptionsFilter, \
                   S3TextFilter, \
                   s3_get_filter_opts
    from s3db.inv import SHIP_STATUS_CANCEL, \
                         SHIP_STATUS_RETURNING, \
                         inv_shipment_status_labels

    recv_status_opts = OrderedDict(
        sorted(
            inv_shipment_status_labels().items(),
            key=lambda i: i[0],
        ))
    # We don't currently use these statuses
    del recv_status_opts[SHIP_STATUS_CANCEL]
    del recv_status_opts[SHIP_STATUS_RETURNING]

    filter_widgets = [
        S3TextFilter(
            [
                "req_ref",
                #"send_ref",
            ],
            label=T("Search"),
        ),
        S3OptionsFilter(
            "status",
            cols=3,
            options=recv_status_opts,
            sort=False,
        ),
        S3DateFilter(
            "date",
            hidden=True,
        ),
        S3OptionsFilter(
            "track_item.item_id",
            hidden=True,
            options=lambda: s3_get_filter_opts("supply_item"),
        ),
    ]

    return filter_widgets
示例#8
0
    def customise_hrm_human_resource_resource(r, tablename):

        s3db = current.s3db

        if r.interactive:
            # Custom CRUD form
            from s3 import S3SQLCustomForm
            crud_form = S3SQLCustomForm(
                "organisation_id",
                "person_id",
                "job_title_id",
                "department_id",
            )

            # Custom filter widgets
            from s3 import S3TextFilter, S3OptionsFilter, s3_get_filter_opts
            filter_widgets = [
                S3TextFilter(
                    [
                        "person_id$first_name",
                        "person_id$middle_name",
                        "person_id$last_name",
                        "person_id$email.value",
                    ],
                    label=T("Search"),
                    comment=T("You can search by name or email address."),
                ),
                S3OptionsFilter(
                    "organisation_id",
                    filter=True,
                    header="",
                ),
                S3OptionsFilter(
                    "job_title_id",
                    options=s3_get_filter_opts("hrm_job_title"),
                    hidden=True,
                ),
            ]

            s3db.configure(
                "hrm_human_resource",
                crud_form=crud_form,
                filter_widgets=filter_widgets,
            )

        # Configure table
        s3db.configure(
            "hrm_human_resource",
            list_fields=human_resource_list_fields,
        )
示例#9
0
def due_followups():
    """ RESTful Controller for Due Follow-ups """

    # CRUD Strings
    s3.crud_strings["po_household_followup"] = Storage(
        title_display=T("Follow-up Details"),
        title_list=T("Due Follow-ups"),
        title_update=T("Edit Follow-up Details"),
        label_list_button=T("List Follow-ups"),
        msg_record_modified=T("Follow-up Details updated"),
        msg_list_empty=T("No due follow-ups"),
    )

    # Filter Widgets
    from s3 import S3DateFilter, S3OptionsFilter, S3TextFilter
    filter_widgets = [
        S3TextFilter(
            [
                "household_id$location_id$addr_street",
                "followup_required",
                "comments",
            ],
            label=T("Search"),
        ),
        S3OptionsFilter("household_id$area_id"),
        S3DateFilter(
            "household_id$date_visited",
            label=T("Date visited"),
            hidden=True,
        ),
        S3DateFilter(
            "followup_date",
            hidden=True,
        ),
    ]

    s3db.configure(
        "po_household_followup",
        insertable=False,
        deletable=False,
        filter_widgets=filter_widgets,
        list_fields=[
            "followup_date",
            "household_id$area_id",
            "household_id",
            "followup_required",
            "comments",
        ],
    )

    def prep(r):
        if not r.record:
            query = (FS("followup_date") <= datetime.datetime.utcnow().date()) & \
                    (FS("completed") != True)
            r.resource.add_filter(query)
        return True

    s3.prep = prep

    return s3_rest_controller("po", "household_followup")
示例#10
0
文件: pr.py 项目: xetch/eden
    def prep(r):
        person_id = get_vars.get("person", None)
        if person_id:
            # Coming from s3.contacts.js [s3db.pr_Contacts()]
            # Lookup the controller
            controller = get_vars.get("controller", "pr")
            # Lookup the access
            access = get_vars.get("access", None)
            if access is None:
                method = "contacts"
            elif access == "1":
                method = "private_contacts"
            elif access == "2":
                method = "public_contacts"
            s3db.configure("pr_contact",
                           create_next = URL(c=controller,
                                             f="person",
                                             args=[person_id, method]),
                           update_next = URL(c=controller,
                                             f="person",
                                             args=[person_id, method])
                           )
            if r.method == "create":
                table = s3db.pr_person
                pe_id = db(table.id == person_id).select(table.pe_id,
                                                         limitby=(0, 1)
                                                         ).first().pe_id
                table = s3db.pr_contact
                table.pe_id.default = pe_id
                # Public or Private?
                if access:
                    table.access.default = access
        else:
            field = s3db.pr_contact.pe_id
            if r.method in ("create", "create.popup"):
                # Coming from Profile page
                pe_id = get_vars.get("~.pe_id", None)
                if pe_id:
                    field.default = pe_id
                else:
                    field.label = T("Entity")
                    field.readable = field.writable = True
            else:
                # @ToDo: Document which workflow uses this?
                field.label = T("Entity")
                field.readable = field.writable = True
                from s3 import S3TextFilter, S3OptionsFilter
                filter_widgets = [S3TextFilter(["value",
                                                "comments",
                                                ],
                                               label = T("Search"),
                                               comment = T("You can search by value or comments."),
                                               ),
                                  S3OptionsFilter("contact_method"),
                                  ]
                s3db.configure("pr_contact",
                               filter_widgets = filter_widgets,
                               )

        return True
示例#11
0
def monitor_task():

    from s3 import S3OptionsFilter, s3_set_default_filter

    tablename = "setup_monitor_task"

    filter_widgets = [S3OptionsFilter("enabled",
                                      label = T("Enabled"),
                                      options = {True: T("Yes"),
                                                 False: T("No"),
                                                 },
                                      cols = 2,
                                      ),
                      ]

    s3db.configure(tablename,
                   filter_widgets = filter_widgets,
                   orderby = "setup_monitor_task.status desc",
                   )

    # Only show Enabled Tasks by default
    # @ToDo: Also hide those from disabled Servers
    s3_set_default_filter("~.enabled",
                          lambda selector, tablename: True,
                          tablename = tablename)

    def postp(r, output):
        if r.interactive and not r.id:
            # Normal Action Buttons
            s3_action_buttons(r)
            # Custom Action Buttons for Enable/Disable
            table = r.table
            rows = db(table.deleted == False).select(table.id,
                                                     table.enabled,
                                                     )
            restrict_e = [str(row.id) for row in rows if not row.enabled]
            restrict_d = [str(row.id) for row in rows if row.enabled]
            s3.actions += [{"url": URL(args=["[id]", "enable"]),
                            "_class": "action-btn",
                            "label": s3_str(T("Enable")),
                            "restrict": restrict_e,
                            },
                           {"url": URL(args = ["[id]", "disable"]),
                            "_class": "action-btn",
                            "label": s3_str(T("Disable")),
                            "restrict": restrict_d,
                            },
                           ]
            if not s3task._is_alive():
                # No Scheduler Running
                s3.actions.append({"url": URL(args = ["[id]", "check"]),
                                   "_class": "action-btn",
                                   "label": s3_str(T("Check")),
                                   })
        return output
    s3.postp = postp

    return s3_rest_controller(rheader = s3db.setup_rheader,
                              )
示例#12
0
文件: config.py 项目: thuyxd/Turkey
        def custom_prep(r):
            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
            else:
                result = True
            if r.controller == "vol":
                s3db = current.s3db
                list_fields = ["course_id$code"]
                list_fields.append("course_id")
                list_fields.append("person_id")

                from s3 import S3TextFilter, S3OptionsFilter, S3LocationFilter
                filter_widgets = [
                    S3TextFilter(
                        [
                            "course_id$code",
                            "course_id$name",
                            "person_id$first_name",
                            "person_id$middle_name",
                            "person_id$last_name",
                        ],
                        label=T("Search"),
                    ),
                ]
                if is_admin:
                    filter_widgets.append(
                        S3OptionsFilter("course_id$organisation_id"))
                filter_widgets.append(
                    S3LocationFilter(
                        "person_id$location_id",
                        levels=("L1", "L2", "L3", "L4"),
                        label=T("Location"),
                        #hidden = True,
                    ), )
                filter_widgets.append(S3OptionsFilter("course_id"))

                s3db.configure("hrm_training",
                               list_fields=list_fields,
                               filter_widgets=filter_widgets)

            return result
示例#13
0
    def __call__(self):
        """ Main entry point, configuration """

        T = current.T

        # Must be logged in
        auth = current.auth
        if not auth.s3_logged_in():
            auth.permission.fail()

        # Available resources
        resources = [
            dict(resource="cms_post",
                 url="default/index/newsfeed",
                 label=T("Updates")),
        ]

        # Filter widgets
        # @note: subscription manager has no resource context, so
        #        must configure fixed options or lookup resources
        #        for filter widgets which need it.
        filters = [
            S3OptionsFilter(
                "series_id",
                label=T("Subscribe to"),
                represent="%(name)s",
                cols=2,
                resource="cms_post",
                _name="type-filter",
            ),
            S3LocationFilter(
                "location_id",
                label=T("Location(s)"),
                levels=("L1", ),
                resource="cms_post",
                _name="location-filter",
            ),
            #S3OptionsFilter("created_by$organisation_id",
            #                label = T("Filter by Organization"),
            #                represent = s3db.org_organisation_represent,
            #                #represent = "%(name)s",
            #                resource = "cms_post",
            #                _name = "organisation-filter",
            #                ),
        ]

        # Title and view
        title = T("Notification Settings")
        self._view(THEME, "subscriptions.html")

        # Form
        form = self._manage_subscriptions(resources, filters)

        return dict(title=title, form=form)
示例#14
0
文件: config.py 项目: Neetuj/eden
def customise_stats_demographic_data_resource(r, tablename):

    s3db = current.s3db
    table = s3db.stats_demographic_data

    # Add a Timeplot tab to summary page
    # @ToDo: Widget version of timeplot
    #settings.ui.summary = list(settings.ui.summary) + {"name": "timeplot",
    #                                                   "label": "TimePlot",
    #                                                   "widgets": [{"method": "timeplot", "ajax_init": True}],
    #                                                   }

    from s3 import S3OptionsFilter, S3LocationFilter
    filter_widgets = [S3OptionsFilter("parameter_id",
                                      label = T("Type"),
                                      multiple = False,
                                      # Not translateable
                                      #represent = "%(name)s",
                                      ),
                      # @ToDo: 'Month' &/or Week VF
                      #S3OptionsFilter("month",
                      #                #multiple = False,
                      #                operator = "anyof",
                      #                options = lambda: \
                      #                  stats_month_options("stats_demographic_data"),
                      #                ),
                      ]
    
    if r.method != "timeplot":
        # This is critical for the Map, but breaks aggregated Report data
        filter_widgets.append(S3OptionsFilter("location_id$level",
                                              label = T("Level"),
                                              multiple = False,
                                              # Not translateable
                                              #represent = "%(name)s",
                                              ))
    filter_widgets.append(S3LocationFilter("location_id"))
示例#15
0
    def prep(r):
        person_id = get_vars.get("person", None)
        if person_id:
            # Currently no other options available, but we could create hrm
            # & vol specific versions
            controller = get_vars.get("controller", "pr")
            s3db.configure("pr_contact",
                           create_next=URL(c=controller,
                                           f="person",
                                           args=[person_id, "contacts"]),
                           update_next=URL(c=controller,
                                           f="person",
                                           args=[person_id, "contacts"]))
            if r.method == "create":
                table = s3db.pr_person
                pe_id = db(table.id == person_id).select(
                    table.pe_id, limitby=(0, 1)).first().pe_id
                s3db.pr_contact.pe_id.default = pe_id

        elif r.method in ("create", "create.popup"):
            # Coming from Profile page
            pe_id = get_vars.get("~.pe_id", None)
            if pe_id:
                s3db.pr_contact.pe_id.default = pe_id

        else:
            from s3 import S3TextFilter, S3OptionsFilter
            filter_widgets = [
                S3TextFilter(
                    [
                        "value",
                        "comments",
                    ],
                    label=T("Search"),
                    comment=T("You can search by value or comments."),
                ),
                S3OptionsFilter("contact_method"),
            ]
            s3db.configure(
                "pr_contact",
                filter_widgets=filter_widgets,
            )

        return True
示例#16
0
    def __call__(self):
        """ Main entry point, configuration """

        T = current.T
        s3db = current.s3db

        # Must be logged in
        auth = current.auth
        if not auth.s3_logged_in():
            auth.permission.fail()

        # Available resources
        resources = [
            dict(resource="project_task",
                 url="project/task",
                 label=T("Updates")),
        ]

        # Filter widgets
        # @note: subscription manager has no resource context, so
        #        must configure fixed options or lookup resources
        #        for filter widgets which need it.

        filters = [
            S3OptionsFilter(
                "task_project.project_id",
                label="Project",
                resource="project_project",
                _name="project-filter",
                options=s3db.project_task_project_opts(),
            ),
        ]

        # Title and view
        title = T("Notification Settings")
        self._view(THEME, "subscriptions.html")

        # Form
        form = self._manage_subscriptions(resources, filters)

        return dict(title=title, form=form)
示例#17
0
文件: br.py 项目: rashedomar/eden
    def prep(r):

        resource = r.resource
        table = resource.table

        labels = s3db.br_terminology()
        human_resource_id = auth.s3_logged_in_human_resource()

        # Filter for valid+open cases
        query = (FS("person_id$case.id") != None) & \
                (FS("person_id$case.invalid") == False) & \
                (FS("person_id$case.status_id$is_closed") == False)

        resource.add_filter(query)

        if not r.record:

            # Enable bigtable features for better performance
            settings.base.bigtable = True

            get_vars = r.get_vars
            crud_strings = response.s3.crud_strings["br_case_activity"]

            # Filter for "my activities"
            mine = get_vars.get("mine")
            if mine == "1":
                mine = True
                if human_resource_id:
                    query = FS("human_resource_id") == human_resource_id
                else:
                    query = FS("human_resource_id").belongs(set())
                resource.add_filter(query)
                crud_strings.title_list = T("My Activities")
            else:
                mine = False

            # Adapt list title when filtering for priority 0 (Emergency)
            if get_vars.get("~.priority") == "0":
                crud_strings.title_list = T("Emergencies")

            case_activity_status = settings.get_br_case_activity_status()
            case_activity_need = settings.get_br_case_activity_need()

            # Default status
            if case_activity_status:
                s3db.br_case_activity_default_status()

            # Filter widgets
            from s3 import S3DateFilter, \
                           S3OptionsFilter, \
                           S3TextFilter, \
                           s3_get_filter_opts

            text_filter_fields = [
                "person_id$pe_label",
                "person_id$first_name",
                "person_id$middle_name",
                "person_id$last_name",
            ]
            if settings.get_br_case_activity_subject():
                text_filter_fields.append("subject")
            if settings.get_br_case_activity_need_details():
                text_filter_fields.append("need_details")

            filter_widgets = [
                S3TextFilter(
                    text_filter_fields,
                    label=T("Search"),
                ),
            ]

            multiple_orgs = s3db.br_case_read_orgs()[0]
            if multiple_orgs:
                filter_widgets.append(
                    S3OptionsFilter("person_id$case.organisation_id"))

            if case_activity_status:
                stable = s3db.br_case_activity_status
                query = (stable.deleted == False)
                rows = db(query).select(
                    stable.id,
                    stable.name,
                    stable.is_closed,
                    cache=s3db.cache,
                    orderby=stable.workflow_position,
                )
                status_filter_options = OrderedDict(
                    (row.id, T(row.name)) for row in rows)
                status_filter_defaults = [
                    row.id for row in rows if not row.is_closed
                ]
                filter_widgets.append(
                    S3OptionsFilter(
                        "status_id",
                        options=status_filter_options,
                        default=status_filter_defaults,
                        cols=3,
                        hidden=True,
                        sort=False,
                    ))

            if not mine and settings.get_br_case_activity_manager():
                filter_widgets.append(
                    S3OptionsFilter(
                        "human_resource_id",
                        hidden=True,
                    ))

            filter_widgets.extend([
                S3DateFilter(
                    "date",
                    hidden=True,
                ),
                S3OptionsFilter(
                    "person_id$person_details.nationality",
                    label=T("Client Nationality"),
                    hidden=True,
                ),
            ])

            if case_activity_need:
                org_specific_needs = settings.get_br_needs_org_specific()
                filter_widgets.append(S3OptionsFilter("need_id",
                                                      hidden = True,
                                                      header = True,
                                                      options = lambda: \
                                                                s3_get_filter_opts(
                                                                  "br_need",
                                                                  org_filter = org_specific_needs,
                                                                  translate = True,
                                                                  ),
                                                      ))

            resource.configure(filter_widgets=filter_widgets)

            # Report options
            if r.method == "report":
                facts = (
                    (T("Number of Activities"), "count(id)"),
                    (labels.NUMBER_OF_CASES, "count(person_id)"),
                )
                axes = [
                    "person_id$case.organisation_id",
                    "person_id$gender",
                    "person_id$person_details.nationality",
                    "person_id$person_details.marital_status",
                    "priority",
                ]
                default_rows = "person_id$case.organisation_id"
                default_cols = "person_id$person_details.nationality"

                if settings.get_br_manage_assistance() and \
                   settings.get_br_assistance_themes():
                    axes.insert(1, "assistance_measure_theme.theme_id")
                if case_activity_need:
                    axes.insert(1, "need_id")
                    default_cols = "need_id"
                if case_activity_status:
                    axes.insert(4, "status_id")

                report_options = {
                    "rows": axes,
                    "cols": axes,
                    "fact": facts,
                    "defaults": {
                        "rows": default_rows,
                        "cols": default_cols,
                        "fact": "count(id)",
                        "totals": True,
                    },
                }
                resource.configure(report_options=report_options)

        # Set default for human_resource_ids
        if human_resource_id:
            table.human_resource_id.default = human_resource_id

            utable = s3db.br_case_activity_update
            utable.human_resource_id.default = human_resource_id

        # Represent person_id as link to case file
        field = table.person_id
        field.label = labels.CASE
        field.represent = s3db.pr_PersonRepresent(show_link=True)

        # Add case data to list fields
        list_fields = resource.get_config("list_fields")
        list_fields[1:1] = [
            (T("ID"), "person_id$pe_label"),
            "person_id",
        ]

        # Create/delete must happen on case file tab, not here
        resource.configure(
            insertable=False,
            deletable=False,
        )

        return True
示例#18
0
文件: br.py 项目: rashedomar/eden
    def prep(r):

        # Filter to persons who have a case registered
        resource = r.resource
        resource.add_filter(FS("case.id") != None)

        labels = s3db.br_terminology()
        CASES = labels.CASES

        human_resource_id = auth.s3_logged_in_human_resource()
        insertable = True

        record = r.record
        if not record:

            # Enable bigtable strategies for better performance
            settings.base.bigtable = True

            get_vars = r.get_vars
            queries = []

            # Filter for "my cases"
            mine = get_vars.get("mine")
            if mine == "1":
                if human_resource_id:
                    queries.append(
                        FS("case.human_resource_id") == human_resource_id)
                else:
                    queries.append(FS("case.human_resource_id").belongs(set()))
                CURRENT = labels.CURRENT_MINE
                CASES = labels.CASES_MINE
            else:
                query = None
                CURRENT = labels.CURRENT

            # Filter to open/closed cases
            closed = get_vars.get("closed")
            get_status_filter_opts = s3db.br_case_status_filter_opts
            if closed == "1":
                # Only closed cases
                queries.append(FS("case.status_id$is_closed") == True)
                CASES = labels.CLOSED
                insertable = False
                status_filter_opts = lambda: get_status_filter_opts(closed=True
                                                                    )
            elif closed == "0":
                # Only open cases
                queries.append((FS("case.status_id$is_closed") == False) | \
                               (FS("case.status_id$is_closed") == None))
                CASES = CURRENT
                status_filter_opts = lambda: get_status_filter_opts(closed=
                                                                    False)
            else:
                status_filter_opts = get_status_filter_opts

            # Filter to valid/invalid cases
            invalid = get_vars.get("invalid")
            if invalid == "1":
                queries.append(FS("case.invalid") == True)
                CASES = T("Invalid Cases")
                insertable = False
            else:
                queries.append((FS("case.invalid") == False) | \
                               (FS("case.invalid") == None))

            if queries:
                query = reduce(lambda a, b: a & b, queries)
                resource.add_filter(query)

        # Adapt CRUD strings to perspective (& terminology)
        crud_strings = s3db.br_crud_strings("pr_person")
        crud_strings.title_list = CASES
        s3.crud_strings["pr_person"] = crud_strings

        # Configure Anonymizer
        from s3 import S3Anonymize
        s3db.set_method(
            "pr",
            "person",
            method="anonymize",
            action=S3Anonymize,
        )

        # Update resource configuration for perspective
        resource.configure(
            anonymize=s3db.br_person_anonymize(),
            deletable=False,
            insertable=insertable,
        )

        # Configure ID Cards
        if id_card_export:
            if r.representation == "card":
                # Configure ID card layout
                resource.configure(pdf_card_layout=id_card_layout,
                                   #pdf_card_pagesize="A4",
                                   )

            if not r.id and not r.component:
                # Add export-icon for ID cards
                export_formats = list(settings.get_ui_export_formats())
                export_formats.append(
                    ("card", "fa fa-id-card", T("Export ID Cards")))
                settings.ui.export_formats = export_formats
                s3.formats["card"] = r.url(method="")

        if not r.component:

            # Module-specific field and form configuration
            from s3 import S3SQLInlineComponent

            # Adapt fields to module context
            table = resource.table
            ctable = s3db.br_case
            multiple_orgs = s3db.br_case_read_orgs()[0]

            # Configure pe_label
            field = table.pe_label
            field.label = T("ID")
            field.comment = None

            # Make gender mandatory, remove "unknown"
            field = table.gender
            field.default = None
            options = dict(s3db.pr_gender_opts)
            del options[1]  # Remove "unknown"
            field.requires = IS_PERSON_GENDER(options, sort=True)

            # Configure case.organisation_id
            field = ctable.organisation_id
            field.comment = None
            if not field.default:
                default_org, selectable = s3db.br_case_default_org()
                if default_org and settings.get_br_case_hide_default_org():
                    field.writable = selectable
                    field.readable = selectable or multiple_orgs
                field.default = default_org
            requires = field.requires
            if isinstance(requires, IS_EMPTY_OR):
                field.requires = requires.other

            # Configure case.human_resource_id
            field = ctable.human_resource_id
            if settings.get_br_case_manager():
                if human_resource_id:
                    field.default = human_resource_id
                field.readable = field.writable = True
            else:
                field.readable = field.writable = False

            # Size of family
            if settings.get_br_household_size() in (False, "auto"):
                field = ctable.household_size
                field.readable = field.writable = False

            # Address (optional)
            if settings.get_br_case_address():
                address = S3SQLInlineComponent(
                    "address",
                    label=T("Current Address"),
                    fields=[("", "location_id")],
                    filterby={
                        "field": "type",
                        "options": "1",
                    },
                    link=False,
                    multiple=False,
                )
            else:
                address = None

            # Language details (optional)
            if settings.get_br_case_language_details():
                language_details = S3SQLInlineComponent(
                    "case_language",
                    fields=[
                        "language",
                        "quality",
                        "comments",
                    ],
                    label=T("Language / Communication Mode"),
                )
            else:
                language_details = None

            # Expose the "invalid"-flag? (update forms only)
            if record and r.method != "read":
                field = ctable.invalid
                field.readable = field.writable = True

            # Custom CRUD form
            crud_fields = [
                "case.date",
                "case.organisation_id",
                "case.human_resource_id",
                "case.status_id",
                "pe_label",
                # +name fields
                "person_details.nationality",
                "date_of_birth",
                "gender",
                "person_details.marital_status",
                "case.household_size",
                address,
                S3SQLInlineComponent(
                    "contact",
                    fields=[("", "value")],
                    filterby={
                        "field": "contact_method",
                        "options": "SMS",
                    },
                    label=T("Mobile Phone"),
                    multiple=False,
                    name="phone",
                ),
                "person_details.literacy",
                language_details,
                "case.comments",
                "case.invalid",
            ]

            # Custom list fields
            list_fields = [
                "pe_label",
                # +name fields
                "gender",
                "date_of_birth",
                "person_details.nationality",
                "case.date",
                "case.status_id",
            ]

            # Add organisation if user can see cases from multiple orgs
            if multiple_orgs:
                list_fields.insert(-2, "case.organisation_id")

            # Insert name fields in name-format order
            NAMES = ("first_name", "middle_name", "last_name")
            keys = s3base.StringTemplateParser.keys(
                settings.get_pr_name_format())
            name_fields = [fn for fn in keys if fn in NAMES]
            crud_fields[5:5] = name_fields
            list_fields[1:1] = name_fields

            resource.configure(
                crud_form=s3base.S3SQLCustomForm(*crud_fields),
                list_fields=list_fields,
            )

            # Filter Widgets
            if not record:
                from s3 import S3TextFilter, S3DateFilter, S3OptionsFilter
                filter_widgets = [
                    S3TextFilter(
                        name_fields + ["pe_label", "case.comments"],
                        label=T("Search"),
                        comment=T("You can search by name, ID or comments"),
                    ),
                    S3DateFilter(
                        "date_of_birth",
                        hidden=True,
                    ),
                    S3OptionsFilter(
                        "case.status_id",
                        cols=3,
                        options=status_filter_opts,
                        sort=False,
                        hidden=True,
                    ),
                    S3OptionsFilter(
                        "person_details.nationality",
                        hidden=True,
                    ),
                    S3DateFilter(
                        "case.date",
                        hidden=True,
                    ),
                ]

                # Org-filter if user can see cases from multiple orgs/branches
                if multiple_orgs:
                    filter_widgets.insert(
                        1,
                        S3OptionsFilter("case.organisation_id"),
                    )

                resource.configure(filter_widgets=filter_widgets)

            # Autocomplete search-method
            s3db.set_method(
                "pr",
                "person",
                method="search_ac",
                action=s3db.pr_PersonSearchAutocomplete(name_fields),
            )

        elif r.component_name == "case_activity":

            atable = r.component.table

            assistance_inline = settings.get_br_manage_assistance() and \
                                settings.get_br_assistance_inline()
            mtable = s3db.br_assistance_measure

            # Default status
            if settings.get_br_case_activity_status():
                s3db.br_case_activity_default_status()

            # Default human_resource_id
            if human_resource_id:

                # Activities
                if settings.get_br_case_activity_manager():
                    atable.human_resource_id.default = human_resource_id

                # Inline updates
                if settings.get_br_case_activity_updates():
                    utable = s3db.br_case_activity_update
                    utable.human_resource_id.default = human_resource_id

                # Inline assistance measures
                if assistance_inline:
                    mtable.human_resource_id.default = human_resource_id

            root_org = None
            org_specific_needs = settings.get_br_case_activity_need() and \
                                 settings.get_br_needs_org_specific()
            if org_specific_needs:
                root_org = s3db.br_case_root_org(r.id)
                if not root_org:
                    root_org = auth.root_org()

            # Limit selectable need types to the case root org
            if org_specific_needs and root_org:
                field = atable.need_id
                field.requires = IS_EMPTY_OR(
                    IS_ONE_OF(
                        db,
                        "br_need.id",
                        field.represent,
                        filterby="organisation_id",
                        filter_opts=(root_org, ),
                    ))

            # Configure inline assistance measures
            if assistance_inline:
                if record:
                    mtable.person_id.default = record.id
                if settings.get_br_assistance_themes() and root_org:
                    # Limit selectable themes to the case root org
                    field = mtable.theme_ids
                    dbset = s3db.br_org_assistance_themes(root_org)
                    field.requires = IS_EMPTY_OR(
                        IS_ONE_OF(
                            dbset,
                            "br_assistance_theme.id",
                            field.represent,
                            multiple=True,
                        ))
                s3db.br_assistance_default_status()

        elif r.component_name == "assistance_measure":

            mtable = r.component.table
            ltable = s3db.br_assistance_measure_theme

            # Default status
            s3db.br_assistance_default_status()

            # Default human_resource_id
            if human_resource_id and settings.get_br_assistance_manager():
                mtable.human_resource_id.default = human_resource_id

            # Filter case_activity_id selector to current case
            field = mtable.case_activity_id
            if record and field.writable:
                requires = field.requires
                if isinstance(requires, IS_EMPTY_OR):
                    requires = requires.other
                requires.set_filter(filterby="person_id",
                                    filter_opts=(record.id, ))

            # Represent for br_assistance_measure_theme.id
            details_per_theme = settings.get_br_assistance_details_per_theme()
            if details_per_theme:
                ltable.id.represent = s3db.br_AssistanceMeasureThemeRepresent(
                    paragraph=True,
                    details=True,
                )

            # Filter theme_id selectors to case root org
            root_org = s3db.br_case_root_org(r.id)
            if not root_org:
                root_org = auth.root_org()
            if root_org:
                dbset = s3db.br_org_assistance_themes(root_org)
                field = mtable.theme_ids
                field.requires = IS_EMPTY_OR(
                    IS_ONE_OF(
                        dbset,
                        "br_assistance_theme.id",
                        field.represent,
                        multiple=True,
                    ))
                field = ltable.theme_id
                field.requires = IS_EMPTY_OR(
                    IS_ONE_OF(
                        dbset,
                        "br_assistance_theme.id",
                        field.represent,
                    ))

            # Allow organizer to set an end_date
            if r.method == "organize" and \
               settings.get_br_assistance_measures_use_time():
                field = mtable.end_date
                field.writable = True

        elif r.component_name == "br_note":

            # Represent the note author by their name (rather than email)
            ntable = r.component.table
            ntable.modified_by.represent = s3base.s3_auth_user_represent_name

        return True
示例#19
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",
                       "timestmp",
                       "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 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
示例#20
0
    def __call__(self):

        T = current.T
        output = {}
        s3db = current.s3db
        request = current.request

        #------------------------
        # Map to display needs
        map_id = "default_map"

        ftable = s3db.gis_layer_feature
        query = (ftable.controller == "req") & \
                (ftable.function == "need_line")
        layer = current.db(query).select(ftable.layer_id,
                                         limitby=(0, 1)).first()
        try:
            layer_id = layer.layer_id
        except AttributeError:
            current.log.error("Cannot find Layer for Map")
            layer_id = None

        feature_resources = [{
            "name": T("Needs"),
            "id": "search_results",
            "layer_id": layer_id,
            "active": False,
        }]

        _map = current.gis.show_map(
            callback='''S3.search.s3map()''',
            catalogue_layers=True,
            collapsed=True,
            feature_resources=feature_resources,
            save=False,
            search=True,
            toolbar=True,
        )
        output["_map"] = _map

        # ---------------------------------------------------------------------
        # Display needs list
        resource = s3db.resource("req_need_line")
        #resource.table.commit_status.represent = None
        #list_id = "req_datalist"
        #list_fields = [#"purpose",
        #               "location_id",
        #               #"priority",
        #               #"req_ref",
        #               #"site_id",
        #               "date",
        #               ]
        # Order with most recent request first
        #orderby = "req_need.date"
        #datalist, numrows = resource.datalist(fields = list_fields,
        #                                      limit = None,
        #                                      list_id = list_id,
        #                                      orderby = orderby,
        #                                      )
        #if numrows == 0:
        #    current.response.s3.crud_strings["req_need"].msg_no_match = T("No needs at present.")

        #ajax_url = URL(c="req", f="need", args="datalist.dl",
        #               vars={"list_id": list_id})
        #@ToDo: Implement pagination properly
        #output[list_id] = datalist.html(ajaxurl = ajax_url,
        #                                pagesize = 0,
        #                                )

        # ----------------------------
        # Filter Form
        # - can we have a single form for both Activities & Needs?
        #
        filter_widgets = [
            S3TextFilter(
                [  #"need_id$req_number.value",
                    "item_id$name",
                    # These levels are for SHARE/LK
                    #"location_id$L1",
                    "location_id$L2",
                    #"location_id$L3",
                    #"location_id$L4",
                    "need_id$name",
                    "need_id$comments",
                ],
                label=T("Search"),
                comment=
                T("Search for a Need by Request Number, Item, Location, Summary or Comments"
                  ),
            ),
            S3LocationFilter(
                "location_id",
                # These levels are for SHARE/LK
                levels=("L2", "L3", "L4"),
            ),
            S3OptionsFilter("item_id"),
            S3OptionsFilter(
                "status",
                cols=3,
                label=T("Status"),
            ),
            S3OptionsFilter(
                "need_id$event.event_type_id",
                hidden=True,
            ),
            # @ToDo: Filter this list dynamically based on Event Type:
            S3OptionsFilter("need_id$event__link.event_id"),
            S3OptionsFilter(
                "sector_id",
                hidden=True,
            ),
            S3OptionsFilter(
                "need_id$organisation__link.organisation_id",
                hidden=True,
            ),
            S3OptionsFilter(
                "need_id$verified.value",
                cols=2,
                label=T("Verified"),
                hidden=True,
            ),
        ]
        filter_form = S3FilterForm(
            filter_widgets,
            ajax=True,
            submit=True,
            #url = ajax_url,
        )
        output["req_filter_form"] = filter_form.html(
            resource,
            request.get_vars,
            #target = "%s %s" % list_id, map_id
            target=map_id)

        # View title
        output["title"] = current.deployment_settings.get_system_name()

        self._view(THEME, "dashboard.html")

        # Custom JS
        current.response.s3.scripts.append(
            "/%s/static/themes/SHARE/js/homepage.js" % request.application)

        return output
示例#21
0
    def prep(r):
        if r.component:
            if r.component.alias == "select":
                if not r.method:
                    r.method = "select"
                if r.method == "select":
                    r.custom_action = s3db.deploy_alert_select_recipients

            elif r.component_name == "response":
                s3db.configure(r.component.tablename,
                               deletable = False,
                               editable = False,
                               insertable = False,
                               )

            elif r.component_name == "recipient":
                settings.search.filter_manager = False
                from s3 import S3TextFilter, S3OptionsFilter
                recipient_filters = [
                    S3TextFilter([
                            "human_resource_id$person_id$first_name",
                            "human_resource_id$person_id$middle_name",
                            "human_resource_id$person_id$last_name",
                        ],
                        label=current.T("Name"),
                    ),
                    S3OptionsFilter(
                        "human_resource_id$organisation_id",
                        widget="multiselect",
                        search=True,
                        header="",
                        hidden=True,
                    ),
                ]
                if settings.get_org_regions():
                    recipient_filters.insert(1,
                        s3base.S3HierarchyFilter(
                            "human_resource_id$organisation_id$region_id",
                            lookup="org_region",
                            hidden=True,
                        )
                    )
                s3db.configure(r.component.tablename,
                               filter_widgets = recipient_filters,
                               )

                if r.record.message_id:
                    s3db.configure(r.component.tablename,
                                   deletable = False,
                                   insertable = False,
                                   )
        else:
            # No component
            if r.record:
                if r.record.message_id:
                    # Already sent - so lock
                    s3db.configure(r.tablename,
                                   deletable = False,
                                   editable = False,
                                   )
            else:
                alert_create_script()
                if settings.get_deploy_manual_recipients():
                    create_next = URL(f="alert", args=["[id]", "select"])
                else:
                    create_next = URL(f="alert", args=["[id]", "recipient"])
                s3db.configure(r.tablename,
                               create_next = create_next,
                               deletable = False,
                               # @ToDo: restrict in postp to change this action button
                               #editable = False,
                               )

        return True
示例#22
0
    def prep(r):

        # Filter to persons who have a case registered
        resource = r.resource
        resource.add_filter(FS("dvr_case.id") != None)

        get_vars = r.get_vars
        mine = True if get_vars.get("mine") == "1" else False

        beneficiary = settings.get_dvr_label(
        )  # If we add more options in future then == "Beneficiary"
        if beneficiary:
            CASES = T("Beneficiaries")
            CURRENT = T("Current Beneficiaries")
            CLOSED = T("Former Beneficiaries")
        else:
            if mine:
                CASES = T("My Cases")
                CURRENT = T("My Current Cases")
            else:
                CASES = T("Cases")
                CURRENT = T("Current Cases")
            CLOSED = T("Closed Cases")

        # Filters to split case list
        if not r.record:

            # Filter to active/archived cases
            archived = get_vars.get("archived")
            if archived == "1":
                archived = True
                CASES = T("Archived Cases")
                query = FS("dvr_case.archived") == True
            else:
                archived = False
                query = (FS("dvr_case.archived") == False) | \
                        (FS("dvr_case.archived") == None)

            # Filter for cases assigned to the logged-in user
            if mine:
                human_resource_id = auth.s3_logged_in_human_resource()
                if human_resource_id:
                    query &= (
                        FS("dvr_case.human_resource_id") == human_resource_id)
                else:
                    query &= (FS("dvr_case.human_resource_id").belongs(set()))

            # Filter to open/closed cases
            # (also filtering status filter opts)
            closed = get_vars.get("closed")
            get_status_opts = s3db.dvr_case_status_filter_opts
            if closed == "1":
                CASES = CLOSED
                query &= FS("dvr_case.status_id$is_closed") == True
                status_opts = lambda: get_status_opts(closed=True)
            elif closed == "0":
                CASES = CURRENT
                query &= (FS("dvr_case.status_id$is_closed") == False) | \
                         (FS("dvr_case.status_id$is_closed") == None)
                status_opts = lambda: get_status_opts(closed=False)
            else:
                status_opts = get_status_opts

            resource.add_filter(query)
        else:
            archived = False
            status_opts = s3db.dvr_case_status_filter_opts

            # Set default for dvr_case_effort.person_id and hide it
            etable = s3db.dvr_case_effort
            field = etable.person_id
            field.default = r.record.id
            field.readable = field.writable = False

            # Set default for dvr_case_effort.human_resource_id
            field = etable.human_resource_id
            field.default = auth.s3_logged_in_human_resource()

        # Should not be able to delete records in this view
        resource.configure(deletable=False)

        if r.component and r.id:
            ctable = r.component.table
            if "case_id" in ctable.fields and \
               str(ctable.case_id.type)[:18] == "reference dvr_case":

                # Find the Case ID
                dvr_case = s3db.dvr_case
                query = (dvr_case.person_id == r.id) & \
                        (dvr_case.deleted != True)
                cases = db(query).select(dvr_case.id, limitby=(0, 2))

                case_id = ctable.case_id
                if cases:
                    # Set default
                    case_id.default = cases.first().id
                if len(cases) == 1:
                    # Only one case => hide case selector
                    case_id.readable = case_id.writable = False
                else:
                    # Configure case selector
                    case_id.requires = IS_ONE_OF(
                        db(query),
                        "dvr_case.id",
                        case_id.represent,
                    )

        if r.interactive:

            # Adapt CRUD strings to context
            if beneficiary:
                s3.crud_strings["pr_person"] = Storage(
                    label_create=T("Create Beneficiary"),
                    title_display=T("Beneficiary Details"),
                    title_list=CASES,
                    title_update=T("Edit Beneficiary Details"),
                    label_list_button=T("List Beneficiaries"),
                    label_delete_button=T("Delete Beneficiary"),
                    msg_record_created=T("Beneficiary added"),
                    msg_record_modified=T("Beneficiary details updated"),
                    msg_record_deleted=T("Beneficiary deleted"),
                    msg_list_empty=T("No Beneficiaries currently registered"))
            else:
                s3.crud_strings["pr_person"] = Storage(
                    label_create=T("Create Case"),
                    title_display=T("Case Details"),
                    title_list=CASES,
                    title_update=T("Edit Case Details"),
                    label_list_button=T("List Cases"),
                    label_delete_button=T("Delete Case"),
                    msg_record_created=T("Case added"),
                    msg_record_modified=T("Case details updated"),
                    msg_record_deleted=T("Case deleted"),
                    msg_list_empty=T("No Cases currently registered"))

            if not r.component:

                from s3 import S3SQLCustomForm, \
                               S3SQLInlineComponent, \
                               S3TextFilter, \
                               S3OptionsFilter, \
                               s3_get_filter_opts

                # Expose the "archived"-flag? (update forms only)
                if r.record and r.method != "read":
                    ctable = s3db.dvr_case
                    field = ctable.archived
                    field.readable = field.writable = True

                # Module-specific CRUD form
                # NB: this assumes single case per person, must use
                #     case perspective (dvr/case) for multiple cases
                #     per person!
                crud_form = S3SQLCustomForm(
                    "dvr_case.reference",
                    "dvr_case.organisation_id",
                    "dvr_case.date",
                    "dvr_case.status_id",
                    "first_name",
                    "middle_name",
                    "last_name",
                    "date_of_birth",
                    "gender",
                    S3SQLInlineComponent(
                        "contact",
                        fields=[
                            ("", "value"),
                        ],
                        filterby={
                            "field": "contact_method",
                            "options": "EMAIL",
                        },
                        label=T("Email"),
                        multiple=False,
                        name="email",
                    ),
                    S3SQLInlineComponent(
                        "contact",
                        fields=[
                            ("", "value"),
                        ],
                        filterby={
                            "field": "contact_method",
                            "options": "SMS",
                        },
                        label=T("Mobile Phone"),
                        multiple=False,
                        name="phone",
                    ),
                    "person_details.nationality",
                    S3SQLInlineComponent(
                        "address",
                        label=T("Current Address"),
                        fields=[
                            ("", "location_id"),
                        ],
                        filterby={
                            "field": "type",
                            "options": "1",
                        },
                        link=False,
                        multiple=False,
                    ),
                    "dvr_case.comments",
                    "dvr_case.archived",
                )

                # Module-specific filter widgets
                filter_widgets = [
                    S3TextFilter(
                        [
                            "pe_label",
                            "first_name",
                            "middle_name",
                            "last_name",
                            #"email.value",
                            #"phone.value",
                            "dvr_case.reference",
                        ],
                        label=T("Search"),
                        comment=T("You can search by name, ID or case number"),
                    ),
                    S3OptionsFilter(
                        "dvr_case.status_id",
                        cols=3,
                        default=default_status,
                        #label = T("Case Status"),
                        options=status_opts,
                        sort=False,
                    ),
                    S3OptionsFilter("person_details.nationality", ),
                ]

                # Add filter for case flags
                if settings.get_dvr_case_flags():
                    filter_widgets.append(
                        S3OptionsFilter(
                            "case_flag_case.flag_id",
                            label=T("Flags"),
                            options=s3_get_filter_opts(
                                "dvr_case_flag",
                                translate=True,
                            ),
                            cols=3,
                            hidden=True,
                        ))

                # Add filter for transferability if relevant for deployment
                if settings.get_dvr_manage_transferability():
                    filter_widgets.append(
                        S3OptionsFilter(
                            "dvr_case.transferable",
                            options={
                                True: T("Yes"),
                                False: T("No"),
                            },
                            cols=2,
                            hidden=True,
                        ))

                resource.configure(
                    crud_form=crud_form,
                    filter_widgets=filter_widgets,
                )

            elif r.component.tablename == "dvr_case_activity":

                # Set default statuses for components
                if settings.get_dvr_case_activity_use_status():
                    s3db.dvr_case_activity_default_status()

                if settings.get_dvr_manage_response_actions():
                    s3db.dvr_response_default_status()

            elif r.component_name == "allowance" and \
                 r.method in (None, "update"):

                records = r.component.select(["status"], as_rows=True)
                if len(records) == 1:
                    record = records[0]
                    table = r.component.table
                    readonly = []
                    if record.status == 2:
                        # Can't change payment details if already paid
                        readonly = [
                            "person_id",
                            "entitlement_period",
                            "date",
                            "paid_on",
                            "amount",
                            "currency",
                        ]
                    for fn in readonly:
                        if fn in table.fields:
                            field = table[fn]
                            field.writable = False
                            field.comment = None

            elif r.component_name == "evaluation":

                from s3 import S3SQLInlineComponent

                crud_fields = [  #"person_id",
                    #"case_id",
                    #"date",
                ]
                cappend = crud_fields.append

                table = s3db.dvr_evaluation_question
                rows = db(table.deleted != True).select(
                    table.id,
                    table.section,
                    #table.header,
                    table.number,
                    table.name,
                    orderby=table.number,
                )

                #subheadings = {}

                section = None
                for row in rows:
                    name = "number%s" % row.number
                    if row.section != section:
                        label = section = row.section
                        #subheadings[T(section)] = "sub_%sdata" % name
                    else:
                        label = ""
                    cappend(
                        S3SQLInlineComponent(
                            "data",
                            name=name,
                            label=label,
                            fields=(
                                ("", "question_id"),
                                ("", "answer"),
                            ),
                            filterby=dict(field="question_id", options=row.id),
                            multiple=False,
                        ), )

                cappend("comments")
                crud_form = s3base.S3SQLCustomForm(*crud_fields)

                s3db.configure(
                    "dvr_evaluation",
                    crud_form=crud_form,
                    #subheadings = subheadings,
                )

        # Module-specific list fields (must be outside of r.interactive)
        list_fields = [
            "dvr_case.reference",
            "first_name",
            "middle_name",
            "last_name",
            "date_of_birth",
            "gender",
            "dvr_case.date",
            "dvr_case.status_id",
        ]
        resource.configure(list_fields=list_fields, )

        return True
示例#23
0
文件: evr.py 项目: rullmanmike/eden
    def prep(r):

        fiscal_code = s3db.evr_case.fiscal_code
        levels = current.gis.get_relevant_hierarchy_levels()

        if r.method == "update":
            fiscal_code.requires = None
        else:
            fiscal_code.requires = \
                    IS_EMPTY_OR(IS_NOT_IN_DB(db(db.evr_case.deleted != True),
                                             fiscal_code),
                                null=""
                                )

        report_fields = [
            "id",
            "last_name",
            "case.organisation_id",
            "gender",
            "date_of_birth",
            "person_details.nationality",
            "person_details.marital_status",
            "shelter_registration.shelter_id",
            "shelter_registration.check_in_date",
            "shelter_registration.check_out_date",
        ]
        if settings.get_cr_shelter_housing_unit_management():
            report_fields.append("shelter_registration.shelter_unit_id")

        for level in levels:
            lfield = "location_id$%s" % level
            report_fields.append(lfield)

        report_options = Storage(
            rows=report_fields,
            cols=report_fields,
            fact=report_fields,
            defaults=Storage(
                rows="shelter_registration.shelter_id",
                cols="gender",
                #totals=True,
            ))
        list_fields = [
            "id",
            "first_name",
            #"middle_name",
            "last_name",
            "gender",
            "date_of_birth",
        ]
        if settings.get_evr_link_to_organisation():
            list_fields.append("case.organisation_id")
        list_fields.append("shelter_registration.shelter_id")
        if settings.get_cr_shelter_housing_unit_management():
            list_fields.append("shelter_registration.shelter_unit_id")
        list_fields.append("shelter_registration.check_in_date")
        list_fields.append("shelter_registration.check_out_date")

        r.resource.configure(list_fields=list_fields,
                             report_options=report_options)

        if r.interactive and not r.component:

            resource = r.resource

            # Filter widgets
            from s3 import S3OptionsFilter, S3TextFilter, S3LocationFilter, S3DateFilter
            filter_widgets = [
                S3TextFilter(
                    [
                        "first_name",
                        #"middle_name",
                        "last_name",
                        #"local_name",
                        "identity.value",
                        "case.fiscal_code",
                    ],
                    label=T("Name and/or ID"),
                    comment=T("To search for a person, enter any of the "
                              "first, middle or last names and/or an ID "
                              "number of a person, separated by spaces. "
                              "You may use % as wildcard."),
                ),
                S3LocationFilter(
                    "address.location_id",
                    label=T("Current Residence"),
                    levels=levels,
                ),
                S3DateFilter("date_of_birth", label=T("Date Of Birth")),
                S3OptionsFilter(
                    "person_details.nationality",
                    label=T("Nationality"),
                ),
                S3OptionsFilter(
                    "case.organisation_id",
                    label=T("Organisation"),
                ),
                S3OptionsFilter(
                    "shelter_registration.shelter_id",
                    label=T("Shelter"),
                ),
                S3OptionsFilter(
                    "shelter_registration.registration_status",
                    label=T("Registration Status"),
                ),
            ]

            # Custom Form for Persons
            from s3 import S3SQLCustomForm, S3SQLInlineComponent
            crud_form = S3SQLCustomForm(
                "case.organisation_id",
                "first_name",
                #"middle_name",
                "last_name",
                "date_of_birth",
                "location_id",
                "person_details.place_of_birth",
                "case.fiscal_code",
                S3SQLInlineComponent(
                    "identity",
                    label=T("Identity Documents"),
                    fields=[
                        "type",
                        "value",
                    ],
                ),
                "person_details.nationality",
                "gender",
                "person_details.marital_status",
                "person_details.religion",
                "person_details.occupation",
                #"person_details.company",
                "comments",
            )
            resource.configure(
                crud_form=crud_form,
                filter_widgets=filter_widgets,
            )

        elif r.representation in ("pdf", "xls"):
            # List fields
            list_fields = [
                "id",
                "first_name",
                #"middle_name",
                "last_name",
                "gender",
                #"date_of_birth",
                (T("Age"), "age"),
                "person_details.nationality",
                "person_details.religion",
                (T("Contact"), "contact.value"),
                (T("Shelter"), "shelter_registration.shelter_id$name")
            ]
            r.resource.configure(list_fields=list_fields)
        return True
示例#24
0
    def customise_org_facility_resource(r, tablename):
        """
            Customise event_event resource
            - List Fields
            - Form
            - Filter
            - Report
            Runs after controller customisation
            But runs before prep
        """

        s3db = current.s3db

        from s3 import IS_LOCATION, S3LocationSelector
        levels = ("L0", "L1", "L2")
        loc_field = r.table.location_id
        loc_field.requires = IS_LOCATION()
        loc_field.widget = S3LocationSelector(
            levels=levels,
            show_address=True,
        )

        list_fields = [
            "name",
            (T("Type"), "facility_type.name"),
            #"organisation_id",
            "location_id",
            "contact",
            "phone1",
            "email",
            "comments",
        ]

        from s3 import S3OptionsFilter, S3TextFilter
        filter_widgets = [
            S3TextFilter(
                [
                    "name",
                    "site_facility_type.facility_type_id",
                    #"organisation_id",
                    "location_id",
                    "contact",
                    "phone1",
                    "email",
                    "comments"
                ],
                label=T("Search"),
            ),
            S3OptionsFilter(
                "site_facility_type.facility_type_id",
                header=True,
                label=T("Type of Place"),
            ),
            #S3OptionsFilter("organisation_id",
            #                header = True,
            #                represent = "%(name)s",
            #                ),
        ]

        report_fields = [  #"name",
            "site_facility_type.facility_type_id",
            "site_org_group.group_id",
            "location_id$L3",
            "organisation_id",
        ]

        report_options = Storage(
            rows=report_fields,
            cols=[],
            fact=[(T("Number of Facilities"), "count(name)")],
            defaults=Storage(
                rows="site_facility_type.facility_type_id",
                #cols = "site_org_group.group_id",
                fact="count(name)",
                totals=True,
                chart="barchart:rows",
                table="collapse",
            ))

        # Custom Crud Form
        from s3 import S3SQLCustomForm, S3SQLInlineComponentMultiSelectWidget
        crud_form = S3SQLCustomForm(
            "name",
            S3SQLInlineComponentMultiSelectWidget(
                "facility_type",
                #label = T("Type of Place"),
                field="facility_type_id",
            ),
            #"organisation_id",
            "location_id",
            "contact",
            "phone1",
            "email",
            "comments",
        )

        s3db.configure(
            tablename,
            crud_form=crud_form,
            filter_widgets=filter_widgets,
            list_fields=list_fields,
            report_options=report_options,
        )
示例#25
0
    def customise_project_project_resource(r, tablename):

        from s3 import S3LocationSelector, S3Represent, S3TextFilter, S3OptionsFilter, S3LocationFilter

        s3db = current.s3db
        table = s3db.project_project

        table.code.label = "SOF"

        s3db.project_location.location_id.widget = S3LocationSelector(
            levels=("L1", "L2", "L3"),
            show_map=False,
        )

        # Always SC
        otable = s3db.org_organisation
        org = current.db(otable.name == SAVE).select(otable.id,
                                                     cache=s3db.cache,
                                                     limitby=(0, 1)).first()
        try:
            SCI = org.id
        except:
            current.log.error("Cannot find org %s - prepop not done?" % SAVE)
        else:
            f = table.organisation_id
            f.default = SCI

        org_represent = s3db.org_OrganisationRepresent(acronym=False,
                                                       show_link=True)
        s3db.project_organisation.organisation_id.represent = org_represent
        try:
            s3db.project_donor_organisation.organisation_id.represent = org_represent
        except:
            # Table not present on Activities tab
            pass

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink

        # @ToDo: Inherit Locations from Disaster?

        crud_form = S3SQLCustomForm(
            S3SQLInlineLink(
                "programme",
                label=T("Program"),
                field="programme_id",
                multiple=False,
            ),
            "name",
            "code",
            "status_id",
            "start_date",
            "end_date",
            "budget",
            "currency",
            S3SQLInlineComponent(
                "location",
                label=T("Locations"),
                fields=["location_id"],
            ),
            S3SQLInlineComponent(
                "organisation",
                name="donor",
                label=T("Donor(s)"),
                fields=["organisation_id"],
            ),
            # @ToDo: Set Metadata on File: Org, Location, Disaster, Date
            S3SQLInlineComponent(
                "document",
                name="concept_note",
                label=T("Concept Note"),
                fields=["file"],
                multiple=False,
            ),
            # @ToDo: Be able to retrieve the correct document
            #S3SQLInlineComponent("document",
            #                     name = "log_frame",
            #                     label = T("Log Frame"),
            #                     fields = ["file"],
            #                     multiple = False,
            #                     ),
            "comments",
        )

        filter_widgets = [
            S3TextFilter(
                [
                    "name",
                    "code",
                    #"description",
                ],
                label=T("Search"),
                comment=T("Search for a Project by name or code"),
            ),
            S3OptionsFilter(
                "status_id",
                label=T("Status"),
                cols=3,
            ),
            S3OptionsFilter(
                "donor.organisation_id",
                label=T("Donor"),
                hidden=True,
            ),
            S3LocationFilter(
                "location.location_id",
                levels=("L1", "L2", "L3"),
                hidden=True,
            ),
            S3OptionsFilter(
                "programme_project.programme_id",
                label=T("Program"),
                hidden=True,
            ),
            #S3OptionsFilter("sector_project.sector_id",
            #                label = T("Sector"),
            #                location_filter = True,
            #                none = True,
            #                hidden = True,
            #                ),
        ]

        list_fields = [
            "status_id",
            "code",
            "name",
            (T("Donors"), "donor.organisation_id"),
            (T("Locations"), "location.location_id"),
            "start_date",
            "end_date",
            "budget",
            "currency",
            (T("Program"), "programme.name"),
        ]

        s3db.configure(
            "project_project",
            crud_form=crud_form,
            filter_widgets=filter_widgets,
            list_fields=list_fields,
        )
示例#26
0
文件: requests.py 项目: sahana/eden
def send_filter_widgets():
    """
        Filter widgets for outgoing shipments

        @returns: list of filter widgets
    """

    T = current.T

    from s3 import S3DateFilter, \
                   S3LocationFilter, \
                   S3OptionsFilter, \
                   S3TextFilter, \
                   s3_get_filter_opts
    from s3db.inv import SHIP_STATUS_CANCEL, \
                         SHIP_STATUS_RETURNING, \
                         inv_shipment_status_labels

    send_status_opts = OrderedDict(inv_shipment_status_labels())

    # We don't currently use these statuses
    del send_status_opts[SHIP_STATUS_CANCEL]
    del send_status_opts[SHIP_STATUS_RETURNING]

    filter_widgets = [
        S3TextFilter(
            [
                "req_ref",
                #"send_ref",
            ],
            label=T("Search"),
        ),
        S3DateFilter("date"),
        S3OptionsFilter(
            "status",
            cols=3,
            options=send_status_opts,
            sort=False,
        ),
        S3OptionsFilter(
            "track_item.item_id",
            hidden=True,
            options=lambda: s3_get_filter_opts("supply_item"),
        ),
    ]

    if current.auth.s3_has_role("SUPPLY_COORDINATOR"):

        coordinator_filters = [
            S3OptionsFilter(
                "to_site_id$organisation_id$delivery.value",
                label=T("Delivery##supplying"),
                options=delivery_tag_opts(),
            ),
            S3OptionsFilter(
                "site_id",
                label=T("Distribution Center"),
            ),
            S3OptionsFilter(
                "to_site_id",
                hidden=True,
            ),
            S3LocationFilter("to_site_id$location_id",
                             levels=["L3", "L4"],
                             hidden=True),
            S3TextFilter("to_site_id$location_id$addr_postcode",
                         label=T("Postcode"),
                         hidden=True),
        ]
        filter_widgets[3:3] = coordinator_filters

    return filter_widgets
示例#27
0
def _newsfeed():
    """
        Custom Page
        - Filterable DataList of CMS Posts & a DataList of Events
    """

    #if not current.auth.is_logged_in():
    #    current.auth.permission.fail()

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

    # Ensure that filtered views translate into options which update the Widget
    get_vars = request.get_vars
    if "~.series_id$name" in get_vars:
        series_name = get_vars["~.series_id$name"]
        table = s3db.cms_series
        series = current.db(table.name == series_name).select(table.id,
                                                              limitby=(0, 1)).first()
        if series:
            series_id = str(series.id)
            get_vars.pop("~.series_id$name")
            get_vars["~.series_id__belongs"] = series_id

    current.deployment_settings.customise_controller("cms_post")

    list_layout = s3.render_posts

    filter_widgets = [S3TextFilter(["body"],
                                   label="",
                                   _class="filter-search",
                                   #_placeholder=T("Search").upper(),
                                   ),
                      S3OptionsFilter("series_id",
                                      label=T("Filter by Type"),
                                      represent="%(name)s",
                                      widget="multiselect",
                                      hidden=True,
                                      ),
                      S3LocationFilter("location_id",
                                       label=T("Filter by Location"),
                                       levels=("L1", "L2", "L3"),
                                       widget="multiselect",
                                       hidden=True,
                                       ),
                      S3OptionsFilter("created_by$organisation_id",
                                      label=T("Filter by Organization"),
                                      # Can't use this for integers, use field.represent instead
                                      #represent="%(name)s",
                                      widget="multiselect",
                                      hidden=True,
                                      ),
                      S3DateFilter("created_on",
                                   label=T("Filter by Date"),
                                   hide_time=True,
                                   hidden=True,
                                   ),
                      ]

    s3db.configure("cms_post",
                   # We use a custom Advanced widget
                   filter_advanced = False,
                   filter_formstyle = filter_formstyle,
                   filter_submit = (T("SEARCH"), "btn btn-primary"),
                   filter_widgets = filter_widgets,
                   list_layout = list_layout,
                   # Create form comes via AJAX in a Modal
                   insertable = False,
                   notify_fields = [(T("Type"), "series_id"),
                                    (T("Date"), "date"),
                                    (T("Location"), "location_id"),
                                    (T("Description"), "body"),
                                    ],
                   notify_template = "notify_post",
                   )

    s3.dl_pagelength = 6  # 5 forces an AJAX call

    old_args = request.args
    if "datalist_dl_post" in old_args:
        # DataList pagination or Ajax-deletion request
        request.args = ["datalist_f"]
        ajax = "list"
    elif "datalist_dl_filter" in old_args:
        # FilterForm options update request
        request.args = ["filter"]
        ajax = "filter"
    elif "validate.json" in old_args:
        # Inline component validation request
        request.args = []
        ajax = True
    elif current.auth.permission.format == "msg":
        # Subscription lookup request
        request.args = []
        ajax = True
    else:
        # Default
        request.args = ["datalist_f"]
        ajax = None

    def prep(r):
        if ajax == "list":
            r.representation = "dl"
        elif ajax == "filter":
            r.representation = "json"
        return True
    s3.prep = prep

    output = current.rest_controller("cms", "post",
                                     list_ajaxurl = URL(f="index",
                                                        args="datalist_dl_post"),
                                     filter_ajax_url = URL(f="index",
                                                           args="datalist_dl_filter",
                                                           vars={}),
                                     )

    request.args = old_args

    if ajax == "list":
        # Don't override view if this is an Ajax-deletion request
        if not "delete" in request.get_vars:
            response.view = "plain.html"
    elif not ajax:
        # Set Title & View after REST Controller, in order to override
        output["title"] = T("News Feed")
        view = path.join(request.folder, "modules", "templates",
                         THEME, "views", "newsfeed.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.js_global.append('''i18n.adv_search="%s"''' % T("Advanced Search"))
        s3.scripts.append("/%s/static/themes/%s/js/newsfeed.js" % (request.application, THEME))

        # Latest 5 Disasters
        resource = s3db.resource("event_event")
        layout = render_events
        list_id = "event_datalist"
        limit = 5
        orderby = "start_date desc"
        list_fields = ["name",
                       "event_type_id$name",
                       "start_date",
                       "closed",
                       ]
        output["disasters"] = latest_records(resource, layout, list_id, limit, list_fields, orderby)

    return output
示例#28
0
        def custom_prep(r):

            resource = r.resource

            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
                if not result:
                    return False

            # Customise list_fields
            if r.method == "review":
                list_fields = [
                    "id",
                    "created_on",
                    "modified_on",
                    "name",
                    "start_date",
                    (T("Countries"), "location.location_id"),
                    (T("Hazards"), "hazard.name"),
                    (T("Lead Organization"), "organisation_id"),
                    (T("Donors"), "donor.organisation_id"),
                ]
            elif r.representation == "xls":
                # All readable Fields should be exported
                list_fields = [
                    "id",
                    "name",
                    "code",
                    "description",
                    "status_id",
                    "start_date",
                    "end_date",
                    "drrpp.duration",
                    (T("Countries"), "location.location_id"),
                    "drrpp.L1",
                    (T("Hazards"), "hazard.name"),
                    (T("Themes"), "theme.name"),
                    "objectives",
                    "drrpp.activities",
                    "output.name",
                    "drr.hfa",
                    "drrpp.rfa",
                    "drrpp.pifacc",
                    "drrpp.jnap",
                    (T("Lead Organization"), "organisation_id"),
                    (T("Partners"), "partner.organisation_id"),
                    (T("Donors"), "donor.organisation_id"),
                    "budget",
                    "currency",
                    "drrpp.focal_person",
                    "drrpp.organisation_id",
                    "drrpp.email",
                    "url.url",
                    "drrpp.parent_project",
                    "comments",
                ]
                if logged_in:
                    list_fields.extend([
                        "created_by",
                        "created_on",
                        "modified_by",
                        "modified_on",
                    ])
            else:
                list_fields = [
                    "id",
                    "name",
                    "start_date",
                    (T("Countries"), "location.location_id"),
                    (T("Hazards"), "hazard.name"),
                    (T("Lead Organization"), "organisation_id"),
                    (T("Donors"), "donor.organisation_id"),
                ]

            resource.configure(list_fields=list_fields)

            # Customise report_options
            if r.method == "report":
                report_fields = [
                    "name",
                    (T("Countries"), "location.location_id"),
                    (T("Hazards"), "hazard.name"),
                    (T("Themes"), "theme.name"),
                    (T("HFA Priorities"), "drr.hfa"),
                    (T("RFA Priorities"), "drrpp.rfa"),
                    (T("Lead Organization"), "organisation_id"),
                    (T("Partner Organizations"), "partner.organisation_id"),
                    (T("Donors"), "donor.organisation_id"),
                ]

                # Report Settings for charts
                if "chart" in r.get_vars and r.representation != "json":
                    s3.crud_strings[tablename].title_report = T(
                        "Project Graph")
                    report_fact_default = "count(id)"
                    report_facts = [(T("Number of Projects"), "count(id)")]
                    show_table = False
                else:
                    s3.crud_strings[tablename].title_report = T(
                        "Project Matrix")
                    report_fact_default = "count(id)"
                    report_facts = [
                        (T("Number of Projects"), "count(id)"),
                        (T("Number of Countries"),
                         "count(location.location_id)"),
                        (T("Number of Hazards"), "count(hazard.id)"),
                        (T("Number of Themes"), "count(theme.id)"),
                        (T("Number of HFA Priorities"), "count(drr.hfa)"),
                        (T("Number of RFA Priorities"), "count(drrpp.rfa)"),
                        (T("Number of Lead Organizations"),
                         "count(organisation_id)"),
                        (T("Number of Partner Organizations"),
                         "count(partner.organisation_id)"),
                        (T("Number of Donors"),
                         "count(donor.organisation_id)"),
                    ]
                    show_table = True
                report_options = Storage(rows=report_fields,
                                         cols=report_fields,
                                         fact=report_facts,
                                         defaults=Storage(
                                             rows="hazard.name",
                                             cols="location.location_id",
                                             fact=report_fact_default,
                                             totals=True,
                                             table=show_table,
                                         ))
                resource.configure(report_options=report_options)
                current.deployment_settings.ui.hide_report_options = True

            if r.interactive:

                # Don't show Update/Delete button on Search table
                if r.method is None and not r.id:
                    resource.configure(editable=False, deletable=False)

                # JS to show/hide Cook Island fields
                s3.scripts.append("/%s/static/themes/DRRPP/js/drrpp.js" %
                                  current.request.application)

                if r.method == "read":
                    table_pl = s3db.project_location
                    table_l = s3db.gis_location
                    countries = [
                        row.name
                        for row in db((table_pl.project_id == r.record.id)
                                      & (table_pl.location_id == table_l.id)).
                        select(table_l.name)
                    ]
                    if not ("Cook Islands" in countries
                            and len(countries) == 1):
                        s3db.project_drrpp.L1.readable = False
                        s3db.project_drrpp.pifacc.readable = False
                        s3db.project_drrpp.jnap.readable = False

                # Filter Options
                project_hfa_opts = s3db.project_hfa_opts()
                hfa_options = dict(
                    (key, "HFA %s" % key) for key in project_hfa_opts)
                #hfa_options[None] = NONE # to search NO HFA
                project_rfa_opts = s3db.project_rfa_opts()
                rfa_options = dict(
                    (key, "RFA %s" % key) for key in project_rfa_opts)
                #rfa_options[None] = NONE # to search NO RFA
                project_pifacc_opts = s3db.project_pifacc_opts()
                pifacc_options = dict(
                    (key, "PIFACC %s" % key) for key in project_pifacc_opts)
                #pifacc_options[None] = NONE # to search NO PIFACC
                project_jnap_opts = s3db.project_jnap_opts()
                jnap_options = dict(
                    (key, "JNAP %s" % key) for key in project_jnap_opts)
                #jnap_options[None] = NONE # to search NO JNAP

                # Filter widgets
                from s3 import S3TextFilter, S3OptionsFilter, s3_get_filter_opts
                filter_widgets = [
                    S3TextFilter(["name",
                                  "code",
                                  "description",
                                  "location.location_id",
                                  "hazard.name",
                                  "theme.name",
                                  ],
                                  label = T("Search Projects"),
                                  comment = T("Search for a Project by name, code, or description."),
                                  ),
                    S3OptionsFilter("status_id",
                                    label = T("Status"),
                                    cols = 4,
                                    ),
                    S3OptionsFilter("location.location_id",
                                    label = T("Country"),
                                    cols = 3,
                                    hidden = True,
                                    ),
                    #S3OptionsFilter("drrpp.L1",
                    #                label = T("Cook Islands"),
                    #                cols = 3,
                    #                hidden = True,
                    #                ),
                    S3OptionsFilter("hazard.id",
                                    label = T("Hazard"),
                                    options = lambda: \
                                        s3_get_filter_opts("project_hazard",
                                                           translate=True),
                                    help_field = s3db.project_hazard_help_fields,
                                    cols = 4,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("theme.id",
                                    label = T("Theme"),
                                    options = lambda: \
                                        s3_get_filter_opts("project_theme",
                                                           translate=True),
                                    help_field = s3db.project_theme_help_fields,
                                    cols = 4,
                                    # Don't group
                                    size = None,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("drr.hfa",
                                    label = T("HFA"),
                                    options = hfa_options,
                                    help_field = project_hfa_opts,
                                    cols = 5,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("drrpp.rfa",
                                    label = T("RFA"),
                                    options = rfa_options,
                                    help_field = project_rfa_opts,
                                    cols = 6,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("drrpp.pifacc",
                                    label = T("PIFACC"),
                                    options = pifacc_options,
                                    help_field = project_pifacc_opts,
                                    cols = 6,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("drrpp.jnap",
                                    label = T("JNAP"),
                                    options = jnap_options,
                                    help_field = project_jnap_opts,
                                    cols = 6,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("organisation_id",
                                    label = T("Lead Organization"),
                                    cols = 3,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("partner.organisation_id",
                                    label = T("Partners"),
                                    cols = 3,
                                    hidden = True,
                                    ),
                    S3OptionsFilter("donor.organisation_id",
                                    label = T("Donors"),
                                    cols = 3,
                                    hidden = True,
                                    )
                ]

                resource.configure(filter_widgets=filter_widgets)
            return True
示例#29
0
    def customise_project_location_controller(**attr):

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

        # Load normal model
        table = s3db.project_location

        # Custom Components
        s3db.add_components(
            "project_project",
            project_drrpp={
                "joinby": "project_id",
                "multiple": False,
            },
        )

        # Custom CRUD Strings
        s3.crud_strings.project_location.title_map = T("Project Map")

        # Custom Search Filters
        from s3.s3filter import S3TextFilter, S3OptionsFilter, S3LocationFilter
        filter_widgets = [
            S3TextFilter(
                [
                    "project_id$name",
                    "project_id$code",
                    "project_id$description",
                    #"location_id$name",
                    #"project_id$organisation.name",
                    #"project_id$organisation.acronym",
                ],
                label=T("Search Projects"),
                _class="filter-search",
            ),
            S3OptionsFilter(
                "project_id$status_id",
                label=T("Status"),
                widget="groupedpts",
                #widget = "multiselect",
                cols=3,
                #hidden=True,
            ),
            S3LocationFilter(
                "location_id",
                label=T("Country"),
                levels=("L0", ),
                widget="groupedpts",
                #widget = "multiselect",
                cols=3,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$hazard_project.hazard_id",
                label=T("Hazard"),
                widget="groupedpts",
                #widget = "multiselect",
                cols=4,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$theme_project.theme_id",
                label=T("Theme"),
                widget="groupedpts",
                #widget = "multiselect",
                cols=4,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$drr.hfa",
                label=T("HFA"),
                widget="groupedpts",
                #widget = "multiselect",
                cols=5,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$drrpp.rfa",
                label=T("RFA"),
                widget="groupedpts",
                #widget = "multiselect",
                cols=6,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$organisation_id",
                label=T("Lead Organization"),
                represent="%(name)s",
                widget="groupedpts",
                #widget = "multiselect",
                cols=3,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$partner.organisation_id",
                label=T("Partners"),
                represent="%(name)s",
                widget="groupedpts",
                #widget = "multiselect",
                cols=3,
                hidden=True,
            ),
            S3OptionsFilter(
                "project_id$donor.organisation_id",
                label=T("Donors"),
                represent="%(name)s",
                widget="groupedpts",
                #widget = "multiselect",
                cols=3,
                hidden=True,
            ),
        ]

        s3db.configure(
            "project_location",
            filter_widgets=filter_widgets,
            # Add CSS to default class better than patching
            #map_submit = (T("Search"), "search-button"),
            map_advanced=(T("Advanced Search"), T("Simple Search")),
        )

        return attr
示例#30
0
文件: requests.py 项目: sahana/eden
def req_filter_widgets():
    """
        Filter widgets for requests

        @returns: list of filter widgets
    """

    T = current.T

    from s3 import S3DateFilter, \
                   S3LocationFilter, \
                   S3OptionsFilter, \
                   S3TextFilter, \
                   s3_get_filter_opts

    from s3db.req import req_status_opts

    req_status_opts = OrderedDict(
        sorted(
            req_status_opts().items(),
            key=lambda i: i[0],
        ))

    filter_widgets = [
        S3TextFilter(
            ["req_ref"],
            label=T("Order No."),
        ),
        S3DateFilter("date"),
        S3OptionsFilter(
            "transit_status",
            cols=3,
            options=req_status_opts,
            sort=False,
        ),
        S3OptionsFilter(
            "fulfil_status",
            cols=3,
            hidden=True,
            options=req_status_opts,
            sort=False,
        ),
        S3OptionsFilter(
            "req_item.item_id",
            hidden=True,
            options=lambda: s3_get_filter_opts("supply_item"),
        ),
    ]

    if current.auth.s3_has_role("SUPPLY_COORDINATOR"):

        coordinator_filters = [
            S3LocationFilter(
                "site_id$location_id",
                levels=["L3", "L4"],
            ),
            S3TextFilter(
                "site_id$location_id$addr_postcode",
                label=T("Postcode"),
            ),
            S3OptionsFilter("site_id", hidden=True),
            S3OptionsFilter(
                "site_id$organisation_id$delivery.value",
                label=T("Delivery##supplying"),
                options=delivery_tag_opts(),
            ),
        ]
        filter_widgets[2:2] = coordinator_filters

    return filter_widgets