Example #1
0
    def _execute_action(self, action):
        tokens = action.split(_(u' in '))
        action_name = tokens[0].strip()
        verbose_name = tokens[1].strip()
        model = find_model_by_verbose_name(verbose_name)
        action_dict = find_action(model, action_name)
        func = action_dict['function']

        func_signature = u'%s_em_%s(self)' % (func.__name__.lower(),
                                              model.__name__.lower())
        self._test_flow_code.append(u'\t\t\t# %s' % action)
        self._test_flow_code.append(
            u'\t\t\tself.%s_em_%s()' %
            (func.__name__.lower(), model.__name__.lower()))

        self._test_function_code.append(u'\tdef %s:' % func_signature)
        self._view(model, True)
        if hasattr(func, '_action'):
            button_label = func._action['title']
            params = func.func_code.co_varnames[1:func.func_code.co_argcount]
            if params:
                interaction = _(u'The user clicks the button')
                self._interactions.append(u'%s "%s"' %
                                          (interaction, button_label))
                self._interactions.append(
                    _(u'The system displays a popup window'))

                self._test_function_code.append(
                    u"\t\tself.click_button(u'%s')" % button_label)
                self._test_function_code.append(
                    u"\t\tself.look_at_popup_window()")
                form = factory.get_action_form(self._mocked_request(), model(),
                                               func._action)
                self._fill_out(form)

            interaction = _(u'The user clicks the button')
            self._interactions.append(u'%s "%s"' % (interaction, button_label))
            self._test_function_code.append(u"\t\tself.click_button(u'%s')" %
                                            button_label)
            self._test_function_code.append(u"\t\tself.click_icon(u'%s')" %
                                            u'Principal')

            description = func.__doc__ and func.__doc__.decode(
                'utf-8').strip() or ''
            business_rules = utils.extract_exception_messages(func)
            post_condition = _(u'Action successfully performed')
            self.name = action_dict['title']
            self.description = description
            self.business_rules = business_rules
            self.post_condition = post_condition
            for can_execute in action_dict['can_execute']:
                self.actors.append(can_execute)
            if not self.actors:
                self.actors.append(_(u'Superuser'))
Example #2
0
def action(request, app, cls, action_name, pk=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')

    for group in loader.actions[_model]:
        if action_name in loader.actions[_model][group]:
            break

    form_action = loader.actions[_model][group][action_name]
    action_title = form_action['title']
    action_can_execute = form_action['can_execute']
    action_condition = form_action['condition']
    action_function = form_action['function']
    action_message = 'message' in form_action and form_action['message'] or None
    action_permission = '{}.{}'.format(_model._meta.app_label,
                                       action_function.__name__)
    action_input = form_action['input']
    redirect_to = form_action['redirect_to']

    obj = pk and _model.objects.all(request.user).get(pk=pk) or _model()
    obj.request = request
    obj._user = request.user
    title = action_title

    if check_condition(action_condition,
                       obj) and (not action_can_execute
                                 or permissions.check_group_or_permission(
                                     request, action_permission)):

        func = getattr(_model, action_function.__name__, action_function)
        form = factory.get_action_form(request, obj, form_action)

        if func.__code__.co_argcount > 1 or action_input:
            if form.is_valid():
                if 'instance' in form.fields:
                    obj = form.cleaned_data['instance']
                func = getattr(obj, action_function.__name__, action_function)
                params = []
                for param in func.__code__.co_varnames[1:func.__code__.
                                                       co_argcount]:
                    if param in form.cleaned_data:
                        params.append(form.cleaned_data[param])
                try:
                    f_return = func(*params)
                    if not redirect_to:
                        if func.__code__.co_argcount > 1:
                            return httprr(request, '..', action_message)
                        else:
                            return httprr(request, '.', action_message)
                    else:
                        return httprr(
                            request,
                            Template(redirect_to).render(Context({'self':
                                                                  obj})),
                            action_message)
                except ValidationError as e:
                    form.add_error(None, str(e.message))
        else:
            try:
                if form.fields and form.is_valid() or not form.fields:
                    if form.fields:
                        obj = form.cleaned_data['instance']
                    func = getattr(obj, action_function.__name__,
                                   action_function)
                    f_return = func()
                    if not redirect_to:
                        if func.__code__.co_argcount > 1:
                            return httprr(request, '..', action_message)
                        else:
                            return httprr(request, '.', action_message)
                    else:
                        return httprr(
                            request,
                            Template(redirect_to).render(Context({'self':
                                                                  obj})),
                            action_message)
            except ValidationError as e:
                return httprr(request, '.', str(e.message))

        if form.title == DEFAULT_FORM_TITLE:
            form.title = action_title
        if form.submit_label == DEFAULT_SUBMIT_LABEL:
            form.submit_label = action_title
        return render(request, 'default.html', locals())
    else:
        return HttpResponseForbidden()
Example #3
0
    def _execute_action(self, action):
        tokens = action.split(_(' in '))
        action_name = tokens[0].strip()
        verbose_name = tokens[1].strip()
        model = find_model_by_verbose_name(verbose_name)
        action_dict = find_action(model, action_name)
        func = action_dict['function']
        username_attr = ''
        if CACHE['LAST_AUTHENTICATED_USERNAME']:
            username_attr = ", '{}'".format(
                CACHE['LAST_AUTHENTICATED_USERNAME'])
        func_decorator = '@testcase(\'{}\'{})'.format(self.name, username_attr)
        self._func_signature = '{}_em_{}(self)'.format(func.__name__.lower(),
                                                       model.__name__.lower())

        self._test_function_code.append('    {}'.format(func_decorator))
        self._test_function_code.append('    def {}:'.format(
            self._func_signature))
        self._view(model, True)
        if hasattr(func, '_action'):
            button_label = func._action['verbose_name']
            params = get_parameters_names(func)
            if params:
                interaction = _('The user clicks the button')
                self._interactions.append('{} "{}"'.format(
                    interaction, button_label))
                self._interactions.append(
                    _('The system displays a popup window'))

                self._test_function_code.append(
                    "        self.click_button('{}')".format(button_label))
                self._test_function_code.append(
                    "        self.look_at_popup_window()")
                obj = model()
                obj.pk = 0
                form = factory.get_action_form(self._mocked_request(), obj,
                                               func._action)
                self._fill_out(form)

            interaction = _('The user clicks the button')
            self._interactions.append('{} "{}"'.format(interaction,
                                                       button_label))
            self._test_function_code.append(
                "        self.click_button('{}')".format(button_label))
            self._test_function_code.append(
                "        self.click_icon('{}')".format('Principal'))

            description = func.__doc__ and func.__doc__.strip() or ''
            business_rules = utils.extract_exception_messages(func)
            post_condition = _('Action successfully performed')
            self.name = action_dict['verbose_name']
            self.description = description
            self.business_rules = business_rules
            self.post_condition = post_condition
            for can_execute in action_dict['can_execute']:
                self.actors.append(can_execute)
            if not self.actors:
                self.actors.append(_('Superuser'))
        elif hasattr(func, '_view_action'):
            button_label = func._view_action['verbose_name']
            interaction = _('The user clicks the button')
            self._interactions.append('{} "{}"'.format(interaction,
                                                       button_label))
            self._test_function_code.append(
                "        self.click_button('{}')".format(button_label))
Example #4
0
def action(request, app, cls, action_name, pk=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError as e:
        return page_not_found(request, e, 'error404.html')

    for group in loader.instance_actions[_model]:
        if action_name in loader.instance_actions[_model][group]:
            break

    form_action = loader.instance_actions[_model][group][action_name]
    action_verbose_name = form_action['verbose_name']
    action_can_execute = form_action['can_execute']
    action_condition = form_action['condition']
    action_function = form_action['function']
    action_message = 'message' in form_action and form_action['message'] or None
    action_permission = '{}.{}'.format(_model._meta.app_label,
                                       action_function.__name__)
    action_input = form_action['input']
    action_display = form_action['display']
    action_style = form_action['style']
    action_redirect = form_action['redirect_to']

    obj = pk and _model.objects.all(
        request.user).distinct().get(pk=pk) or _model()
    obj.request = request
    obj._user = request.user
    title = action_verbose_name
    redirect_to = None

    if check_condition(request.user, action_condition,
                       obj) and (not action_can_execute
                                 or permissions.check_group_or_permission(
                                     request, action_permission)):
        f_return = None
        func = getattr(_model, action_function.__name__, action_function)
        form = factory.get_action_form(request, obj, form_action)
        if count_parameters_names(func) > 1 or action_input:
            if form.is_valid():
                if 'instance' in form.fields:
                    obj = form.cleaned_data['instance']
                func = getattr(obj, action_function.__name__, action_function)
                params = []
                for param in get_parameters_names(func,
                                                  include_annotated=True):
                    if param in form.cleaned_data:
                        params.append(form.cleaned_data[param])
                    else:
                        params.append(
                            get_role_value_for_action(func, request.user,
                                                      param))
                try:
                    f_return = func(*params)
                    if not action_redirect:
                        if count_parameters_names(func) > 0 or action_display:
                            redirect_to = '..'
                        else:
                            redirect_to = '.'
                    else:
                        redirect_to = Template(action_redirect).render(
                            Context({'self': obj}))
                except ValidationError as e:
                    form.add_error(None, str(e.message))
        else:
            try:
                if form.fields and form.is_valid() or not form.fields:
                    if 'instance' in form.fields:
                        obj = form.cleaned_data['instance']
                    func = getattr(obj, action_function.__name__,
                                   action_function)
                    params = []
                    for param in get_parameters_names(func,
                                                      include_annotated=True):
                        params.append(
                            get_role_value_for_action(func, request.user,
                                                      param))
                    f_return = func(*params)
                    if not action_redirect:
                        if count_parameters_names(func) > 0 or action_display:
                            redirect_to = '..'
                        else:
                            redirect_to = '.'
                    else:
                        redirect_to = Template(action_redirect).render(
                            Context({'self': obj}))
            except ValidationError as e:
                if form.fields:
                    form.add_error(None, str(e.message))
                return httprr(request, '.', e.message, error=True)

        if f_return:
            template_name = '{}.html'.format(action_function.__name__)
            return return_response(f_return, request, title, action_style,
                                   template_name)

        elif redirect_to:
            return httprr(request, redirect_to, action_message)

        if form.title == _('Form'):
            form.title = action_verbose_name
        if form.submit_label == _('Send'):
            form.submit_label = action_verbose_name
        return render(request, 'default.html', locals())
    else:
        return HttpResponseForbidden()
Example #5
0
def api(request, app_label, model_name, arg1=None, arg2=None):
    from djangoplus.admin.models import User

    obj = None
    form = None
    result = None
    errors = None
    func_name = None
    message = None
    args = {}

    http_authorization = request.META.get('HTTP_AUTHORIZATION')
    if http_authorization and 'Token' in http_authorization:
            page= int(request.GET.get('page', '') or 0)
            token = http_authorization[5:].strip()
            user = User.objects.get(token=token)
            request.user = user
            if app_label and model_name:
                model = apps.get_model(app_label, model_name)
                if model == User and str(user.pk) == arg1:
                    data = dict(name=user.name, username=user.username, photo=user.photo.url, email=user.email)
                    return HttpResponse(
                        json_serialize(result, request.GET, errors=[], message=_('Action successfully performed.'), exception=None, result=data)
                    )
                # model @action or @meta | manager @subset [@action or @meta]
                elif arg1 and arg2:
                    # model
                    if arg1.isdigit():
                        obj = model.objects.all(user).get(pk=arg1)
                        if arg2:
                            # @action
                            group = None
                            for group in CACHE['INSTANCE_ACTIONS'][model]:
                                if arg2 in CACHE['INSTANCE_ACTIONS'][model][group]:
                                    action_dict = CACHE['INSTANCE_ACTIONS'][model][group][arg2]
                                    message = action_dict.get('message')
                                    func_name = arg2
                                    break
                            if func_name:
                                func = getattr(obj, func_name)
                                form_action = CACHE['INSTANCE_ACTIONS'][model][group][arg2]
                                # with input
                                if count_parameters_names(func) > 0:
                                    form = factory.get_action_form(request, obj, form_action)
                            # it is not @action
                            else:
                                # @meta
                                for method in CACHE['INSTANCE_METHODS'].get(model, []):
                                    if method['function'] == arg2:
                                        func_name = arg2
                                        func = getattr(obj, func_name)
                                        break
                    # manager @subset
                    else:
                        obj = model.objects.all(user)
                        pks = request.GET.get('ids', [])
                        if pks:
                            obj = obj.filter(pk__in=pks)
                        group = None
                        # @action
                        for group in CACHE['QUERYSET_ACTIONS'][model]:
                            if arg2 in CACHE['QUERYSET_ACTIONS'][model][group]:
                                action_dict = CACHE['QUERYSET_ACTIONS'][model][group][arg2]
                                message = action_dict.get('message')
                                func_name = arg2
                                break
                        if func_name:
                            func = getattr(obj, func_name)
                            form_action = CACHE['QUERYSET_ACTIONS'][model][group][arg2]
                            # with input
                            if count_parameters_names(func) > 0:
                                form = factory.get_class_action_form(request, obj.model, form_action, func)
                        # it is not @action
                        else:
                            # @meta
                            for method in CACHE['MANAGER_METHODS'].get(model, []):
                                if method['function'] == arg1:
                                    func_name = arg2
                                    func = getattr(obj, func_name)
                                    break
                # model | manager @subset or @action or @meta
                elif arg1:
                    if arg1.isdigit():
                        # model
                        obj = model.objects.all(user).get(pk=arg1)
                        if request.method.lower() == 'get':
                            result = obj
                        elif request.method.lower() == 'delete':
                            result = None
                            obj.delete()
                            message = _('Deletion successfully performed.')
                        else:
                            form = factory.get_register_form(request, obj)
                    else:
                        # manager @subset or @action or @meta
                        obj = model.objects.all(user)
                        pks = request.GET.get('ids', [])
                        if pks:
                            obj = obj.filter(pk__in=pks)
                        group = None

                        # @action
                        func = None
                        action_dict = None
                        for group in CACHE['QUERYSET_ACTIONS'][model]:
                            if arg1 in CACHE['QUERYSET_ACTIONS'][model][group]:
                                action_dict = CACHE['QUERYSET_ACTIONS'][model][group][arg1]
                                message = action_dict.get('message')
                                func = getattr(obj, arg1)
                                func_name = arg1
                                break
                        if not func_name:
                            for group in CACHE['CLASS_ACTIONS'][model]:
                                if arg1 in CACHE['CLASS_ACTIONS'][model][group]:
                                    action_dict = CACHE['CLASS_ACTIONS'][model][group][arg1]
                                    message = action_dict.get('message')
                                    func = getattr(obj, arg1)
                                    func_name = arg1
                                    break
                        if func_name:
                            # with input
                            if count_parameters_names(func) > 0:
                                form = factory.get_class_action_form(request, obj.model, action_dict, func)
                        # it is not @action
                        else:
                            # @subset or @meta
                            for subset in CACHE['SUBSETS'][model]:
                                if arg1 == subset['name']:
                                    func_name = arg1
                                    break
                            if func_name:
                                func = getattr(obj, func_name)
                            # it is not @subset
                            else:
                                # @meta
                                for method in CACHE['MANAGER_METHODS'].get(model, []):
                                    if method['function'] == arg1:
                                        func_name = arg1
                                        func = getattr(obj, func_name)
                                        break
                # list or save
                else:
                    if request.method.lower() == 'get':
                        obj = model.objects.all(user)
                        func_name = 'all'
                    else:
                        form = factory.get_register_form(request, model())

            # list or action
            if func_name:
                if form:
                    if form.is_valid():
                        params = []
                        func = getattr(obj, func_name)
                        for param in get_parameters_names(func, include_annotated=True):
                            if param in form.cleaned_data:
                                params.append(form.cleaned_data[param])
                            else:
                                params.append(get_role_value_for_action(func, request.user, param))
                        try:
                            result = func(*params)
                            if hasattr(result, 'all'):
                                result = result[page*10:(page*10)+10]
                            
                        except ValidationError as e:
                            message = None
                            form.add_error(None, e.message)
                    else:
                        errors = form.errors
                elif obj:
                    try:
                        func = getattr(obj, func_name)
                        args = get_role_values_for_condition(func, request.user)
                        result = func(*args)
                        if hasattr(result, 'all'):
                            result = result[page*10:(page*10)+10]
                    except ValidationError as e:
                        errors = {'__all__': e.message}
                        message = None
                return HttpResponse(
                    json_serialize(result, request.GET, errors=errors, message=message, exception=None)
                )
            # add or edit
            elif form:
                if form.is_valid():
                    result = form.save()
                    message = _('Action successfully performed.')
                else:
                    errors = form.errors
                return HttpResponse(
                    json_serialize(result, request.GET, errors=errors, message=message, exception=None)
                )
            # get or delete
            else:
                return HttpResponse(
                    json_serialize(result, request.GET, errors=errors, message=message, exception=None)
                )
    else:
        user = auth.authenticate(username=request.POST['username'], password=request.POST['password'])
        if user is not None:
            return HttpResponse(
                json_serialize(result, request.GET, errors=[], message=_('Action successfully performed.'), exception=None, result=dict(token=user.token, id=user.id))
            )
        else:
            return HttpResponseForbidden()
Example #6
0
def action(request, app, cls, action_name, pk=None):

    try:
        _model = apps.get_model(app, cls)
    except LookupError:
        return page_not_found(request)

    for group in loader.actions[_model]:
        if action_name in loader.actions[_model][group]:
            break

    form_action = loader.actions[_model][group][action_name]
    action_title = form_action['title']
    action_can_execute = form_action['can_execute']
    action_condition = form_action['condition']
    action_function = form_action['function']
    action_message = 'message' in form_action and form_action['message'] or None
    action_permission = '%s.%s' % (_model._meta.app_label,
                                   action_function.func_name)
    action_input = form_action['input']
    redirect_to = form_action['redirect_to']

    obj = pk and _model.objects.all(request.user).get(pk=pk) or _model()
    obj.request = request
    obj._user = request.user
    title = action_title

    if check_condition(action_condition,
                       obj) and (not action_can_execute
                                 or permissions.check_group_or_permission(
                                     request, action_permission)):

        func = getattr(_model, action_function.func_name, action_function)
        form = factory.get_action_form(request, obj, form_action)

        if func.func_code.co_argcount > 1 or action_input:
            if form.is_valid():
                if 'instance' in form.fields:
                    obj = form.cleaned_data['instance']
                func = getattr(obj, action_function.func_name, action_function)
                params = []
                for param in func.func_code.co_varnames[1:func.func_code.
                                                        co_argcount]:
                    if param in form.cleaned_data:
                        params.append(form.cleaned_data[param])
                try:
                    f_return = func(*params)
                    if not redirect_to:
                        if func.func_code.co_argcount > 1:
                            return httprr(request, '..', action_message)
                        else:
                            return httprr(request, '.', action_message)
                    else:
                        return httprr(
                            request,
                            Template(redirect_to).render(Context({'self':
                                                                  obj})),
                            action_message)
                except ValidationError, e:
                    form.add_error(None, unicode(e.message))
        else:
            try:
                if form.fields and form.is_valid() or not form.fields:
                    if form.fields:
                        obj = form.cleaned_data['instance']
                    func = getattr(obj, action_function.func_name,
                                   action_function)
                    f_return = func()
                    if not redirect_to:
                        if func.func_code.co_argcount > 1:
                            return httprr(request, '..', action_message)
                        else:
                            return httprr(request, '.', action_message)
                    else:
                        return httprr(
                            request,
                            Template(redirect_to).render(Context({'self':
                                                                  obj})),
                            action_message)
            except ValidationError, e:
                return httprr(request, '.', unicode(e.message))