Browse Source

优化用户反馈模块(添加‘收藏’;实现导出)

guanhailong 2 years ago
parent
commit
6693d96994
2 changed files with 146 additions and 51 deletions
  1. 145 51
      AdminController/UserManageController.py
  2. 1 0
      Model/models.py

+ 145 - 51
AdminController/UserManageController.py

@@ -20,6 +20,7 @@ import oss2
 import simplejson
 import simplejson as json
 import requests
+import xlwt
 from django.contrib.auth.hashers import make_password, check_password  # 对密码加密模块
 from django.db import transaction
 from django.db.models import Q
@@ -64,12 +65,10 @@ class LoginView(TemplateView):
         request.encoding = 'utf-8'
         request_dict = request.POST
         language = request_dict.get('language', 'en')
-        response = ResponseObject(language,'pc')
+        response = ResponseObject(language, 'pc')
 
         return self.validates(request_dict, response)
 
-
-
     def validates(self, request_dict, response):
         username = request_dict.get('username', None)
         password = request_dict.get('password', None)
@@ -136,8 +135,6 @@ class LoginView(TemplateView):
             return response.json(tko.code)
 
 
-
-
 # 获取登录权限
 class GetPermissions(TemplateView):
     @method_decorator(csrf_exempt)  # @csrf_exempt
@@ -150,23 +147,19 @@ class GetPermissions(TemplateView):
         request_dict = request.GET
         language = request_dict.get('language', 'en')
         response = ResponseObject(language, 'pc')
-        return self.validates(request_dict,token, response)
-
+        return self.validates(request_dict, token, response)
 
-
-
-    def validates(self, request_dict,token, response):
-        tko = TokenObject(token,returntpye='pc')
+    def validates(self, request_dict, token, response):
+        tko = TokenObject(token, returntpye='pc')
         response.lang = tko.lang
         if tko.code != 0:
             return response.json(tko.code)
         userID = tko.userID
 
-
         user_qs = Device_User.objects.filter(userID=userID)
         if not user_qs.exists():
             return response.json(104)
-        #待补充逻辑
+        # 待补充逻辑
         username = user_qs[0].username
         userIconPath = user_qs[0].userIconPath.url
         if userIconPath:
@@ -175,20 +168,20 @@ class GetPermissions(TemplateView):
                 userIconUrl = SERVER_DOMAIN + 'account/getAvatar/' + userIconPath
 
         role_qs = Role.objects.filter(device_user=userID)
-        menu_qs = MenuModel.objects.filter(role__in=role_qs,menutype=2);
+        menu_qs = MenuModel.objects.filter(role__in=role_qs, menutype=2);
         perms = []
         for menu in menu_qs:
             perms.append(menu.menu_code)
-        res={
-          "code": 200,
-          "msg": "success",
-          "data": {
-            "roles": ["admin"], # 一个用户可包含多个角色如["admin","editor","XXXX"],必须返回,如小项目用不到角色权限请返回 ["admin"]
-            "ability": ["READ", "WRITE", "DELETE"], # 如果用不到rabc精细化权限可以不返回,建议返回
-            "username": username, # 用户名,必须返回
-            "avatar": userIconUrl,# 头像,必须返回
-            "perms": perms
-          }
+        res = {
+            "code": 200,
+            "msg": "success",
+            "data": {
+                "roles": ["admin"],  # 一个用户可包含多个角色如["admin","editor","XXXX"],必须返回,如小项目用不到角色权限请返回 ["admin"]
+                "ability": ["READ", "WRITE", "DELETE"],  # 如果用不到rabc精细化权限可以不返回,建议返回
+                "username": username,  # 用户名,必须返回
+                "avatar": userIconUrl,  # 头像,必须返回
+                "perms": perms
+            }
         }
         return response.json(0, res)
 
@@ -205,46 +198,45 @@ class GetList(TemplateView):
         request_dict = request.GET
         language = request_dict.get('language', 'en')
         response = ResponseObject(language, 'pc')
-        return self.validates(request_dict,token, response)
+        return self.validates(request_dict, token, response)
 
-
-    def validates(self, request_dict,token, response):
-        tko = TokenObject(token,returntpye='pc')
+    def validates(self, request_dict, token, response):
+        tko = TokenObject(token, returntpye='pc')
         response.lang = tko.lang
         if tko.code != 0:
             return response.json(tko.code)
         userID = tko.userID
 
-        role_qs =Role.objects.filter(device_user=userID)
-        menu_qs = MenuModel.objects.filter(parentId=0,role__in=role_qs,menutype=1);
+        role_qs = Role.objects.filter(device_user=userID)
+        menu_qs = MenuModel.objects.filter(parentId=0, role__in=role_qs, menutype=1);
         list = []
 
         for menu in menu_qs:
             list.append(
                 {
-                'id': menu.id,
-                'parentId': menu.parentId,
-                'path': menu.path,
-                'name': menu.name,
-                'component': menu.component,
-                'meta': {
+                    'id': menu.id,
+                    'parentId': menu.parentId,
+                    'path': menu.path,
+                    'name': menu.name,
+                    'component': menu.component,
+                    'meta': {
                         'hidden': menu.hidden,
                         'levelHidden': menu.levelHidden,
                         'title': menu.title,
                         'icon': menu.icon,
-                        'isCustomSvg':menu.isCustomSvg,
+                        'isCustomSvg': menu.isCustomSvg,
                         'noKeepAlive': menu.noKeepAlive,
-                        'noClosable':menu.noClosable,
+                        'noClosable': menu.noClosable,
                         'badge': menu.badge,
                         'tabHidden': menu.tabHidden,
                         'activeMenu': menu.activeMenu,
-                        'dot':menu.dot,
+                        'dot': menu.dot,
                         'dynamicNewTab': menu.dynamicNewTab,
                         'sort': menu.sort
                     }
                 }
             )
-        menu_qs = MenuModel.objects.filter(role__in=role_qs,menutype=1)
+        menu_qs = MenuModel.objects.filter(role__in=role_qs, menutype=1)
         menulist = []
         for objlist in list:
             menulist.append(self.menulist(menu_qs, objlist))
@@ -290,7 +282,6 @@ class GetList(TemplateView):
         return objlist
 
 
-
 class UserManagement(View):
     def get(self, request, *args, **kwargs):
         request.encoding = 'utf-8'
@@ -313,6 +304,8 @@ class UserManagement(View):
             return self.replyFeedBack(request_dict, response)
         elif operation == 'sendSysMsgToUser':
             return self.sendSysMsgToUser(request_dict, response)
+        elif operation == 'collectFeedBack':
+            return self.collectFeedBack(request_dict, response)
         else:
             tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'), returntpye='pc')
             if tko.code != 0:
@@ -338,7 +331,7 @@ class UserManagement(View):
 
     def getUserInfo(self, userID, request_dict, response):
         print('request_dict: ', request_dict)
-        username = request_dict.get('username', '').strip()   # 移除字符串头尾的空格
+        username = request_dict.get('username', '').strip()  # 移除字符串头尾的空格
         NickName = request_dict.get('NickName', '').strip()
         phone = request_dict.get('phone', '').strip()
         userEmail = request_dict.get('userEmail', '').strip()
@@ -372,7 +365,7 @@ class UserManagement(View):
             user_list = []
             for device_user in device_users:
                 role = device_user.role.first()
-                rid = role.rid if role else 1   # 不存在角色默认分配为'Users'
+                rid = role.rid if role else 1  # 不存在角色默认分配为'Users'
                 user_ex_qs = UserExModel.objects.filter(userID_id=device_user.userID).values('appBundleId')
                 app_bundle_id = user_ex_qs[0]['appBundleId'] if user_ex_qs.exists() else ''
                 user_list.append({
@@ -395,7 +388,7 @@ class UserManagement(View):
     def AddOrEditAccount(self, userID, request_dict, response):
         # 添加/编辑用户
         print('request_dict: ', request_dict)
-        username = request_dict.get('username', '').strip()   # 移除字符串头尾的空格
+        username = request_dict.get('username', '').strip()  # 移除字符串头尾的空格
         userEmail = request_dict.get('userEmail', '').strip()
         roleName = request_dict.get('role', None)
         password = request_dict.get('password', None)
@@ -430,11 +423,11 @@ class UserManagement(View):
                     device_user_role.clear()
                     role_qs = Role.objects.filter(roleName=roleName)  # 账号角色
                     device_user_qs[0].role.set(role_qs)
-            else:   # 添加用户
+            else:  # 添加用户
                 # 查询邮箱是否已注册
                 if Device_User.objects.filter(userEmail=userEmail).exists():
                     return response.json(103)
-                role_qs = Role.objects.filter(roleName=roleName)    # 账号角色
+                role_qs = Role.objects.filter(roleName=roleName)  # 账号角色
                 # 创建用户
                 user_data = {
                     "username": username,
@@ -480,6 +473,8 @@ class UserManagement(View):
     def getFeedbackList(self, request_dict, response):
         status = request_dict.get('status', 0)
         username = request_dict.get('username', None)
+        collect_status = request_dict.get('collectStatus', 0)
+        fileType = request_dict.get('fileType', None)
         pageNo = request_dict.get('pageNo', None)
         pageSize = request_dict.get('pageSize', None)
 
@@ -490,16 +485,20 @@ class UserManagement(View):
         line = int(pageSize)
         try:
             filter_data = {}
-            if status or username:
+            if status or username or collect_status or fileType:
                 if status:
                     filter_data['status'] = int(status)
                 if username:
                     filter_data['userID_id'] = ModelService.get_userID_byname(username)
+                if collect_status:
+                    filter_data['collect_status'] = int(collect_status)
+                if fileType:
+                    return self.download(status, collect_status)
             feed_back_qs = FeedBackModel.objects.filter()
             if filter_data:
                 feed_back_qs = feed_back_qs.filter(**filter_data)
             total = feed_back_qs.count()
-            feed_backs = feed_back_qs[(page - 1) * line:page * line]. values(
+            feed_backs = feed_back_qs[(page - 1) * line:page * line].values(
                 'id',
                 'userID__username',
                 'userID__phone',
@@ -555,8 +554,8 @@ class UserManagement(View):
                 return response.json(173)
             with transaction.atomic():
                 SysMsgModel.objects.create(userID_id=feed_back_qs.first().userID_id, msg=msg, uid=uid,
-                                           addTime=nowTime, updTime=nowTime)   # 创建系统消息
-                feed_back_qs.update(status=1)   # 更新状态为已回复
+                                           addTime=nowTime, updTime=nowTime)  # 创建系统消息
+                feed_back_qs.update(status=1)  # 更新状态为已回复
             return response.json(0)
         except Exception as e:
             print(e)
@@ -661,7 +660,7 @@ class UserManagement(View):
                 # 根据UserExModel表的userID群发消息给用户
                 region_list = lang.split(',')
                 appBundleId_list = recever.split(',')
-                userID_list = UserExModel.objects.filter(appBundleId__in=appBundleId_list, region__in=region_list)\
+                userID_list = UserExModel.objects.filter(appBundleId__in=appBundleId_list, region__in=region_list) \
                     .values_list('userID_id', flat=True)
                 sys_msg_list = []
                 for userID in userID_list:
@@ -675,3 +674,98 @@ class UserManagement(View):
             print(e)
             return response.json(500, repr(e))
 
+    def collectFeedBack(self, request_dict, response):
+        feedBackID = request_dict.get('feedBackID', None)
+        collect_status = request_dict.get('collectStatus', None)
+        if not all([feedBackID, collect_status]):
+            return response.json(444)
+        feedBackID = int(feedBackID)
+        collect_status = int(collect_status)
+        feed_back_qs = FeedBackModel.objects.filter(id=feedBackID, collect_status=collect_status)  # 判断是否存在
+        if feed_back_qs.exists():
+            feed_qs = feed_back_qs.first()
+            feed_qs.collect_status = 0
+            feed_qs.save()
+        else:
+            FeedBackModel.objects.filter(id=feedBackID).update(collect_status=collect_status)
+        return response.json(0)
+
+    def download(self, status, collect_status):
+        response = HttpResponse(content_type='application/vnd.ms-excel')
+        response['Content-Disposition'] = 'attachment; filename=FeedBack' + time.strftime('-%Y-%m-%d-%H-%M-%S',
+                                                                                          time.localtime()) + '.xls'
+        workbook = xlwt.Workbook(encoding='utf-8')
+        ws = workbook.add_sheet('FeedBack')
+        row_num = 0
+        font_style = xlwt.XFStyle()
+        font_style.font.bold = True
+
+        columns = ['id', 'userID__username', 'userID__phone', 'userID__userEmail', 'content', 'addTime', 'status',
+                   'type', 'app', 'app_version', 'phone_model', 'os_version', 'uid', 'appBundleId', 'score', 'img_url',
+                   'collect_status']
+
+        for col_num in range(len(columns)):
+            ws.write(row_num, col_num, columns[col_num], font_style)
+
+        font_style = xlwt.XFStyle()
+
+        filter_data = {}
+        if status or collect_status:
+            if status:
+                filter_data['status'] = int(status)
+            if collect_status:
+                filter_data['collect_status'] = int(collect_status)
+        feed_back_qs = FeedBackModel.objects.filter()
+        if filter_data:
+            feed_back_qs = feed_back_qs.filter(**filter_data)
+        # rows = Exception.objects.filter().values_list()
+        feed_backs = feed_back_qs.values(
+            'id',
+            'userID__username',
+            'userID__phone',
+            'userID__userEmail',
+            'content',
+            'addTime',
+            'status',
+            'type',
+            'app',
+            'app_version',
+            'phone_model',
+            'os_version',
+            'uid',
+            'appBundleId',
+            'score',
+            'collect_status'
+        )
+
+        feed_back_id_list = [feed_back['id'] for feed_back in feed_backs]
+        stat_res_qs = StatResModel.objects.filter(
+            feedbackmodel__id__in=feed_back_id_list).values(
+            'name', 'feedbackmodel__id')
+        auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
+        bucket = oss2.Bucket(
+            auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
+        try:
+            feed_back_list = []
+            for feed_back in feed_backs:
+                feed_back['img_url'] = []
+                for stat_res in stat_res_qs:
+                    if stat_res['feedbackmodel__id'] == feed_back['id']:
+                        obj = 'feedback/' + stat_res['name']
+                        img_url = bucket.sign_url('GET', obj, 3600)
+                        feed_back['img_url'].append(img_url)
+                        if not feed_back['userID__username']:
+                            feed_back['userID__username'] = feed_back['userID__userEmail'] if feed_back[
+                                'userID__userEmail'] else feed_back['userID__phone']
+                feed_back_list.append(feed_back)
+
+            for row in feed_back_list:
+                row_num += 1
+                row = [values for k, values in row.items()]
+
+                for col_num in range(len(row)):
+                    ws.write(row_num, col_num, str(row[col_num]), font_style)
+            workbook.save(response)
+            return response
+        except Exception as e:
+            print(e)

+ 1 - 0
Model/models.py

@@ -646,6 +646,7 @@ class FeedBackModel(models.Model):
     appBundleId = models.CharField(max_length=32, default='', verbose_name='app版本appBundleId')
     email = models.CharField(max_length=32, default='', verbose_name='app版本email')
     score = models.CharField(max_length=32, default='0', verbose_name='评分--星星数')
+    collect_status = models.SmallIntegerField(default=0, verbose_name='收藏[0:未收藏, 1:已收藏]')
 
     def __str__(self):
         return self.id