Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- submission_request_property.py
- from datetime import timedelta
- from functools import reduce
- import logging
- from typing import Any, List, Union, Optional
- from django.db.models import QuerySet, Q
- from django.http import HttpRequest
- from django.urls import reverse
- from django.utils import timezone
- from django.utils.crypto import get_random_string
- from rest_framework import permissions
- from rest_framework.decorators import permission_classes
- from rest_framework.request import Request
- from rest_framework.response import Response
- from crm_notification.models import Notification
- from itrade import settings
- from misc.spliting import split_query
- from misc.to_int import safe_to_int
- from misc.views.generic_api_single_view import GenericApiSingleView
- from misc.views.generic_api_view import GenericApiView
- from misc.views.generic_filters import GenericFilters
- from misc.views.table_style import TableStyle
- from partners.systems import System
- from users.models import (
- SubmissionRequest,
- AuthorizationInformationLV,
- ResetPasswordPin,
- User,
- )
- log = logging.getLogger(__name__)
- @permission_classes((permissions.AllowAny,))
- class SubmissionRequestPropertyElementView(GenericApiSingleView):
- """Определяет структуру и содержание ответа на запросы к данным элемента User (Таб с историей активности)."""
- table_name = 'SubmissionRequestProperty'
- element_verbose = 'Запрос на имущество'
- PERMISSIONS = {
- # 'create': 'users.crm_users_can_add_employee',
- 'view': 'users.crm_users_can_view_employee',
- 'edit': 'users.crm_users_can_edit_employee',
- # 'delete': 'users.crm_users_can_delete_employee',
- 'view_all': 'users.crm_users_can_view_and_edit_all',
- 'edit_current_user_personal_information': 'users.crm_users_edit_current_user_personal_information',
- }
- def get_queryset(self, context: dict, user: User) -> QuerySet:
- """Возвращает базовый (до фильтрации и пагинации) QuerySet."""
- if not user.has_perm(self.PERMISSIONS.get('view_all')):
- submission_request_queryset = SubmissionRequest.objects.filter(user=user)
- else:
- submission_request_queryset = SubmissionRequest.objects.all()
- return submission_request_queryset
- def additional_permission_check(self, obj: Any, request: Union[HttpRequest, Request]) -> bool:
- """Дополнительные проверки на разрешения."""
- user = request.user
- if not user.has_perm(self.PERMISSIONS.get('view_all')):
- set_of_user = User.objects.get_set_of_subordinates_user(user=user)
- if obj not in set_of_user:
- return False
- return True
- def prepare_tabs_args(self, request: Union[HttpRequest, Request], obj: Any, pk: Optional[int] = -1,
- parent_id: Optional[int] = None) -> dict:
- """Подготавливает словарь аргументов для табов."""
- return {
- 'user_id': pk,
- 'submission_request_access_tab_for_user_id': pk,
- 'submission_request_property_tab_for_user_id': pk,
- }
- @staticmethod
- def additional_check_for_tab(tab_name: str, user: User, context: dict, obj: Optional[Any] = None) -> bool:
- """
- Дополнительная проверка для таба
- Возвращает логическое значения, разрешать ли выводит таб или нет
- Пока решил не делать проверку каждого таба на права (у которых не делал, одинаковые права как и у этого таба),
- тк метод has_view_permission и сама работа с пермишенами, скорее всего, будут изменятся
- """
- from crm_control.views.personnel_accounting import PersonnelAccountingElementView
- if tab_name == 'personnel_accounting':
- personnel_accounting_obj = (
- obj.record_in_personnel_accounting.id
- if hasattr(obj, 'record_in_personnel_accounting') and obj.record_in_personnel_accounting else None
- )
- return PersonnelAccountingElementView.has_view_permission(
- user=user, context=context, obj=personnel_accounting_obj
- )
- return True
- def get_tables(self, context: dict, user: User, obj: Any, pk: int) -> list:
- """Возвращает встроенные таблицы."""
- user_property_access_table_style = TableStyle.get_table_style(
- mode=TableStyle.TableStyleMode.SIMPLE,
- hide_options=False,
- hide_clear_button=False,
- hide_create_button=True,
- hide_pagination_info=True,
- )
- tables = []
- if obj:
- tables = [
- {
- 'name': 'UserProperty',
- 'verbose': 'Имущество',
- 'url': reverse('submission_request_property_list'),
- 'prefilters': {
- 'table_style': user_property_access_table_style,
- 'user_id_field': str(pk),
- },
- },
- ]
- return tables
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement