init
This commit is contained in:
0
AuthApp/api/__init__.py
Normal file
0
AuthApp/api/__init__.py
Normal file
88
AuthApp/api/api_1C_views.py
Normal file
88
AuthApp/api/api_1C_views.py
Normal file
@@ -0,0 +1,88 @@
|
||||
# coding=utf-8
|
||||
from BaseModels.api.base_api_views import *
|
||||
from ..models import *
|
||||
from rest_framework.response import Response
|
||||
from BaseModels.mailSender import techSendMail
|
||||
import json
|
||||
from BaseModels.api.base_api_permissions import *
|
||||
from datetime import datetime
|
||||
import re
|
||||
from rest_framework import status
|
||||
from BaseModels.api.base_api_serializers import Import_Pocket_Srializer
|
||||
|
||||
|
||||
|
||||
class Managers_1C_get_timestamp(APIBaseSimplaClass):
|
||||
|
||||
permission_classes = (api_1C_perm,)
|
||||
serializer_class = Import_Pocket_Srializer
|
||||
|
||||
def get(self, request):
|
||||
from GeneralApp.views import get_timestamp_by_property_item_name
|
||||
|
||||
property_item_name = u'1S_managers'
|
||||
|
||||
last_timestamp = get_timestamp_by_property_item_name(property_item_name)
|
||||
|
||||
return Response({
|
||||
'property_item_name' : property_item_name,
|
||||
'timestamp' : last_timestamp
|
||||
})
|
||||
|
||||
|
||||
class Managers_1C_import(APIBaseSimplaClass):
|
||||
|
||||
# authentication_classes = (authentication.TokenAuthentication,)
|
||||
permission_classes = (api_1C_perm,)
|
||||
serializer_class = Import_Pocket_Srializer
|
||||
|
||||
def post(self, request, format=None):
|
||||
"""
|
||||
import 1C companies data
|
||||
"""
|
||||
|
||||
log = ''
|
||||
res = ''
|
||||
|
||||
try:
|
||||
|
||||
data = request.data
|
||||
|
||||
if not data:
|
||||
msg = 'нет данных в пакете'
|
||||
res_Dict = {
|
||||
'status': 'error',
|
||||
'error': msg
|
||||
}
|
||||
return Response(res_Dict, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
from .import_1C_data import import_1C_pocket
|
||||
res = import_1C_pocket(data)
|
||||
|
||||
res_Dict = {
|
||||
'status': 'finished',
|
||||
'log': log
|
||||
}
|
||||
res_Dict.update(res)
|
||||
|
||||
return Response(res_Dict)
|
||||
|
||||
except Exception as e:
|
||||
len_data = 0
|
||||
if request.data:
|
||||
len_data = len(request.data)
|
||||
title = 'ОШИБКА tE Managers_1C_import'
|
||||
msg = 'Managers_1C_import Error = {0}({1})<br>lenght data = {2}<br>log...<br>{3}'.format(
|
||||
str(e), str(e.args), str(len_data), str(res)
|
||||
)
|
||||
from BaseModels.mailSender import techSendMail_for_specified_email_list
|
||||
from tEDataProj.inter import problem_solvers_personal_1S
|
||||
techSendMail_for_specified_email_list(msg, problem_solvers_personal_1S, title=title)
|
||||
|
||||
res_Dict = {
|
||||
'status': 'error',
|
||||
'error': str(e)
|
||||
}
|
||||
|
||||
return Response(res_Dict, status=status.HTTP_400_BAD_REQUEST)
|
||||
76
AuthApp/api/api_permissions.py
Normal file
76
AuthApp/api/api_permissions.py
Normal file
@@ -0,0 +1,76 @@
|
||||
# coding=utf-8
|
||||
from rest_framework.permissions import BasePermission
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from tEDataProj.inter import check_user_key_inter
|
||||
|
||||
|
||||
class Auth_API_perms(BasePermission):
|
||||
"""
|
||||
Allows access only users w full access.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
|
||||
if not request.user or request.user.is_anonymous or not request.user.is_active:
|
||||
return False
|
||||
|
||||
# auth_data = request.query_params
|
||||
# if not check_user_key_inter(auth_data):
|
||||
# raise PermissionDenied(code=403)
|
||||
|
||||
user = request.user
|
||||
groups = user.groups.all()
|
||||
|
||||
groups_name_list = groups.values_list('name', flat=True)
|
||||
|
||||
if u'API 1С импорт' in groups_name_list:
|
||||
return False
|
||||
|
||||
if view.basename == u'user':
|
||||
# if view.action in ('get_subordinate_staff',):
|
||||
# return True
|
||||
|
||||
if view.action in (
|
||||
'get_sales_department_staff',) and u'Отдел продаж: Начальник отдела продаж' in groups_name_list:
|
||||
return True
|
||||
|
||||
if view.action in ('create',):
|
||||
perm = user.has_perm('AuthApp.UI_managers_create')
|
||||
return perm
|
||||
|
||||
if view.action in ('update', 'partial_update', 'add_communication_item'):
|
||||
perm = user.has_perm('AuthApp.UI_managers_modify')
|
||||
return perm
|
||||
|
||||
if view.action in ('destroy',):
|
||||
perm = user.has_perm('AuthApp.UI_managers_delete')
|
||||
return perm
|
||||
|
||||
if view.action in (
|
||||
'retrieve', 'list', 'list_by_company_id', 'list_by_office_id', 'get_subordinate_staff',
|
||||
'get_all_staff'):
|
||||
perm = user.has_perm('AuthApp.UI_managers_retrieve')
|
||||
return perm
|
||||
|
||||
if view.action in ('get_sales_stat_by_productid', 'stat_list'):
|
||||
perm = user.has_perm('AuthApp.UI_managers_all_stat') or user.has_perm('AuthApp.UI_managers_self_stat')
|
||||
return perm
|
||||
|
||||
# if view.basename == u'userprofile':
|
||||
#
|
||||
# if view.action in ('create',):
|
||||
# perm = user.has_perm('AuthApp.add_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('update', 'partial_update'):
|
||||
# perm = user.has_perm('AuthApp.change_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('destroy',):
|
||||
# perm = user.has_perm('AuthApp.delete_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('retrieve', 'list'):
|
||||
# return True
|
||||
|
||||
return False
|
||||
17
AuthApp/api/api_urls.py
Normal file
17
AuthApp/api/api_urls.py
Normal file
@@ -0,0 +1,17 @@
|
||||
from django.conf.urls import url, include
|
||||
# from .api_views import *
|
||||
from rest_framework import routers
|
||||
from .api_1C_views import *
|
||||
from .v1.user.user_api_views import *
|
||||
|
||||
router = routers.SimpleRouter()
|
||||
# router.register(r'user', UserProfile_ViewSet)
|
||||
# router.register(r'client_person', Client_Person_ViewSet)
|
||||
router.register(r'v1/managers', v1_Managers_ViewSet)
|
||||
router.register(r'v1/personal', v1_Personal_ViewSet)
|
||||
|
||||
urlpatterns = router.urls + [
|
||||
url(r'^1c/import_managers_data$', Managers_1C_import.as_view()),
|
||||
# url(r'^1c/managers_import_1C_pocket_from_file$', ),
|
||||
url(r'^1c/import_managers/get_last_timestamp$', Managers_1C_get_timestamp.as_view()),
|
||||
]
|
||||
94
AuthApp/api/api_views.py
Normal file
94
AuthApp/api/api_views.py
Normal file
@@ -0,0 +1,94 @@
|
||||
# coding=utf-8
|
||||
from BaseModels.api.base_api_views import *
|
||||
from AuthApp.models import *
|
||||
from .serializers import *
|
||||
from .api_permissions import *
|
||||
from rest_framework.decorators import action
|
||||
|
||||
|
||||
|
||||
def get_buttons_states_Dict(user):
|
||||
|
||||
Dict = {
|
||||
'managers_menu': user.has_perm('AuthApp.UI_managers_show'),
|
||||
'managers_add_but': user.has_perm('AuthApp.UI_managers_create'),
|
||||
'managers_change_but': user.has_perm('AuthApp.UI_managers_modify'),
|
||||
'managers_delete_but': user.has_perm('AuthApp.UI_managers_delete'),
|
||||
|
||||
'admin_group_menu': user.has_perm('AuthApp.UI_adminGroup_show'), #показываем в меню группу Администрирование
|
||||
'personal_show': user.has_perm('AuthApp.UI_personal_show'), #показываем в группе Администрирование пункт Персонал
|
||||
}
|
||||
|
||||
return Dict
|
||||
|
||||
|
||||
|
||||
class Client_Person_ViewSet(APIViewSet_ModelClass):
|
||||
queryset = UserProfile.objects.filter(user__is_staff=False)
|
||||
serializer_class = UserProfile_Serializer
|
||||
permission_classes = (Auth_API_perms,)
|
||||
|
||||
def get_serializer_class(self):
|
||||
|
||||
try:
|
||||
if self.action == 'retrieve':
|
||||
return UserProfile_Serializer
|
||||
|
||||
except (KeyError, AttributeError):
|
||||
pass
|
||||
|
||||
return super(Client_Person_ViewSet, self).get_serializer_class()
|
||||
|
||||
|
||||
|
||||
|
||||
class Staff_Person_ViewSet(APIViewSet_ModelClass):
|
||||
queryset = UserProfile.objects.filter(user__is_staff=True)
|
||||
serializer_class = UserProfile_Serializer
|
||||
permission_classes = (Auth_API_perms,)
|
||||
|
||||
def get_serializer_class(self):
|
||||
|
||||
try:
|
||||
if self.action == 'retrieve':
|
||||
return UserProfile_Serializer
|
||||
|
||||
except (KeyError, AttributeError):
|
||||
pass
|
||||
|
||||
return super(Staff_Person_ViewSet, self).get_serializer_class()
|
||||
|
||||
|
||||
|
||||
class UserProfile_ViewSet(APIViewSet_ModelClass):
|
||||
queryset = UserProfile.objects.all()
|
||||
serializer_class = UserProfile_Serializer
|
||||
permission_classes = (Auth_API_perms,)
|
||||
|
||||
def get_serializer_class(self):
|
||||
|
||||
try:
|
||||
if self.action == 'retrieve':
|
||||
return UserProfile_Serializer
|
||||
|
||||
except (KeyError, AttributeError):
|
||||
pass
|
||||
|
||||
return super(UserProfile_ViewSet, self).get_serializer_class()
|
||||
|
||||
# @action(methods=['GET'], detail=True)
|
||||
# def get_current_order(self, request, pk):
|
||||
# from B2BApp.models import Order
|
||||
# from B2BApp.api.serializers import B2B_Order_serializer
|
||||
#
|
||||
# try:
|
||||
# from B2BApp.views import get_waiting_order_or_create_new
|
||||
# order = get_waiting_order_or_create_new(request, pk)
|
||||
# except Order.DoesNotExist:
|
||||
# raise serializers.ValidationError(
|
||||
# u'Ошибка, функция недоступна'
|
||||
# )
|
||||
#
|
||||
# order_data = B2B_Order_serializer(order)
|
||||
#
|
||||
# return Response(order_data.data)
|
||||
194
AuthApp/api/import_1C_data.py
Normal file
194
AuthApp/api/import_1C_data.py
Normal file
@@ -0,0 +1,194 @@
|
||||
# coding=utf-8
|
||||
from BaseModels.mailSender import techSendMail
|
||||
|
||||
from ..models import *
|
||||
from datetime import date, datetime
|
||||
from GeneralApp.views import get_timestamp_by_property_item_name, set_timestamp_by_propertiy_item_name
|
||||
from BaseModels.error_processing import *
|
||||
from uuid import uuid1
|
||||
from GeneralApp.temp_data_funcs import add_tmp_data, del_tmp_data_by_obj
|
||||
|
||||
def avg(val):
|
||||
"""uses floating-point division."""
|
||||
return sum(val) / float(len(val))
|
||||
|
||||
|
||||
from django.http import HttpResponse
|
||||
import json
|
||||
|
||||
def import_1C_pocket_from_file(request):
|
||||
|
||||
if not request.user.is_superuser:
|
||||
return HttpResponse(u'import_1C_pocket_from_file PERMISSION FAIL')
|
||||
|
||||
try:
|
||||
f = open('companies_1s.txt')
|
||||
data = f.read()
|
||||
except:
|
||||
return HttpResponse(u'import_1C_pocket_from_file READ FILE FAIL')
|
||||
|
||||
import re
|
||||
data = re.sub(r'[\r\n\t]', ' ', data)
|
||||
data = re.sub(r'\s+', ' ', data)
|
||||
|
||||
request_data = data
|
||||
|
||||
data = json.loads(request_data)
|
||||
|
||||
import_1C_pocket(data)
|
||||
|
||||
return HttpResponse(u'import_1C_pocket_from_file Accept')
|
||||
|
||||
|
||||
def import_1C_pocket(json_data):
|
||||
|
||||
|
||||
log = ''
|
||||
log_begin_DT = datetime.now()
|
||||
msg = 'import_1C_pocket MANAGERS start - {0}<br>---------------<br><br>'.format(str(log_begin_DT))
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
try:
|
||||
data = json_data['data_list']
|
||||
timestamp = json_data['timestamp']
|
||||
msg = str(timestamp)
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
# dt = datetime.fromtimestamp(timestamp)
|
||||
|
||||
saved_timestamp = get_timestamp_by_property_item_name('1S_managers')
|
||||
|
||||
if saved_timestamp and saved_timestamp >= timestamp:
|
||||
# generate_error(f, u'import_1S_companies', u'1S_companies пакет устарел, импорт не был произведен', u'')
|
||||
msg = '<b style="color : red;">!!!!! --- 1S_managers пакет устарел, импорт не был произведен</b>'
|
||||
print(msg)
|
||||
return {u'result': u'1S_managers пакет устарел, импорт не был произведен', 'error': 304}
|
||||
set_timestamp_by_propertiy_item_name('1S_managers', timestamp)
|
||||
except:
|
||||
data = json_data
|
||||
|
||||
# сохраняем данные для импорта временно в БД
|
||||
tmp_data = add_tmp_data(data_type='import_proc', data_target='managers_1s_import', data=data)
|
||||
|
||||
|
||||
for item in data:
|
||||
# print(str(item))
|
||||
# break
|
||||
|
||||
json_item = json.dumps(item, ensure_ascii=False)
|
||||
|
||||
try:
|
||||
if not u'id' in item:
|
||||
# generate_error(f, u'import_1S_companies', u'1S_companies ID отсутствует в экзепляре данных', json_item)
|
||||
msg = '<b style="color : red;">!!!!! --- 1S_managers ID отсутствует в экзепляре данных</b>'
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
return {
|
||||
u'result': msg,
|
||||
u'error': 400,
|
||||
|
||||
}
|
||||
|
||||
msg = '{0} - {1}'.format(item[u'id'], item[u'name'])
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
user_profiles = UserProfile.objects.filter(id_1s=item[u'id'])
|
||||
|
||||
|
||||
kwargs = {
|
||||
'name' : item[u'name'].replace(u"'", '"'),
|
||||
'id_1s' : item[u'id'],
|
||||
'company_position' : item[u'position'],
|
||||
'departament': str(item[u'subdiv']),
|
||||
}
|
||||
|
||||
work_start_D = item[u'datein'].replace(u" ", '')
|
||||
if len(work_start_D) > 9:
|
||||
work_start_D = datetime.strptime(work_start_D, "%d.%m.%Y")
|
||||
kwargs.update({'work_start_D' : work_start_D})
|
||||
|
||||
work_finish_D = item[u'dateout'].replace(u" ", '')
|
||||
if len(work_finish_D) > 9:
|
||||
work_finish_D = datetime.strptime(work_finish_D, "%d.%m.%Y")
|
||||
kwargs.update({'work_finish_D': work_finish_D})
|
||||
|
||||
birthday = item[u'birthday'].replace(u" ", '')
|
||||
if len(birthday) > 9:
|
||||
birthday = datetime.strptime(birthday, "%d.%m.%Y")
|
||||
kwargs.update({'birthdate': birthday})
|
||||
|
||||
|
||||
|
||||
user = None
|
||||
u_profile = None
|
||||
if user_profiles:
|
||||
user_profiles.update(**kwargs)
|
||||
u_profile = user_profiles[0]
|
||||
msg = ' - ОБНОВЛЕНИЕ данных МЕНЕДЖЕРА - {0}'.format(str(u_profile.__dict__))
|
||||
user = u_profile.user
|
||||
|
||||
if not user:
|
||||
username = str(item[u'id'])
|
||||
mail = '{0}@truenergy.by'.format(str(item[u'id']))
|
||||
password = user_id = str(uuid1().hex)[:10]
|
||||
user = User.objects.create_user(username=username, email=mail, password=password)
|
||||
user.is_staff = True
|
||||
user.is_active = True
|
||||
user.is_superuser = False
|
||||
user.set_password(password)
|
||||
user.save()
|
||||
|
||||
kwargs.update({'user': user})
|
||||
|
||||
user_profiles = UserProfile.objects.filter(user=user)
|
||||
user_profiles.update(**kwargs)
|
||||
u_profile = user_profiles[0]
|
||||
|
||||
msg = ' - СОЗДАНИЕ МЕНЕДЖЕРА - {0}'.format(str(u_profile.__dict__))
|
||||
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
msg = ''
|
||||
if 'work_finish_D' in kwargs and user.is_active:
|
||||
user.is_active = False
|
||||
msg = ' - отключен доступ<br>'
|
||||
name_list = item[u'name'].split(' ')
|
||||
if len(name_list) > 1 and user.first_name != ' '.join(name_list[1:]):
|
||||
user.first_name = ' '.join(name_list[1:])
|
||||
msg = ' - изменено имя<br>'
|
||||
if len(name_list) > 0 and user.last_name != name_list[0]:
|
||||
user.last_name = name_list[0]
|
||||
msg = ' - изменена фамилия'
|
||||
|
||||
if msg:
|
||||
user.save()
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
|
||||
|
||||
except Exception as e:
|
||||
# generate_error(f, u'import_1S_companies', str(e), json_item)
|
||||
msg = '<b style="color : red;">!!!!! --- import_1C_pocket MANAGERS error={0}</b>'.format(str(e))
|
||||
print(msg)
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
# close_log_file(f, u'END import_1S_companies')
|
||||
|
||||
# удаляем временные данные для импорта из БД
|
||||
if tmp_data:
|
||||
del_tmp_data_by_obj(tmp_data)
|
||||
|
||||
msg = 'import_1C_package MANAGERS finish - {0} (processing time = {1}<br>---------------<br><br>'.format(
|
||||
str(datetime.now()),
|
||||
str(datetime.now() - log_begin_DT)
|
||||
)
|
||||
log = '{0}<br>{1}'.format(log, msg)
|
||||
|
||||
title = 'import_1C_pocket MANAGERS'
|
||||
techSendMail(log, title)
|
||||
|
||||
return {
|
||||
u'result': log
|
||||
}
|
||||
|
||||
|
||||
|
||||
26
AuthApp/api/init_api.py
Normal file
26
AuthApp/api/init_api.py
Normal file
@@ -0,0 +1,26 @@
|
||||
from ..models import mail_list_types
|
||||
from django.http import JsonResponse, Http404
|
||||
|
||||
|
||||
def init_API(request, get_Dict=False):
|
||||
|
||||
# auth_data = request.GET
|
||||
# if not check_user_key_inter(auth_data):
|
||||
# raise exceptions.PermissionDenied()
|
||||
|
||||
Dict = {
|
||||
|
||||
}
|
||||
|
||||
mail_list_types_Dict = {}
|
||||
for item in mail_list_types:
|
||||
mail_list_types_Dict.update({
|
||||
item[0] : item[1]
|
||||
})
|
||||
Dict.update({'mail_list_types' : mail_list_types_Dict})
|
||||
|
||||
if get_Dict:
|
||||
return Dict
|
||||
|
||||
|
||||
return JsonResponse({'data': Dict})
|
||||
49
AuthApp/api/serializers.py
Normal file
49
AuthApp/api/serializers.py
Normal file
@@ -0,0 +1,49 @@
|
||||
from rest_framework import serializers
|
||||
from AuthApp.models import *
|
||||
|
||||
|
||||
# Person
|
||||
|
||||
|
||||
class client_UserProfile_Serializer(serializers.ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = UserProfile
|
||||
fields = (
|
||||
'id',
|
||||
# 'name', 'company', 'departament', 'company_position', 'phone', 'email', 'document_sign_person',
|
||||
# 'days_to_order_cancellation_default', 'days_to_pay_default', 'pay_terms', 'discount', 'birthdate',
|
||||
|
||||
)
|
||||
|
||||
|
||||
class staff_UserProfile_Serializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = UserProfile
|
||||
fields = (
|
||||
'id',
|
||||
# 'name', 'company', 'departament', 'company_position', 'phone', 'email',
|
||||
# 'birthdate',
|
||||
)
|
||||
|
||||
|
||||
class UserProfile_Serializer(serializers.ModelSerializer):
|
||||
|
||||
class Meta:
|
||||
model = UserProfile
|
||||
fields = (
|
||||
'id',
|
||||
# 'name', 'company', 'departament', 'company_position', 'phone', 'email', 'document_sign_person',
|
||||
# 'days_to_order_cancellation_default', 'days_to_pay_default', 'pay_terms', 'discount', 'birthdate',
|
||||
)
|
||||
|
||||
class UserProfile_list_Serializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = UserProfile
|
||||
fields = (
|
||||
'id',
|
||||
# 'name'
|
||||
)
|
||||
|
||||
|
||||
# ----------------------------------------
|
||||
116
AuthApp/api/v1/permissions/personal_api_permissions.py
Normal file
116
AuthApp/api/v1/permissions/personal_api_permissions.py
Normal file
@@ -0,0 +1,116 @@
|
||||
# coding=utf-8
|
||||
from rest_framework.permissions import BasePermission
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
from tEDataProj.inter import check_user_key_inter
|
||||
from AuthApp.models import User
|
||||
|
||||
|
||||
def check_of_user_is_manager_of_company(user, view):
|
||||
if not 'pk' in view.kwargs:
|
||||
return False
|
||||
|
||||
try:
|
||||
objs = User.objects.get(
|
||||
user_profile__company_obj__manager_obj=user,
|
||||
id=view.kwargs['pk']
|
||||
)
|
||||
except:
|
||||
return False
|
||||
|
||||
return objs
|
||||
|
||||
|
||||
def check_of_user_is_company_staff(user, view):
|
||||
if not 'pk' in view.kwargs:
|
||||
return False
|
||||
|
||||
try:
|
||||
objs = User.objects.get(
|
||||
user_profile__company_obj=user.user_profile.company_obj,
|
||||
id=view.kwargs['pk']
|
||||
)
|
||||
except:
|
||||
return False
|
||||
|
||||
return objs
|
||||
|
||||
|
||||
class Personal_API_perms(BasePermission):
|
||||
"""
|
||||
Allows access only users w full access.
|
||||
"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
|
||||
if not request.user or request.user.is_anonymous or not request.user.is_active:
|
||||
return False
|
||||
|
||||
# auth_data = request.query_params
|
||||
# if not check_user_key_inter(auth_data):
|
||||
# raise PermissionDenied(code=403)
|
||||
|
||||
user = request.user
|
||||
groups = user.groups.all()
|
||||
|
||||
groups_name_list = groups.values_list('name', flat=True)
|
||||
|
||||
if u'API 1С импорт' in groups_name_list:
|
||||
return False
|
||||
|
||||
if view.basename == u'user':
|
||||
|
||||
if view.action in ('create',):
|
||||
perm = user.has_perm('AuthApp.UI_company_staff_create')
|
||||
return perm
|
||||
|
||||
if view.action in (
|
||||
'update', 'partial_update', 'add_communication_item', 'get_connected_mailings', 'possible_mailings',
|
||||
'change_mailing_status'):
|
||||
# perm = user.has_perm('AuthApp.UI_managers_modify')
|
||||
# return perm
|
||||
if not user.is_staff:
|
||||
# персонал компании
|
||||
if user.has_perm('AuthApp.UI_company_staff_modify_if_staff_company'):
|
||||
return check_of_user_is_company_staff(user, view)
|
||||
|
||||
return False
|
||||
|
||||
# если персонал
|
||||
else:
|
||||
if check_of_user_is_manager_of_company(user, view) and user.has_perm(
|
||||
'AuthApp.UI_company_staff_modify_if_manager'):
|
||||
return True
|
||||
elif user.has_perm('AuthApp.UI_company_staff_modify_any'):
|
||||
return True
|
||||
|
||||
if view.action in ('destroy',):
|
||||
perm = user.has_perm('AuthApp.UI_company_staff_delete')
|
||||
return perm
|
||||
|
||||
if view.action in (
|
||||
'retrieve', 'list', 'list_by_company_id', 'list_by_office_id',
|
||||
'possible_departaments_list', 'possible_company_positions_list'
|
||||
):
|
||||
perm = user.has_perm('AuthApp.UI_company_staff_retrieve_any_no_staff')
|
||||
if not perm:
|
||||
perm = user.has_perm('AuthApp.UI_company_staff_retrieve')
|
||||
return perm
|
||||
|
||||
# if view.basename == u'userprofile':
|
||||
#
|
||||
# if view.action in ('create',):
|
||||
# perm = user.has_perm('AuthApp.add_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('update', 'partial_update'):
|
||||
# perm = user.has_perm('AuthApp.change_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('destroy',):
|
||||
# perm = user.has_perm('AuthApp.delete_userprofile')
|
||||
# return perm
|
||||
#
|
||||
# if view.action in ('retrieve', 'list'):
|
||||
# return True
|
||||
|
||||
return False
|
||||
124
AuthApp/api/v1/user/user_api_serializars.py
Normal file
124
AuthApp/api/v1/user/user_api_serializars.py
Normal file
@@ -0,0 +1,124 @@
|
||||
from rest_framework import serializers
|
||||
from ....models import *
|
||||
from ....funcs import fullname_for_user
|
||||
|
||||
|
||||
class Personal_change_mailing_status_Serializer(serializers.Serializer):
|
||||
mailing_ID = serializers.IntegerField()
|
||||
mailing_status = serializers.BooleanField()
|
||||
|
||||
|
||||
class User_sync_Serializer(serializers.ModelSerializer):
|
||||
id_1s = serializers.SerializerMethodField()
|
||||
|
||||
def get_id_1s(self, obj):
|
||||
return obj.user_profile.id_1s
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = (
|
||||
'id_1s',
|
||||
)
|
||||
|
||||
|
||||
class Profile_list_Serializer(serializers.ModelSerializer):
|
||||
from GeneralApp.api.v1.communications.communications_api_serializers import Communications_create_Serializer
|
||||
|
||||
office_name = serializers.SerializerMethodField(required=False)
|
||||
company_name = serializers.SerializerMethodField(required=False)
|
||||
manager_name = serializers.SerializerMethodField(required=False)
|
||||
company_client_type = serializers.SerializerMethodField(required=False)
|
||||
|
||||
communications = Communications_create_Serializer(many=True)
|
||||
|
||||
def get_company_client_type(self, obj):
|
||||
try:
|
||||
if obj and obj.company_obj:
|
||||
return obj.company_obj.client_type
|
||||
else:
|
||||
return None
|
||||
except:
|
||||
return None
|
||||
|
||||
def get_office_name(self, obj):
|
||||
try:
|
||||
if obj and obj.office:
|
||||
return obj.office.name
|
||||
except:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
def get_company_name(self, obj):
|
||||
try:
|
||||
if obj and obj.company_obj:
|
||||
return obj.company_obj.name
|
||||
except:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
def get_manager_name(self, obj):
|
||||
try:
|
||||
if obj and obj.company_obj and obj.company_obj.manager_obj:
|
||||
return '{0} {1}'.format(obj.company_obj.manager_obj.last_name, obj.company_obj.manager_obj.first_name)
|
||||
except:
|
||||
return None
|
||||
|
||||
return None
|
||||
|
||||
class Meta:
|
||||
model = UserProfile
|
||||
fields = (
|
||||
'id',
|
||||
'enable',
|
||||
'company_obj', 'company_name',
|
||||
'company_position', 'company_client_type',
|
||||
'phone',
|
||||
'delivery_address',
|
||||
'office', 'office_name',
|
||||
'departament',
|
||||
'document_sign_person',
|
||||
'work_start_D',
|
||||
'work_finish_D',
|
||||
'birthdate',
|
||||
'comment',
|
||||
'communications',
|
||||
'priority_connect_type',
|
||||
'modifiedDT',
|
||||
'mailing_sets',
|
||||
'manager_name'
|
||||
)
|
||||
|
||||
|
||||
class User_list_Serializer(serializers.ModelSerializer):
|
||||
full_name = serializers.SerializerMethodField('get_full_name_user', required=False)
|
||||
|
||||
# user_profile = Profile_list_Serializer()
|
||||
|
||||
def get_full_name_user(self, obj):
|
||||
name = fullname_for_user(obj)
|
||||
if not name:
|
||||
name = obj.email
|
||||
return name
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = (
|
||||
'id', 'full_name'
|
||||
)
|
||||
|
||||
|
||||
class Personal_list_Serializer(User_list_Serializer):
|
||||
user_profile = Profile_list_Serializer()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = (
|
||||
'id', 'full_name', 'first_name', 'last_name', 'is_active', 'is_staff', 'user_profile', 'email'
|
||||
)
|
||||
extra_kwargs = {
|
||||
'email': {'required': 'False'},
|
||||
'first_name': {'required': 'False'},
|
||||
'last_name': {'required': 'False'},
|
||||
}
|
||||
1180
AuthApp/api/v1/user/user_api_views.py
Normal file
1180
AuthApp/api/v1/user/user_api_views.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user