Exemple #1
0
    def customise_org_organisation_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink
        crud_form = S3SQLCustomForm(
            "name",
            "acronym",
            S3SQLInlineLink(
                "organisation_type",
                field="organisation_type_id",
                label=T("Type"),
                multiple=False,
                #widget = "hierarchy",
            ),
            S3SQLInlineComponent(
                "tag",
                label=T("CAP OID"),
                multiple=False,
                fields=[("", "value")],
                filterby=dict(
                    field="tag",
                    options="cap_oid",
                ),
            ),
            "website",
            "comments",
        )

        current.s3db.configure(
            "org_organisation",
            crud_form=crud_form,
        )
Exemple #2
0
        def custom_prep(r):
            # Call standard prep
            if callable(standard_prep):
                if not standard_prep(r):
                    return False

            if r.controller == "dvr":
                # Beneficiaries
                from s3 import S3SQLCustomForm, S3SQLInlineComponent
                crud_fields = customise_beneficiary_form()
                crud_fields.insert(
                    0,
                    # @ToDo: Create isn't refreshing the dropdown
                    S3SQLInlineComponent(
                        "project_case_activity",
                        fields=[
                            ("", "activity_id"),
                        ],
                        label=T("Activity"),
                        link=False,
                        multiple=False,
                    ))
                s3db.configure(
                    "pr_person",
                    crud_form=S3SQLCustomForm(*crud_fields),
                )

            return True
Exemple #3
0
 def prep(r):
     # Make the team status visible in list/read views
     if r.interactive or r.representation == "aadata":
         resource = r.resource
         list_fields = [
             "name",
             "description",
             "team_status_team.status_id",
             "comments",
         ]
         resource.configure(list_fields=list_fields)
     if r.interactive:
         from s3 import S3SQLCustomForm, S3SQLInlineComponent
         crud_fields = [
             "name",
             "description",
             S3SQLInlineComponent(
                 "team_status_team",
                 fields=[("", "status_id")],
                 label=T("Status"),
                 multiple=False,
             ),
             "comments",
         ]
         crud_form = S3SQLCustomForm(*crud_fields)
         r.resource.configure(crud_form=crud_form)
     return True
Exemple #4
0
    def customise_project_programme_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent

        crud_form = S3SQLCustomForm(
            "name",
            (T("Project Code"), "code"),
            (T("Master Budget"), "budget"),
            "currency",
            # @ToDo: Link Programmes to Locations
            #S3SQLInlineComponent("location",
            #                     label = T("Locations"),
            #                     fields = ["location_id"],
            #                     ),
            # @ToDo: Set Metadata on File: Org, Location, Disaster, Date
            S3SQLInlineComponent(
                "document",
                label=T("Response Plan"),
                fields=["file"],
                multiple=False,
            ),
            "comments",
        )

        current.s3db.configure(
            tablename,
            crud_form=crud_form,
        )
Exemple #5
0
    def customise_dvr_household_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent

        crud_form = S3SQLCustomForm(
            "hoh_relationship",
            "hoh_name",
            "hoh_date_of_birth",
            "hoh_gender",
            S3SQLInlineComponent(
                "beneficiary_data",
                fields=[
                    (T("Age Group"), "beneficiary_type_id"),
                    "female",
                    "male",
                    "other",
                    "in_school",
                    "employed",
                ],
                label=T("Household Members"),
                explicit_add=T("Add Household Members"),
            ),
            "comments",
        )

        current.s3db.configure(
            "dvr_household",
            crud_form=crud_form,
        )
Exemple #6
0
    def customise_cms_post_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent

        crud_form = S3SQLCustomForm(
            "name",
            "body",
            "date",
            S3SQLInlineComponent(
                "document",
                name="file",
                label=T("Attachments"),
                fields=["file", "comments"],
                filterby={
                    "field": "file",
                    "options": "",
                    "invert": True,
                },
            ),
            "comments",
        )

        current.s3db.configure(
            "cms_post",
            crud_form=crud_form,
            list_fields=[
                "post_module.module",
                "post_module.resource",
                "name",
                "date",
                "comments",
            ],
        )
Exemple #7
0
    def customise_org_organisation_resource(r, tablename):

        s3db = current.s3db

        # Custom Components
        s3db.add_components(
            tablename,
            org_organisation_tag=(  # On-call Duty Number
                {
                    "name": "duty",
                    "joinby": "organisation_id",
                    "filterby": {
                        "tag": "duty",
                    },
                    "multiple": False,
                }, ),
        )

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink, \
                       IS_EMPTY_OR, IS_PHONE_NUMBER_MULTI, S3PhoneWidget, s3_phone_represent

        # Individual settings for specific tag components
        components_get = s3db.resource(tablename).components.get

        duty = components_get("duty")
        f = duty.table.value
        f.represent = s3_phone_represent,
        f.requires = IS_EMPTY_OR(IS_PHONE_NUMBER_MULTI())
        f.widget = S3PhoneWidget()

        crud_form = S3SQLCustomForm(
            "name",
            "acronym",
            S3SQLInlineLink(
                "organisation_type",
                field="organisation_type_id",
                # Default 10 options just triggers which adds unnecessary complexity to a commonly-used form & commonly an early one (create Org when registering)
                filter=False,
                label=T("Type"),
                multiple=False,
                widget="multiselect",
            ),
            "country",
            (T("Reception Phone #"), "phone"),
            S3SQLInlineComponent(
                "duty",
                label=T("On-call Duty Number"),
                fields=[("", "value")],
                multiple=False,
            ),
            "website",
            "logo",
            "comments",
        )

        s3db.configure(
            tablename,
            crud_form=crud_form,
        )
Exemple #8
0
def evaluation():
    """
        RESTful CRUD Controller
        - unused
    """

    S3SQLInlineComponent = s3base.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,
    )

    return s3_rest_controller()
Exemple #9
0
def capacity_assessment():
    """ RESTful CRUD controller """

    from s3 import S3SQLCustomForm, S3SQLInlineComponent

    crud_fields = [
        "organisation_id",
        "date",
        "person_id",
    ]
    cappend = crud_fields.append

    table = s3db.org_capacity_indicator
    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["sub_%sdata" % name] = T(section)
        else:
            label = ""
        cappend(
            S3SQLInlineComponent(
                "data",
                name=name,
                label=label,
                fields=(
                    (row.header, "indicator_id"),
                    "rating",
                    "ranking",
                ),
                filterby={
                    "field": "indicator_id",
                    "options": row.id
                },
                multiple=False,
            ), )

    crud_form = S3SQLCustomForm(*crud_fields)

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

    return s3_rest_controller()
Exemple #10
0
    def customise_event_event_resource(r, tablename):

        from gluon import IS_EMPTY_OR, IS_INT_IN_RANGE
        from s3 import S3LocationSelector, S3SQLCustomForm, S3SQLInlineComponent
        s3db = current.s3db
        s3db.event_event_location.location_id.widget = \
                                    S3LocationSelector(levels=("L1", "L2"))
        # Cat 1: Extra-ordinary
        # Cat 2: Large
        # Cat 3: Medium
        # Cat 4: Small
        s3db.event_event_tag.value.requires = IS_EMPTY_OR(IS_INT_IN_RANGE(
            1, 5))
        crud_form = S3SQLCustomForm(
            "name",
            "event_type_id",
            "start_date",
            S3SQLInlineComponent(
                "tag",
                fields=[
                    ("", "value"),
                ],
                filterby={
                    "field": "tag",
                    "options": "category",
                },
                label=T("Category"),
                multiple=False,
            ),
            "closed",
            "comments",
        )

        list_fields = [
            "name",
            "event_type_id",
            "start_date",
            (T("Category"), "tag.value"),
            "closed",
            "comments",
        ]

        # If we have default ones defined then need to add them in a cascade:
        #onaccept = s3db.get_config("event_event", "onaccept")
        #ondelete = s3db.get_config("event_event", "ondelete")
        onaccept = lambda form: response_locations()
        update_onaccept = s3db.get_config("event_event", "update_onaccept")
        update_onaccept = [update_onaccept, onaccept]

        s3db.configure(
            "event_event",
            crud_form=crud_form,
            list_fields=list_fields,
            onaccept=onaccept,
            ondelete=onaccept,
            update_onaccept=update_onaccept,
        )
Exemple #11
0
    def prep(r):

        resource = r.resource

        # Filter to locally hosted data sets
        resource.add_filter(FS("repository_id") == None)

        if not r.component:

            table = resource.table

            if r.interactive:
                # Require code to be unique among exposed data sets
                from s3 import IS_NOT_ONE_OF
                from s3db.sync import sync_dataset_code_requires
                table.code.requires = sync_dataset_code_requires + \
                                 [IS_NOT_ONE_OF(db(table.repository_id == None),
                                    "sync_dataset.code",
                                    error_message = "Code already in use",
                                    ),
                                  ]

            # Name is required for locally hosted data sets
            table.name.requires = IS_NOT_EMPTY()

        if r.record and r.component_name == "task":

            table = r.component.table

            # Default sync mode PULL
            table.mode.default = 1

            # TODO adapt tooltips to context

            # Reduced form
            from s3 import S3SQLCustomForm, S3SQLInlineComponent
            crud_form = S3SQLCustomForm("resource_name",
                                        "components",
                                        S3SQLInlineComponent("resource_filter",
                                                             label = T("Filters"),
                                                             fields = ["tablename",
                                                                       "filter_string",
                                                                       ],
                                                             ),
                                        )

            # Reduced list fields
            list_fields = ["resource_name",
                           ]

            s3db.configure("sync_task",
                           crud_form = crud_form,
                           list_fields = list_fields,
                           )
        return True
Exemple #12
0
    def customise_org_organisation_resource(r, tablename):

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink, s3_comments_widget

        s3db = current.s3db
        s3db.org_organisation_tag.value.widget = s3_comments_widget

        crud_form = S3SQLCustomForm(
            "name",
            "acronym",
            S3SQLInlineLink(
                "organisation_type",
                field="organisation_type_id",
                # Default 10 options just triggers which adds unnecessary complexity to a commonly-used form & commonly an early one (create Org when registering)
                filter=False,
                label=T("Type"),
                multiple=False,
                widget="multiselect",
            ),
            S3SQLInlineLink(
                "sector",
                columns=4,
                label=T("Sectors"),
                field="sector_id",
            ),
            S3SQLInlineLink(
                "service",
                columns=4,
                label=T("Services"),
                field="service_id",
            ),
            "country",
            "phone",
            "website",
            "logo",
            (T("About"), "comments"),
            S3SQLInlineComponent(
                "tag",
                label=T("Vision"),
                fields=[("", "value")],
                filterby={
                    "field": "tag",
                    "options": "vision",
                },
                multiple=False,
            ),
        )

        s3db.configure(
            tablename,
            crud_form=crud_form,
        )
Exemple #13
0
        def prep(r):
            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
            else:
                result = True

            if not r.component:
                from s3 import S3SQLCustomForm, S3SQLInlineComponent

                s3.crud.submit_button = T("Save")

                s3db = current.s3db

                # Dropdown not Autocomplete
                itable = s3db.req_req_item
                itable.item_id.widget = None
                jquery_ready = s3.jquery_ready
                jquery_ready.append('''
$.filterOptionsS3({
 'trigger':{'alias':'req_item','name':'item_id'},
 'target':{'alias':'req_item','name':'item_pack_id'},
 'scope':'row',
 'lookupPrefix':'supply',
 'lookupResource':'item_pack',
 'msgNoRecords':i18n.no_packs,
 'fncPrep':S3.supply.fncPrepItem,
 'fncRepresent':S3.supply.fncRepresentItem
})''')

                crud_form = S3SQLCustomForm(
                    "site_id",
                    "requester_id",
                    "date",
                    S3SQLInlineComponent("req_item",
                                         label=T("Items"),
                                         fields=[
                                             "item_id", "item_pack_id",
                                             "quantity", "comments"
                                         ]),
                    "security_req",
                    "req_status",
                    "comments",
                )

                s3db.configure(
                    "req_req",
                    crud_form=crud_form,
                )

            return result
Exemple #14
0
    def customise_org_sector_controller(**attr):

        s3db = current.s3db
        tablename = "org_sector"

        # Just 1 set of sectors / sector leads nationally
        # @ToDo: Deployment Setting
        #f = s3db.org_sector.location_id
        #f.readable = f.writable = False

        # Custom Component for Sector Leads
        s3db.add_components(
            tablename,
            org_sector_organisation={
                "name": "sector_lead",
                "joinby": "sector_id",
                "filterby": {
                    "lead": True,
                },
            },
        )

        from s3 import S3SQLCustomForm, S3SQLInlineComponent
        crud_form = S3SQLCustomForm(
            "name",
            "abrv",
            "comments",
            S3SQLInlineComponent(
                "sector_lead",
                label=T("Lead Organization(s)"),
                fields=[
                    ("", "organisation_id"),
                ],
            ),
        )

        s3db.configure(
            tablename,
            crud_form=crud_form,
            list_fields=[
                "name",
                "abrv",
                (T("Lead Organization(s)"), "sector_lead.organisation_id"),
            ],
        )

        return attr
Exemple #15
0
    def customise_project_activity_resource(r, tablename):

        s3db = current.s3db
        s3db.gis_location.addr_street.label = T("Precise Location")

        from s3 import S3SQLCustomForm, S3SQLInlineComponent

        crud_form = S3SQLCustomForm(
            "name",
            "date",
            "status_id",
            S3SQLInlineComponent(
                "sector_activity",
                label=T("Sectors"),
                fields=[("", "sector_id")],
            ),
            "location_id",
            "comments",
        )

        list_fields = [
            "name",
            "date",
            "status_id",
            (T("Sectors"), "sector_activity.sector_id"),
            (T("Items"), "distribution.parameter_id"),
            "location_id$L1",
            "location_id$L2",
            "location_id$L3",
            "location_id$L4",
            #"comments",
        ]

        # If we have default ones defined then need to add them in a cascade:
        #onaccept = s3db.get_config("project_activity", "onaccept")
        #ondelete = s3db.get_config("project_activity", "ondelete")
        onaccept = lambda form: response_locations()

        s3db.configure(
            "project_activity",
            crud_form=crud_form,
            list_fields=list_fields,
            onaccept=onaccept,
            ondelete=onaccept,
        )
Exemple #16
0
    def customise_cms_post_resource(r, tablename):

        s3db = current.s3db
        table = s3db.cms_post

        from s3 import S3SQLCustomForm, S3SQLInlineComponent
        crud_form = S3SQLCustomForm(
            (T("Text"), "body"),
            # @ToDo: Tags widget
            S3SQLInlineComponent(
                "tag_post",
                fields=[("", "tag_id")],
                label=T("Tags"),
            ),
        )

        s3db.configure(
            tablename,
            crud_form=crud_form,
        )
Exemple #17
0
    def customise_event_incident_report_resource(r, tablename):

        s3db = current.s3db

        table = s3db.event_incident_report
        table.name.label = T("Description")

        # ImageCrop widget doesn't currently work within an Inline Form
        from gluon.validators import IS_IMAGE
        image_field = s3db.doc_image.file
        image_field.requires = IS_IMAGE()
        image_field.widget = None

        from s3 import S3SQLCustomForm, S3SQLInlineComponent
        crud_form = S3SQLCustomForm(
            S3SQLInlineComponent(
                "image",
                label=T("Photo"),
                fields=[
                    ("", "file"),
                ],
            ),
            "name",
            "location_id",
        )

        list_fields = [
            "location_id",
            "name",
        ]

        s3db.configure(
            "event_incident_report",
            crud_form=crud_form,
            list_fields=list_fields,
        )
Exemple #18
0
    def customise_doc_sitrep_resource(r, tablename):
        """
            All SitReps are SAVE
            All SitReps are National in scope
        """

        #if not current.auth.s3_has_role("AUTHENTICATED"):
        #    # @ToDo: Just show the External (Public) parts
        #    pass

        from s3 import S3DateFilter, S3OptionsFilter, S3SQLCustomForm, S3SQLInlineComponent

        db = current.db
        s3db = current.s3db
        table = s3db.doc_sitrep

        # Always SC
        otable = s3db.org_organisation
        org = 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

        # Always National
        PH = "Philippines"
        gtable = s3db.gis_location
        loc = db((gtable.name == PH) & (gtable.level == "L0")).select(
            gtable.id, cache=s3db.cache, limitby=(0, 1)).first()
        try:
            PH = loc.id
        except:
            current.log.error("Cannot find loc %s - prepop not done?" % PH)
        else:
            f = table.location_id
            f.default = PH

        # Default to currently-open Event (if just 1)
        s3db.event_sitrep.event_id.default = current.session.s3.event

        crud_form = S3SQLCustomForm(
            S3SQLInlineComponent(
                "event_sitrep",
                label=T("Disaster"),
                fields=[("", "event_id")],
                multiple=False,
                required=True,
            ),
            "date",
            "name",
            "description",
            "comments",
        )

        filter_widgets = [
            S3OptionsFilter("event_sitrep.event_id"),
            S3DateFilter("date"),
        ]

        list_fields = [
            "event_sitrep.event_id",
            "date",
            "name",
            "comments",
        ]

        s3db.configure(
            "doc_sitrep",
            crud_form=crud_form,
            filter_widgets=filter_widgets,
            list_fields=list_fields,
        )
Exemple #19
0
    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
Exemple #20
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
Exemple #21
0
    def customise_event_event_resource(r, tablename):
        """
            Customise event_event resource
            - List Fields
            - CRUD Strings
            - Form
            - Filter
            - Report
            Runs after controller customisation
            But runs before prep
        """

        from s3 import S3SQLCustomForm, S3SQLInlineComponent, IS_LOCATION, S3LocationSelector

        db = current.db
        s3db = current.s3db
        table = r.table
        table.name.label = T("Disaster Number")

        location_field = s3db.event_event_location.location_id
        location_field.requires = IS_LOCATION()
        location_field.widget = S3LocationSelector(levels=gis_levels)

        impact_fields = OrderedDict(
            killed="Killed",
            total_affected="Total Affected",
            est_damage="Estimated Damage (US$ Million)",
        )

        ptable = s3db.stats_impact_type
        rows = db(ptable.name.belongs(impact_fields.values())).select(
            ptable.id,
            ptable.name,
        )
        parameters = rows.as_dict(key="name")

        impact_components = []
        impact_crud_form_fields = []
        impact_list_fields = []
        impact_report_fields = []
        for tag, label in impact_fields.items():
            parameter = parameters[label]["id"]
            impact_components.append({
                "name": tag,
                "link": "event_event_impact",
                "joinby": "event_id",
                "key": "impact_id",
                "filterby": "parameter_id",
                "filterfor": (parameter, ),
            })
            label = T(label)
            impact_crud_form_fields.append(
                S3SQLInlineComponent(tag,
                                     label=label,
                                     link=False,
                                     multiple=False,
                                     fields=[("", "value")],
                                     filterby=dict(field="parameter_id",
                                                   options=parameter)))
            impact_list_fields.append((label, "%s.value" % tag))
            impact_report_fields.append(
                (T("Total %(param)s") % dict(param=label),
                 "sum(%s.value)" % tag))

        s3db.add_components(
            "event_event",
            stats_impact=impact_components,
        )

        crud_form = S3SQLCustomForm(
            "name",
            "event_type_id",
            "start_date",
            "end_date",
            # @ToDo: Inline location_id field
            #S3SQLInlineComponent("event_location",
            #                     label = T("Location"),
            #                     multiple = False,
            #                     fields = [("", "location_id")],
            #                     ),
            "comments",
            *impact_crud_form_fields)

        list_fields = [  #"name",
            "event_type_id",
        ]
        lappend = list_fields.append

        for level in gis_levels:
            location_level = "event_location.location_id$%s" % level
            lappend(location_level)

        s3db.add_components(
            "gis_location",
            gis_location_tag={
                "name": "pcode",
                "joinby": "location_id",
                "filterby": "tag",
                "filterfor": ("PCode", ),
            },
        )
        lappend(("PCode", "event_location.location_id$pcode.value"))

        list_fields.extend((
            "start_date",
            "end_date",
        ))
        list_fields.extend(impact_list_fields)

        report_facts = [(T("Number of Disasters"), "count(id)")]
        report_facts.extend(impact_report_fields)

        report_options = s3db.get_config("event_event", "report_options")
        report_options.fact = report_facts

        s3db.configure(
            "event_event",
            crud_form=crud_form,
            list_fields=list_fields,
        )

        if r.interactive:
            # Labels
            table.comments.label = T("Description")

            current.response.s3.crud_strings["event_event"] = Storage(
                label_create=T("Record Disaster"),
                title_display=T("Disaster Details"),
                title_list=T("Disasters"),
                title_update=T("Edit Disaster"),
                label_list_button=T("List Disasters"),
                label_delete_button=T("Delete Disaster"),
                msg_record_created=T("Disaster added"),
                msg_record_modified=T("Disaster updated"),
                msg_record_deleted=T("Disaster deleted"),
                msg_list_empty=T("No Disasters currently registered"))
Exemple #22
0
        def custom_prep(r):
            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
                if not result:
                    return False

            s3db = current.s3db

            # Hack to provide additional languages for L10n location names
            # without activating them in the GUI
            l10n_languages = dict(settings.L10n.languages)
            l10n_languages["ky"] = "Kyrgyz"
            l10n_languages["ru"] = "Russian"
            l10n_languages["hy"] = "Armenian"
            l10n_languages["az"] = "Azerbaijani"
            l10n_languages["ka"] = "Georgian"
            l10n_languages["kk"] = "Kazakh"
            l10n_languages["tg"] = "Tajik"
            l10n_languages["tk"] = "Turkmen"
            l10n_languages["uk"] = "Ukraine"
            l10n_languages["uz"] = "Uzbek"
            from s3 import IS_ISO639_2_LANGUAGE_CODE
            s3db.gis_location_name.language.requires = IS_ISO639_2_LANGUAGE_CODE(
                select=l10n_languages)

            if r.interactive or r.representation == "aadata":
                if r.vars.get("location.level__ne"):
                    s3.crud_strings["gis_location"] = Storage(
                        title_list=T("Administrative Areas"), )
                else:
                    s3.crud_strings["gis_location"] = Storage(
                        #label_create = T("Record Disaster"),
                        #title_display = T("Disaster Details"),
                        title_list=T("Locations"))

                    # Remove level column & filter
                    list_fields = s3db.get_config("gis_location",
                                                  "list_fields")
                    list_fields.remove("level")

                    filter_widgets = s3db.get_config("gis_location",
                                                     "filter_widgets")
                    # NB Fragile: dependent on filters defined in gis/location controller
                    filter_widgets.pop(1)
            if r.method != "import":
                table = s3db.gis_location
                # Custom filtered components for custom list_fields
                s3db.add_components(
                    "gis_location",
                    gis_location_name={
                        "name": "name_ru",
                        "joinby": "location_id",
                        "filterby": "language",
                        "filterfor": ("ru", ),
                    },
                    gis_location_tag=(
                        {
                            "name": "pcode",
                            "joinby": "location_id",
                            "filterby": "tag",
                            "filterfor": ("PCode", ),
                        },
                        {
                            "name": "lat_lon_source",
                            "joinby": "location_id",
                            "filterby": "tag",
                            "filterfor": ("LatLon Source", ),
                        },
                        {
                            "name": "lat_lon_date",
                            "joinby": "location_id",
                            "filterby": "tag",
                            "filterfor": ("LatLon Date", ),
                        },
                    ),
                )

                from s3 import S3MultiSelectWidget, S3SQLCustomForm, S3SQLInlineComponent
                table.parent.widget = S3MultiSelectWidget(multiple=False)

                crud_form = S3SQLCustomForm(
                    "name",
                    #"name_ru.name_l10n",
                    S3SQLInlineComponent(
                        "name_ru",
                        label=T("Russian Name"),
                        multiple=False,
                        fields=[("", "name_l10n")],
                    ),
                    "level",
                    S3SQLInlineComponent(
                        "pcode",
                        label=T("PCode"),
                        multiple=False,
                        fields=[("", "value")],
                    ),
                    S3SQLInlineComponent(
                        "lat_lon_source",
                        label=T("Lat/Lon Source"),
                        multiple=False,
                        fields=[("", "value")],
                    ),
                    S3SQLInlineComponent(
                        "lat_lon_date",
                        label=T("Lat/Lon Date"),
                        multiple=False,
                        fields=[("", "value")],
                    ),
                    #"pcode.value",
                    "parent",
                )

                NONE = current.messages["NONE"]
                levels = current.gis.get_location_hierarchy()
                table.level.represent = lambda l: levels[l] if l else NONE

                #field = table.inherited
                #field.label =  T("Mapped?")
                #field.represent =  lambda v: T("No") if v else T("Yes")

                filter_widgets = s3db.get_config("gis_location",
                                                 "filter_widgets")
                # Remove L2 & L3 filters
                # NB Fragile: dependent on filters defined in gis/location controller
                filter_widgets.pop()
                filter_widgets.pop()

                s3db.configure(
                    "gis_location",
                    crud_form=crud_form,
                    filter_widgets=filter_widgets,
                    list_fields=[
                        "name",
                        # @ToDo: Investigate whether we can support this style & hence not need to define custom components
                        #(T("Russian Name"), "name.name_l10n?location_name.language=ru"),
                        #("PCode", "tag.value?location_tag.tag=PCode"),
                        (T("Russian Name"), "name_ru.name_l10n"),
                        "level",
                        ("PCode", "pcode.value"),
                        "L0",
                        "L1",
                        "L2",
                        "inherited",
                    ])
            return True
Exemple #23
0
        def custom_prep(r):

            # Call standard prep
            if callable(standard_prep):
                result = standard_prep(r)
            else:
                result = True

            if r.controller == "dvr" and not r.component:

                ctable = s3db.dvr_case
                root_org = current.auth.root_org()

                field = ctable.valid_until

                # Case is valid for 5 years
                from dateutil.relativedelta import relativedelta
                field.default = r.utcnow + relativedelta(years=5)
                field.readable = field.writable = True

                if root_org:
                    # Set default for organisation_id and hide the field
                    field = ctable.organisation_id
                    field.default = root_org
                    field.readable = field.writable = False

                    # Hide organisation_id in list_fields, too
                    list_fields = r.resource.get_config("list_fields")
                    if "dvr_case.organisation_id" in list_fields:
                        list_fields.remove("dvr_case.organisation_id")

                    # Limit sites to root_org
                    field = ctable.site_id
                    requires = field.requires
                    if requires:
                        from gluon import IS_EMPTY_OR
                        if isinstance(requires, IS_EMPTY_OR):
                            requires = requires.other
                        if hasattr(requires, "dbset"):
                            stable = s3db.org_site
                            query = (stable.organisation_id == root_org)
                            requires.dbset = current.db(query)

                resource = r.resource
                if r.interactive:
                    # Custom CRUD form
                    from s3 import S3SQLCustomForm, S3SQLInlineComponent
                    crud_form = S3SQLCustomForm(
                        "dvr_case.reference",
                        "dvr_case.organisation_id",
                        "dvr_case.date",
                        "dvr_case.valid_until",
                        "dvr_case.status_id",
                        "first_name",
                        "last_name",
                        "date_of_birth",
                        "gender",
                        "person_details.nationality",
                        "person_details.marital_status",
                        S3SQLInlineComponent(
                            "contact",
                            fields=[
                                ("", "value"),
                            ],
                            filterby={
                                "field": "contact_method",
                                "options": "SMS",
                            },
                            label=T("Mobile Phone"),
                            multiple=False,
                            name="phone",
                        ),
                        "person_details.illiterate",
                        S3SQLInlineComponent(
                            "case_language",
                            fields=[
                                "language",
                                "quality",
                                "comments",
                            ],
                            label=T("Language / Communication Mode"),
                        ),
                        "dvr_case.comments",
                    )
                    resource.configure(crud_form=crud_form, )

                    # Remove filter default for case status
                    filter_widgets = resource.get_config("filter_widgets")
                    for fw in filter_widgets:
                        if fw.field == "dvr_case.status_id":
                            fw.opts.default = None
                            break

                # Custom list fields (must be outside of r.interactive)
                list_fields = [
                    "dvr_case.reference",
                    "first_name",
                    "last_name",
                    "date_of_birth",
                    "gender",
                    "person_details.nationality",
                    "dvr_case.date",
                    "dvr_case.valid_until",
                    "dvr_case.status_id",
                ]
                resource.configure(list_fields=list_fields, )
            return result
Exemple #24
0
    def prep(r):
        # Function to call for all Site Instance Types
        from s3db.org import org_site_prep
        org_site_prep(r)

        if r.interactive:
            if r.component:
                component_name = r.component_name
                if component_name in ("asset", "vehicle"):
                    atable = s3db.asset_asset
                    # Stay within Site tab
                    s3db.configure(
                        "asset_asset",
                        create_next=None,
                    )
                    if component_name == "asset":
                        # Default/Hide the Organisation field
                        org_field = atable.organisation_id
                        org_field.default = r.record.organisation_id
                        org_field.readable = org_field.writable = False
                        # Filter out Vehicles
                        r.resource.add_component_filter(
                            component_name, (FS("type") != 1))
                    else:
                        atable.organisation_id.required = False  # Otherwise needs to be in crud_form & isn't defaulted
                        # Default new to Vehicle
                        atable.type.default = 1
                        # Only select from vehicles
                        ctable = s3db.supply_item_category
                        vehicle_categories = db(
                            ctable.is_vehicle == True).select(ctable.id)
                        atable.item_id.requires.set_filter(
                            filterby="item_category_id",
                            filter_opts=[row.id for row in vehicle_categories],
                        )
                        # Include Vehicle Details in the form
                        from s3 import S3SQLCustomForm, S3SQLInlineComponent

                        def vehicle_postprocess(form):
                            # Set the organisation_id
                            db(atable.id == form.vars.id).update(
                                organisation_id=r.record.organisation_id)

                        crud_form = S3SQLCustomForm(
                            "number",
                            (T("Vehicle Type"), "item_id"),
                            (T("License Plate"), "sn"),
                            "purchase_date",
                            "purchase_price",
                            "purchase_currency",
                            "cond",
                            S3SQLInlineComponent(
                                "vehicle",
                                label="",
                                multiple=False,
                                fields=[  #"vehicle_type_id",
                                    "mileage",
                                    "service_mileage",
                                    "service_date",
                                    "insurance_date",
                                ],
                            ),
                            postprocess=vehicle_postprocess,
                        )
                        s3db.configure(
                            "asset_asset",
                            crud_form=crud_form,
                        )
                        s3.crud_strings["asset_asset"] = Storage(
                            label_create=T("Add Vehicle Details"),
                            title_display=T("Vehicle Details"),
                            title_list=T("Vehicles"),
                            title_update=T("Edit Vehicle Details"),
                            label_list_button=T("List Vehicle Details"),
                            label_delete_button=T("Delete Vehicle Details"),
                            msg_record_created=T("Vehicle Details added"),
                            msg_record_modified=T("Vehicle Details updated"),
                            msg_record_deleted=T("Vehicle Details deleted"),
                            msg_list_empty=T(
                                "No Vehicle Details currently defined"),
                        )
        return True
Exemple #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,
        )
Exemple #26
0
    def customise_org_organisation_resource(r, tablename):

        from gluon.html import DIV, INPUT
        from s3 import s3_comments_widget, \
                       S3LocationSelector, \
                       S3MultiSelectWidget, \
                       S3SQLCustomForm, \
                       S3SQLInlineComponent, \
                       S3SQLVerticalSubFormLayout

        s3db = current.s3db

        # Filtered component to access phone number and email
        s3db.add_components(
            tablename,
            org_facility={
                "name": "main_facility",
                "joinby": "organisation_id",
                "filterby": {
                    "main_facility": True,
                },
            },
        )

        s3db.org_organisation_location.location_id.widget = S3LocationSelector(
            levels=("L2", "L3"),
            show_map=False,
            labels=False,
        )

        crud_fields = [
            "name",
            "acronym",
            S3SQLInlineLink(
                "organisation_type",
                field="organisation_type_id",
                label=T("Type"),
                multiple=False,
            ),
            S3SQLInlineLink(
                "service",
                label=T("Services"),
                field="service_id",
            ),
            S3SQLInlineComponent(
                "facility",
                label=T("Main Facility"),
                fields=[
                    "name",
                    "phone1",
                    "phone2",
                    "email",
                    "location_id",
                ],
                layout=S3SQLVerticalSubFormLayout,
                filterby={
                    "field": "main_facility",
                    "options": True,
                },
                multiple=False,
            ),
            "website",
            S3SQLInlineComponent(
                "contact",
                name="twitter",
                label=T("Twitter"),
                multiple=False,
                fields=[("", "value")],
                filterby=dict(
                    field="contact_method",
                    options="TWITTER",
                ),
            ),
            S3SQLInlineComponent(
                "contact",
                name="facebook",
                label=T("Facebook"),
                multiple=False,
                fields=[("", "value")],
                filterby=dict(
                    field="contact_method",
                    options="FACEBOOK",
                ),
            ),
            "comments",
        ]

        crud_form = S3SQLCustomForm(*crud_fields)

        from s3 import S3LocationFilter, S3OptionsFilter, S3TextFilter  #, S3HierarchyFilter
        filter_widgets = [
            S3TextFilter(
                ["name", "acronym"],
                label=T("Search"),
                comment=
                T("Search by organization name or acronym. You can use * as wildcard."
                  ),
                _class="filter-search",
            ),
            S3LocationFilter(
                "org_facility.location_id",
                label=T("Location"),
                #hidden = True,
            ),
            S3OptionsFilter(
                "organisation_organisation_type.organisation_type_id",
                label=T("Type"),
                #hidden = True,
            ),
            S3OptionsFilter("service_organisation.service_id",
                            #hidden = True,
                            ),
        ]

        list_fields = [
            "name",
            (T("Type"), "organisation_organisation_type.organisation_type_id"),
            (T("Services"), "service.name"),
            (T("Adresse"), "main_facility.location_id"),
            (T("Phone #"), "main_facility.phone1"),
            (T("Email"), "main_facility.email"),
            (T("Facebook"), "facebook.value"),
            "website",
            (T("Last Updated"), "modified_on"),
        ]

        s3db.configure(
            tablename,
            crud_form=crud_form,
            filter_widgets=filter_widgets,
            list_fields=list_fields,
        )
Exemple #27
0
    def customise_req_organisation_needs_resource(r, tablename):

        s3db = current.s3db
        table = current.s3db.req_organisation_needs

        CASH = T("Cash Donations needed")

        if r.tablename == "req_organisation_needs":

            from s3 import IS_ONE_OF, S3DateTime

            # Allow only organisations which do not have a needs record
            # yet (single component):
            field = table.organisation_id
            dbset = current.db(table.id == None)
            left = table.on(
                table.organisation_id == current.s3db.org_organisation.id)
            field.requires = IS_ONE_OF(
                dbset,
                "org_organisation.id",
                field.represent,
                left=left,
                orderby="org_organisation.name",
                sort=True,
            )

            # Format modified_on as date
            field = table.modified_on
            field.represent = lambda d: S3DateTime.date_represent(d, utc=True)

        if r.representation in ("html", "aadata", "iframe"):

            # Structured lists for interactive views
            from gluon import Field
            table.needs_skills = Field.Method(lambda row: \
                                    organisation_needs(row, need_type="skills"))
            table.needs_items = Field.Method(lambda row: \
                                    organisation_needs(row, need_type="items"))
            current.response.s3.stylesheets.append("../themes/RW/needs.css")

            needs_skills = (T("Volunteers needed"), "needs_skills")
            needs_items = (T("Supplies needed"), "needs_items")

            # Filter widgets
            from s3 import S3LocationFilter, S3OptionsFilter, S3TextFilter
            filter_widgets = [  #S3TextFilter(["organisation_id$name",
                #              ],
                #              label = T("Search"),
                #             ),
                S3OptionsFilter("organisation_id"),
                S3OptionsFilter(
                    "organisation_needs_skill.skill_id",
                    label=T("Skills sought"),
                ),
                S3OptionsFilter(
                    "organisation_needs_item.item_id",
                    label=T("Supplies sought"),
                ),
                S3LocationFilter(
                    "organisation_id$active_service_location.site_id$location_id",
                ),
            ]

            # CRUD form
            from s3 import S3SQLCustomForm, S3SQLInlineComponent
            crud_form = S3SQLCustomForm(
                "organisation_id",
                S3SQLInlineComponent(
                    "organisation_needs_skill",
                    label=T("Volunteers needed"),
                    fields=[
                        "skill_id",
                        "demand",
                        "comments",
                    ],
                ),
                S3SQLInlineComponent(
                    "organisation_needs_item",
                    label=T("Supplies needed"),
                    fields=[
                        "item_id",
                        "demand",
                        "comments",
                    ],
                ),
                (CASH, "money"),
                "money_details",
                #"vol",
                #"vol_details",
            )

            next_page = r.url(method="") \
                        if r.tablename == "req_organisation_needs" else None

            s3db.configure(
                "req_organisation_needs",
                crud_form=crud_form,
                filter_widgets=filter_widgets,
                create_next=next_page,
                update_next=next_page,
            )
        else:
            # Simple fields for exports
            needs_skills = (T("Volunteers needed"),
                            "organisation_needs_skill.skill_id")
            needs_items = (T("Supplies needed"),
                           "organisation_needs_item.item_id")

        # List fields (all formats)
        list_fields = [
            "organisation_id",
            needs_skills,
            needs_items,
            (CASH, "money"),
            (T("Cash Donation Details"), "money_details"),
            (T("Last Update"), "modified_on"),
        ]

        s3db.configure(
            "req_organisation_needs",
            list_fields=list_fields,
        )
Exemple #28
0
    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
Exemple #29
0
    def customise_project_activity_resource(r, tablename):

        s3db = current.s3db

        if r.tablename == "project_project":
            # crud_form needs modifying to filter sectors by project's

            from s3 import S3SQLCustomForm, S3SQLInlineComponent, S3SQLInlineLink

            # Limit Sectors to those for the Project
            table = s3db.project_sector_project
            query = (table.project_id == r.id) & \
                    (table.deleted == False)
            rows = current.db(query).select(table.sector_id)
            sector_ids = [row.sector_id for row in rows]

            crud_form = S3SQLCustomForm(
                "name",
                "status_id",
                S3SQLInlineLink(
                    "sector",
                    field="sector_id",
                    label=T("Sectors"),
                    filterby="id",
                    options=sector_ids,
                    widget="groupedopts",
                ),
                S3SQLInlineLink(
                    "activity_type",
                    field="activity_type_id",
                    label=T("Activity Types"),
                    widget="groupedopts",
                ),
                "location_id",
                "date",
                "end_date",
                S3SQLInlineComponent(
                    "distribution",
                    fields=[
                        "parameter_id",
                        "value",
                        (T("Intended Impact"), "comments"),
                    ],
                    label=T("Distributed Supplies"),
                ),
                "person_id",
                "comments",
            )

            s3db.configure(
                tablename,
                crud_form=crud_form,
            )

            list_fields = s3db.get_config(tablename, "list_fields")
            list_fields.insert(
                3, (T("Distributions"), "distribution.parameter_id"))
            # Done automatically from settings now
            #list_fields.insert(2, (T("Sectors"), "sector_activity.sector_id"))
            #list_fields.insert(3, (T("Activity Types"), "activity_activity_type.activity_type_id"))

        elif r.tablename == "project_activity":
            # Modify list_fields for desired Report format
            list_fields = [
                ("CSO", "project_id$organisation_id"),
                (T("Activity"), "name"),
                (T("Intended Impact"), "distribution.comments"),
                (T("Location"), "location_id"),
            ]

            s3db.configure(
                tablename,
                deletable=False,
                editable=False,
                insertable=False,
                list_fields=list_fields,
            )
Exemple #30
0
    def customise_beneficiary_form():

        s3db = current.s3db
        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:
            s3db.dvr_case.organisation_id.default = SCI

        mobile_list_fields = [  # No need for Mobile client to know which Activity a Case is linked to
            #"project_case_activity.activity_id$name",
            "dvr_case.reference",
            "dvr_case.date",
            "first_name",
            "middle_name",
            "last_name",
            "date_of_birth",
            "gender",
            "person_details.disabled",
            "phone.value",
            "email.value",
            # @ToDo: Use just parent in Mobile LocationSelector
            #"address.location_id$L1",
            #"address.location_id$L2",
            #"address.location_id$L3",
            #"address.location_id$L4",
            "address.location_id$parent",
            # Restore once list_fields working
            #"address.location_id$parent$uuid",
            "address.location_id$addr_street",
            "dvr_case.comments",
        ]

        s3db.configure(
            "pr_person",
            # TESTING - remove when done
            #list_fields = [#"address.location_id",
            #               #"address.location_id$id",
            #               #"address.location_id$uuid",
            #               #"address.location_id$parent",
            #               #"address.location_id$parent$id",
            #               "address.location_id$parent$name",
            #               #"address.location_id$parent$uuid",
            #               ],
            mobile_list_fields=mobile_list_fields,
        )

        from s3 import S3SQLInlineComponent
        crud_fields = [  # @ToDo: Scan this in from barcode on preprinted card
            "dvr_case.reference",
            "dvr_case.date",
            "first_name",
            "middle_name",
            "last_name",
            "date_of_birth",
            "gender",
            "person_details.disabled",
            S3SQLInlineComponent(
                "phone",
                fields=[
                    ("", "value"),
                ],
                #filterby = {"field": "contact_method",
                #            "options": "SMS",
                #            },
                label=T("Mobile Phone"),
                multiple=False,
                #name = "phone",
            ),
            S3SQLInlineComponent(
                "email",
                fields=[
                    ("", "value"),
                ],
                #filterby = {"field": "contact_method",
                #            "options": "EMAIL",
                #            },
                label=T("Email"),
                multiple=False,
                #name = "email",
            ),
            S3SQLInlineComponent(
                "address",
                label=T("Current Address"),
                fields=[
                    ("", "location_id"),
                ],
                filterby={
                    "field": "type",
                    "options": "1",
                },
                link=False,
                multiple=False,
            ),
            "dvr_case.comments",
        ]

        return crud_fields