예제 #1
0
def contact():
    """
    Controller for a simple contact form.
    """
    mail = current.mail
    keydata = {}
    with open('applications/grammateus3/private/app.keys', 'r') as keyfile:
        for line in keyfile:
            k, v = line.split()
            keydata[k] = v

    form = SQLFORM.factory(Field('your_email_address', requires=IS_EMAIL()),
                           Field('message_title', requires=IS_NOT_EMPTY()),
                           Field('message', 'text', requires=IS_NOT_EMPTY()),
                           submit_button='Send message',
                           separator=' ')
    captcha = Recaptcha2(request, keydata['captcha_public_key'],
                         keydata['captcha_private_key'])
    form.element('table').insert(-1, TR('', captcha, ''))
    if form.process().accepted:
        if mail.send(to='*****@*****.**',
                     subject='OCP Contact: {}'.format(form.vars.message_title),
                     message=form.vars.message):
            response.flash = 'Thank you for your message.'
            response.js = "jQuery('#%s').hide()" % request.cid
        else:
            form.errors.your_email = "Sorry, we were unable to send the email"
    return dict(form=form)
예제 #2
0
    def define_tables(self,db,migrate):
        from gluon import current
        logging.debug('defining tables (migrate=%s)' % migrate)
        now = datetime.datetime.now()
        db.define_table(
            'scheduler_task',
            Field('application_name',requires=IS_NOT_EMPTY(),
                  default=None,writable=False),
            Field('task_name',requires=IS_NOT_EMPTY()),
            Field('group_name',default='main',writable=False),
            Field('status',requires=IS_IN_SET(TASK_STATUS),
                  default=QUEUED,writable=False),
            Field('function_name',
                  requires=IS_IN_SET(sorted(self.tasks.keys()))),
            Field('args','text',default='[]',requires=TYPE(list)),
            Field('vars','text',default='{}',requires=TYPE(dict)),
            Field('enabled','boolean',default=True),
            Field('start_time','datetime',default=now),
            Field('next_run_time','datetime',default=now),
            Field('stop_time','datetime',default=now+datetime.timedelta(days=1)),
            Field('repeats','integer',default=1,comment="0=unlimted"),
            Field('period','integer',default=60,comment='seconds'),
            Field('timeout','integer',default=60,comment='seconds'),
            Field('times_run','integer',default=0,writable=False),
            Field('last_run_time','datetime',writable=False,readable=False),
            Field('assigned_worker_name',default='',writable=False),
            migrate=migrate,format='%(task_name)s')
        if hasattr(current,'request'):
            db.scheduler_task.application_name.default=current.request.application

        db.define_table(
            'scheduler_run',
            Field('scheduler_task','reference scheduler_task'),
            Field('status',requires=IS_IN_SET(RUN_STATUS)),
            Field('start_time','datetime'),
            Field('stop_time','datetime'),
            Field('output','text'),
            Field('result','text'),
            Field('traceback','text'),
            Field('worker_name',default=self.worker_name),
            migrate=migrate)

        db.define_table(
            'scheduler_worker',
            Field('worker_name'),
            Field('first_heartbeat','datetime'),
            Field('last_heartbeat','datetime'),
            Field('status',requires=IS_IN_SET(WORKER_STATUS)),
            migrate=migrate)
        db.commit()
예제 #3
0
파일: desk.py 프로젝트: zahedbri/nstock
def create():
    org = db.organization(session.org_id)
    tbl = db.desk
    tbl.item_list.readable = False
    tbl.item_list.writable = False
    tbl.name.requires = IS_NOT_EMPTY()

    form = SQLFORM(db.desk)
    form.add_button(T('Cancel'), URL('org', 'view', args=[org.id]))

    if form.process().accepted:
        # add the new desk to the org list
        desk_id = form.vars.id
        # add current users as the one with permission to update manage
        # this desk
        auth.add_permission(
            auth.user_group(auth.user.id),
            'update',
            db.desk,
            desk_id)
        desk_list = org.desks
        desk_list.insert(0, desk_id)
        org.update_record(desks=desk_list)
        # return to the org desk list
        redirect(URL('org', 'view', args=[org.id]))

    return locals()
예제 #4
0
def create():
    """Create a new organization"""
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [
        IS_NOT_EMPTY(error_message=T("Cannot be empty")),
        IS_NOT_IN_DB(
            db,
            'organization.name',
            error_message=T(
                "An Organization witch that name is allready in nStock"))
    ]

    form = SQLFORM(tbl)
    form.add_button(T('Cancel'), URL('index'))

    if form.process().accepted:
        # add the new organization
        g_id = auth.user_group(auth.user.id)
        # give the user all perms over this org
        auth.add_permission(g_id, 'update', tbl, form.vars.id)
        auth.add_permission(g_id, 'read', tbl, form.vars.id)
        auth.add_permission(g_id, 'delete', tbl, form.vars.id)
        redirect(URL('index'))

    return locals()
예제 #5
0
def _():
    plugins = PluginManager('text', app=None)
    if plugins.text.app is not None:
        # this will register the content/type on the application
        plugins.text.app.registerContentType('text', ContentText())
        if not hasattr(db, 'plugin_text_text'):
            # configure ckeditor
            editor = CKEditor(db=db)
            # definimos la BD
            tbl = db.define_table(
                'plugin_text_text',
                Field('byline', 'string', length=250, default=''),
                Field('body', 'text', label=T('Content')),
                Field('item_id', 'string', length=64),
                auth.signature,
            )
            tbl.byline.label = T('By line')
            tbl.item_id.readable = False
            tbl.item_id.writable = False
            tbl.body.requires = IS_NOT_EMPTY()
            tbl.body.widget = editor.widget

            # enable record  versioning
            tbl._enable_record_versioning()

    return
예제 #6
0
        def prep(r):
            # Call standard prep
            result = standard_prep(r) if callable(standard_prep) else True

            from gluon import IS_NOT_EMPTY
            from s3 import S3SQLCustomForm, \
                           StringTemplateParser

            # Determine order of name fields
            NAMES = ("first_name", "middle_name", "last_name")
            keys = StringTemplateParser.keys(settings.get_pr_name_format())
            name_fields = [fn for fn in keys if fn in NAMES]

            if r.controller == "default":
                # Personal profile (default/person)
                if not r.component:

                    # Last name is required
                    table = r.resource.table
                    table.last_name.requires = IS_NOT_EMPTY()

                    # Custom Form
                    crud_fields = name_fields
                    r.resource.configure(
                        crud_form=S3SQLCustomForm(*crud_fields),
                        deletable=False,
                    )
            return result
예제 #7
0
def _():
    tbl = db.define_table(
        'plugin_comment_comment',
        Field('body', 'text', label=T('Your comment')),
        Field('item_id', 'string', length=64),
        auth.signature,
    )
    tbl.item_id.readable = False
    tbl.item_id.writable = False
    tbl.body.requires = IS_NOT_EMPTY()

    return lambda item_id: LOAD(
        'plugin_comment', 'index.load', args=[item_id], ajax=True)
예제 #8
0
def edit():
    org = db.organization(request.args(0))
    tbl = db.organization
    tbl.users.readable = False
    tbl.users.writable = False
    tbl.desks.readable = False
    tbl.desks.writable = False
    tbl.name.requires = [IS_NOT_EMPTY()]

    # edit form
    form = SQLFORM(db.organization, record=org, showid=False)
    if form.process().accepted:
        redirect(URL('view', args=[org.id]))

    return locals()
예제 #9
0
    def __call__(self):

        request = current.request
        response = current.response

        from gluon import Field, SQLFORM, IS_NOT_EMPTY, IS_EMAIL, IS_IN_SET, IS_EMPTY_OR
        from s3 import s3_mark_required, S3StringWidget

        T = current.T
        formstyle = current.deployment_settings.get_ui_formstyle()

        fields = [Field("address",
                        label = T("Your e-mail address"),
                        requires = IS_EMAIL(),
                        widget = lambda *args, **kwargs: \
                                 S3StringWidget(placeholder="*****@*****.**")(_type="email", *args, **kwargs),
                        ),
                  Field("subject",
                        label = T("Subject"),
                        requires = IS_EMPTY_OR(IS_IN_SET(("Solution Development",
                                                          "Workshop / Training",
                                                          "SAHANA Deployment / Support",
                                                          "Other / General Inquiry",
                                                          ),
                                                         zero = "What can we do for you?",
                                                         sort = False,
                                                         )),
                        ),
                  Field("message", "text",
                        label = T("Message"),
                        requires = IS_NOT_EMPTY(),
                        ),
                  ]

        labels, required = s3_mark_required(fields)
        response.form_label_separator = ""
        form = SQLFORM.factory(
            formstyle=formstyle,
            labels=labels,
            submit_button=T("Send Message"),
            _id="mailform",
            *fields,
        )

        if form.accepts(
                request.post_vars,
                current.session,
                formname="default/index/contact",
                #onvalidation = onvalidation,
                keepvalues=False,
                hideerror=False,
        ):

            form_vars = form.vars
            subject = "Request on AidIQ website"
            if form_vars.subject:
                subject = "%s: %s" % (subject, form_vars.subject)

            result = current.msg.send_email(
                to=current.deployment_settings.get_mail_approver(),
                subject=form_vars.subject,
                message=form_vars.message,
                reply_to=form_vars.address,
            )
            if result:
                response.confirmation = "Thank you for your message - we'll be in touch shortly"

        appname = request.application
        s3 = response.s3
        sappend = s3.scripts.append
        if s3.cdn:
            if s3.debug:
                sappend(
                    "//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"
                )
            else:
                sappend(
                    "//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"
                )

        else:
            if s3.debug:
                sappend("/%s/static/scripts/jquery.validate.js" % appname)
            else:
                sappend("/%s/static/scripts/jquery.validate.min.js" % appname)
        sappend("/%s/static/themes/AidIQ/js/contact.js" % appname)

        response.title = "Contact Us | AidIQ.com"

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

        return {
            "form": DIV(form, _class="form-container"),
        }
예제 #10
0
    def __call__(self):

        output = {}

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

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

        # Login/Registration forms
        self_registration = settings.get_security_registration_visible()
        registered = False
        login_form = None
        login_div = None
        register_form = None
        register_div = None

        # Project Links
        project_links = DIV(_class="title-links hide-for-small")
        project_description = settings.get_frontpage("project_description")
        if project_description:
            project_links.append(
                A(
                    ICON("link"),
                    T("Project Description"),
                    _class="action-lnk",
                    _href=project_description,
                    _target="_blank",
                ))
        project_links.append(
            A(
                ICON("link"),
                T("User Manual"),
                _class="action-lnk",
                _href=URL(
                    c="default",
                    f="index",
                    args=["docs"],
                    vars={"name": "UserManual"},
                ),
                _target="_blank",
            ))
        mailing_list = settings.get_frontpage("mailing_list")
        if mailing_list:
            project_links.append(
                A(
                    ICON("link"),
                    T("Mailing List"),
                    _class="action-lnk",
                    _href=mailing_list,
                    _target="_blank",
                ))

        # Contact Form
        request_email = settings.get_frontpage("request_email")
        if request_email:
            from gluon import IS_NOT_EMPTY, SQLFORM
            from s3dal import Field
            fields = [
                Field(
                    "name",
                    label="Your name",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "address",
                    label="Your e-mail address",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "subject",
                    label="Subject",
                    requires=IS_NOT_EMPTY(),
                ),
                Field(
                    "message",
                    "text",
                    label="Message",
                    requires=IS_NOT_EMPTY(),
                ),
            ]
            from s3 import s3_mark_required
            labels, required = s3_mark_required(fields)
            s3.has_required = required

            response.form_label_separator = ""
            contact_form = SQLFORM.factory(
                formstyle=settings.get_ui_formstyle(),
                submit_button=T("Submit"),
                labels=labels,
                separator="",
                table_name="contact",  # Dummy table name
                _id="mailform",
                *fields)

            if contact_form.accepts(request.post_vars,
                                    current.session,
                                    formname="contact_form",
                                    keepvalues=False,
                                    hideerror=False):
                # Processs Contact Form
                form_vars = contact_form.vars
                sender = "%s <%s>" % (form_vars.name, form_vars.address)
                result = current.msg.send_email(
                    to=request_email,
                    sender=sender,
                    subject=form_vars.subject,
                    message=form_vars.message,
                    reply_to=form_vars.address,
                )
                if result:
                    response.confirmation = "Thank you for your message - we'll be in touch shortly"
            if s3.cdn:
                if s3.debug:
                    s3.scripts.append(
                        "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"
                    )
                else:
                    s3.scripts.append(
                        "http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"
                    )
            else:
                if s3.debug:
                    s3.scripts.append("/%s/static/scripts/jquery.validate.js" %
                                      request.application)
                else:
                    s3.scripts.append(
                        "/%s/static/scripts/jquery.validate.min.js" %
                        request.application)
            validation_script = '''
$('#mailform').validate({
 errorClass:'req',
 rules:{
  name:{
   required:true
  },
  address: {
   required:true,
   email:true
  },
  subject:{
   required:true
  },
  message:{
   required:true
  }
 },
 messages:{
  name:"Enter your name",
  subject:"Enter a subject",
  message:"Enter a message",
  address:{
   required:"Please enter a valid email address",
   email:"Please enter a valid email address"
  }
 },
 errorPlacement:function(error,element){
  error.appendTo(element.parents('div.controls'))
 },
 submitHandler:function(form){
  form.submit()
 }
})'''
            s3.jquery_ready.append(validation_script)

        else:
            contact_form = ""

        if AUTHENTICATED not in roles:

            login_buttons = DIV(A(T("Login"),
                                  _id="show-login",
                                  _class="tiny secondary button"),
                                _id="login-buttons")
            script = '''
$('#show-mailform').click(function(e){
 e.preventDefault()
 $('#login_box').fadeOut(function(){$('#intro').fadeIn()})
})
$('#show-login').click(function(e){
 e.preventDefault()
 $('#login_form').show()
 $('#register_form').hide()
 $('#intro').fadeOut(function(){$('#login_box').fadeIn()})
})'''
            s3.jquery_ready.append(script)

            # This user isn't yet logged-in
            if request.cookies.has_key("registered"):
                # This browser has logged-in before
                registered = True

            if self_registration is True:
                # Provide a Registration box on front page
                login_buttons.append(
                    A(T("Register"),
                      _id="show-register",
                      _class="tiny secondary button",
                      _style="margin-left:5px"))
                script = '''
$('#show-register').click(function(e){
 e.preventDefault()
 $('#login_form').hide()
 $('#register_form').show()
 $('#intro').fadeOut(function(){$('#login_box').fadeIn()})
})'''
                s3.jquery_ready.append(script)

                register_form = auth.register()
                register_div = DIV(H3(T("Register")),
                                   P(XML(T("If you would like to help, then please %(sign_up_now)s") % \
                                            dict(sign_up_now=B(T("sign-up now"))))))

                register_script = '''
$('#register-btn').click(function(e){
 e.preventDefault()
 $('#login_form').fadeOut(function(){$('#register_form').fadeIn()})
})
$('#login-btn').click(function(e){
 e.preventDefault()
 $('#register_form').fadeOut(function(){$('#login_form').fadeIn()})
})'''
                s3.jquery_ready.append(register_script)

            # Provide a login box on front page
            auth.messages.submit_button = T("Login")
            login_form = auth.login(inline=True)
            login_div = DIV(H3(T("Login")),
                            P(XML(T("Registered users can %(login)s to access the system") % \
                                  dict(login=B(T("login"))))))

        else:
            login_buttons = ""

        # Create output dict
        output = {
            "login_buttons": login_buttons,
            "self_registration": self_registration,
            "registered": registered,
            "login_div": login_div,
            "login_form": login_form,
            "register_div": register_div,
            "register_form": register_form,
            "contact_form": contact_form,
            "project_links": project_links,
        }

        # Count records (@todo: provide total/updated counters?)
        s3db = current.s3db
        db = current.db

        # Organisations
        table = s3db.org_organisation
        query = (table.deleted != True)
        count = table.id.count()
        row = db(query).select(count).first()
        output["total_organisations"] = row[count]

        # Service Locations (@todo)
        #table = s3db.org_service_location
        #query = (table.deleted != True)
        #count = table.id.count()
        #row = db(query).select(count).first()
        output["total_services"] = 0  #row[count]

        # Needs lists
        table = s3db.req_organisation_needs
        query = (table.deleted != True)
        count = table.id.count()
        row = db(query).select(count).first()
        output["total_needs"] = row[count]

        # Frontpage Feed Control
        if settings.frontpage.rss:
            s3.external_stylesheets.append(
                "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.css"
            )
            s3.scripts.append(
                "http://www.google.com/jsapi?key=notsupplied-wizard")
            s3.scripts.append(
                "http://www.google.com/uds/solutions/dynamicfeed/gfdynamicfeedcontrol.js"
            )
            counter = 0
            feeds = ""
            for feed in settings.frontpage.rss:
                counter += 1
                feeds = "".join((feeds, "{title:'%s',\n" % feed["title"],
                                 "url:'%s'}" % feed["url"]))
                # Don't add a trailing comma for old IEs
                if counter != len(settings.frontpage.rss):
                    feeds += ",\n"
            # feedCycleTime: milliseconds before feed is reloaded (5 minutes)
            feed_control = "".join(('''
function LoadDynamicFeedControl(){
 var feeds=[
  ''', feeds, '''
 ]
 var options={
  feedCycleTime:300000,
  numResults:5,
  stacked:true,
  horizontal:false,
  title:"''', str(T("News")), '''"
 }
 new GFdynamicFeedControl(feeds,'feed-control',options)
}
google.load('feeds','1')
google.setOnLoadCallback(LoadDynamicFeedControl)'''))

        s3.js_global.append(feed_control)
        s3.stylesheets.append("../themes/RW/homepage.css")

        self._view(THEME, "index.html")
        return output
예제 #11
0
    def define_tables(self, db, migrate):
        from gluon.dal import DEFAULT
        logger.debug('defining tables (migrate=%s)', migrate)
        now = self.now
        db.define_table('scheduler_task',
                        Field('application_name',
                              requires=IS_NOT_EMPTY(),
                              default=None,
                              writable=False),
                        Field('task_name', default=None),
                        Field('group_name', default='main'),
                        Field('status',
                              requires=IS_IN_SET(TASK_STATUS),
                              default=QUEUED,
                              writable=False),
                        Field('function_name',
                              requires=IS_IN_SET(sorted(self.tasks.keys()))
                              if self.tasks else DEFAULT),
                        Field('uuid',
                              length=255,
                              requires=IS_NOT_IN_DB(db, 'scheduler_task.uuid'),
                              unique=True,
                              default=web2py_uuid),
                        Field('args',
                              'text',
                              default='[]',
                              requires=TYPE(list)),
                        Field('vars',
                              'text',
                              default='{}',
                              requires=TYPE(dict)),
                        Field('enabled', 'boolean', default=True),
                        Field('start_time',
                              'datetime',
                              default=now,
                              requires=IS_DATETIME()),
                        Field('next_run_time', 'datetime', default=now),
                        Field('stop_time', 'datetime'),
                        Field('repeats',
                              'integer',
                              default=1,
                              comment="0=unlimited",
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('retry_failed',
                              'integer',
                              default=0,
                              comment="-1=unlimited",
                              requires=IS_INT_IN_RANGE(-1, None)),
                        Field('period',
                              'integer',
                              default=60,
                              comment='seconds',
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('prevent_drift',
                              'boolean',
                              default=False,
                              comment='Cron-like start_times between runs'),
                        Field('timeout',
                              'integer',
                              default=60,
                              comment='seconds',
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('sync_output',
                              'integer',
                              default=0,
                              comment="update output every n sec: 0=never",
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('times_run',
                              'integer',
                              default=0,
                              writable=False),
                        Field('times_failed',
                              'integer',
                              default=0,
                              writable=False),
                        Field('last_run_time',
                              'datetime',
                              writable=False,
                              readable=False),
                        Field('assigned_worker_name',
                              default='',
                              writable=False),
                        on_define=self.set_requirements,
                        migrate=self.__get_migrate('scheduler_task', migrate),
                        format='%(task_name)s')

        db.define_table('scheduler_run',
                        Field('task_id', 'reference scheduler_task'),
                        Field('status', requires=IS_IN_SET(RUN_STATUS)),
                        Field('start_time', 'datetime'),
                        Field('stop_time', 'datetime'),
                        Field('run_output', 'text'),
                        Field('run_result', 'text'),
                        Field('traceback', 'text'),
                        Field('worker_name', default=self.worker_name),
                        migrate=self.__get_migrate('scheduler_run', migrate))

        db.define_table('scheduler_worker',
                        Field('worker_name', length=255, unique=True),
                        Field('first_heartbeat', 'datetime'),
                        Field('last_heartbeat', 'datetime'),
                        Field('status', requires=IS_IN_SET(WORKER_STATUS)),
                        Field('is_ticker',
                              'boolean',
                              default=False,
                              writable=False),
                        Field('group_names',
                              'list:string',
                              default=self.group_names),
                        migrate=self.__get_migrate('scheduler_worker',
                                                   migrate))

        if migrate is not False:
            db.commit()
예제 #12
0
def _():
    plugins = PluginManager('picture', app=None)
    # this will register the content/type on the application
    if plugins.picture.app is not None:
        editor = CKEditor(db=db)
        plugins.picture.app.registerContentType('picture', ContentPicture())
        if not hasattr(db, 'plugin_picture_rendition'):
            tbl = db.define_table(
                'plugin_picture_rendition',
                Field('picture',
                      'upload',
                      uploadseparate=True,
                      autodelete=True),
                Field('purpose', 'string', length=50, default='raw'),
                Field('height',
                      'integer',
                      default=0,
                      readable=False,
                      writable=False),
                Field('width',
                      'integer',
                      default=0,
                      readable=False,
                      writable=False),
                Field('color',
                      'string',
                      length=20,
                      readable=False,
                      writable=False),
                Field('format',
                      'string',
                      length=10,
                      readable=False,
                      writable=False))
            tbl.purpose.comment = T('''
            It may contain any value but it is recommended to use one of the
            values: raw, web, thumbnail, print
            ''')
            tbl.purpose.label = T('Purpose')
            tbl.height.label = T('Height')
            tbl.width.label = T('Width')
            tbl.color.label = T('Color space')
            tbl.format.label = T('Format')
            tbl.format.comment = T('Automatic form PIL')
            tbl.picture.label = T('Picture')
            tbl.picture.requires = [IS_IMAGE(), IS_NOT_EMPTY()]

        if not hasattr(db, 'plugin_picture_info'):
            # definimos la BD
            tbl = db.define_table(
                'plugin_picture_info',
                Field('credit_line', 'string', length=250, default=''),
                Field('description',
                      'text',
                      label=T('Description'),
                      default=''),
                Field('caption', 'string', length=250, default=''),
                Field('thumbnail',
                      'upload',
                      uploadseparate=True,
                      autodelete=True,
                      default=None),
                Field('renditions', 'list:reference plugin_picture_rendition'),
                Field('item_id', 'string', length=64),
                auth.signature,
            )
            tbl.credit_line.label = T("Credit line")
            tbl.description.label = T('Description')
            tbl.description.widget = editor.widget
            tbl.caption.label = T("Caption")
            tbl.renditions.label = T("Renditions")
            tbl.item_id.readable = False
            tbl.item_id.writable = False

            # enable record  versioning
            tbl._enable_record_versioning()

    return
    def formfields():
        """
            Generate the form fields for the registration form

            @returns: a tuple (formfields, required_fields, subheadings)
                      - formfields = list of form fields
                      - required_fields = list of field names of required fields
                      - subheadings = list of tuples (position, heading) to
                                      insert into the form
        """

        T = current.T
        request = current.request

        db = current.db
        s3db = current.s3db

        auth = current.auth
        auth_settings = auth.settings
        auth_messages = auth.messages

        utable = auth_settings.table_user
        passfield = auth_settings.password_field

        occupation_type_represent = S3Represent(
            lookup="pr_occupation_type",
            multiple=True,
        )

        # Instantiate Consent Tracker
        consent = s3db.auth_Consent(processing_types=["SHARE"])

        # Last name is required
        utable.last_name.requires = IS_NOT_EMPTY(
            error_message=T("input required"))

        ltable = s3db.gis_location

        # Form fields
        formfields = [utable.first_name,
                      utable.last_name,
                      s3_date("date_of_birth",
                              label = T("Date of Birth"),
                              future = -156,
                              empty = False,
                              ),
                      # --------------------------------------------
                      utable.email,
                      utable[passfield],

                      # Password Verification Field
                      Field("password_two", "password",
                            label = auth_messages.verify_password,
                            requires = IS_EXPR("value==%s" % \
                                               repr(request.vars.get(passfield)),
                                               error_message = auth_messages.mismatched_password,
                                               ),
                            comment = DIV(_class = "tooltip",
                                          _title = "%s|%s" % (auth_messages.verify_password,
                                                              T("Enter the same password again"),
                                                              ),
                                          ),
                            ),
                      # --------------------------------------------
                      Field("home_phone",
                            label = T("Phone"),
                            requires = IS_EMPTY_OR(IS_PHONE_NUMBER_MULTI()),
                            ),
                      Field("mobile_phone",
                            label = T("Mobile Phone"),
                            requires = IS_EMPTY_OR(IS_PHONE_NUMBER_SINGLE()),
                            ),
                      #Field("office_phone",
                      #      label = T("Office Phone"),
                      #      requires = IS_EMPTY_OR(IS_PHONE_NUMBER_MULTI()),
                      #      ),
                      # --------------------------------------------
                      s3db.gis_location_id("location_id",
                                           widget = S3LocationSelector(
                                                       show_address = False,
                                                       show_postcode = False,
                                                       show_map = False,
                                                       ),
                                           ),
                      Field("addr_street",
                            label = ltable.addr_street.label,
                            ),
                      Field("addr_postcode",
                            label = ltable.addr_postcode.label,
                            requires = IS_NOT_EMPTY(),
                            ),

                      # --------------------------------------------
                      Field("occupation_type_ids",
                            "list:reference pr_occupation_type",
                            label = T("Occupation Type"),
                            requires = IS_EMPTY_OR(IS_ONE_OF(db,
                                          "pr_occupation_type.id",
                                          occupation_type_represent,
                                          multiple=True,
                                          )),
                            represent = occupation_type_represent,
                            widget = S3MultiSelectWidget(),
                            comment = DIV(_class = "tooltip",
                                          _title = "%s|%s" % (T("Occupation Type"),
                                                              T("Select all that apply"),
                                                              ),
                                          ),
                            ),
                      Field("occupation",
                            label = T("Occupation / Speciality"),
                            comment = DIV(_class = "tooltip",
                                          _title = "%s|%s" % (T("Occupation / Speciality"),
                                                              T("Specify your exact job designation"),
                                                              ),
                                          ),
                            ),

                      # --------------------------------------------
                      s3_date("start_date",
                              label = T("Available from"),
                              default = "now",
                              past = 0,
                              set_min = "#auth_user_start_date",
                              ),
                      s3_date("end_date",
                              label = T("Available until"),
                              past = 0,
                              set_max = "#auth_user_start_date",
                              ),
                      Field("hours_per_week", "integer",
                            label = T("Hours per Week"),
                            requires = IS_EMPTY_OR(IS_INT_IN_RANGE(1, 60)),
                            comment = DIV(_class = "tooltip",
                                          _title = "%s|%s" % (T("Hours per Week"),
                                                              T("Specify the maximum number of weekly hours"),
                                                              ),
                                          ),
                            ),
                      Field("schedule", "text",
                            label = T("Availability Schedule"),
                            widget = s3_comments_widget,
                            comment = DIV(_class = "tooltip",
                                          _title = "%s|%s" % (T("Availability Schedule"),
                                                              T("Specify days/hours like: Monday 10-12; Tuesday 10-12 and 14-19; Friday 13-15"),
                                                              ),
                                          ),
                            ),
                      s3db.hrm_multi_skill_id(
                            label = T("Skills / Resources"),
                            widget = S3GroupedOptionsWidget(cols = 1,
                                                            size = None,
                                                            help_field = "comments",
                                                            ),
                            ),

                      # --------------------------------------------
                      Field("comments", "text",
                            label = T("Comments"),
                            widget = s3_comments_widget,
                            ),

                      # --------------------------------------------
                      Field("consent",
                           label = T("Consent"),
                           widget = consent.widget,
                           ),
                      ]

        # Required fields
        required_fields = [
            "first_name",
            "last_name",
        ]

        # Subheadings
        subheadings = (
            (3, T("User Account")),
            (6, T("Contact Information")),
            (8, T("Address")),
            (11, T("Occupation")),
            (13, T("Availability and Resources")),
            (18, T("Comments")),
            (19, T("Privacy")),
        )

        return formfields, required_fields, subheadings
    def __call__(self):

        T = current.T

        request = current.request
        response = current.response
        session = current.session

        settings = current.deployment_settings

        # Get the registration key
        if request.env.request_method == "POST":
            key = request.post_vars.registration_key
        elif len(request.args) > 1:
            key = request.args[-1]
        else:
            key = None
        if not key:
            session.error = T("Missing registration key")
            redirect(URL(c="default", f="index"))

        formfields = [
            Field(
                "activation_code",
                label=T("Please enter your Activation Code"),
                requires=IS_NOT_EMPTY(),
            ),
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(
            table_name="auth_user",
            record=None,
            hidden={
                "_next": request.vars._next,
                "registration_key": key,
            },
            separator=":",
            showid=False,
            submit_button=T("Submit"),
            formstyle=settings.get_ui_formstyle(),
            #buttons = buttons,
            *formfields)

        if form.accepts(
                request.vars,
                session,
                formname="register_confirm",
        ):

            db = current.db
            s3db = current.s3db

            auth = current.auth
            auth_settings = auth.settings
            register.customise_auth_messages()

            # Get registration key from URL
            code = form.vars.activation_code

            # Find the pending user account
            utable = auth_settings.table_user
            query = (utable.registration_key == register.keyhash(key, code))
            user = db(query).select(limitby=(0, 1), ).first()
            if not user:
                session.error = T("Registration not found")
                redirect(auth_settings.verify_email_next)

            # Configure callback to process custom fields
            s3db.configure(
                "auth_user",
                register_onaccept=register.register_onaccept,
            )

            # Approve and link user
            auth.s3_approve_user(user)

            # Send welcome email (custom)
            self.send_welcome_email(user)

            # Log them in
            user = Storage(utable._filter_fields(user, id=True))
            auth.login_user(user)

            auth_messages = auth.messages
            auth.log_event(auth_messages.verify_email_log, user)

            session = current.session
            session.confirmation = auth_messages.email_verified
            session.flash = auth_messages.registration_successful

            redirect(URL(c="default", f="person"))

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

        return {
            "title": T("Confirm Registration"),
            "form": form,
        }
    def define_tables(self, db, migrate):
        from gluon import current
        from gluon.dal import DEFAULT
        logging.debug('defining tables (migrate=%s)' % migrate)
        now = self.now()
        db.define_table('scheduler_task',
                        Field('application_name',
                              requires=IS_NOT_EMPTY(),
                              default=None,
                              writable=False),
                        Field('task_name', default=None),
                        Field('group_name', default='main', writable=False),
                        Field('status',
                              requires=IS_IN_SET(TASK_STATUS),
                              default=QUEUED,
                              writable=False),
                        Field('function_name',
                              requires=IS_IN_SET(sorted(self.tasks.keys()))
                              if self.tasks else DEFAULT),
                        Field('uuid',
                              requires=IS_NOT_IN_DB(db, 'scheduler_task.uuid'),
                              unique=True,
                              default=web2py_uuid),
                        Field('args',
                              'text',
                              default='[]',
                              requires=TYPE(list)),
                        Field('vars',
                              'text',
                              default='{}',
                              requires=TYPE(dict)),
                        Field('enabled', 'boolean', default=True),
                        Field('start_time',
                              'datetime',
                              default=now,
                              requires=IS_NOT_EMPTY()),
                        Field('next_run_time', 'datetime', default=now),
                        Field('stop_time', 'datetime'),
                        Field('repeats',
                              'integer',
                              default=1,
                              comment="0=unlimited",
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('retry_failed',
                              'integer',
                              default=0,
                              comment="-1=unlimited",
                              requires=IS_INT_IN_RANGE(-1, None)),
                        Field('period',
                              'integer',
                              default=60,
                              comment='seconds',
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('timeout',
                              'integer',
                              default=60,
                              comment='seconds',
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('sync_output',
                              'integer',
                              default=0,
                              comment="update output every n sec: 0=never",
                              requires=IS_INT_IN_RANGE(0, None)),
                        Field('times_run',
                              'integer',
                              default=0,
                              writable=False),
                        Field('times_failed',
                              'integer',
                              default=0,
                              writable=False),
                        Field('last_run_time',
                              'datetime',
                              writable=False,
                              readable=False),
                        Field('assigned_worker_name',
                              default='',
                              writable=False),
                        migrate=migrate,
                        format='%(task_name)s')
        if hasattr(current, 'request'):
            db.scheduler_task.application_name.default = '%s/%s' % (
                current.request.application, current.request.controller)

        db.define_table('scheduler_run',
                        Field('scheduler_task', 'reference scheduler_task'),
                        Field('status', requires=IS_IN_SET(RUN_STATUS)),
                        Field('start_time', 'datetime'),
                        Field('stop_time', 'datetime'),
                        Field('output', 'text'),
                        Field('result', 'text'),
                        Field('traceback', 'text'),
                        Field('worker_name', default=self.worker_name),
                        migrate=migrate)

        db.define_table('scheduler_worker',
                        Field('worker_name', unique=True),
                        Field('first_heartbeat', 'datetime'),
                        Field('last_heartbeat', 'datetime'),
                        Field('status', requires=IS_IN_SET(WORKER_STATUS)),
                        Field('is_ticker',
                              'boolean',
                              default=False,
                              writable=False),
                        Field('group_names',
                              'list:string',
                              default=self.group_names),
                        migrate=migrate)
        db.commit()
예제 #16
0
파일: po.py 프로젝트: sahana/eden
    def model(self):

        T = current.T
        auth = current.auth

        super_link = self.super_link

        #root_org = auth.root_org()
        #ADMIN = current.session.s3.system_roles.ADMIN
        #is_admin = auth.s3_has_role(ADMIN)

        # ---------------------------------------------------------------------
        # Area
        #
        tablename = "po_area"
        self.define_table(
            tablename,
            super_link("doc_id", "doc_entity"),
            # This was included to allow Areas to be realm entities but this is currently not used
            # Re-enable onaccept/ondelete & S3EntityRoleManager if this becomes required in future
            #super_link("pe_id", "pr_pentity"),
            Field(
                "name",
                requires=IS_NOT_EMPTY(),
            ),
            self.gis_location_id(widget=S3LocationSelector(
                points=False,
                polygons=True,
                feature_required=True,
            ), ),
            # Included primarily to set realm
            self.org_organisation_id(
                default=auth.user and auth.user.organisation_id,
                #default = root_org,
                #readable = is_admin,
                #writable = is_admin,
            ),
            Field(
                "attempted_visits",
                "integer",
                comment=DIV(
                    _class="tooltip",
                    _title="%s|%s" %
                    (T("Attempted Visits"),
                     T("Number of households in the area where nobody was at home at the time of visit"
                       ))),
                default=0,
                label=T("Attempted Visits"),
                requires=IS_EMPTY_OR(IS_INT_IN_RANGE(minimum=0)),
            ),
            s3_comments(),
            *s3_meta_fields())

        # CRUD Strings
        current.response.s3.crud_strings[tablename] = Storage(
            label_create=T("Create Area"),
            title_display=T("Area Details"),
            title_list=T("Areas"),
            title_update=T("Edit Area"),
            label_list_button=T("List Areas"),
            label_delete_button=T("Delete Area"),
            msg_record_created=T("Area created"),
            msg_record_modified=T("Area updated"),
            msg_record_deleted=T("Area deleted"),
            msg_list_empty=T("No Areas currently registered"),
        )

        # Reusable field
        represent = S3Represent(lookup=tablename, show_link=True)
        area_id = S3ReusableField(
            "area_id",
            "reference %s" % tablename,
            label=T("Area"),
            represent=represent,
            requires=IS_ONE_OF(
                current.db,
                "po_area.id",
                represent,
            ),
            sortby="name",
            comment=S3PopupLink(
                f="area",
                tooltip=T("Create a new area"),
            ),
        )

        # Components
        self.add_components(
            tablename,
            po_household="area_id",
            org_organisation={
                "link": "po_organisation_area",
                "joinby": "area_id",
                "key": "organisation_id",
                "actuate": "hide",
            },
        )

        levels = current.gis.get_relevant_hierarchy_levels()

        # Filters
        filter_widgets = [
            S3TextFilter(["name"]),
            S3LocationFilter("location_id", levels=levels),
        ]

        # @todo: reports

        # Table Configuration
        self.configure(
            tablename,
            deduplicate=S3Duplicate(ignore_deleted=True),
            filter_widgets=filter_widgets,
            #onaccept = self.area_onaccept,
            #ondelete = self.area_ondelete,
            realm_components=("household", ),
            summary=(
                {
                    "common": True,
                    "name": "add",
                    "widgets": [{
                        "method": "create"
                    }],
                },
                {
                    "name": "table",
                    "label": "Table",
                    "widgets": [{
                        "method": "datatable"
                    }]
                },
                {
                    "name": "map",
                    "label": "Map",
                    "widgets": [{
                        "method": "map",
                        "ajax_init": True
                    }],
                },
            ),
            #super_entity = ("doc_entity", "pr_pentity"),
            super_entity="doc_entity",
            update_realm=True,
        )

        # ---------------------------------------------------------------------
        # Pass names back to global scope (s3.*)
        #
        return {
            "po_area_id": area_id,
        }
예제 #17
0
파일: po.py 프로젝트: sahana/eden
    def model(self):

        T = current.T
        db = current.db

        define_table = self.define_table
        super_link = self.super_link
        configure = self.configure

        s3 = current.response.s3
        crud_strings = s3.crud_strings

        person_id = self.pr_person_id

        # ---------------------------------------------------------------------
        # Household
        #
        tablename = "po_household"
        define_table(
            tablename,
            super_link("doc_id", "doc_entity"),
            # Instance, not Component
            # If needed to be accessed via pr_PersonEntityRepresent, then need to pass in custom instance_types
            # instance_types = {"po_household": T("Household")}
            super_link("pe_id", "pr_pentity"),
            self.po_area_id(),
            # Controller (area prep) makes it inherit Lx from area
            self.gis_location_id(
                label=T("Address"),
                widget=S3LocationSelector(
                    show_address=True,
                    # Defaults:
                    #show_map=settings.get_gis_map_selector(),
                    #show_postcode=settings.get_gis_postcode_selector(),
                    prevent_duplicate_addresses=True,
                ),
            ),
            s3_date(
                "date_visited",
                default="now",
                empty=False,
                label=T("Date visited"),
            ),
            Field(
                "followup",
                "boolean",
                default=False,
                label=T("Follow up"),
                represent=s3_yes_no_represent,
            ),
            s3_comments(),
            *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            label_create=T("Create Household"),
            title_display=T("Household Details"),
            title_list=T("Households"),
            title_update=T("Edit Household"),
            label_list_button=T("List Households"),
            label_delete_button=T("Delete Household"),
            msg_record_created=T("Household created"),
            msg_record_modified=T("Household updated"),
            msg_record_deleted=T("Household deleted"),
            msg_list_empty=T("No Households currently registered"),
        )

        # Reusable Field
        represent = po_HouseholdRepresent()
        household_id = S3ReusableField(
            "household_id",
            "reference %s" % tablename,
            label=T("Household"),
            represent=represent,
            requires=IS_ONE_OF(
                db,
                "po_household.id",
                represent,
            ),
            sortby="name",
            comment=S3PopupLink(
                f="household",
                tooltip=T("Create a new household"),
            ),
        )

        sticker_opts = {
            "W": T("White"),
            "Y": T("Yellow"),
            "R": T("Red"),
        }

        # Filter Widgets
        filter_widgets = [
            S3TextFilter(
                (
                    "household_member.person_id$first_name",
                    "household_member.person_id$middle_name",
                    "household_member.person_id$last_name",
                    "location_id$addr_street",
                ),
                label=T("Search"),
                comment=T("Search by Address or Name of Household Member"),
            ),
            S3OptionsFilter("area_id",
                            #hidden = True,
                            ),
            S3OptionsFilter(
                "household_dwelling.sticker",
                cols=3,
                options=sticker_opts,
            ),
            S3OptionsFilter(
                "emotional_need__link.emotional_need_id",
                label=T("Emotional Needs"),
                hidden=True,
            ),
            S3OptionsFilter(
                "practical_need__link.practical_need_id",
                label=T("Practical Needs"),
                hidden=True,
            ),
            S3DateFilter(
                "date_visited",
                label=T("Date visited"),
                hidden=True,
            ),
            S3OptionsFilter(
                "followup",
                cols=2,
                hidden=True,
            ),
            S3DateFilter(
                "household_followup.followup_date",
                label=T("Follow-up Date"),
                hidden=True,
            ),
            S3OptionsFilter(
                "household_followup.completed",
                cols=2,
                hidden=True,
            ),
            S3OptionsFilter(
                "organisation_household.organisation_id",
                hidden=True,
            ),
        ]

        # List fields
        list_fields = (
            "area_id",
            "location_id",
            "date_visited",
            "household_dwelling.sticker",
            (T("Emotional Needs"), "emotional_need__link.emotional_need_id"),
            (T("Practical Needs"), "practical_need__link.practical_need_id"),
            "followup",
            "household_followup.followup_date",
            "household_followup.completed",
            "organisation_household.organisation_id",
            "comments",
        )

        # Reports
        report_axes = [
            "area_id",
            "followup",
            "organisation_household.organisation_id",
            "household_followup.completed",
            "household_followup.evaluation",
        ]

        # Custom Form
        crud_form = S3SQLCustomForm(
            "area_id",
            "location_id",
            "date_visited",
            "household_dwelling.sticker",
            S3SQLInlineLink(
                "emotional_need",
                field="emotional_need_id",
                label=T("Emotional Needs"),
            ),
            S3SQLInlineLink(
                "practical_need",
                field="practical_need_id",
                label=T("Practical Needs"),
            ),
            "followup",
            S3SQLInlineComponent(
                "contact",
                label=T("Contact Information"),
                fields=[
                    "priority",
                    (T("Type"), "contact_method"),
                    (T("Number"), "value"),
                    "comments",
                ],
                orderby="priority",
            ),
            "household_social.language",
            "household_social.community",
            "household_dwelling.dwelling_type",
            "household_dwelling.type_of_use",
            "household_dwelling.repair_status",
            "comments",
        )

        configure(
            tablename,
            create_next=self.household_create_next,
            crud_form=crud_form,
            deduplicate=S3Duplicate(primary=("location_id", )),
            filter_widgets=filter_widgets,
            list_fields=list_fields,
            onaccept=self.household_onaccept,
            realm_components=(
                "pr_person",
                "household_dwelling",
                "household_social",
                "household_followup",
                "organisation_household",
            ),
            report_options={
                "rows": report_axes,
                "cols": report_axes,
                "fact": ((T("Number of Households Visited"), "count(id)"), ),
                "defaults": {
                    "rows": "area_id",
                    "cols": "followup",
                    "fact": "count(id)",
                },
            },
            super_entity=("doc_entity", "pr_pentity"),
        )

        # Components
        self.add_components(
            tablename,
            pr_person={
                "link": "po_household_member",
                "joinby": "household_id",
                "key": "person_id",
                "actuate": "replace",
            },
            po_household_dwelling={
                "joinby": "household_id",
                "multiple": False,
            },
            po_household_social={
                "joinby": "household_id",
                "multiple": False,
            },
            po_household_followup={
                "joinby": "household_id",
                "multiple": False,
            },
            po_emotional_need={
                "link": "po_household_emotional_need",
                "joinby": "household_id",
                "key": "emotional_need_id",
            },
            po_practical_need={
                "link": "po_household_practical_need",
                "joinby": "household_id",
                "key": "practical_need_id",
            },
            po_organisation_household="household_id",
        )

        # ---------------------------------------------------------------------
        # Household Members
        #
        tablename = "po_household_member"
        define_table(tablename, household_id(), person_id(), s3_comments(),
                     *s3_meta_fields())

        # ---------------------------------------------------------------------
        # Household Member Age Groups (under 18,18-30,30-55,56-75,75+)
        #
        age_groups = ("<18", "18-30", "30-55", "56-75", "75+")
        tablename = "po_age_group"
        define_table(
            tablename, person_id(),
            Field(
                "age_group",
                label=T("Age Group"),
                requires=IS_EMPTY_OR(IS_IN_SET(age_groups)),
            ), *s3_meta_fields())

        # ---------------------------------------------------------------------
        # Dwelling
        #
        dwelling_type = {
            "U": T("Unit"),
            "H": T("House"),
            "A": T("Apartment"),
            "S": T("Supervised House"),
            "O": T("Other"),
        }
        type_of_use = {
            "S": T("Owner-occupied"),
            "R": T("Renting"),
            "B": T("Boarding"),
            "O": T("Other"),
        }
        repair_status = {
            "W": T("waiting"),
            "R": T("rebuild"),
            "C": T("completed"),
            "N": T("not required"),
            "O": T("other"),
        }

        tablename = "po_household_dwelling"
        define_table(
            tablename, household_id(),
            Field(
                "dwelling_type",
                label=T("Type of Dwelling"),
                represent=s3_options_represent(dwelling_type),
                requires=IS_EMPTY_OR(IS_IN_SET(dwelling_type)),
            ),
            Field(
                "type_of_use",
                label=T("Type of Use"),
                represent=s3_options_represent(type_of_use),
                requires=IS_EMPTY_OR(IS_IN_SET(type_of_use)),
            ),
            Field(
                "repair_status",
                label=T("Stage of Repair"),
                represent=s3_options_represent(repair_status),
                requires=IS_EMPTY_OR(IS_IN_SET(repair_status)),
            ),
            Field(
                "sticker",
                label=T("Sticker"),
                represent=s3_options_represent(sticker_opts),
                requires=IS_EMPTY_OR(IS_IN_SET(sticker_opts)),
            ), s3_comments(), *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            title_update=T("Edit Dwelling Data"), )

        # Table configuration
        configure(
            tablename,
            deduplicate=S3Duplicate(primary=("household_id", )),
        )

        # ---------------------------------------------------------------------
        # Emotional Needs
        #
        tablename = "po_emotional_need"
        define_table(tablename,
                     Field(
                         "name",
                         label=T("Name"),
                         requires=IS_NOT_EMPTY(),
                     ), s3_comments(), *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            label_create=T("Create Emotional Need"),
            title_display=T("Emotional Need Details"),
            title_list=T("Emotional Needs"),
            title_update=T("Edit Emotional Need"),
            label_list_button=T("List Emotional Needs"),
            label_delete_button=T("Delete Emotional Need"),
            msg_record_created=T("Emotional Need created"),
            msg_record_modified=T("Emotional Need updated"),
            msg_record_deleted=T("Emotional Need deleted"),
            msg_list_empty=T("No Emotional Needs currently registered"),
        )

        configure(
            tablename,
            deduplicate=S3Duplicate(),
        )

        # Reusable Field
        represent = S3Represent(lookup=tablename)
        emotional_need_id = S3ReusableField(
            "emotional_need_id",
            "reference %s" % tablename,
            label=T("Emotional Need"),
            ondelete="CASCADE",
            represent=represent,
            requires=IS_ONE_OF(
                db,
                "po_emotional_need.id",
                represent,
            ),
            sortby="name",
            comment=S3PopupLink(
                f="emotional_need",
                tooltip=T("Create a new emotional need"),
            ),
        )

        tablename = "po_household_emotional_need"
        define_table(tablename, household_id(), emotional_need_id(),
                     *s3_meta_fields())

        # ---------------------------------------------------------------------
        # Practical Needs
        #
        tablename = "po_practical_need"
        define_table(tablename,
                     Field(
                         "name",
                         label=T("Name"),
                         requires=IS_NOT_EMPTY(),
                     ), s3_comments(), *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            label_create=T("Create Practical Need"),
            title_display=T("Practical Need Details"),
            title_list=T("Practical Needs"),
            title_update=T("Edit Practical Need"),
            label_list_button=T("List Practical Needs"),
            label_delete_button=T("Delete Practical Need"),
            msg_record_created=T("Practical Need created"),
            msg_record_modified=T("Practical Need updated"),
            msg_record_deleted=T("Practical Need deleted"),
            msg_list_empty=T("No Practical Needs currently registered"),
        )

        configure(
            tablename,
            deduplicate=S3Duplicate(),
        )

        # Reusable Field
        represent = S3Represent(lookup=tablename)
        practical_need_id = S3ReusableField(
            "practical_need_id",
            "reference %s" % tablename,
            label=T("Practical Need"),
            ondelete="CASCADE",
            represent=represent,
            requires=IS_ONE_OF(
                db,
                "po_practical_need.id",
                represent,
            ),
            sortby="name",
            comment=S3PopupLink(
                f="practical_need",
                tooltip=T("Create a new practical need"),
            ),
        )

        tablename = "po_household_practical_need"
        define_table(tablename, household_id(), practical_need_id(),
                     *s3_meta_fields())

        # ---------------------------------------------------------------------
        # Social Information
        #
        tablename = "po_household_social"
        define_table(
            tablename, household_id(),
            s3_language(
                label=T("Main Language"),
                select=None,
            ), Field(
                "community",
                "text",
                label=T("Community Connections"),
            ), s3_comments(), *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            title_update=T("Edit Social Information"), )

        # Table configuration
        configure(
            tablename,
            deduplicate=S3Duplicate(primary=("household_id", )),
        )

        # ---------------------------------------------------------------------
        # Follow-up Details
        #
        evaluation = {
            "B": T("better"),
            "S": T("same"),
            "W": T("worse"),
        }

        twoweeks = current.request.utcnow + datetime.timedelta(days=14)

        tablename = "po_household_followup"
        define_table(
            tablename, household_id(),
            Field(
                "followup_required",
                label=T("Follow-up required"),
            ),
            s3_date(
                "followup_date",
                label=T("Date for Follow-up"),
                default=twoweeks,
                past=0,
            ), Field(
                "followup",
                "text",
                label=T("Follow-up made"),
            ),
            Field(
                "completed",
                "boolean",
                default=False,
                label="Follow-up completed",
                represent=s3_yes_no_represent,
            ),
            Field(
                "evaluation",
                label=T("Evaluation"),
                represent=s3_options_represent(evaluation),
                requires=IS_EMPTY_OR(IS_IN_SET(evaluation)),
            ), s3_comments(), *s3_meta_fields())

        # CRUD Strings
        crud_strings[tablename] = Storage(
            title_update=T("Edit Follow-up Details"), )

        configure(
            tablename,
            deduplicate=S3Duplicate(primary=("household_id", )),
            deletable=False,
        )

        # ---------------------------------------------------------------------
        # Pass names back to global scope (s3.*)
        #
        return {
            "po_household_id": household_id,
        }
예제 #18
0
    def customise_project_project_resource(r, tablename):

        s3db = current.s3db

        table = s3db.project_project

        # Make project description mandatory
        field = table.description
        from gluon import IS_NOT_EMPTY
        field.requires = IS_NOT_EMPTY(
            error_message=T("Enter a project description"), )

        if r.interactive:

            # Custom filter widgets
            LEAD_ROLE = settings.get_project_organisation_lead_role()
            org_label = settings.get_project_organisation_roles()[LEAD_ROLE]
            from s3 import S3DateFilter, \
                           S3LocationFilter, \
                           S3OptionsFilter, \
                           S3TextFilter
            filter_widgets = [
                S3TextFilter(
                    [
                        "name",
                        "description",
                    ],
                    label=T("Search"),
                    comment=T("Search for a Project by name or description."),
                ),
                S3LocationFilter("location.location_id", ),
                S3OptionsFilter(
                    "sector_project.sector_id",
                    label=T("Sector"),
                    location_filter=True,
                    none=True,
                ),
                S3OptionsFilter(
                    "hazard_project.hazard_id",
                    label=T("Hazard"),
                    help_field=s3db.project_hazard_help_fields,
                    cols=4,
                    hidden=True,
                ),
                S3OptionsFilter(
                    "status_id",
                    label=T("Status"),
                    cols=4,
                    hidden=True,
                ),
                S3DateFilter(
                    "start_date",
                    hidden=True,
                ),
                S3DateFilter(
                    "end_date",
                    hidden=True,
                ),
                S3OptionsFilter(
                    "organisation_id",
                    label=org_label,
                    hidden=True,
                ),
            ]

            # Custom CRUD form
            from s3 import S3SQLCustomForm, \
                           S3SQLInlineComponent, \
                           S3SQLInlineLink
            crud_form = S3SQLCustomForm(
                "organisation_id",
                "name",
                "description",
                "status_id",
                "start_date",
                "end_date",
                "budget",
                "currency",
                S3SQLInlineLink(
                    "hazard",
                    label=T("Hazards"),
                    field="hazard_id",
                    help_field=s3db.project_hazard_help_fields,
                    cols=4,
                    translate=True,
                ),
                S3SQLInlineLink(
                    "sector",
                    label=T("Sectors"),
                    field="sector_id",
                    cols=4,
                    translate=True,
                ),
                "objectives",
                "human_resource_id",
                S3SQLInlineComponent(
                    "document",
                    fields=[
                        (T("Title"), "name"),
                        "file",
                    ],
                    filterby={
                        "field": "file",
                        "options": "",
                        "invert": True,
                    },
                    label=T("Files"),
                    name="file",
                ),
                S3SQLInlineComponent(
                    "document",
                    fields=[
                        (T("Title"), "name"),
                        "url",
                    ],
                    filterby={
                        "field": "url",
                        "options": None,
                        "invert": True,
                    },
                    label=T("Links"),
                    name="url",
                ),
                "comments",
            )

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

        # Custom list fields
        list_fields = [
            "name",
            "location.location_id",
            "organisation_id",
            (T("Sectors"), "sector_project.sector_id"),
            (T("Hazards"), "hazard_project.hazard_id"),
            "status_id",
            "start_date",
            "end_date",
        ]

        s3db.configure(
            "project_project",
            list_fields=list_fields,
        )
예제 #19
0
    Field('item_type', 'string', length='100', default='text'),
    Field(
        'unique_id', 'string', length=64, default=uuid.uuid4(),
        writable=False, readable=False
    ),
)
db.item._before_insert.append(_get_slugline)
db.item._before_update.append(_update_slugline)
db.item.id.readable = False
db.item.id.writable = False
db.item.item_type.readable = False
db.item.item_type.writable = False
db.item.copyright_url.label = T('Copyright URL')
db.item.pubstatus.requires = IS_IN_SET(PUB_STATUS, zero=None)
db.item.pubstatus.label = T('Status')
db.item.headline.requires = IS_NOT_EMPTY()
db.item.headline.label = T('Headline')
db.item.headline.comment = T('Headline or descriptive title')
db.item.headline.requires = IS_NOT_EMPTY()
db.item.language_tag.label = T('Language')
db.item.keywords.label = T("Keywords")
db.item.keywords.requires = IS_NOT_EMPTY()
db.item.keywords.comment = T("One keyword per line")
db.item.section_page.label = T("Section")
db.item.section_page.comment = T(
    "Section or page in with this item is intended to be used")
db.item.located.label = T("Located")
db.item.located.comment = T(
    """
    It can be the name of a city or may contain details, for example: HAVANA,
    CUBA""")