Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import logging
- from functools import reduce
- from typing import Any, List, Union
- from django.db.models import QuerySet
- from django.http import HttpRequest
- from django.urls import reverse
- from rest_framework.request import Request
- from rest_framework import permissions
- from rest_framework.decorators import permission_classes
- from misc.to_int import safe_to_int
- from misc.views.generic_api_view import GenericApiView
- from misc.views.generic_serializer import GenericSerializer
- from misc.views.generic_api_single_view import GenericApiSingleView
- from misc.views.generic_filters import GenericFilters
- from users.models import (
- User,
- UserAccess,
- ConnectingUserToAccess,
- )
- log = logging.getLogger(__name__)
- @permission_classes((permissions.AllowAny,))
- class ConnectingUserToAccessTableView(GenericApiView):
- """Определяет структуру и содержание ответа на запросы к данным таблицы ConnectingUserToAccess."""
- table_name = 'ConnectingUserToAccess'
- class Filters(GenericFilters):
- pass
- FIELDS_FILTERS = [
- GenericApiView.get_filter(
- filter_name='id_field',
- field_name='id',
- filer_method=Filters.generic_int_equal_filter,
- ),
- GenericApiView.get_filter(
- filter_name='transfer_date_field',
- field_name='transfer_date',
- filer_method=Filters.generic_str_contains_filter,
- ),
- GenericApiView.get_filter(
- filter_name='return_date_field',
- field_name='return_date',
- filer_method=Filters.generic_str_contains_filter,
- ),
- GenericApiView.get_filter(
- filter_name='comment_field',
- field_name='comment',
- filer_method=Filters.generic_str_contains_filter,
- ),
- GenericApiView.get_filter(
- filter_name='user_access_field',
- field_name='user_access',
- filer_method=Filters.generic_str_contains_filter,
- ),
- GenericApiView.get_filter(
- filter_name='user_field',
- field_name='user',
- filer_method=Filters.generic_str_contains_filter,
- ),
- ]
- # PERMISSIONS = {
- # 'create': 'users.crm_users_access_can_add_request',
- # 'view': 'users.crm_users_access_can_view_request',
- # 'edit': 'users.crm_users_access_can_respond_request',
- # 'delete': 'users.crm_users_access_can_delete_request',
- # 'view_all': 'users.crm_users_can_view_and_edit_all',
- # }
- PERMISSIONS = {
- 'create': 'users.crm_users_can_edit_employee',
- 'view': 'users.crm_users_can_view_employee',
- 'edit': 'users.crm_users_can_edit_employee',
- 'delete': 'users.crm_users_access_can_delete_request',
- 'view_all': 'users.crm_users_can_view_and_edit_all',
- }
- def get_queryset(self, context: dict, user: 'UserAccess') -> QuerySet:
- """Возвращает базовый (до фильтрации и пагинации) QuerySet для таблицы."""
- user_id = context.get('user_id_field', -1)
- return ConnectingUserToAccess.objects.filter(user__id=user_id)
- def get_filtered_table_fields(self, table_fields: list, request: Union[HttpRequest, Request]) -> list:
- """Метод определяющий логику отсеивания полей таблицы."""
- excluded_fields = []
- if not request.user.has_perm(self.PERMISSIONS.get('view_all')):
- excluded_fields += ['delete_btn_field', ]
- return GenericSerializer.get_fields_without_excluded(
- serializer_fields=table_fields, excluded_fields=excluded_fields
- )
- @classmethod
- def get_actions(cls) -> list:
- """Возвращает список со списком действий, применимый к набору данных. """
- actions = [
- cls.get_action(
- name='edit',
- verbose='Сохранить изменения',
- url=reverse('user_access_list'),
- ),
- ]
- return actions
- @staticmethod
- def get_field_dict(context: dict, user: User) -> dict:
- """Распаковывает ответ и возвращает словарь со значениями полей"""
- user_id_field = ConnectingUserToAccessTableView.get_unpack_value(context.get('user_field'))
- user_id_field = safe_to_int(user_id_field, -1)
- user_field = User.objects.filter(id=user_id_field).first()
- user_access_id_field = ConnectingUserToAccessTableView.get_unpack_value(context.get('user_access_field'))
- user_access_id_field = safe_to_int(user_access_id_field, -1)
- user_access_field = UserAccess.objects.filter(id=user_access_id_field).first()
- data = {
- 'user': user_field,
- 'user_access': user_access_field,
- 'transfer_date': ConnectingUserToAccessTableView.get_unpack_value(context.get('transfer_date_field')),
- 'return_date': ConnectingUserToAccessTableView.get_unpack_value(context.get('return_date_field')),
- 'comment': ConnectingUserToAccessTableView.get_unpack_value(context.get('comment_field')),
- }
- return data
- def get_action_methods(self) -> dict:
- """Возвращает словарь соотношений названий действий с их методом."""
- return {
- 'edit': self.edit_elements,
- }
- def get_empty_item_prefilled_fields(self, context: dict) -> dict:
- """Возвращает список предзаполненных полей для пустого элемента."""
- user_field = context.get('user_id_field')
- prefilled_fields = {'user_field': user_field}
- return prefilled_fields
- @permission_classes((permissions.AllowAny,))
- class ConnectingUserToAccessElementView(GenericApiSingleView):
- """
- Определяет структуру и содержание ответа на запросы к данным элемента ConnectingUserToAccess.
- В данный момент используется только для работы с методом DELETE
- """
- table_name = 'ConnectingUserToAccess'
- element_verbose = 'Доступы у сотрудника'
- table_view_model = ConnectingUserToAccessTableView
- PERMISSIONS = {
- # 'create': 'users.crm_users_can_edit_employee',
- 'view': 'users.crm_users_can_view_employee',
- # 'edit': 'users.crm_users_can_edit_employee',
- 'delete': 'users.crm_users_can_edit_employee',
- 'view_all': 'users.crm_users_can_view_and_edit_all',
- 'edit_current_user_personal_information': 'users.crm_users_edit_current_user_personal_information',
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement