Exemplo n.º 1
0
 def get_list_row_actions(self):
     actions = super().get_list_row_actions()
     if self.can_edit:
         actions = [a for a in actions if not isinstance(a, EditRowAction)]
         actions.insert(
             0,
             LinkRowAction(
                 "fa fa-pencil",
                 url=self._get_edit_view_endpoint,
                 title=lazy_gettext("Edit record"),
             ),
         )
     if self.can_delete:
         actions = [a for a in actions if not isinstance(a, OyDeleteRowAction)]
         actions.insert(
             0,
             LinkRowAction(
                 "fa fa-trash",
                 url=self._get_delete_endpoint,
                 title=lazy_gettext("Delete record"),
             ),
         )
     actions.extend(
         [
             TemplateLinkRowAction(
                 template_name="oy.add_child_row_action",
                 title=lazy_gettext("Add child"),
             ),
             TemplateLinkRowAction(
                 template_name="oy.children_row_action",
                 title=gettext("Show children"),
             ),
         ]
     )
     return actions
Exemplo n.º 2
0
class AdminServerView(AdminContractView):
    column_default_sort = ('id', True)
    form_ajax_refs = {
        'ips':
        ServerIPQueryAjaxModelLoader('ips',
                                     db.session,
                                     model.IP,
                                     fields=['ip_address'],
                                     page_size=10)
    }

    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-user', 'u?id={row_id}')
    ]

    @expose('/u', methods=('GET', ))
    def user_redirect_view(self):
        id = get_mdict_item_or_list(request.args, 'id')
        if id:
            server = self.get_one(id)
            if server:
                return redirect(
                    url_for('admin/users.edit_view',
                            id=server.admin_c.id,
                            url=self.get_url('.index_view')))
            else:
                flash(gettext('Does not exist.'), 'error')
                return redirect(return_url)
Exemplo n.º 3
0
 def __new__(cls, name, bases, d):
     if 'DisplayableAdmin' not in [c.__name__ for c in bases]:
         return type.__new__(cls, name, bases, d)
     for key, value in DISPLAYABEL_DEFAULTS.items():
         if key not in d:
             d[key] = value
         else:
             if type(value) is dict:
                 d[key].update(value)
             elif type(value) in (list, tuple):
                 opt = list()
                 opt.extend(value)
                 if key in ['form_rules', 'form_columns', 'column_list']:
                     # Attention: order is important, so a tuple in the
                     # form (order, field) should be provided for each entry.
                     for order, field in d[key]:
                         opt.insert(order, field)
                 else:
                     opt.extend(d[key])
                 d[key] = opt
     row_actions = list(default_row_actions)
     crowactions = d.get('column_extra_row_actions', [])
     if 'get_preview_url' in d:
         crowactions.append(
             LinkRowAction(icon_class='fa fa-eye',
                           url=lambda v, i, r: d['get_preview_url'](r),
                           title=lazy_gettext('Preview in site')))
     crowactions.extend(row_actions)
     d['column_extra_row_actions'] = crowactions
     return type.__new__(cls, name, bases, d)
Exemplo n.º 4
0
    class ItemView(ModelView):
        column_display_pk = True
        form_columns = [
            'manufacturer', 'product', 'serial', 'location', 'user',
            'responsible', 'notes', 'project'
        ]
        can_view_details = True
        details_template = 'details.html'
        column_searchable_list = ('manufacturer', 'product', 'serial')
        #column_filters = ('project',)
        column_extra_row_actions = [
            LinkRowAction('glyphicon glyphicon-tag', '/label?ids={row_id}')
        ]

        def on_model_change(self, form, model, is_created):
            if not is_created:
                changed_cols = [col for col in self.form_columns \
                       if getattr(form, col).data != getattr(form, col).object_data]
                for col in changed_cols:
                    c = Change()
                    c.user = '******'
                    c.field = col
                    c.item_id = model.id
                    c.new_value = str(getattr(form, col).data)
                    c.datetime = datetime.now().replace(microsecond=0)
                    db.session.add(c)
                    db.session.commit()

        @action('get labels', 'get Labels', None)
        def get_labels(self, ids):
            return redirect('/label?ids=' + ','.join(ids))
class Classe_admin_controller(ModelView):
    column_filters = (Classe_catalogage.Date_inventaire, Classe_utilisateurs.nom, Classe_catalogage.Rue, Classe_catalogage.Nom_site)
    column_searchable_list = (Classe_catalogage.Date_inventaire, Classe_utilisateurs.nom, Classe_catalogage.Rue, Classe_catalogage.Nom_site)
    column_extra_row_actions=[
        LinkRowAction(
            icon_class='fa fa-repeat glyphicon icon-repeat',
            url='duplicate?id={row_id}',
            title="Duplicate Row"
        ),
    ]

    list_template = 'admin_templates/list.html'
    create_template = 'admin_templates/create.html'
    edit_template = 'admin_templates/edit.html'

    # classe de contrôle de l'authentification de l'utilisateur pour avoir accès au panneau d'administration
    def is_accessible(self):
        """
        Contrôle de l'authentification de l'utilisateur pour lui donner accès au panneau d'administration
        :return: True ou erreur 404
        """
        if current_user.is_admin == True:
            return current_user.is_authenticated
        else:
            return abort(404)
    def not_auth(self):
        """
        Interdiction d'accès au panneau d'administration
        :return: template
        """
        flash("Vous n'êtes pas autorisé à accéder à cette page.")
        return redirect(url_for('accueil'))

    @expose('/duplicate/')
    def duplicate_record(self):
        """Make a duplicate of the current record"""
        
        view_args = self._get_list_extra_args()

        return_url = get_redirect_target() or self.get_url('.index_view')

        if not self.can_create:
            return redirect(return_url)

        id_ = get_mdict_item_or_list(request.args, 'id')
        if id_ is None:
            flash(gettext("Impossible de trouver le numéro d'inventaire demandé"), 'error')
            return redirect(return_url)

        old_model = self.get_one(id_)
        if old_model is None:
            flash(gettext('Aucun enregistrement existant'), 'error')
            return redirect(return_url)

        Msg, n_inv = Actions.duplicate(old_model)
        flash(gettext(Msg), 'success')

        return redirect(return_url)
Exemplo n.º 6
0
class BlueprintTaskModelView(ModelView):
    current_server = NormalConfig().get_current_ip()
    column_display_pk = True
    create_modal = True
    edit_modal = True
    form_excluded_columns = ['operator']
    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-play',
                      current_server + 'task/divide_task/{row_id}'),
        # EndpointLinkRowAction('glyphicon glyphicon-film', 'apimodules.index_view')
    ]
Exemplo n.º 7
0
 def get_list_row_actions(self):
     actions = super().get_list_row_actions()
     if self.can_delete:
         actions = [a for a in actions if not isinstance(a, DeleteRowAction)]
         actions.append(OyDeleteRowAction())
     if hasattr(self, "get_preview_url"):
         actions.append(
             LinkRowAction(
                 icon_class="fa fa-eye",
                 url=lambda v, i, r: self.get_preview_url(r),
                 title=lazy_gettext("Preview in site"),
             )
         )
     return actions
Exemplo n.º 8
0
class runCaseModelView(ModelView):
    """Custom runCaseModelView"""
    current_server = NormalConfig().get_current_ip()
    column_display_pk = True
    create_modal = True
    edit_modal = True
    form_excluded_columns = ['create_time', 'op_time']
    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-play',
                      current_server + 'main/compare_run/{row_id}'),
        # EndpointLinkRowAction('glyphicon glyphicon-film', 'apimodules.index_view')
    ]
    column_list = ('id', 'name', 'case_id', 'old_', 'new_', 'replace',
                   'paramter_list', 'remark', 'op_time')
    column_default_sort = 'id'
Exemplo n.º 9
0
class TestBedView(MyObjectView):
    column_list = [
        'name',
        'owner',
        'rigs',
    ]
    form_excluded_columns = ['connect_chart', ]

    column_extra_row_actions = [
        LinkRowAction('icon-eye-open', './{row_id}'),
        EndpointLinkRowAction('', 'testbed.index_view')
    ]

    @expose('/<testbed_id>')
    def show_chart(self, testbed_id):
        tb = Testbed.query.filter_by(id=testbed_id).first()
        rigs = tb.rigs
        rig_names = [rig.name for rig in rigs]
        hosts = tb.hosts
        host_names = [host.name for host in hosts]
        rig_names.extend(host_names)
        if tb.connect_chart is None:
            relation_sample = []
        else:
            relation_sample = json.loads(tb.connect_chart)
        rig_connects = RigConnection.query.all()
        rig_connect_names = [rig_connect.name for rig_connect in rig_connects]
        host_usages = HostUsage.query.all()
        host_usage_names = [host_usage.name for host_usage in host_usages]
        rig_connect_names.extend(host_usage_names)
        return self.render('testbed2.html', rig_names=rig_names, tb_name=tb.name,
                           rig_connect_names=rig_connect_names,
                           relation=relation_sample)

    @expose('/save/<tb_name>', methods=['GET', 'POST'])
    def save(self, tb_name):
        print(tb_name)
        content = request.form.get('content')
        print(content)
        # print(Testbed.query.filter_by(name=tb_name).first())
        tb = Testbed.query.filter_by(name=tb_name).first()
        tb.connect_chart = content
        tb.save()
        return 'saved'
Exemplo n.º 10
0
class UserModelView(ModelView):
    column_list = ('id', 'name', 'username')
    column_default_sort = 'id'

    can_view_details = True
    can_delete = False

    # 给 flask-admin 每个 row 添加额外的 action
    column_extra_row_actions = [
        EnvelopeEndpointLinkRowAction('glyphicon glyphicon-envelope',
                                      '.envelope'),
        # EndpointLinkRowAction('glyphicon glyphicon-envelope', '.envelope'),
        LinkRowAction('glyphicon glyphicon-off', ''),
    ]

    @expose('/user/envelope')
    def envelope(self):
        # TODO:
        row_id = request.args.get('id')
        user = User.query.get(row_id)
        flash(f'envelope to {user.name}')
        return redirect(url_for('.index_view'))
Exemplo n.º 11
0
class RigView(MyObjectView):
    inline_models = [(RigInfo, inline_form_options), ]
    column_exclude_list = ['io_interfaces', 'iscsi_interfaces', 'replication_async_interfaces',
                           'replication_sync_interfaces', 'state', 'status']
    column_editable_list = ['model', 'owner', 'device']
    inline_models = [(RigInfo, inline_form_options), ]
    column_extra_row_actions = [
        LinkRowAction('icon-eye-open', './{row_id}'),
        EndpointLinkRowAction('', 'rig.index_view')
    ]

    @expose('/<rig_id>')
    def show_chart(self, rig_id):
        rig = Rig.query.filter_by(id=rig_id).first()
        tbs = Testbed.query.all()
        rig_map_tb = []
        for item in tbs:
            print(f'tb_name :{item.name}')
            rigs = item.rigs
            for checked_rig in rigs:
                if rig.name == checked_rig.name:
                    rig_map_tb.append([rig.name, item.name, 'Used'])
        return self.render('rig.html', relation=rig_map_tb)
Exemplo n.º 12
0
class PowerOuletUserView(UserView, PowerOuletView):
    form_base_class = SecureForm
    can_delete = False
    can_create = False
    can_edit = False
    can_view_details = False

    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-eye-open', 'view/?id={row_id}')
    ]

    column_list = ('server', 'outlet')
    column_sortable_list = ()

    def create_view(self):
        pass

    def delete_view(self):
        pass

    def ajax_update(self):
        pass

    def get_query(self):
        return super(UserView, self).get_query().join(model.Server).filter(
            model.Server.admin_c_id == current_user.id,
            model.Server.active == True, self.model.active == True)

    def get_count_query(self):
        return self.session.query(func.count('*')).select_from(
            self.model).join(model.Server).filter(
                model.Server.admin_c_id == current_user.id,
                model.Server.active == True, self.model.active == True)

    def edit_view(self):
        pass
Exemplo n.º 13
0
 def column_extra_row_actions(self):
     if current_user and 'billing' in current_user.roles:
         return [
             LinkRowAction('glyphicon glyphicon-credit-card',
                           'payments/?id={row_id}')
         ]
Exemplo n.º 14
0
class AdminInvoiceView(ACLView):
    inline_models = (model.InvoiceItem, )
    column_default_sort = ('id', True)

    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-print', 'generate/?id={row_id}')
    ]

    @expose('/generate/', methods=('POST', 'GET'))
    def generate_view(self):
        """
            Invoice download view
        """
        return_url = get_redirect_target() or self.get_url('.index_view')

        if not self.can_view_details:
            return redirect(return_url)

        id = get_mdict_item_or_list(request.args, 'id')

        if id:
            invoice = self.get_one(id)

            if invoice is None:
                flash(gettext('Invoice does not exist.'), 'error')
                return redirect(return_url)

            if len(invoice.items) == 0:
                flash(
                    gettext(
                        'Invoice has no Items, will not create empty invoice.'
                    ), 'error')
                return redirect(return_url)

            if not invoice.sent and not invoice.exported:
                # (re-)generate invoice if it was not sent and not exported
                from ff_housing.controller.accounting import generate_invoice
                generate_invoice(invoice)

            if invoice.path and isfile(invoice.path):
                res = send_file(invoice.path)
                res.headers[
                    'Content-Disposition'] = 'inline;filename*=%s.pdf' % invoice.number
                res.headers[
                    "Cache-Control"] = "no-cache, no-store, must-revalidate"
                res.headers["Pragma"] = "no-cache"
                res.headers["Expires"] = "0"
                return res
            else:
                flash(gettext('File does not exist.'), 'error')

        return redirect(return_url)

    @expose('/edit/', methods=('GET', 'POST'))
    def edit_view(self):
        """
            restrict edit on invoices, that have not been sent.
        """
        return_url = get_redirect_target() or self.get_url('.index_view')

        if not self.can_edit:
            return redirect(return_url)

        id = get_mdict_item_or_list(request.args, 'id')
        if id is None:
            return redirect(return_url)

        invoice = self.get_one(id)

        if invoice is None:
            flash(gettext('Record does not exist.'), 'error')
            return redirect(return_url)

        if invoice.sent:
            flash(
                gettext('Invoice has already been sent and cannot be edited.'),
                'error')
            return redirect(return_url)

        return super(AdminInvoiceView, self).edit_view()

    @action(
        'cancel', 'Cancel Invoice',
        ' If Invoice has already been sent, a cancelation invoice will be created. Are you sure you want to cancel this invoice?'
    )
    def cancel_invoice(self, ids):
        from ff_housing.controller.accounting import cancel_invoice
        if len(ids) > 1:
            raise Exception(
                'Only a single invoice can be cancelled at a time.')
        try:
            invoice = self.get_one(ids[0])

            if not invoice:
                raise Exception('Invoice not found.')
            if invoice.cancelled:
                raise Exception('Invoice has already been cancelled.')
            cancel_invoice(invoice)
        except Exception as ex:
            flash(str(ex), 'error')

    @action(
        'send', 'Send Invoices',
        'Send selected invoices? (max 25) Already sent invoices will not be sent again.'
    )
    def send_invoices(self, ids):
        from ff_housing.controller.accounting import send_invoice
        if len(ids) > 25:
            raise Exception('A maximum of 25 invoices can be sent at a time..')
        try:
            invoices = self.model.query.filter(self.model.id.in_(ids))
            for invoice in invoices:
                send_invoice(invoice)
                flash('Invoices sent.', 'info')

        except Exception as ex:
            flash(str(ex), 'error')
Exemplo n.º 15
0
class BaseModelView(sqla.ModelView):
    column_extra_row_actions = [
        LinkRowAction(
            icon_class='fa fa-copy glyphicon glyphicon-duplicate',
            # Calls the .../duplicate?id={row_id} view
            # with the row_id from the Jinja template
            url='duplicate?id={row_id}',
            title="Duplicate Row"),
    ]

    column_hide_backrefs = False
    can_view_details = True
    edit_modal = True
    create_modal = True
    details_modal = True

    @expose('/duplicate/', methods=('GET', 'POST'))
    def duplicate_view(self):
        """
            Duplicate model view
        """
        return_url = get_redirect_target() or self.get_url('.index_view')

        id = get_mdict_item_or_list(request.args, 'id')
        if id is None:
            return redirect(return_url)

        model = self.get_one(id)

        if model is None:
            flash(gettext('Record does not exist.'), 'error')
            return redirect(return_url)

        form = self.edit_form(obj=model)
        if not hasattr(form,
                       '_validated_ruleset') or not form._validated_ruleset:
            self._validate_form_instance(ruleset=self._form_create_rules,
                                         form=form)

        if self.validate_form(form):
            # in versions 1.1.0 and before, this returns a boolean
            # in later versions, this is the model itself
            model = self.create_model(form)

            if model:
                flash(gettext('Record was successfully created.'), 'success')
                if '_add_another' in request.form:
                    return redirect(request.url)
                elif '_continue_editing' in request.form:
                    # if we have a valid model, try to go to the edit view
                    if model is not True:
                        url = self.get_url('.edit_view',
                                           id=self.get_pk_value(model),
                                           url=return_url)
                    else:
                        url = return_url
                    return redirect(url)
                else:
                    # save button
                    return redirect(
                        self.get_save_return_url(model, is_created=True))

        if request.method == 'GET' or form.errors:
            self.on_form_prefill(form, id)

        form_opts = FormOpts(widget_args=self.form_widget_args,
                             form_rules=self._form_edit_rules)

        if self.edit_modal and request.args.get('modal'):
            template = self.edit_modal_template
        else:
            template = self.edit_template

        return self.render(template,
                           model=model,
                           form=form,
                           form_opts=form_opts,
                           return_url=return_url)

    def is_accessible(self):
        return (current_user.is_active and current_user.is_authenticated
                and current_user.has_role('admin'))

    def _handle_view(self, name, **kwargs):
        """
        Override builtin _handle_view in order to redirect users when a view is not accessible.
        """
        if not self.is_accessible():
            if current_user.is_authenticated:
                # permission denied
                abort(403)
            else:
                return redirect(url_for('security.login', next=request.url))
Exemplo n.º 16
0
class PowerOuletAdminView(ACLView, PowerOuletView):
    page_size = 200

    column_extra_row_actions = [
        LinkRowAction('glyphicon glyphicon-eye-open', 'view/?id={row_id}')
    ]