views.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # coding=utf-8
  2. import traceback
  3. import json
  4. from django.db.models import Q
  5. from rest_framework.decorators import action
  6. from django.db import transaction
  7. from rest_framework.views import APIView
  8. from rest_framework.serializers import ValidationError
  9. from utils.permission import permission_required, isLogin, check_permission
  10. from django.contrib.auth.models import Group, Permission
  11. from rest_framework_jwt.views import ObtainJSONWebToken, VerifyJSONWebToken, RefreshJSONWebToken
  12. from utils import response_error, response_ok
  13. from django.contrib.auth import get_user_model
  14. User = get_user_model()
  15. from apps.account.serializers import JWTSerializer, EmployeeSerializer, GroupDictSerializer, GroupSerializer
  16. from utils.custom_modelviewset import CustomModelViewSet
  17. from apps.account.filters import UserFilter, GroupFilter
  18. from apps.account.models import ManageStoreUser
  19. from apps.log.models import BizLog
  20. from apps.account.consts import PermissionMenu
  21. from collections import OrderedDict
  22. from apps.agent.models import Store, Agent,GeneralAgent
  23. from utils.exceptions import CustomError
  24. class LoginView(ObtainJSONWebToken):
  25. serializer_class = JWTSerializer
  26. def post(self, request, *args, **kwargs):
  27. try:
  28. ser = self.serializer_class(data=request.data)
  29. ser.request = request
  30. # TODO 判断门店是否在用、在有效期内
  31. if ser.is_valid(raise_exception=True):
  32. return response_ok(ser.validated_data)
  33. except ValidationError as e:
  34. return response_error(e.detail['error'][0])
  35. class RefreshTokenView(RefreshJSONWebToken):
  36. def post(self, request, *args, **kwargs):
  37. try:
  38. ser = self.serializer_class(data=request.data)
  39. if ser.is_valid(raise_exception=True):
  40. return response_ok({'token': ser.validated_data['token']})
  41. except ValidationError as e:
  42. return response_error(u'登录状态失效,请重新登录')
  43. class ChangePassword(APIView):
  44. def post(self, request, *args, **kwargs):
  45. id = request.GET.get('id')
  46. data = json.loads(request.body)
  47. try:
  48. with transaction.atomic():
  49. user = User.objects.filter(id=id).first()
  50. if not user:
  51. raise CustomError(u'用户信息错误,请刷新重试!')
  52. user.change_password(data['new_password'], data['confirm_password'], data['old_password'])
  53. BizLog.objects.addnew(request.user, BizLog.UPDATE, u"修改密码[%s],id=%d" % (user.username, user.id))
  54. except CustomError as e:
  55. return response_error(str(e))
  56. except Exception as e:
  57. traceback.print_exc()
  58. return response_error(u'保存失败!')
  59. return response_ok()
  60. class EmployeeViewSet(CustomModelViewSet):
  61. permission_classes = [isLogin, ]
  62. queryset = User.objects.filter()
  63. serializer_class = EmployeeSerializer
  64. @permission_required('account.browse_user')
  65. def filter_queryset(self, queryset):
  66. queryset = queryset.filter()
  67. user = self.request.user
  68. queryset = queryset.filter(
  69. Q(store_id__in=self.request.user.get_manager_range()) |
  70. Q(id=user.id) |
  71. Q(create_user=user) |
  72. Q(agent__create_user=user) |
  73. Q(general_agent__create_user=user)
  74. )
  75. f = UserFilter(self.request.GET, queryset=queryset)
  76. return f.qs
  77. @permission_required('account.add_user')
  78. def perform_create(self, serializer):
  79. super(EmployeeViewSet, self).perform_create(serializer)
  80. instance = serializer.instance
  81. validated_data = serializer.validated_data
  82. BizLog.objects.addnew(self.request.user, BizLog.INSERT,
  83. u'添加用户[%s],id=%d' % (instance.name, instance.id), validated_data)
  84. @permission_required('account.add_user')
  85. def perform_update(self, serializer):
  86. super(EmployeeViewSet, self).perform_update(serializer)
  87. instance = serializer.instance
  88. validated_data = serializer.validated_data
  89. BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
  90. u'修改用户[%s],id=%d' % (instance.name, instance.id), validated_data)
  91. @permission_required('account.delete_user')
  92. def perform_destroy(self, instance):
  93. ManageStoreUser.objects.filter(manage_user=instance).delete()
  94. BizLog.objects.filter(user=instance).delete()
  95. BizLog.objects.addnew(self.request.user, BizLog.DELETE,
  96. u'删除账号[%s],id=%d' % (instance.username, instance.id))
  97. super(EmployeeViewSet, self).perform_destroy(instance)
  98. @action(methods=['post'], detail=True)
  99. def join(self, request, pk):
  100. check_permission(request, 'account.check_user')
  101. try:
  102. with transaction.atomic():
  103. instance = self.get_object()
  104. instance.check_user = request.user
  105. instance.status = User.INSERVICE
  106. instance.save()
  107. BizLog.objects.addnew(self.request.user, BizLog.INSERT,
  108. u'员工[%s]入职,id=%d' % (instance.name, instance.id))
  109. return response_ok()
  110. except Exception as e:
  111. traceback.print_exc()
  112. return response_error(u'入职失败')
  113. @action(methods=['post'], detail=True)
  114. def branch(self, request, pk):
  115. check_permission(request, 'account.manager_store')
  116. data = json.loads(request.POST.get('sotres'))
  117. try:
  118. with transaction.atomic():
  119. instance = self.get_object()
  120. ManageStoreUser.objects.filter(manage_user_id=pk).delete()
  121. for row in data:
  122. ManageStoreUser.objects.create(store_id=row, manage_user_id=pk)
  123. BizLog.objects.addnew(self.request.user, BizLog.INSERT,
  124. u'设置账号[%s]管理门店,id=%d' % (instance.username, instance.id), data)
  125. return response_ok()
  126. except Exception as e:
  127. traceback.print_exc()
  128. return response_error(u'保存失败')
  129. class GroupsViewSet(CustomModelViewSet):
  130. permission_classes = [isLogin, ]
  131. queryset = Group.objects.filter()
  132. serializer_class = GroupSerializer
  133. @permission_required('account.manager_permissions')
  134. def filter_queryset(self, queryset):
  135. if not self.request.user.is_superuser:
  136. groups = self.request.user.groups.all()
  137. queryset = queryset.filter(id__in=[g.id for g in groups])
  138. f = GroupFilter(self.request.GET, queryset=queryset)
  139. return f.qs
  140. @permission_required('account.manager_permissions')
  141. def perform_create(self, serializer):
  142. super(GroupsViewSet, self).perform_create(serializer)
  143. instance = serializer.instance
  144. validated_data = serializer.validated_data
  145. BizLog.objects.addnew(self.request.user, BizLog.INSERT,
  146. u'添加权限组[%s],id=%d' % (instance.name, instance.id), validated_data)
  147. @permission_required('account.manager_permissions')
  148. def perform_update(self, serializer):
  149. super(GroupsViewSet, self).perform_update(serializer)
  150. instance = serializer.instance
  151. validated_data = serializer.validated_data
  152. BizLog.objects.addnew(self.request.user, BizLog.UPDATE,
  153. u'修改权限组[%s],id=%d' % (instance.name, instance.id), validated_data)
  154. @permission_required('account.manager_permissions')
  155. def destroy(self, request, *args, **kwargs):
  156. with transaction.atomic():
  157. instance = self.get_object()
  158. # user_count = instance.user_set.all().count()
  159. # if user_count:
  160. # raise CustomError(u'该权限组已分配给用户,禁止删除!')
  161. BizLog.objects.addnew(self.request.user, BizLog.DELETE,
  162. u'删除权限组[%s],id=%d' % (instance.name, instance.id))
  163. instance.delete()
  164. return response_ok()
  165. class PermissionsListView(APIView):
  166. permission_classes = [isLogin, ]
  167. @permission_required('account.manager_permissions')
  168. def get(self, request):
  169. rows = Permission.objects.all().exclude(name__startswith='Can')
  170. perms_menus = PermissionMenu()
  171. rows = perms_menus.sort_perms(rows)
  172. menus = OrderedDict()
  173. for row in rows:
  174. item = {'id': row.id, 'name': row.name}
  175. mn = perms_menus.get_menuname_of_contenttype(row.content_type.app_label, row.content_type.model)
  176. if mn in menus:
  177. permissions = menus[mn]
  178. else:
  179. permissions = menus[mn] = OrderedDict()
  180. if row.content_type.name in permissions:
  181. if not item in permissions[row.content_type.name]:
  182. permissions[row.content_type.name].append(item)
  183. else:
  184. permissions[row.content_type.name] = [item, ]
  185. return response_ok(menus)
  186. class PermissionDictView(APIView):
  187. permission_classes = [isLogin, ]
  188. @permission_required('account.add_user')
  189. def get(self, request):
  190. rows = Group.objects.filter()
  191. if not request.user.is_superuser:
  192. groups = request.user.groups.all()
  193. rows = rows.filter(id__in=[g.id for g in groups])
  194. serializer = GroupDictSerializer(rows, many=True)
  195. return response_ok(serializer.data)
  196. class StoreTreeView(APIView):
  197. permission_classes = [isLogin, ]
  198. @permission_required('account.manager_store')
  199. def get(self, request):
  200. id = request.GET.get('id')
  201. store_data = []
  202. # 查询当前用户的代理商和管理的门店
  203. agents = Agent.objects.filter()
  204. if not request.user.is_superuser:
  205. agents = agents.filter(id=request.user.agent_id)
  206. agents = agents.values('id', 'name')
  207. for agent in agents:
  208. item = {
  209. 'title': agent['name'],
  210. 'id': agent['id'],
  211. 'field': 'agent',
  212. 'children': [],
  213. }
  214. stores = Store.objects.filter(agent_id=agent['id'],id__in=request.user.get_manager_range(),check_user__isnull=False, enable=True).values('id', 'name')
  215. for store in stores:
  216. manage_store = ManageStoreUser.objects.filter(manage_user_id=id, store_id=store['id']).first()
  217. checked = manage_store and True or False
  218. store_item = {
  219. 'title': store['name'],
  220. 'id': store['id'],
  221. 'checked': checked,
  222. 'field': 'store_{}'.format(store['id']),
  223. }
  224. item['checked'] = checked
  225. item['children'].append(store_item)
  226. store_data.append(item)
  227. return response_ok(store_data)
  228. class EmployeeTreeView(APIView):
  229. permission_classes = [isLogin, ]
  230. def get(self, request):
  231. # 查询当前用户管理门店树形结构
  232. agent_dict = {}
  233. general_agent_dict = {}
  234. data = []
  235. exist_agents = []
  236. manage_storess = request.user.get_manager_range()
  237. for store_id in manage_storess:
  238. store = Store.objects.filter(id=store_id, enable=True).values('name','agent_id')
  239. if not store:
  240. continue
  241. store_item = {
  242. 'title': store[0]['name'],
  243. 'id': store_id,
  244. 'field': 'store',
  245. 'children': [],
  246. }
  247. employees = User.objects.filter(store_id=store_id, is_active=True).values('id', 'name')
  248. for employee in employees:
  249. user_item = {
  250. 'title': employee['name'],
  251. 'id': employee['id'],
  252. 'field': 'user',
  253. }
  254. store_item['children'].append(user_item)
  255. try:
  256. agent_dict[store[0]['agent_id']].append(store_item)
  257. except:
  258. agent_dict[store[0]['agent_id']] = [store_item]
  259. exist_agents.append(store[0]['agent_id'])
  260. ######## 代理
  261. exist_agents = list(set(exist_agents))
  262. exist_general_agents = []
  263. agents = Agent.objects.filter(id__in=exist_agents).values('id', 'name', 'general_agent_id')
  264. for agent in agents:
  265. agent_item = {
  266. 'title': agent['name'],
  267. 'id': agent['id'],
  268. 'field': 'agent',
  269. 'children': agent_dict[agent['id']] ,
  270. }
  271. if not request.user.agent:
  272. # 当前用户有代理商。此时加载和总代理平行的账号
  273. agent_users = User.objects.filter(agent__isnull=False, is_active=True, store__isnull=True)
  274. elif not request.user.store:
  275. # 当前用户有门店。此时加载和代理商平行的账号
  276. agent_users = User.objects.filter(agent_id=agent['id'], is_active=True, store__isnull=True)
  277. else:
  278. # 有门店和代理商,这是店内人员。不需要在加载任何账号
  279. agent_users = []
  280. for agent_user in agent_users:
  281. if agent_user.has_perm('customer.inner_review'):
  282. agent_user_item = {
  283. 'title': agent_user.name,
  284. 'id': agent_user.id,
  285. 'field': 'user',
  286. }
  287. agent_item['children'].insert(0,agent_user_item)
  288. try:
  289. general_agent_dict[agent['general_agent_id']].append(agent_item)
  290. except:
  291. general_agent_dict[agent['general_agent_id']] = [agent_item]
  292. exist_general_agents.append(agent['general_agent_id'])
  293. ###### 总代理
  294. exist_general_agents = list(set(exist_general_agents))
  295. general_agents = GeneralAgent.objects.filter(id__in=exist_general_agents).values('id', 'name')
  296. for general_agent in general_agents:
  297. general_agent_item = {
  298. 'title': general_agent['name'],
  299. 'id': general_agent['id'],
  300. 'field': 'general_agent',
  301. 'children': general_agent_dict[general_agent['id']],
  302. }
  303. # 当前用户没有代理商,则是总代理账号。此时加载和总代理平行的账号
  304. if not request.user.agent:
  305. general_agent_users = User.objects.filter(general_agent_id=general_agent['id'], agent__isnull=True, store__isnull=True, is_active=True)
  306. for general_agent_user in general_agent_users:
  307. if general_agent_user.has_perm('customer.inner_review'):
  308. general_agent_user_item = {
  309. 'title': general_agent_user.name,
  310. 'id': general_agent_user.id,
  311. 'field': 'user',
  312. }
  313. general_agent_item['children'].insert(0, general_agent_user_item)
  314. data.append(general_agent_item)
  315. # 总代理只有一级,去掉总代理
  316. # if len(data) == 1:
  317. # data = data[0]['children']
  318. # 代理只有一级,去掉代理
  319. # if len(data) == 1:
  320. # data = data[0]['children']
  321. return response_ok(data)