views.py 16 KB

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