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.urls import reverse
- from django.http import HttpRequest
- 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_single_view import GenericApiSingleView
- from misc.views.generic_serializer import GenericSerializer
- from misc.views.generic_api_view import GenericApiView
- from misc.views.generic_filters import GenericFilters
- from users.models import (
- User,
- UserProperty,
- Property,
- )
- log = logging.getLogger(__name__)
- @permission_classes((permissions.AllowAny,))
- class UserPropertyTableView(GenericApiView):
- """Определяет структуру и содержание ответа на запросы к данным таблицы UserProperty."""
- table_name = 'UserProperty'
- 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='quantity_field',
- field_name='quantity',
- 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='user_property_field',
- field_name='user_property',
- 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_property_can_add_request',
- # 'view': 'users.crm_users_property_can_view_request',
- # 'edit': 'users.crm_users_property_can_respond_request',
- # 'delete': 'users.crm_users_property_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_property_can_delete_request',
- 'view_all': 'users.crm_users_can_view_and_edit_all',
- }
- def get_queryset(self, context: dict, user: 'User') -> QuerySet:
- """Возвращает базовый (до фильтрации и пагинации) QuerySet для таблицы."""
- user_id = context.get('user_id_field', -1)
- return UserProperty.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_property_list'),
- ),
- ]
- return actions
- @staticmethod
- def get_field_dict(context: dict, user: User) -> dict:
- """Распаковывает ответ и возвращает словарь со значениями полей"""
- user_id_field = UserPropertyTableView.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_property_id_field = UserPropertyTableView.get_unpack_value(context.get('user_property_field'))
- user_property_id_field = safe_to_int(user_property_id_field, -1)
- user_property = Property.objects.filter(id=user_property_id_field).first()
- data = {
- 'user': user_field,
- 'user_property': user_property,
- 'transfer_date': UserPropertyTableView.get_unpack_value(context.get('transfer_date_field')),
- 'quantity_field': UserPropertyTableView.get_unpack_value(context.get('quantity_field')),
- 'return_date': UserPropertyTableView.get_unpack_value(context.get('return_date_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 UserPropertyElementView(GenericApiSingleView):
- """
- Определяет структуру и содержание ответа на запросы к данным элемента UserProperty.
- В данный момент используется только для работы с методом DELETE
- """
- table_name = 'UserProperty'
- element_verbose = 'Имущество у сотрудника'
- table_view_model = UserPropertyTableView
- 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