Beispiel #1
0
    def init_requires(field, o, d):
        """
            Initialize all IS_NOT_IN_DB to allow override of
            both original and duplicate value

            @param field: the Field
            @param o: the original value
            @param d: the duplicate value
        """

        allowed_override = [str(o), str(d)]

        requires = field.requires
        if field.unique and not requires:
            field.requires = IS_NOT_IN_DB(current.db,
                                          str(field),
                                          allowed_override=allowed_override)
        else:
            if not isinstance(requires, (list, tuple)):
                requires = [requires]
            for r in requires:
                if hasattr(r, "allowed_override"):
                    r.allowed_override = allowed_override
                if hasattr(r, "other") and \
                   hasattr(r.other, "allowed_override"):
                    r.other.allowed_override = allowed_override
        return
Beispiel #2
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()
Beispiel #3
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()
    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()
Beispiel #5
0
    def invite(self, r, **attr):
        """
            Prepare and process invitation form

            @param r: the S3Request instance
            @param attr: controller attributes
        """

        T = current.T

        db = current.db
        s3db = current.s3db

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

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

        output = {
            "title": T("Invite Organisation"),
        }

        # Get all accounts that are linked to this org
        utable = auth_settings.table_user
        oltable = s3db.org_organisation_user
        pltable = s3db.pr_person_user

        organisation_id = r.record.id
        join = oltable.on((oltable.user_id == utable.id) & \
                          (oltable.deleted == False))
        left = pltable.on((pltable.user_id == utable.id) & \
                          (pltable.deleted == False))
        query = (oltable.organisation_id == organisation_id)
        rows = db(query).select(
            utable.id,
            utable.first_name,
            utable.last_name,
            utable.email,
            utable.registration_key,
            pltable.pe_id,
            join=join,
            left=left,
        )

        active, disabled, invited = [], [], []
        for row in rows:
            user = row[utable]
            person_link = row.pr_person_user
            if person_link.pe_id:
                if user.registration_key:
                    disabled.append(user)
                else:
                    active.append(user)
            else:
                invited.append(user)

        if active or disabled:
            response.error = T(
                "There are already user accounts registered for this organization"
            )

            from gluon import UL, LI, H4, DIV
            from s3 import s3_format_fullname

            fullname = lambda user: s3_format_fullname(
                fname=user.first_name,
                lname=user.last_name,
                truncate=False,
            )
            account_list = DIV(_class="org-account-list")
            if active:
                account_list.append(H4(T("Active Accounts")))
                accounts = UL()
                for user in active:
                    accounts.append(
                        LI("%s <%s>" % (fullname(user), user.email)))
                account_list.append(accounts)
            if disabled:
                account_list.append(H4(T("Disabled Accounts")))
                accounts = UL()
                for user in disabled:
                    accounts.append(
                        LI("%s <%s>" % (fullname(user), user.email)))
                account_list.append(accounts)

            output["item"] = account_list
            response.view = self._view(r, "display.html")
            return output

        account = invited[0] if invited else None

        # Look up existing invite-account
        email = None
        if account:
            email = account.email
        else:
            ctable = s3db.pr_contact
            query = (ctable.pe_id == r.record.pe_id) & \
                    (ctable.contact_method == "EMAIL") & \
                    (ctable.deleted == False)
            contact = db(query).select(
                ctable.value,
                orderby=ctable.priority,
                limitby=(0, 1),
            ).first()
            if contact:
                email = contact.value

        # Form Fields
        dbset = db(utable.id != account.id) if account else db
        formfields = [
            Field("email",
                  default=email,
                  requires=[
                      IS_EMAIL(error_message=auth_messages.invalid_email),
                      IS_LOWER(),
                      IS_NOT_IN_DB(
                          dbset,
                          "%s.email" % utable._tablename,
                          error_message=auth_messages.duplicate_email,
                      ),
                  ]),
        ]

        # Generate labels (and mark required fields in the process)
        labels, has_required = s3_mark_required(formfields, )
        response.s3.has_required = has_required

        # Form buttons
        SEND_INVITATION = T("Send New Invitation") if account else T(
            "Send Invitation")
        buttons = [
            INPUT(
                _type="submit",
                _value=SEND_INVITATION,
            ),
            # TODO cancel-button?
        ]

        # Construct the form
        response.form_label_separator = ""
        form = SQLFORM.factory(
            table_name="invite",
            record=None,
            hidden={"_next": request.vars._next},
            labels=labels,
            separator="",
            showid=False,
            submit_button=SEND_INVITATION,
            #delete_label = auth_messages.delete_label,
            formstyle=settings.get_ui_formstyle(),
            buttons=buttons,
            *formfields)

        # Identify form for CSS & JS Validation
        form.add_class("send_invitation")

        if form.accepts(
                request.vars,
                session,
                formname="invite",
                #onvalidation = auth_settings.register_onvalidation,
        ):

            error = self.invite_account(r.record,
                                        form.vars.email,
                                        account=account)
            if error:
                response.error = T(
                    "Could not send invitation (%(reason)s)") % {
                        "reason": error
                    }
            else:
                response.confirmation = T("Invitation sent")
        else:
            if account:
                response.warning = T(
                    "This organisation has been invited before!")

        output["form"] = form

        response.view = self._view(r, "update.html")

        return output