Added Django REST but have some bugs

This commit is contained in:
Yuriy Kulakov
2021-03-07 21:30:02 +03:00
parent 5909750fcc
commit 8488ea88c2
10 changed files with 176 additions and 40 deletions

View File

@@ -3,9 +3,9 @@ import os
from zenpy import Zenpy
from zenpy.lib.exception import APIException
from main.models import UserProfile
from main.models import UserProfile, User
from access_controller.settings import ZENDESK_ROLES as ROLES
from access_controller.settings import ZENDESK_ROLES as ROLES, ZENDESK_ROLES
class ZendeskAdmin:
@@ -28,7 +28,7 @@ class ZendeskAdmin:
email: str = os.getenv('ACCESS_CONTROLLER_API_EMAIL')
token: str = os.getenv('ACCESS_CONTROLLER_API_TOKEN')
password: str = os.getenv('ACCESS_CONTROLLER_API_PASSWORD')
_instance=None
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
@@ -144,8 +144,9 @@ def get_users_list() -> list:
Функция **get_users_list** возвращает список пользователей Zendesk, относящихся к организации.
"""
zendesk = ZendeskAdmin()
admin = zendesk.get_user(zendesk.email)
org = next(zendesk.admin.users.organizations(user=admin))
# У пользователей должна быть организация SYSTEM
org = next(zendesk.admin.search(type='organization', name='SYSTEM'))
return zendesk.admin.organizations.users(org)
@@ -191,3 +192,37 @@ def check_user_auth(email: str, password: str) -> bool:
except APIException:
return False
return True
def update_user_in_model(profile, zendesk_user):
profile.name = zendesk_user.name
profile.role = zendesk_user.role
profile.image = zendesk_user.photo['content_url'] if zendesk_user.photo else None
profile.save()
def count_users(users) -> tuple:
"""
Функция подсчета количества сотрудников с ролями engineer и light_a
.. todo::
this func counts users from all zendesk instead of just from a model:
"""
engineers, light_agents = 0, 0
for user in users:
if user.custom_role_id == ZENDESK_ROLES['engineer']:
engineers += 1
elif user.custom_role_id == ZENDESK_ROLES['light_agent']:
light_agents += 1
return engineers, light_agents
def update_users_in_model():
"""
Обновляет пользователей в модели UserProfile по списку пользователей в организации
"""
users = get_users_list()
for user in users:
profile = User.objects.get(email=user.email).userprofile
update_user_in_model(profile, user)
return users

17
main/serializers.py Normal file
View File

@@ -0,0 +1,17 @@
from django.contrib.auth.models import User
from rest_framework import serializers
from main.models import UserProfile
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ['email']
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
class Meta:
model = UserProfile
fields = ['user', 'role', 'name']

View File

@@ -27,6 +27,7 @@
</style>
{% block extra_css %}{% endblock %}
{% block extra_scripts %}{% endblock %}
</head>
<body class="d-flex flex-column h-100">

View File

@@ -10,6 +10,13 @@
<link rel="stylesheet" href="{% static 'main/css/work.css' %}"/>
{% endblock %}
{% block extra_scripts %}
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
{% endblock%}
{% block content %}
<div class="container-md">
<div class="new-section">
@@ -37,25 +44,22 @@
<table class="light-table">
<thead>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Name(link to profile)</th>
<th>Checked</th>
</thead>
<tbody>
<tbody id="table">
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td><a href="#">{{ user.name }}</a></td>
<td>{{ user.user.email }}</td>
<td>{{ user.role }}</td>
<td><a href="#">{{ user.name }}</a></td>
<td class="checkbox_field"></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock%}
@@ -103,6 +107,6 @@
{% endblock %}
</div>
<script src="{% static 'main/js/control.js'%}"></script>
<script src="{% static 'main/js/control.js'%}" type="text/babel"></script>
{% endblock %}

6
main/urls.py Normal file
View File

@@ -0,0 +1,6 @@
from rest_framework.routers import DefaultRouter
from main.views import UsersViewSet
router = DefaultRouter()
router.register(r'users', UsersViewSet)

View File

@@ -14,7 +14,7 @@ from zenpy import Zenpy
from access_controller.settings import EMAIL_HOST_USER
from main.extra_func import check_user_exist, update_profile, get_user_organization, \
make_engineer, make_light_agent, get_users_list
make_engineer, make_light_agent, get_users_list, update_users_in_model, count_users
from django.contrib.auth.models import User, Permission
from main.models import UserProfile
@@ -27,6 +27,11 @@ from django.core.exceptions import PermissionDenied
from access_controller.settings import ZENDESK_ROLES
from zenpy.lib.api_objects import User as ZenpyUser
# Django REST
from rest_framework import viewsets, status
from main.serializers import ProfileSerializer
from rest_framework.response import Response
from rest_framework.decorators import action
content_type_temp = ContentType.objects.get_for_model(UserProfile)
permission_temp, created = Permission.objects.get_or_create(
@@ -193,22 +198,6 @@ class AdminPageView(LoginRequiredMixin, PermissionRequiredMixin, FormView):
def make_light_agents(users):
[make_light_agent(user) for user in users]
@staticmethod
def count_users(users) -> tuple:
"""
Функция подсчета количества сотрудников с ролями engineer и light_a
.. todo::
this func counts users from all zendesk instead of just from a model:
"""
engineers, light_agents = 0, 0
for user in users:
if user.custom_role_id == ZENDESK_ROLES['engineer']:
engineers += 1
elif user.custom_role_id == ZENDESK_ROLES['light_agent']:
light_agents += 1
return engineers, light_agents
def get_context_data(self, **kwargs) -> dict:
"""
Функция формирования контента страницы администратора (с проверкой прав доступа)
@@ -216,9 +205,10 @@ class AdminPageView(LoginRequiredMixin, PermissionRequiredMixin, FormView):
if self.request.user.userprofile.role != 'admin':
raise PermissionDenied
context = super().get_context_data(**kwargs)
context['users'] = get_list_or_404(
users = get_list_or_404(
UserProfile, role='agent')
context['engineers'], context['light_agents'] = self.count_users(get_users_list())
context['users'] = users
context['engineers'], context['light_agents'] = count_users(users)
return context # TODO: need to get profile page url
@@ -227,3 +217,18 @@ class CustomLoginView(LoginView):
Отображение страницы авторизации пользователя
"""
form_class = CustomAuthenticationForm
class UsersViewSet(viewsets.ReadOnlyModelViewSet):
"""
Класс для получения пользователей с помощью api
"""
queryset = UserProfile.objects.filter(role='agent')
serializer_class = ProfileSerializer
def list(self, request, *args, **kwargs):
users = update_users_in_model()
profiles = UserProfile.objects.filter(role='agent')
count = count_users(users)
serializer = self.get_serializer(data=profiles, many=True)
return Response(serializer.data + {'engineers': count[0], 'light_agents': count[1]})