Commit 50394f56 authored by zhengjinlei's avatar zhengjinlei

查询坐席

parent 413eb2d1
...@@ -5,16 +5,14 @@ from rest_framework import viewsets ...@@ -5,16 +5,14 @@ from rest_framework import viewsets
from rest_framework.decorators import action from rest_framework.decorators import action
from rest_framework.request import Request from rest_framework.request import Request
from rest_framework.response import Response from rest_framework.response import Response
from inspect_report.models import Tasks, CheckSession, RulesStat from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from config.config import TABLE_PRE from config.config import TABLE_PRE
from django.views.decorators.clickjacking import xframe_options_exempt from django.views.decorators.clickjacking import xframe_options_exempt
from inspect_report import permissions
import logging import logging
from pypinyin import Style, pinyin from pypinyin import Style, pinyin
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from functools import reduce
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -112,63 +110,6 @@ class TasksApi(viewsets.ViewSet): ...@@ -112,63 +110,6 @@ class TasksApi(viewsets.ViewSet):
# data_sort = sorted(data_sort, key=lambda x: x['count'], reverse=True) # data_sort = sorted(data_sort, key=lambda x: x['count'], reverse=True)
return Response({'code': 0, 'msg': 'success', 'data': data_sort}) return Response({'code': 0, 'msg': 'success', 'data': data_sort})
@action(['post'], detail=False)
def rule_bak(self, req: Request):
"""
获取违规项分析
:param req:
:return:
"""
task_id = req.data.get('task', '')
agent_name = req.data.get('agentName', '')
start_date = req.data.get('start_date', (datetime.now()+timedelta(days=-1)).strftime('%Y-%m-%d'))
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
if task_id:
task_condition['name__startswith'] = task_id
tasks = Tasks.objects.filter(**task_condition).values('id', 'sessionCollectionId')
task_dict = {}
for t in tasks:
if t['sessionCollectionId'] in task_dict.keys():
task_dict[t['sessionCollectionId']].append(t['id'])
else:
task_dict[t['sessionCollectionId']] = [t['id'], ]
return_data = {}
for k, v in task_dict.items():
# session_collection = t.sessionCollectionId
table_name = TABLE_PRE + k
tn = CheckSession.set_table(table_name)
session_condition = {'taskId__in': v}
if agent_name:
session_condition['agentName'] = agent_name
checks = tn.objects.filter(**session_condition).values('id', 'checkResult', 'agentName', 'customName',
'remainTime', 'score', 'sessionId', 'taskId')
# checks = tn.objects.filter(**session_condition).values('id', 'checkResult')
for check in checks:
result = check['checkResult']
detail = {'agentName': check['agentName'], 'customName': check['customName'],
'remainTime': check['remainTime'], 'score': check['score'], 'sessionId': check['sessionId'],
'sessionCollectionId': k, 'taskId': check['taskId']}
# session_id = check['id']
if result:
data = json.loads(result)
for d in data:
if 'isViolation' in d.keys() and d['isViolation'] and 'rule' in d.keys() and 'name' in d['rule'].keys():
name = d['rule']['name']
if name in return_data.keys():
return_data[name]['count'] += 1
return_data[name]['details'].append(detail)
# return_data[name]['ids'].append(session_id)
else:
return_data[name] = {'count': 1, 'details': [detail, ]}
# return_data[name] = {'count': 1, 'ids': [session_id, ]}
data_sort = []
for k, v in return_data.items():
v['rule'] = k
data_sort.append(v)
data_sort = sorted(data_sort, key=lambda x: x['count'], reverse=True)
return Response({'code': 0, 'msg': 'success', 'data': data_sort})
@action(['post'], detail=False) @action(['post'], detail=False)
def seat_session(self, req: Request): def seat_session(self, req: Request):
""" """
...@@ -259,57 +200,49 @@ class TasksApi(viewsets.ViewSet): ...@@ -259,57 +200,49 @@ class TasksApi(viewsets.ViewSet):
:return: :return:
""" """
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
a_name = req.data.get('agentName', '') agent_name = req.data.get('agentName', '')
sort = req.data.get('sort', 'des') sort = req.data.get('sort', 'des')
page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10')
start_date = req.data.get('start_date', (datetime.now()+timedelta(days=-1)).strftime('%Y-%m-%d')) start_date = req.data.get('start_date', (datetime.now()+timedelta(days=-1)).strftime('%Y-%m-%d'))
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d')) end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'} q_start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
q_end_date = (datetime.strptime(end_date, '%Y-%m-%d') + + timedelta(days=1)).date()
task_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date}
if task_id: if task_id:
task_condition['name__startswith'] = task_id task_condition['task'] = task_id
tasks = Tasks.objects.filter(**task_condition).values('id', 'sessionCollectionId') if agent_name:
task_dict = {} task_condition['agentName'] = agent_name
for t in tasks: if sort == 'des':
if t['sessionCollectionId'] in task_dict.keys(): seats = SeatStat.objects.filter(**task_condition).values('agentName', 'validate_session', 'total_session')\
task_dict[t['sessionCollectionId']].append(t['id']) .order_by('-validate_session')
else: else:
task_dict[t['sessionCollectionId']] = [t['id'], ] seats = SeatStat.objects.filter(**task_condition).values('agentName', 'validate_session', 'total_session') \
return_data = {} .order_by('validate_session')
for k, v in task_dict.items(): paginator = Paginator(seats, page_size)
table_name = TABLE_PRE + k total_count = paginator.count
tn = CheckSession.set_table(table_name) try:
session_condition = {'taskId__in': v} seats = paginator.page(page)
if a_name: except PageNotAnInteger:
session_condition['agentName'] = a_name seats = paginator.page(1)
checks = tn.objects.filter(**session_condition).values('agentName', 'violationRuleCount') except EmptyPage:
for check in checks: seats = paginator.page(paginator.num_pages)
agent_name = check['agentName'] return_data = []
if agent_name: for s in seats:
if agent_name in return_data.keys(): detail = {'agentName': s['agentName'], 'validate_session': s['validate_session'],
return_data[agent_name]['total_session'] += 1 'total_session': s['total_session'], 'ratio': round(s['validate_session']/s['total_session'], 2)}
if check['violationRuleCount'] > 0: return_data.append(detail)
return_data[agent_name]['validate_session'] += 1
else:
if check['violationRuleCount'] > 0:
return_data[agent_name] = {'total_session': 1, 'validate_session': 1}
else:
return_data[agent_name] = {'total_session': 1, 'validate_session': 0}
# data_max = sorted(return_data.items(), key=lambda item: item[1], reverse=False)
pre_data_sort = []
for k, v in return_data.items():
ratio = round(v['validate_session']/v['total_session'], 2)
v['ratio'] = ratio
v['agentName'] = k
pre_data_sort.append(v)
if sort == 'asc': if sort == 'asc':
data_sort = sorted(pre_data_sort, key=lambda x: x['ratio']) data_sort = sorted(return_data, key=lambda x: x['ratio'])
for i in range(len(data_sort)): for i in range(len(data_sort)):
data_sort[i]['ranking'] = len(data_sort) - i data_sort[i]['ranking'] = total_count - (int(page)-1)*int(page_size) - i
data_sort[i]['ratio'] = '{0}%'.format(int(data_sort[i]['ratio'] * 100))
else: else:
data_sort = sorted(pre_data_sort, key=lambda x: x['ratio'], reverse=True) data_sort = sorted(return_data, key=lambda x: x['ratio'], reverse=True)
for i in range(len(data_sort)): for i in range(len(data_sort)):
data_sort[i]['ranking'] = i + 1 data_sort[i]['ranking'] = (int(page)-1)*int(page_size) + i + 1
data_sort[i]['ratio'] = '{0}%'.format(int(data_sort[i]['ratio'] * 100)) data_sort[i]['ratio'] = '{0}%'.format(int(data_sort[i]['ratio'] * 100))
return Response({'code': 0, 'msg': 'success', 'data': data_sort}) return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': data_sort})
@action(['post'], detail=False) @action(['post'], detail=False)
def static(self, req: Request): def static(self, req: Request):
......
# coding: utf-8 # coding: utf-8
from rest_framework.request import Request from rest_framework.request import Request
from datetime import datetime, timedelta from datetime import datetime, timedelta
from inspect_report.models import Tasks, CheckSession, RulesStat from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat
from config.config import TABLE_PRE from config.config import TABLE_PRE
import json import json
import logging import logging
...@@ -49,3 +49,36 @@ def rule_stat(start_date, end_date): ...@@ -49,3 +49,36 @@ def rule_stat(start_date, end_date):
rd.save() rd.save()
stat_count += 1 stat_count += 1
logger.info('统计数量为:%s' % stat_count) logger.info('统计数量为:%s' % stat_count)
def seat_stat(start_date, end_date):
"""
首页概述-违规项统计
:return:
"""
task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date}
tasks = Tasks.objects.filter(**task_condition).values('id', 'name', 'sessionCollectionId')
for t in tasks:
table_name = TABLE_PRE + t['sessionCollectionId']
tn = CheckSession.set_table(table_name)
session_condition = {'taskId': t['id']}
checks = tn.objects.filter(**session_condition).values('id', 'agentName', 'taskId', 'violationRuleCount')
for check in checks:
seat_condition = {'create_date': start_date, 'agentName': check['agentName']}
seats = SeatStat.objects.filter(**seat_condition)
if seats:
seat = seats[0]
seat.total_session += 1
seat.validate_session += 1 if check['violationRuleCount'] > 0 else 0
seat.save()
else:
seat = SeatStat()
seat.create_date = start_date
seat.agentName = check['agentName']
seat.taskId = check['taskId']
seat.task = t['name'].split('_')[0]
seat.sessionCollectionId = t['sessionCollectionId']
seat.total_session = 1
seat.validate_session = 1 if check['violationRuleCount'] > 0 else 0
seat.save()
...@@ -45,6 +45,22 @@ class RulesStat(models.Model): ...@@ -45,6 +45,22 @@ class RulesStat(models.Model):
db_table = 'rules_datastat' db_table = 'rules_datastat'
class SeatStat(models.Model):
sessionCollectionId = models.CharField('所在表', null=True, max_length=32)
validate_session = models.IntegerField('违规会话数量', default=0)
total_session = models.IntegerField('会话数量', default=0)
task = models.CharField('所在地市', null=True, max_length=24)
create_date = models.DateField('统计日期', null=True)
agentName = models.CharField('坐席名称', null=True, max_length=64)
taskId = models.IntegerField('质检任务标识')
def __str__(self):
return self.agentName
class Meta:
db_table = 'seats_datastat'
class CheckSession(models.Model): class CheckSession(models.Model):
taskId = models.IntegerField('质检任务标识') taskId = models.IntegerField('质检任务标识')
sessionId = models.CharField('会话唯一标识') sessionId = models.CharField('会话唯一标识')
......
...@@ -16,7 +16,7 @@ Including another URLconf ...@@ -16,7 +16,7 @@ Including another URLconf
from django.contrib import admin from django.contrib import admin
from django.urls import path from django.urls import path
from .api.tasksapi import rule, seat, group, score, check from .api.tasksapi import rule, seat, group, score, check
from .views import stat_rules_every from .views import stat_rules_every, stat_seats_every
urlpatterns = [ urlpatterns = [
# path('admin/', admin.site.urls), # path('admin/', admin.site.urls),
...@@ -25,5 +25,6 @@ urlpatterns = [ ...@@ -25,5 +25,6 @@ urlpatterns = [
path('inspect/group/', group), path('inspect/group/', group),
path('inspect/score/', score), path('inspect/score/', score),
path('inspect/check/', check), path('inspect/check/', check),
path('inspect/stat/', stat_rules_every), path('inspect/stat/rule/', stat_rules_every),
path('inspect/stat/seat/', stat_seats_every),
] ]
from datetime import datetime, timedelta from datetime import datetime, timedelta
from .cron import rule_stat from .cron import rule_stat, seat_stat
from django.http.response import JsonResponse from django.http.response import JsonResponse
from dateutil.rrule import rrule, DAILY
# Create your views here. # Create your views here.
...@@ -8,5 +9,24 @@ def stat_rules_every(request): ...@@ -8,5 +9,24 @@ def stat_rules_every(request):
date = request.GET.get('date') date = request.GET.get('date')
start_date = datetime.strptime(date, '%Y-%m-%d') start_date = datetime.strptime(date, '%Y-%m-%d')
end_date = datetime.strptime(date + ' 23:59:59', '%Y-%m-%d %H:%M:%S') end_date = datetime.strptime(date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
rule_stat(start_date, end_date) s_date = datetime.strptime(start_date, '%Y-%m-%d')
e_date = datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
seed_dt = list(rrule(DAILY, byweekday=[0, 1, 2, 3, 4, 5, 6], dtstart=s_date, until=e_date))
for date in seed_dt:
start_date = date
end_date = datetime.strptime(date.strftime('%Y-%m-%d') + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
rule_stat(start_date, end_date)
return JsonResponse({'code': 0, 'msg': 'stat success'})
def stat_seats_every(request):
start_date = request.GET.get('start_date')
end_date = request.GET.get('end_date')
s_date = datetime.strptime(start_date, '%Y-%m-%d')
e_date = datetime.strptime(end_date + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
seed_dt = list(rrule(DAILY, byweekday=[0, 1, 2, 3, 4, 5, 6], dtstart=s_date, until=e_date))
for date in seed_dt:
start_date = date
end_date = datetime.strptime(date.strftime('%Y-%m-%d') + ' 23:59:59', '%Y-%m-%d %H:%M:%S')
seat_stat(start_date, end_date)
return JsonResponse({'code': 0, 'msg': 'stat success'}) return JsonResponse({'code': 0, 'msg': 'stat success'})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment