Commit 2147ea60 authored by lvshibao's avatar lvshibao

group页面修改,model的添加

parent 93ddb338
...@@ -10,9 +10,9 @@ init: ## 初始化python环境,并加载测试数据 ...@@ -10,9 +10,9 @@ init: ## 初始化python环境,并加载测试数据
stop: ## 停止 make prd/ make run 启动的服务 stop: ## 停止 make prd/ make run 启动的服务
-lsof -i:8099 | awk 'NR==2{print $$2}' | xargs kill -lsof -i:8099 | awk 'NR==2{print $$2}' | xargs kill
run: stop ## 运行后端服务(front) run: stop ## 运行后端服务(front)
env/bin/python3 src/manage.py runserver 8099 export DEBUG=True && env/bin/python3 src/manage.py runserver 8099
prd: stop ## 生产环境运行(backend) prd: stop ## 生产环境运行(backend)
nohup env/bin/python3 src/manage.py runserver 8099 2>&1 & nohup env/bin/python3 src/manage.py runserver 8099 2>&1 &
......
import json # import json
import logging import logging
import os
import requests import requests
from requests.cookies import RequestsCookieJar from requests.cookies import RequestsCookieJar
from functools import wraps # from functools import wraps
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 config.config import USER_INFO_URL from config.config import USER_INFO_URL
...@@ -26,14 +27,13 @@ def transfer_cookie(cookies): ...@@ -26,14 +27,13 @@ def transfer_cookie(cookies):
return cookie_jar return cookie_jar
def get_account_info(func): def get_account_info(req):
""" """
装饰器,对请求进行权限验证 获取用户的账户信息
:param func: :param req:
:return: :return:
""" """
@wraps(func) if not (os.environ.get('DEBUG', False) == "True"):
def account_info(obj, req: Request, *args, **kw):
# logger.info('req中的data为: ' + json.dumps(req.COOKIES)) # logger.info('req中的data为: ' + json.dumps(req.COOKIES))
cookie_jar = transfer_cookie(req.COOKIES) cookie_jar = transfer_cookie(req.COOKIES)
info = requests.get(USER_INFO_URL, cookies=cookie_jar) info = requests.get(USER_INFO_URL, cookies=cookie_jar)
...@@ -42,12 +42,11 @@ def get_account_info(func): ...@@ -42,12 +42,11 @@ def get_account_info(func):
if info.json()['code'] != 200: if info.json()['code'] != 200:
logger.info('未能获取用户信息: ' + info.text) logger.info('未能获取用户信息: ' + info.text)
return Response({'code': -1, 'msg': '未能获取用户信息'}) return Response({'code': -1, 'msg': '未能获取用户信息'})
except Exception: except RuntimeError:
logger.info('未能获取用户信息: ' + info.text) logger.exception('未能获取用户信息: ' + info.text)
return Response({'code': -1, 'msg': '未能获取用户信息'}) return Response({'code': -1, 'msg': '未能获取用户信息'})
req.data['username'] = info.json()['data']['userInfo']['name'] req.data['username'] = info.json()['data']['userInfo']['name']
return func(obj, req, *args, **kw) return req
return req
return account_info
# get_account_info() # get_account_info()
from datetime import datetime, timedelta
from functools import wraps
from rest_framework.request import Request
from account import get_account_info
from config.config import name_list
def before_request(func):
"""
对请求参数进行集中处理
:param func:
:return:
"""
@wraps(func)
def request_to_session_condition(obj, req: Request, *args, **kw):
req = get_account_info(req)
if req.method == "GET":
start_date = req.GET.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d'))
end_date = req.GET.get('end_date', datetime.now().strftime('%Y-%m-%d'))
else:
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'))
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()
date_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date}
at_condition = {'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
req.data['date_condition'] = date_condition
req.data['at_condition'] = at_condition
return func(obj, req, *args, **kw)
return request_to_session_condition
...@@ -3,3 +3,4 @@ ...@@ -3,3 +3,4 @@
from .toolapi import ToolsApi from .toolapi import ToolsApi
from .tasksapi import TasksApi from .tasksapi import TasksApi
from .dataapi import DataApi from .dataapi import DataApi
from .agencyapi import AgencyApi
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
from before_request import before_request
from inspect_report.models import Country, Team
class AgencyApi(viewsets.ViewSet):
authentication_classes = ()
permission_classes = ()
# permission_classes = (permissions.ValidateToken, )
@action(['get'], detail=False)
@before_request
def city(self, req: Request):
"""
加载城市列表
:param req:
:return:
"""
username = req.data.get('username', '')
city_list = list()
country_list = list()
top = Country.objects.filter(name=username).first()
if top is not None:
if top.parent is None:
cities = Country.objects.filter(parent=top.id).all()
else:
cities = None
city_id = top.id
else:
top = Country.objects.filter(parent=None).first()
cities = Country.objects.filter(parent=top.id).all()
city_id = top.id
if cities is not None:
city_list.append({'id': top.id, 'name': top.name})
for city in cities:
city_list.append({'id': city.id, 'name': city.name})
else:
city_list.append({'id': top.id, 'name': top.name})
countries = Country.objects.filter(parent=top.id).all()
country_id_list = list()
if len(countries) > 0:
for country in countries:
print(country.name)
if len(Team.objects.filter(country=country.id).all()) > 0:
country_list.append({'id': country.id, 'name': country.name})
country_id_list.append(country.id)
return_data = {'city_list': city_list, 'country_list': country_list, 'city_id': city_id}
return Response({'code': 0, 'msg': 'success', 'data': return_data})
@action(['get'], detail=False)
def country(self, req: Request):
"""
查询任务列表
:param req:
:return:
"""
city_id = req.GET.get('city_id', '')
country_list = list()
top = Country.objects.filter(id=city_id).first()
if top is not None:
if top.parent is None:
pass
else:
countries = Country.objects.filter(parent=city_id).all()
for country in countries:
country_list.append({'id': country.id, 'name': country.name})
return Response({'code': 0, 'msg': 'success', 'data': {'country_list': country_list}})
else:
return Response({'code': -1, 'msg': '未找到对应的县市'})
...@@ -3,6 +3,8 @@ from django.db.models import Count, Sum, Avg ...@@ -3,6 +3,8 @@ from django.db.models import Count, Sum, Avg
from rest_framework import viewsets 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 before_request import before_request
from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat, ScoreStat, Round from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat, ScoreStat, Round
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
...@@ -14,8 +16,6 @@ import csv ...@@ -14,8 +16,6 @@ import csv
import codecs import codecs
from django.utils.http import urlquote from django.utils.http import urlquote
from inspect_report.utils.account import get_account_info
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -24,7 +24,7 @@ class DataApi(viewsets.ViewSet): ...@@ -24,7 +24,7 @@ class DataApi(viewsets.ViewSet):
permission_classes = () permission_classes = ()
@action(['get'], detail=False) @action(['get'], detail=False)
@get_account_info @before_request
def static_score_export(self, req: Request): def static_score_export(self, req: Request):
""" """
概览-地市得分统计-导出 概览-地市得分统计-导出
...@@ -34,11 +34,7 @@ class DataApi(viewsets.ViewSet): ...@@ -34,11 +34,7 @@ class DataApi(viewsets.ViewSet):
username = req.data.get('username', '') username = req.data.get('username', '')
task_id = req.GET.get('task', '') task_id = req.GET.get('task', '')
sort = req.GET.get('sort', '-avg_score') sort = req.GET.get('sort', '-avg_score')
start_date = req.GET.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('date_condition', {})
end_date = req.GET.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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['task'] = task_id task_condition['task'] = task_id
if username in name_list: if username in name_list:
......
# coding: utf-8 # coding: utf-8
from django.shortcuts import render from django.shortcuts import render
from django.db.models import Count, Sum, Avg from django.db.models import Count, Sum, Avg, Q
from rest_framework import viewsets 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, SeatStat, ScoreStat, Round
from before_request import before_request
from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat, ScoreStat, Round, Team, Country
import json import json
from datetime import datetime, timedelta from datetime import datetime, timedelta
from config.config import TABLE_PRE, name_list, name_code_dict from config.config import TABLE_PRE, name_list, name_code_dict
...@@ -14,29 +16,28 @@ import logging ...@@ -14,29 +16,28 @@ 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 inspect_report.utils.account import get_account_info
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class TasksApi(viewsets.ViewSet): class TasksApi(viewsets.ViewSet):
authentication_classes = () authentication_classes = ()
permission_classes = () permission_classes = ()
# permission_classes = (permissions.ValidateToken, ) # permission_classes = (permissions.ValidateToken, )
@action(['get'], detail=False) # @action(['get'], detail=False)
def obtain(self, req: Request): # def obtain(self, req: Request):
""" # """
查询任务列表 # 查询任务列表
:param req: # :param req:
:return: # :return:
""" # """
tasks = Tasks.objects.all().order_by('-createdAt').values('id', 'name') # tasks = Tasks.objects.all().order_by('-createdAt').values('id', 'name')
# return render(req, 'inspect/index.html', {'tasks': tasks}) # # return render(req, 'inspect/index.html', {'tasks': tasks})
return Response({'code': 0, 'msg': 'success', 'data': tasks}) # return Response({'code': 0, 'msg': 'success', 'data': tasks})
@action(['get'], detail=False) @action(['get'], detail=False)
@get_account_info @before_request
def seat(self, req: Request): def seat(self, req: Request):
""" """
获取坐席列表 获取坐席列表
...@@ -45,11 +46,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -45,11 +46,7 @@ class TasksApi(viewsets.ViewSet):
""" """
username = req.data.get('username', '') username = req.data.get('username', '')
task_id = req.GET.get('task', '') task_id = req.GET.get('task', '')
start_date = req.GET.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) session_condition = req.data.get('date_condition', {})
end_date = req.GET.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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()
session_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date}
if task_id: if task_id:
session_condition['task'] = task_id session_condition['task'] = task_id
if username in name_list: if username in name_list:
...@@ -70,7 +67,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -70,7 +67,7 @@ class TasksApi(viewsets.ViewSet):
""" """
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
agent_name = req.data.get('agentName', '') agent_name = req.data.get('agentName', '')
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'))
q_start_date = datetime.strptime(start_date, '%Y-%m-%d').date() 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() q_end_date = (datetime.strptime(end_date, '%Y-%m-%d') + + timedelta(days=1)).date()
...@@ -109,7 +106,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -109,7 +106,7 @@ class TasksApi(viewsets.ViewSet):
""" """
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
num = req.data.get('num', '10') num = req.data.get('num', '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'} task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
if task_id: if task_id:
...@@ -150,7 +147,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -150,7 +147,7 @@ class TasksApi(viewsets.ViewSet):
""" """
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
num = req.data.get('num', '10') num = req.data.get('num', '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'} task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
if task_id: if task_id:
...@@ -183,7 +180,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -183,7 +180,7 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'data': data_max_return}) return Response({'code': 0, 'msg': 'success', 'data': data_max_return})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def seat_rule(self, req: Request): def seat_rule(self, req: Request):
""" """
坐席违规分析-按照得分 坐席违规分析-按照得分
...@@ -196,11 +193,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -196,11 +193,7 @@ class TasksApi(viewsets.ViewSet):
sort = req.data.get('sort', 'des') sort = req.data.get('sort', 'des')
page = req.data.get('page', '1') page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10') page_size = req.data.get('page_size', '10')
start_date = req.data.get('start_date', (datetime.now()+timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('date_condition', {})
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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['task'] = task_id task_condition['task'] = task_id
if username in name_list: if username in name_list:
...@@ -228,22 +221,22 @@ class TasksApi(viewsets.ViewSet): ...@@ -228,22 +221,22 @@ class TasksApi(viewsets.ViewSet):
for s in seats: for s in seats:
detail = {'agentName': s['agentName'], 'validate_session': s['validate_session'], detail = {'agentName': s['agentName'], 'validate_session': s['validate_session'],
'remainTime': s['remainTime'], 'total_session': s['total_session'], 'remainTime': s['remainTime'], 'total_session': s['total_session'],
'ratio': round(s['validate_session']/s['total_session'], 2)} 'ratio': round(s['validate_session'] / s['total_session'], 2)}
return_data.append(detail) return_data.append(detail)
if sort == 'asc': if sort == 'asc':
data_sort = sorted(return_data, 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'] = total_count - (int(page)-1)*int(page_size) - 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)) data_sort[i]['ratio'] = '{0}%'.format(int(data_sort[i]['ratio'] * 100))
else: else:
data_sort = sorted(return_data, 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'] = (int(page)-1)*int(page_size) + 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', 'count': total_count, 'data': data_sort, 'username': username}) return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': data_sort, 'username': username})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def static(self, req: Request): def static(self, req: Request):
""" """
获取违规项分析 获取违规项分析
...@@ -253,11 +246,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -253,11 +246,7 @@ class TasksApi(viewsets.ViewSet):
username = req.data.get('username', '') username = req.data.get('username', '')
# logger.info('username获取: ' + username) # logger.info('username获取: ' + username)
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
start_date = req.data.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) session_condition = req.data.get('date_condition', {})
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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()
session_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date}
if task_id: if task_id:
session_condition['task'] = task_id session_condition['task'] = task_id
if username in name_list: if username in name_list:
...@@ -268,7 +257,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -268,7 +257,7 @@ class TasksApi(viewsets.ViewSet):
return_data = {'validate_session': seat_data['validate_session_sum'], return_data = {'validate_session': seat_data['validate_session_sum'],
'total_session': seat_data['total_session_sum']} 'total_session': seat_data['total_session_sum']}
if seat_data['total_session_sum']: if seat_data['total_session_sum']:
return_data['ratio'] = round(seat_data['validate_session_sum']/seat_data['total_session_sum'], 2) return_data['ratio'] = round(seat_data['validate_session_sum'] / seat_data['total_session_sum'], 2)
return_data['avg_score'] = avg_score['score_avg'] return_data['avg_score'] = avg_score['score_avg']
else: else:
return_data['ratio'] = 0.0 return_data['ratio'] = 0.0
...@@ -316,7 +305,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -316,7 +305,7 @@ class TasksApi(viewsets.ViewSet):
for k, v in return_data.items(): for k, v in return_data.items():
# return_data[k]['ratio'] = round(v['validate_session']/v['total_session'], 2) # return_data[k]['ratio'] = round(v['validate_session']/v['total_session'], 2)
if v['total_session']: if v['total_session']:
v['ratio'] = round(v['validate_session']/v['total_session'], 2) v['ratio'] = round(v['validate_session'] / v['total_session'], 2)
else: else:
v['ratio'] = 0 v['ratio'] = 0
v['date'] = k v['date'] = k
...@@ -325,7 +314,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -325,7 +314,7 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'data': data_sort}) return Response({'code': 0, 'msg': 'success', 'data': data_sort})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def seat_check(self, req: Request): def seat_check(self, req: Request):
""" """
坐席绩效考核汇总 坐席绩效考核汇总
...@@ -337,9 +326,8 @@ class TasksApi(viewsets.ViewSet): ...@@ -337,9 +326,8 @@ class TasksApi(viewsets.ViewSet):
agent_name = req.data.get('agentName', '') agent_name = req.data.get('agentName', '')
page = req.data.get('page', '1') page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10') page_size = req.data.get('page_size', '10')
start_date = req.data.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('at_condition', {})
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d')) task_condition['hasCheck'] = 1
task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
if task_id: if task_id:
task_condition['name__startswith'] = task_id task_condition['name__startswith'] = task_id
if username in name_list: if username in name_list:
...@@ -413,7 +401,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -413,7 +401,7 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': return_data}) return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': return_data})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def seat_area(self, req: Request): def seat_area(self, req: Request):
""" """
地市坐席成绩分析 地市坐席成绩分析
...@@ -426,11 +414,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -426,11 +414,7 @@ class TasksApi(viewsets.ViewSet):
page = req.data.get('page', '1') page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10') page_size = req.data.get('page_size', '10')
sort = req.data.get('sort', '-avg_score') sort = req.data.get('sort', '-avg_score')
start_date = req.data.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('date_condition', '')
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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['task'] = task_id task_condition['task'] = task_id
if username in name_list: if username in name_list:
...@@ -438,11 +422,11 @@ class TasksApi(viewsets.ViewSet): ...@@ -438,11 +422,11 @@ class TasksApi(viewsets.ViewSet):
if agent_name: if agent_name:
task_condition['agentName'] = agent_name task_condition['agentName'] = agent_name
# , 'total_session', 'validate_num', 'validate_session', 'validate_zero' # , 'total_session', 'validate_num', 'validate_session', 'validate_zero'
rules = ScoreStat.objects.filter(**task_condition).extra(select={'area': "task", 'agentName': 'agentName'})\ rules = ScoreStat.objects.filter(**task_condition).extra(select={'area': "task", 'agentName': 'agentName'}) \
.values('area', 'agentName').annotate(avg_score_svc=Round(Avg('service_score'), 2), .values('area', 'agentName').annotate(avg_score_svc=Round(Avg('service_score'), 2),
avg_score_bus=Round(Avg('business_score'), 2), avg_score_bus=Round(Avg('business_score'), 2),
avg_score=Round(Avg('score'), 2), total_session=Sum('total_session'), avg_score=Round(Avg('score'), 2), total_session=Sum('total_session'),
validate_num=Sum('validate_num'), validate_zero=Sum('validate_zero'))\ validate_num=Sum('validate_num'), validate_zero=Sum('validate_zero')) \
.order_by(sort) .order_by(sort)
paginator = Paginator(rules, page_size) paginator = Paginator(rules, page_size)
total_count = paginator.count total_count = paginator.count
...@@ -456,7 +440,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -456,7 +440,7 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list}) return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def static_rule(self, req: Request): def static_rule(self, req: Request):
""" """
首页概述-违规项统计 首页概述-违规项统计
...@@ -465,9 +449,8 @@ class TasksApi(viewsets.ViewSet): ...@@ -465,9 +449,8 @@ class TasksApi(viewsets.ViewSet):
""" """
username = req.data.get('username', '') username = req.data.get('username', '')
task_id = req.data.get('task', '') task_id = req.data.get('task', '')
start_date = req.data.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('at_condition', {})
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d')) task_condition['hasCheck'] = 1
task_condition = {'hasCheck': 1, 'createdAt__gte': start_date, 'createdAt__lt': end_date + ' 23:59:59'}
if task_id: if task_id:
task_condition['name__startswith'] = task_id task_condition['name__startswith'] = task_id
if username in name_list: if username in name_list:
...@@ -488,16 +471,14 @@ class TasksApi(viewsets.ViewSet): ...@@ -488,16 +471,14 @@ class TasksApi(viewsets.ViewSet):
validate_all = tn.objects.filter(**session_condition).aggregate(Count("id")) validate_all = tn.objects.filter(**session_condition).aggregate(Count("id"))
call_count += validate_all['id__count'] call_count += validate_all['id__count']
q_start_date = datetime.strptime(start_date, '%Y-%m-%d').date() task_condition = req.data.get('date_condition', {})
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['task'] = task_id task_condition['task'] = task_id
elif username: elif username:
task_condition['task'] = username task_condition['task'] = username
# tasks = RulesStat.objects.filter(**task_condition).values('rule', 'sessionCollectionId', 'rule_num') # tasks = RulesStat.objects.filter(**task_condition).values('rule', 'sessionCollectionId', 'rule_num')
tasks = RulesStat.objects.all().filter(**task_condition)\ tasks = RulesStat.objects.all().filter(**task_condition) \
.extra(select={'rule': "rule", 'sessionCollectionId': 'sessionCollectionId'})\ .extra(select={'rule': "rule", 'sessionCollectionId': 'sessionCollectionId'}) \
.values('rule', 'sessionCollectionId').annotate(rule_num=Count('id')).order_by('-rule_num') .values('rule', 'sessionCollectionId').annotate(rule_num=Count('id')).order_by('-rule_num')
for t in tasks: for t in tasks:
name = t['rule'] name = t['rule']
...@@ -510,7 +491,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -510,7 +491,7 @@ class TasksApi(viewsets.ViewSet):
data_sort = [] data_sort = []
for k, v in return_data.items(): for k, v in return_data.items():
v['rule'] = k v['rule'] = k
v['ratio'] = round(v['count']/call_count, 2) if call_count else 0 v['ratio'] = round(v['count'] / call_count, 2) if call_count else 0
v['ratio'] = '{0}%'.format(int(v['ratio'] * 100)) v['ratio'] = '{0}%'.format(int(v['ratio'] * 100))
v['call_count'] = call_count v['call_count'] = call_count
data_sort.append(v) data_sort.append(v)
...@@ -518,7 +499,7 @@ class TasksApi(viewsets.ViewSet): ...@@ -518,7 +499,7 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'data': data_sort, 'username': username}) return Response({'code': 0, 'msg': 'success', 'data': data_sort, 'username': username})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def rule_detail(self, req: Request): def rule_detail(self, req: Request):
""" """
首页概述-违规项统计 首页概述-违规项统计
...@@ -530,16 +511,13 @@ class TasksApi(viewsets.ViewSet): ...@@ -530,16 +511,13 @@ class TasksApi(viewsets.ViewSet):
rule_name = req.data.get('rule', '') rule_name = req.data.get('rule', '')
page = req.data.get('page', '1') page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10') page_size = req.data.get('page_size', '10')
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'))
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()
if not isinstance(tables, list): if not isinstance(tables, list):
table_list = json.loads(tables) table_list = json.loads(tables)
else: else:
table_list = tables table_list = tables
session_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date, 'rule': rule_name, session_condition = req.data.get('date_condition', {})
'sessionCollectionId__in': table_list} session_condition['rule'] = rule_name
session_condition['sessionCollectionId__in'] = table_list
if username in name_list: if username in name_list:
session_condition['agentName__contains'] = name_code_dict[username] session_condition['agentName__contains'] = name_code_dict[username]
checks = RulesStat.objects.filter(**session_condition).values('agentName', 'customName', 'remainTime', 'score', checks = RulesStat.objects.filter(**session_condition).values('agentName', 'customName', 'remainTime', 'score',
...@@ -555,27 +533,34 @@ class TasksApi(viewsets.ViewSet): ...@@ -555,27 +533,34 @@ class TasksApi(viewsets.ViewSet):
return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list}) return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list})
@action(['post'], detail=False) @action(['post'], detail=False)
@get_account_info @before_request
def static_score(self, req: Request): def static_score(self, req: Request):
""" """
概览-地市得分统计 概览-地市得分统计
:param req: :param req:
:return: :return:
""" """
username = req.data.get('username', '') city_id = req.data.get('city', '')
task_id = req.data.get('task', '') country_id = req.data.get('country', '')
page = req.data.get('page', '1') page = req.data.get('page', '1')
page_size = req.data.get('page_size', '10') page_size = req.data.get('page_size', '10')
sort = req.data.get('sort', '-avg_score') sort = req.data.get('sort', '-avg_score')
start_date = req.data.get('start_date', (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')) task_condition = req.data.get('date_condition', {})
end_date = req.data.get('end_date', datetime.now().strftime('%Y-%m-%d'))
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() team_names = list()
task_condition = {'create_date__gte': q_start_date, 'create_date__lt': q_end_date} if city_id and country_id:
if task_id: team_names = Team.objects.filter(country_id=country_id).values_list('name')
task_condition['task'] = task_id elif city_id and country_id == '':
if username in name_list: city = Country.objects.filter(id=city_id).first()
task_condition['task'] = username if city.parent is None:
team_names = Team.objects.filter().values_list('name')
else:
country_id_list = Country.objects.filter(Q(parent=city_id) | Q(id=city_id)).values_list('id')
team_names = Team.objects.filter(country_id__in=country_id_list).values_list('name')
task_condition['task__in'] = team_names
rules = ScoreStat.objects.filter(**task_condition).extra(select={'area': "task"}) \ rules = ScoreStat.objects.filter(**task_condition).extra(select={'area': "task"}) \
.values('area').annotate(avg_score_svc=Round(Avg('service_score'), 2), .values('area').annotate(avg_score_svc=Round(Avg('service_score'), 2),
avg_score_bus=Round(Avg('business_score'), 2), avg_score_bus=Round(Avg('business_score'), 2),
...@@ -591,7 +576,8 @@ class TasksApi(viewsets.ViewSet): ...@@ -591,7 +576,8 @@ class TasksApi(viewsets.ViewSet):
except EmptyPage: except EmptyPage:
seats = paginator.page(paginator.num_pages) seats = paginator.page(paginator.num_pages)
return Response({'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list, 'username': username}) return Response(
{'code': 0, 'msg': 'success', 'count': total_count, 'data': seats.object_list})
@action(['post'], detail=False) @action(['post'], detail=False)
def score_detail(self, req: Request): def score_detail(self, req: Request):
...@@ -615,9 +601,9 @@ class TasksApi(viewsets.ViewSet): ...@@ -615,9 +601,9 @@ class TasksApi(viewsets.ViewSet):
if area: if area:
session_condition['task'] = area session_condition['task'] = area
checks = RulesStat.objects.filter(**session_condition)\ checks = RulesStat.objects.filter(**session_condition) \
.extra(select={'sessionCollectionId': 'sessionCollectionId'})\ .extra(select={'sessionCollectionId': 'sessionCollectionId'}) \
.values('agentName', 'customName', 'remainTime', 'score', 'sessionCollectionId', 'sessionId', 'taskId')\ .values('agentName', 'customName', 'remainTime', 'score', 'sessionCollectionId', 'sessionId', 'taskId') \
.distinct() .distinct()
paginator = Paginator(checks, page_size) paginator = Paginator(checks, page_size)
total_count = paginator.count total_count = paginator.count
......
# coding: utf-8 # coding: utf-8
from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat, ScoreStat from inspect_report.models import Tasks, CheckSession, RulesStat, SeatStat, ScoreStat, Team, Seat
from config.config import TABLE_PRE from config.config import TABLE_PRE
import json import json
import logging import logging
import kronos import kronos
from datetime import datetime, timedelta from datetime import datetime, timedelta
"""定时任务 """定时任务
参考:https://github.com/jgorset/django-kronos 参考:https://github.com/jgorset/django-kronos
...@@ -15,12 +16,21 @@ score_item_service = {'服务用语': 15, '开场白': 5, '结束语': 3, '服 ...@@ -15,12 +16,21 @@ score_item_service = {'服务用语': 15, '开场白': 5, '结束语': 3, '服
score_item_business = {'异议处理': 10, '业务促成': 10, '预约及流转': 10, '服务介绍': 10, '未提供报价': 2, '成功件信息核实': 20} score_item_business = {'异议处理': 10, '业务促成': 10, '预约及流转': 10, '服务介绍': 10, '未提供报价': 2, '成功件信息核实': 20}
def team_seat():
teams = Team.objects.values_list('id', 'name')
team_id_name = {team[0]: team[1] for team in teams}
seats = Seat.objects.values_list('code', 'team_id')
seat_code_team_name = {seat[0]: team_id_name[seat[1]] for seat in seats}
return seat_code_team_name
@kronos.register('30 1,8,12 * * *') @kronos.register('30 1,8,12 * * *')
def rule_stat(start_date=None, end_date=None): def rule_stat(start_date=None, end_date=None):
""" """
首页概述-违规项统计 首页概述-违规项统计
:return: :return:
""" """
seat_code_team_name = team_seat()
if not start_date and not end_date: if not start_date and not end_date:
start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d') start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')
end_date = datetime.now().strftime('%Y-%m-%d') end_date = datetime.now().strftime('%Y-%m-%d')
...@@ -48,10 +58,12 @@ def rule_stat(start_date=None, end_date=None): ...@@ -48,10 +58,12 @@ def rule_stat(start_date=None, end_date=None):
start = datetime.strptime(check['startTime'], '%Y-%m-%d %H:%M:%S').timestamp() start = datetime.strptime(check['startTime'], '%Y-%m-%d %H:%M:%S').timestamp()
close = datetime.strptime(check['closeTime'], '%Y-%m-%d %H:%M:%S').timestamp() close = datetime.strptime(check['closeTime'], '%Y-%m-%d %H:%M:%S').timestamp()
remain = int(close - start) remain = int(close - start)
if 'isViolation' in d.keys() and d['isViolation'] and 'rule' in d.keys() and 'name' in d['rule'].keys(): if 'isViolation' in d.keys() and d['isViolation'] and 'rule' in d.keys() and 'name' in d[
'rule'].keys():
name = d['rule']['name'] name = d['rule']['name']
rule_obj = {'create_date': start_date, 'sessionCollectionId': t['sessionCollectionId'], rule_obj = {'create_date': start_date, 'sessionCollectionId': t['sessionCollectionId'],
'rule': name, 'rule_num': 1, 'task': t['name'].split('_')[0], 'rule': name, 'rule_num': 1,
'task': seat_code_team_name.get(check['agentName'], '未找到团队'),
'agentName': check['agentName'], 'customName': check['customName'], 'agentName': check['agentName'], 'customName': check['customName'],
'score': check['score'], 'remainTime': remain, 'score': check['score'], 'remainTime': remain,
'taskId': check['taskId'], 'sessionId': check['sessionId'], 'taskId': check['taskId'], 'sessionId': check['sessionId'],
...@@ -70,6 +82,7 @@ def seat_stat(start_date=None, end_date=None): ...@@ -70,6 +82,7 @@ def seat_stat(start_date=None, end_date=None):
首页概述-违规坐席统计 首页概述-违规坐席统计
:return: :return:
""" """
seat_code_team_name = team_seat()
if not start_date and not end_date: if not start_date and not end_date:
start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d') start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')
end_date = datetime.now().strftime('%Y-%m-%d') end_date = datetime.now().strftime('%Y-%m-%d')
...@@ -101,7 +114,8 @@ def seat_stat(start_date=None, end_date=None): ...@@ -101,7 +114,8 @@ def seat_stat(start_date=None, end_date=None):
seat['validate_session'] += 1 if check['violationRuleCount'] > 0 else 0 seat['validate_session'] += 1 if check['violationRuleCount'] > 0 else 0
else: else:
seat_dict[check['agentName']] = {'create_date': start_date, 'agentName': check['agentName'], seat_dict[check['agentName']] = {'create_date': start_date, 'agentName': check['agentName'],
'taskId': check['taskId'], 'task': t['name'].split('_')[0], 'taskId': check['taskId'],
'task': seat_code_team_name.get(check['agentName'], '未找到团队'),
'sessionCollectionId': t['sessionCollectionId'], 'total_session': 1} 'sessionCollectionId': t['sessionCollectionId'], 'total_session': 1}
seat_dict[check['agentName']]['validate_session'] = 1 if check['violationRuleCount'] > 0 else 0 seat_dict[check['agentName']]['validate_session'] = 1 if check['violationRuleCount'] > 0 else 0
seat_dict[check['agentName']]['remainTime'] = remain seat_dict[check['agentName']]['remainTime'] = remain
...@@ -120,6 +134,7 @@ def score_stat(start_date=None, end_date=None): ...@@ -120,6 +134,7 @@ def score_stat(start_date=None, end_date=None):
坐席得分统计 坐席得分统计
:return: :return:
""" """
seat_code_team_name = team_seat()
if not start_date and not end_date: if not start_date and not end_date:
start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d') start_date = (datetime.now() + timedelta(days=-1)).strftime('%Y-%m-%d')
end_date = datetime.now().strftime('%Y-%m-%d') end_date = datetime.now().strftime('%Y-%m-%d')
...@@ -160,12 +175,13 @@ def score_stat(start_date=None, end_date=None): ...@@ -160,12 +175,13 @@ def score_stat(start_date=None, end_date=None):
seat['total_session'] += 1 seat['total_session'] += 1
seat['validate_session'] += 1 if check['violationRuleCount'] > 0 else 0 seat['validate_session'] += 1 if check['violationRuleCount'] > 0 else 0
seat['validate_num'] += len(score_item) seat['validate_num'] += len(score_item)
seat['score'] = round((seat['score'] + score)/2, 2) seat['score'] = round((seat['score'] + score) / 2, 2)
seat['service_score'] = round((seat['service_score'] + service_score)/2, 2) seat['service_score'] = round((seat['service_score'] + service_score) / 2, 2)
seat['business_score'] = round((seat['business_score'] + business_score)/2, 2) seat['business_score'] = round((seat['business_score'] + business_score) / 2, 2)
else: else:
seat_dict[check['agentName']] = {'create_date': start_date, 'agentName': check['agentName'], seat_dict[check['agentName']] = {'create_date': start_date, 'agentName': check['agentName'],
'taskId': check['taskId'], 'task': t['name'].split('_')[0], 'taskId': check['taskId'],
'task': seat_code_team_name.get(check['agentName'], '未找到团队'),
'sessionCollectionId': t['sessionCollectionId'], 'total_session': 1, 'sessionCollectionId': t['sessionCollectionId'], 'total_session': 1,
'score': score, 'service_score': service_score, 'score': score, 'service_score': service_score,
'business_score': business_score, 'validate_zero': validate_zero} 'business_score': business_score, 'validate_zero': validate_zero}
...@@ -208,7 +224,7 @@ def seat_time_stat(start_date=None, end_date=None): ...@@ -208,7 +224,7 @@ def seat_time_stat(start_date=None, end_date=None):
t.remainTime = remain t.remainTime = remain
t.save(update_fields=['remainTime']) t.save(update_fields=['remainTime'])
""" """
坐席统计 坐席统计
seats = SeatStat.objects.filter(**task_condition) seats = SeatStat.objects.filter(**task_condition)
stat_count = 0 stat_count = 0
for t in seats: for t in seats:
......
...@@ -30,7 +30,7 @@ class RulesStat(models.Model): ...@@ -30,7 +30,7 @@ class RulesStat(models.Model):
rule = models.CharField('违规名称', null=True, max_length=64, db_index=True) rule = models.CharField('违规名称', null=True, max_length=64, db_index=True)
sessionCollectionId = models.CharField('所在表', null=True, max_length=32) sessionCollectionId = models.CharField('所在表', null=True, max_length=32)
rule_num = models.IntegerField('违规数量', default=0) rule_num = models.IntegerField('违规数量', default=0)
task = models.CharField('所在地市', null=True, max_length=24) task = models.CharField('所在团队', null=True, max_length=24)
create_date = models.DateField('统计日期', null=True) create_date = models.DateField('统计日期', null=True)
agentName = models.CharField('坐席名称', null=True, max_length=64) agentName = models.CharField('坐席名称', null=True, max_length=64)
customName = models.CharField('客户名称', null=True, max_length=64) customName = models.CharField('客户名称', null=True, max_length=64)
...@@ -51,7 +51,7 @@ class SeatStat(models.Model): ...@@ -51,7 +51,7 @@ class SeatStat(models.Model):
sessionCollectionId = models.CharField('所在表', null=True, max_length=32) sessionCollectionId = models.CharField('所在表', null=True, max_length=32)
validate_session = models.IntegerField('违规会话数量', default=0) validate_session = models.IntegerField('违规会话数量', default=0)
total_session = models.IntegerField('会话数量', default=0) total_session = models.IntegerField('会话数量', default=0)
task = models.CharField('所在地市', null=True, max_length=24) task = models.CharField('所在团队', null=True, max_length=24)
create_date = models.DateField('统计日期', null=True) create_date = models.DateField('统计日期', null=True)
agentName = models.CharField('坐席名称', null=True, max_length=64) agentName = models.CharField('坐席名称', null=True, max_length=64)
taskId = models.IntegerField('质检任务标识') taskId = models.IntegerField('质检任务标识')
...@@ -69,7 +69,7 @@ class ScoreStat(models.Model): ...@@ -69,7 +69,7 @@ class ScoreStat(models.Model):
validate_session = models.IntegerField('违规会话数量', default=0) validate_session = models.IntegerField('违规会话数量', default=0)
validate_num = models.IntegerField('违规次数', default=0) validate_num = models.IntegerField('违规次数', default=0)
total_session = models.IntegerField('会话数量', default=0) total_session = models.IntegerField('会话数量', default=0)
task = models.CharField('所在地市', null=True, max_length=24) task = models.CharField('所在团队', null=True, max_length=24)
create_date = models.DateField('统计日期', null=True) create_date = models.DateField('统计日期', null=True)
start_time = models.DateTimeField('会话日期', null=True) start_time = models.DateTimeField('会话日期', null=True)
agentName = models.CharField('坐席名称', null=True, max_length=64) agentName = models.CharField('坐席名称', null=True, max_length=64)
...@@ -123,15 +123,15 @@ class CheckSession(models.Model): ...@@ -123,15 +123,15 @@ class CheckSession(models.Model):
abstract = True abstract = True
@classmethod @classmethod
def set_table(Class, table_name): def set_table(cls, table_name):
class Meta: class Meta:
db_table = table_name db_table = table_name
attrs = { attrs = {
'__module__': Class.__module__, '__module__': cls.__module__,
'Meta': Meta 'Meta': Meta
} }
return type(table_name, (Class,), attrs) return type(table_name, (cls,), attrs)
class ScheduleTaskOptions(models.Model): class ScheduleTaskOptions(models.Model):
...@@ -158,6 +158,53 @@ class ScheduleTaskOptions(models.Model): ...@@ -158,6 +158,53 @@ class ScheduleTaskOptions(models.Model):
# name_list = [name[0] for name in names] # name_list = [name[0] for name in names]
class Country(models.Model):
code = models.CharField('机构代码', max_length=190, blank=False)
name = models.CharField('机构名称', max_length=190, blank=False)
user_email = models.CharField('用户email', max_length=190)
parent = models.IntegerField('父机构id', default=None)
in_use = models.IntegerField('是否在用', default=1, blank=False)
createdAt = models.DateTimeField('创建时间')
updatedAt = models.DateTimeField('更新时间')
def __str__(self):
return self.name
class Meta:
db_table = 'country'
class Team(models.Model):
code = models.CharField('团队代码', max_length=190, blank=False)
name = models.CharField('团队名称', max_length=190, blank=False)
country = models.ForeignKey(Country, blank=True, on_delete=models.CASCADE)
parent = models.IntegerField('父机构id', default=None)
in_use = models.IntegerField('是否在用', default=1, blank=False)
createdAt = models.DateTimeField('创建时间')
updatedAt = models.DateTimeField('更新时间')
def __str__(self):
return self.name
class Meta:
db_table = 'team'
class Seat(models.Model):
__tablename__ = 'seat'
code = models.CharField('坐席代码', max_length=190, blank=False)
name = models.CharField('坐席名', max_length=190, blank=False)
team = models.ForeignKey(Team, blank=True, on_delete=models.CASCADE)
in_use = models.IntegerField('是否在用', default=1, blank=False)
createdAt = models.DateTimeField('创建时间')
updatedAt = models.DateTimeField('更新时间')
def __str__(self):
return self.name
class Meta:
db_table = 'seat'
class Round(Func): class Round(Func):
function = 'ROUND' function = 'ROUND'
......
...@@ -87,9 +87,17 @@ ...@@ -87,9 +87,17 @@
end-placeholder="结束日期" end-placeholder="结束日期"
:default-time="['00:00:00', '23:59:59']"> :default-time="['00:00:00', '23:59:59']">
</el-date-picker> </el-date-picker>
<el-select v-if="sel_is_show == true" v-model="taskvalue" filterable placeholder="请选择" @change="changeTask"> <el-select v-model="cityvalue" filterable placeholder="请选择" @change="changeCity">
<el-option <el-option
v-for="item in taskList" v-for="item in cityList"
:key="item.id"
:label="item.name"
:value="item.id">
</el-option>
</el-select>
<el-select v-model="countryvalue" filterable placeholder="请选择" @change="changeCountry">
<el-option
v-for="item in countryList"
:key="item.id" :key="item.id"
:label="item.name" :label="item.name"
:value="item.id"> :value="item.id">
...@@ -101,7 +109,8 @@ ...@@ -101,7 +109,8 @@
<form ref="loadModal" :action="`${BASEURL}api/v1/data/static_score_export/`" method="get"> <form ref="loadModal" :action="`${BASEURL}api/v1/data/static_score_export/`" method="get">
<input type="hidden" name="start_date" :value="start_date"> <input type="hidden" name="start_date" :value="start_date">
<input type="hidden" name="end_date" :value="end_date"> <input type="hidden" name="end_date" :value="end_date">
<input type="hidden" name="task" :value="taskvalue"> <input type="hidden" name="city" :value="cityvalue">
<input type="hidden" name="country" :value="countryvalue">
<input type="hidden" name="sort" :value="sortObj.sort"> <input type="hidden" name="sort" :value="sortObj.sort">
</form> </form>
<!-- <!--
...@@ -287,7 +296,6 @@ ...@@ -287,7 +296,6 @@
<script src="{% static "inspect/js/vue.min.js" %}"></script> <script src="{% static "inspect/js/vue.min.js" %}"></script>
<script src="{% static "inspect/js/element.js" %}"></script> <script src="{% static "inspect/js/element.js" %}"></script>
<script src="{% static "inspect/js/http.js" %}"></script> <script src="{% static "inspect/js/http.js" %}"></script>
<script type="text/javascript" src="{% static "inspect/js/config.js" %}"></script>
<script type="text/javascript" src="{% static "inspect/js/group.js" %}"></script> <script type="text/javascript" src="{% static "inspect/js/group.js" %}"></script>
</body> </body>
</html> </html>
...@@ -23,6 +23,7 @@ router = routers.DefaultRouter() ...@@ -23,6 +23,7 @@ router = routers.DefaultRouter()
router.register(r'tools', api.ToolsApi, base_name='tools') router.register(r'tools', api.ToolsApi, base_name='tools')
router.register(r'tasks', api.TasksApi, base_name='tasks') router.register(r'tasks', api.TasksApi, base_name='tasks')
router.register(r'data', api.DataApi, base_name='data') router.register(r'data', api.DataApi, base_name='data')
router.register(r'agency', api.AgencyApi, base_name='data')
# Wire up our API using automatic URL routing. # Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API. # Additionally, we include login URLs for the browsable API.
......
...@@ -4,9 +4,13 @@ new Vue({ ...@@ -4,9 +4,13 @@ new Vue({
return { return {
ss:'sas', ss:'sas',
dateTime: '', dateTime: '',
taskList:[], cityvalue: null,
taskvalue: '', countryvalue: null,
teamvalue: null,
start_date: '', start_date: '',
init_simple: false,
cityList:[],
countryList:[],
isscrollTop: false, isscrollTop: false,
currentPage:1, currentPage:1,
pagesize: 10, pagesize: 10,
...@@ -71,42 +75,55 @@ new Vue({ ...@@ -71,42 +75,55 @@ new Vue({
changeRange(dateRange){ changeRange(dateRange){
this.start_date = dateRange[0]; this.start_date = dateRange[0];
this.end_date = dateRange[1]; this.end_date = dateRange[1];
this.getRule(this.taskvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据 this.getRule(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
}, },
changeTask(msg){ changeCity(msg){
console.log(msg); console.log(msg);
this.taskvalue = msg; this.cityvalue = msg;
this.getTake() this.countryvalue = null;
this.getRule(this.taskvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据 this.getCountry(this.cityvalue);
this.getRule(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
}, },
changeTake(msg){ changeCountry(msg){
this.takevalue = msg;
this.getRule(this.taskvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
console.log(msg); console.log(msg);
this.countryvalue = msg;
this.getRule(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
}, },
getTask(){ getCountry() {
let that = this;
RquestsGet('api/v1/agency/country/?city_id=' + this.cityvalue).then(data => {
//console.log(data);
if (data.code != 0) {
that.$message('服务器错误')
} else {
that.countryList = data.data.country_list;
}
})
},
getCity(){
let that = this; let that = this;
that.taskList = [ var request = new XMLHttpRequest();
{id:'',name:'全省'},
{id:'合肥',name:'合肥'}, let uri = window_url + 'api/v1/agency/city/';
{id:'芜湖',name:'芜湖'},
{id:'蚌埠',name:'蚌埠'}, request.open('GET', uri, false);
{id:'淮南',name:'淮南'}, request.send(null);
{id:'马鞍山',name:'马鞍山'}, if (request.status === 200) {
{id:'淮北',name:'淮北'}, data = JSON.parse(request.response);
{id:'铜陵',name:'铜陵'}, console.log(data.code);
{id:'安庆',name:'安庆'}, if(data.code != 0){
{id:'黄山',name:'黄山'}, that.$message('服务器错误');
{id:'滁州',name:'滁州'}, } else {
{id:'阜阳',name:'阜阳'}, that.cityList = data.data.city_list;
{id:'亳州',name:'亳州'}, that.countryList = data.data.country_list;
{id:'宿州',name:'宿州'}, that.cityvalue = data.data.city_id;
{id:'六安',name:'六安'}, console.log(that.cityvalue);
{id:'宣城',name:'宣城'}, that.init_simple = true;
{id:'巢湖',name:'巢湖'}, }
{id:'池州',name:'池州'}, } else {
{id:'安徽省营业部',name:'安徽省营业部'}, that.$message('服务器错误');
]; }
//RquestsGet('api/v1/tasks/obtain/').then(data => { //RquestsGet('api/v1/tasks/obtain/').then(data => {
// //console.log(data); // //console.log(data);
// if(data.code != 0){ // if(data.code != 0){
...@@ -117,35 +134,23 @@ new Vue({ ...@@ -117,35 +134,23 @@ new Vue({
// } // }
//}) //})
}, },
getTake(){
let that = this;
RquestsGet('api/v1/tasks/seat/?task=' + that.taskvalue).then(data => {
//console.log(data);
if(data.code != 0){
//that.takeList = [{agentName:'全部坐席'}]
}else{
that.takeList = data.data;
}
})
},
CurrentChange(page){ CurrentChange(page){
this.currentPage = page; this.currentPage = page;
this.getRule(this.taskvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据 this.getRule(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
}, },
popCurrentChange(page){ popCurrentChange(page){
this.poppage = page; this.poppage = page;
this.getDetail(this.taskvalue,this.start_date,this.end_date,this.poptables,this.poprule, this.poppage, this.poppagesize); this.getDetail(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.poptables,this.poprule, this.poppage, this.poppagesize);
}, },
getRule(task,start_date,end_date,agentName,page,page_size){ getRule(city,country,start_date,end_date,agentName,page,page_size){
let that = this; let that = this;
console.log(start_date,end_date); console.log(start_date,end_date);
let arr = []; let arr = [];
this.$loading({text:'数据加载中...'}); this.$loading({text:'数据加载中...'});
let sort = this.sortObj.sort; let sort = this.sortObj.sort;
RquestsPost('api/v1/tasks/static_score/',{task,end_date,start_date,agentName,page,page_size,sort}).then(data => { RquestsPost('api/v1/tasks/static_score/',{city,country,end_date,start_date,agentName,page,page_size,sort}).then(data => {
console.log(data.data); console.log(data.data);
if(data.code != 0){ if(data.code != 0){
that.$message(data.msg); that.$message(data.msg);
...@@ -168,7 +173,7 @@ new Vue({ ...@@ -168,7 +173,7 @@ new Vue({
this.isHidePage = !(data.data.length > 0); this.isHidePage = !(data.data.length > 0);
this.$loading().close(); this.$loading().close();
}) })
RquestsPost('api/v1/tasks/static/',{task,end_date,start_date,agentName}).then(data => { RquestsPost('api/v1/tasks/static/',{city,country,end_date,start_date,agentName}).then(data => {
console.log(data.data); console.log(data.data);
if(data.code != 0){ if(data.code != 0){
that.$message(data.msg); that.$message(data.msg);
...@@ -184,12 +189,6 @@ new Vue({ ...@@ -184,12 +189,6 @@ new Vue({
return false; return false;
} }
that.titleInfo = data.data; that.titleInfo = data.data;
if (name_list.indexOf(data.username) !== -1) {
that.sel_is_show = false;
that.taskvalue = data.username;
} else {
that.sel_is_show = true;
}
//this.$loading().close(); //this.$loading().close();
}) })
}, },
...@@ -206,7 +205,7 @@ new Vue({ ...@@ -206,7 +205,7 @@ new Vue({
this.popcurrentPage = 1; this.popcurrentPage = 1;
this.poppage = 1; this.poppage = 1;
this.taskvalue = tableData.area; this.taskvalue = tableData.area;
this.getDetail(this.taskvalue,this.start_date,this.end_date,this.poptables,this.poprule, this.poppage, this.poppagesize); this.getDetail(this.teamvalue,this.start_date,this.end_date,this.poptables,this.poprule, this.poppage, this.poppagesize);
this.dialogTableVisible = true; this.dialogTableVisible = true;
}, },
...@@ -266,10 +265,10 @@ new Vue({ ...@@ -266,10 +265,10 @@ new Vue({
this.dateRange = [new Date(new Date()-24*60*60*1000), new Date()]; this.dateRange = [new Date(new Date()-24*60*60*1000), new Date()];
this.start_date = this.dateFormat(new Date(new Date()-24*60*60*1000)); this.start_date = this.dateFormat(new Date(new Date()-24*60*60*1000));
this.end_date = this.dateFormat(new Date()); this.end_date = this.dateFormat(new Date());
this.getTask(); // 获取任务 this.getCity(); // 获取市县机构信息
//this.getTake(); // 获取坐席 //this.getTake(); // 获取坐席
this.getRule(this.taskvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据 this.getRule(this.cityvalue,this.countryvalue,this.start_date,this.end_date,this.takevalue, this.currentPage , 10); // 获取统计数据
} }
}, },
......
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