[Update] 优化仪表盘页面加载

pull/3973/head
Bai 2020-05-08 15:41:56 +08:00
parent aec78dc3c7
commit 181973f235
4 changed files with 557 additions and 353 deletions

295
apps/jumpserver/api.py Normal file
View File

@ -0,0 +1,295 @@
from django.core.cache import cache
from django.utils import timezone
from django.utils.timesince import timesince
from django.db.models import Count, Max
from django.http.response import JsonResponse
from rest_framework.views import APIView
from collections import Counter
from users.models import User
from assets.models import Asset
from terminal.models import Session
from orgs.utils import current_org
from common.permissions import IsOrgAdmin
from common.utils import lazyproperty
__all__ = ['IndexApi']
class MonthLoginMetricMixin:
@lazyproperty
def session_month(self):
month_ago = timezone.now() - timezone.timedelta(days=30)
session_month = Session.objects.filter(date_start__gt=month_ago)
return session_month
@lazyproperty
def session_month_dates(self):
dates = self.session_month.dates('date_start', 'day')
return dates
def get_month_metrics_date(self):
month_metrics_date = [d.strftime('%m-%d') for d in self.session_month_dates] or ['0']
return month_metrics_date
@staticmethod
def get_cache_key(date, tp):
date_str = date.strftime("%Y%m%d")
key = "SESSION_MONTH_{}_{}".format(tp, date_str)
return key
def __get_data_from_cache(self, date, tp):
if date == timezone.now().date():
return None
cache_key = self.get_cache_key(date, tp)
count = cache.get(cache_key)
return count
def __set_data_to_cache(self, date, tp, count):
cache_key = self.get_cache_key(date, tp)
cache.set(cache_key, count, 3600*24*7)
@staticmethod
def get_date_start_2_end(d):
time_min = timezone.datetime.min.time()
time_max = timezone.datetime.max.time()
tz = timezone.get_current_timezone()
ds = timezone.datetime.combine(d, time_min).replace(tzinfo=tz)
de = timezone.datetime.combine(d, time_max).replace(tzinfo=tz)
return ds, de
def get_date_login_count(self, date):
tp = "LOGIN"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = Session.objects.filter(date_start__range=(ds, de)).count()
self.__set_data_to_cache(date, tp, count)
return count
def get_month_metrics_total_count_login(self):
data = []
for d in self.session_month_dates:
count = self.get_date_login_count(d)
data.append(count)
if len(data) == 0:
data = [0]
return data
def get_date_user_count(self, date):
tp = "USER"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = len(set(Session.objects.filter(date_start__range=(ds, de)).values_list('user', flat=True)))
self.__set_data_to_cache(date, tp, count)
return count
def get_month_metrics_total_count_active_users(self):
data = []
for d in self.session_month_dates:
count = self.get_date_user_count(d)
data.append(count)
return data
def get_date_asset_count(self, date):
tp = "ASSET"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = len(set(Session.objects.filter(date_start__range=(ds, de)).values_list('asset', flat=True)))
self.__set_data_to_cache(date, tp, count)
return count
def get_month_metrics_total_count_active_assets(self):
data = []
for d in self.session_month_dates:
count = self.get_date_asset_count(d)
data.append(count)
return data
@lazyproperty
def month_total_count_active_users(self):
count = len(set(self.session_month.values_list('user', flat=True)))
return count
@lazyproperty
def month_total_count_inactive_users(self):
total = current_org.get_org_members().count()
active = self.month_total_count_active_users
count = total - active
if count < 0:
count = 0
return count
@lazyproperty
def month_total_count_disabled_users(self):
return current_org.get_org_members().filter(is_active=False).count()
@lazyproperty
def month_total_count_active_assets(self):
return len(set(self.session_month.values_list('asset', flat=True)))
@lazyproperty
def month_total_count_inactive_assets(self):
total = Asset.objects.all().count()
active = self.month_total_count_active_assets
count = total - active
if count < 0:
count = 0
return count
@lazyproperty
def month_total_count_disabled_assets(self):
return Asset.objects.filter(is_active=False).count()
class WeekSessionMetricMixin:
session_week = None
@lazyproperty
def session_week(self):
week_ago = timezone.now() - timezone.timedelta(weeks=1)
session_week = Session.objects.filter(date_start__gt=week_ago)
return session_week
def get_week_login_times_top5_users(self):
users = self.session_week.values_list('user', flat=True)
users = [
{'user': user, 'total': total}
for user, total in Counter(users).most_common(5)
]
return users
def get_week_total_count_login_users(self):
return len(set(self.session_week.values_list('user', flat=True)))
def get_week_total_count_login_times(self):
return self.session_week.count()
def get_week_login_times_top10_assets(self):
assets = self.session_week.values("asset")\
.annotate(total=Count("asset"))\
.annotate(last=Max("date_start")).order_by("-total")[:10]
for asset in assets:
asset['last'] = str(asset['last'])
return list(assets)
def get_week_login_times_top10_users(self):
users = self.session_week.values("user") \
.annotate(total=Count("user")) \
.annotate(last=Max("date_start")).order_by("-total")[:10]
for user in users:
user['last'] = str(user['last'])
return list(users)
def get_week_login_record_top10_sessions(self):
sessions = self.session_week.order_by('-date_start')[:10]
for session in sessions:
session.avatar_url = User.get_avatar_url("")
sessions = [
{
'user': session.user,
'asset': session.asset,
'is_finished': session.is_finished,
'date_start': str(session.date_start),
'timesince': timesince(session.date_start)
}
for session in sessions
]
return sessions
class TotalCountMixin:
@staticmethod
def get_total_count_users():
return current_org.get_org_members().count()
@staticmethod
def get_total_count_assets():
return Asset.objects.all().count()
@staticmethod
def get_total_count_online_users():
count = len(set(Session.objects.filter(is_finished=False).values_list('user', flat=True)))
return count
@staticmethod
def get_total_count_online_assets():
return Session.objects.filter(is_finished=False).count()
class IndexApi(TotalCountMixin, WeekSessionMetricMixin, MonthLoginMetricMixin, APIView):
permission_classes = (IsOrgAdmin,)
http_method_names = ['get']
def get(self, request, *args, **kwargs):
data = {}
query_params = self.request.query_params
_all = query_params.get('all')
if _all or query_params.get('total_count'):
data.update({
'total_count_assets': self.get_total_count_assets(),
'total_count_users': self.get_total_count_users(),
'total_count_online_users': self.get_total_count_online_users(),
'total_count_online_assets': self.get_total_count_online_assets(),
})
if _all or query_params.get('month_metrics'):
data.update({
'month_metrics_date': self.get_month_metrics_date(),
'month_metrics_total_count_login': self.get_month_metrics_total_count_login(),
'month_metrics_total_count_active_users': self.get_month_metrics_total_count_active_users(),
'month_metrics_total_count_active_assets': self.get_month_metrics_total_count_active_assets(),
})
if _all or query_params.get('month_total_count_users'):
data.update({
'month_total_count_active_users': self.month_total_count_active_users,
'month_total_count_inactive_users': self.month_total_count_inactive_users,
'month_total_count_disabled_users': self.month_total_count_disabled_users,
})
if _all or query_params.get('month_total_count_assets'):
data.update({
'month_total_count_active_assets': self.month_total_count_active_assets,
'month_total_count_inactive_assets': self.month_total_count_inactive_assets,
'month_total_count_disabled_assets': self.month_total_count_disabled_assets,
})
if _all or query_params.get('week_total_count'):
data.update({
'week_total_count_login_users': self.get_week_total_count_login_users(),
'week_total_count_login_times': self.get_week_total_count_login_times(),
})
if _all or query_params.get('week_login_times_top5_users'):
data.update({
'week_login_times_top5_users': self.get_week_login_times_top5_users(),
})
if _all or query_params.get('week_login_times_top10_assets'):
data.update({
'week_login_times_top10_assets': self.get_week_login_times_top10_assets(),
})
if _all or query_params.get('week_login_times_top10_users'):
data.update({
'week_login_times_top10_users': self.get_week_login_times_top10_users(),
})
if _all or query_params.get('week_login_record_top10_sessions'):
data.update({
'week_login_record_top10_sessions': self.get_week_login_record_top10_sessions()
})
return JsonResponse(data, status=200)

View File

@ -7,9 +7,10 @@ from django.conf.urls.static import static
from django.conf.urls.i18n import i18n_patterns
from django.views.i18n import JavaScriptCatalog
from . import views
from . import views, api
api_v1 = [
path('index/', api.IndexApi.as_view()),
path('users/', include('users.urls.api_urls', namespace='api-users')),
path('assets/', include('assets.urls.api_urls', namespace='api-assets')),
path('perms/', include('perms.urls.api_urls', namespace='api-perms')),

View File

@ -1,224 +1,12 @@
from django.core.cache import cache
from django.views.generic import TemplateView
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.db.models import Count, Max
from django.shortcuts import redirect
from users.models import User
from assets.models import Asset
from terminal.models import Session
from orgs.utils import current_org
from common.permissions import PermissionsMixin, IsValidUser
from common.utils import timeit, lazyproperty
__all__ = ['IndexView']
class MonthLoginMetricMixin:
@lazyproperty
def session_month(self):
month_ago = timezone.now() - timezone.timedelta(days=30)
session_month = Session.objects.filter(date_start__gt=month_ago)
return session_month
@lazyproperty
def session_month_dates(self):
dates = self.session_month.dates('date_start', 'day')
return dates
def get_month_day_metrics(self):
month_str = [
d.strftime('%m-%d') for d in self.session_month_dates
] or ['0']
return month_str
@staticmethod
def get_cache_key(date, tp):
date_str = date.strftime("%Y%m%d")
key = "SESSION_MONTH_{}_{}".format(tp, date_str)
return key
def __get_data_from_cache(self, date, tp):
if date == timezone.now().date():
return None
cache_key = self.get_cache_key(date, tp)
count = cache.get(cache_key)
return count
def __set_data_to_cache(self, date, tp, count):
cache_key = self.get_cache_key(date, tp)
cache.set(cache_key, count, 3600*24*7)
@lazyproperty
def user_disabled_total(self):
return current_org.get_org_members().filter(is_active=False).count()
@lazyproperty
def asset_disabled_total(self):
return Asset.objects.filter(is_active=False).count()
@staticmethod
def get_date_start_2_end(d):
time_min = timezone.datetime.min.time()
time_max = timezone.datetime.max.time()
tz = timezone.get_current_timezone()
ds = timezone.datetime.combine(d, time_min).replace(tzinfo=tz)
de = timezone.datetime.combine(d, time_max).replace(tzinfo=tz)
return ds, de
def get_date_login_count(self, date):
tp = "LOGIN"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = Session.objects.filter(date_start__range=(ds, de)).count()
self.__set_data_to_cache(date, tp, count)
return count
def get_month_login_metrics(self):
data = []
for d in self.session_month_dates:
count = self.get_date_login_count(d)
data.append(count)
if len(data) == 0:
data = [0]
return data
def get_date_user_count(self, date):
tp = "USER"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = Session.objects.filter(date_start__range=(ds, de))\
.values('user').distinct().count()
self.__set_data_to_cache(date, tp, count)
return count
def get_month_active_user_metrics(self):
data = []
for d in self.session_month_dates:
count = self.get_date_user_count(d)
data.append(count)
return data
def get_date_asset_count(self, date):
tp = "ASSET"
count = self.__get_data_from_cache(date, tp)
if count is not None:
return count
ds, de = self.get_date_start_2_end(date)
count = Session.objects.filter(date_start__range=(ds, de)) \
.values('asset').distinct().count()
self.__set_data_to_cache(date, tp, count)
return count
def get_month_active_asset_metrics(self):
data = []
for d in self.session_month_dates:
count = self.get_date_asset_count(d)
data.append(count)
return data
@lazyproperty
def month_active_user_total(self):
count = self.session_month.values('user').distinct().count()
return count
@lazyproperty
def month_inactive_user_total(self):
total = current_org.get_org_members().count()
active = self.month_active_user_total
count = total - active
if count < 0:
count = 0
return count
@lazyproperty
def month_active_asset_total(self):
return self.session_month.values('asset').distinct().count()
@lazyproperty
def month_inactive_asset_total(self):
total = Asset.objects.all().count()
active = self.month_active_asset_total
count = total - active
if count < 0:
count = 0
return count
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
'month_str': self.get_month_day_metrics(),
'month_total_visit_count': self.get_month_login_metrics(),
'month_user': self.get_month_active_user_metrics(),
'mouth_asset': self.get_month_active_asset_metrics(),
'month_user_active': self.month_active_user_total,
'month_user_inactive': self.month_inactive_user_total,
'month_user_disabled': self.user_disabled_total,
'month_asset_active': self.month_active_asset_total,
'month_asset_inactive': self.month_inactive_asset_total,
'month_asset_disabled': self.asset_disabled_total,
})
return context
class WeekSessionMetricMixin:
session_week = None
@lazyproperty
def session_week(self):
week_ago = timezone.now() - timezone.timedelta(weeks=1)
session_week = Session.objects.filter(date_start__gt=week_ago)
return session_week
def get_top5_user_a_week(self):
users = self.session_week.values('user') \
.annotate(total=Count('user')) \
.order_by('-total')[:5]
return users
def get_week_login_user_count(self):
return self.session_week.values('user').distinct().count()
def get_week_login_asset_count(self):
return self.session_week.count()
def get_week_top10_assets(self):
assets = self.session_week.values("asset")\
.annotate(total=Count("asset"))\
.annotate(last=Max("date_start")).order_by("-total")[:10]
return assets
def get_week_top10_users(self):
users = self.session_week.values("user") \
.annotate(total=Count("user")) \
.annotate(last=Max("date_start")).order_by("-total")[:10]
return users
def get_last10_sessions(self):
sessions = self.session_week.order_by('-date_start')[:10]
for session in sessions:
session.avatar_url = User.get_avatar_url("")
return sessions
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
'user_visit_count_weekly': self.get_week_login_user_count(),
'asset_visit_count_weekly': self.get_week_login_asset_count(),
'user_visit_count_top_five': self.get_top5_user_a_week(),
'last_login_ten': self.get_last10_sessions(),
'week_asset_hot_ten': self.get_week_top10_assets(),
'week_user_hot_ten': self.get_week_top10_users(),
})
return context
class IndexView(PermissionsMixin, MonthLoginMetricMixin, WeekSessionMetricMixin, TemplateView):
class IndexView(PermissionsMixin, TemplateView):
template_name = 'index.html'
permission_classes = [IsValidUser]
@ -229,31 +17,9 @@ class IndexView(PermissionsMixin, MonthLoginMetricMixin, WeekSessionMetricMixin,
return redirect('assets:user-asset-list')
return super(IndexView, self).dispatch(request, *args, **kwargs)
@staticmethod
def get_user_count():
return current_org.get_org_members().count()
@staticmethod
def get_asset_count():
return Asset.objects.all().count()
@staticmethod
def get_online_user_count():
count = Session.objects.filter(is_finished=False)\
.values_list('user', flat=True).distinct().count()
return count
@staticmethod
def get_online_session_count():
return Session.objects.filter(is_finished=False).count()
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context.update({
'assets_count': self.get_asset_count(),
'users_count': self.get_user_count(),
'online_user_count': self.get_online_user_count(),
'online_asset_count': self.get_online_session_count(),
'app': _("Dashboard"),
})
return context

View File

@ -11,7 +11,7 @@
<h5>{% trans 'Total users' %}</h5>
</div>
<div class="ibox-content">
<h1 class="no-margins"><a href="{% url 'users:user-list' %}">{{ users_count }}</a></h1>
<h1 class="no-margins"><a href="{% url 'users:user-list' %}"><span id="total_count_users"></span></a></h1>
<small>All users</small>
</div>
</div>
@ -19,12 +19,12 @@
<div class="col-sm-3">
<div class="ibox float-e-margins">
<div class="ibox-title">
<span class="label label-info pull-right">Hosts</span>
<h5>{% trans 'Total hosts' %}</h5>
<span class="label label-info pull-right">Assets</span>
<h5>{% trans 'Total assets' %}</h5>
</div>
<div class="ibox-content">
<h1 class="no-margins"><a href="{% url 'assets:asset-list' %}">{{ assets_count }}</a></h1>
<small>All hosts</small>
<h1 class="no-margins"><a href="{% url 'assets:asset-list' %}"><span id="total_count_assets"></span></a></h1>
<small>All assets</small>
</div>
</div>
</div>
@ -36,7 +36,7 @@
<h5>{% trans 'Online users' %}</h5>
</div>
<div class="ibox-content">
<h1 class="no-margins"><a href="{% url 'terminal:session-online-list' %}"> <span id="online_users"></span>{{ online_user_count }}</a></h1>
<h1 class="no-margins"><a href="{% url 'terminal:session-online-list' %}"> <span id="total_count_online_users"></span></a></h1>
<small>Online users</small>
</div>
</div>
@ -50,7 +50,7 @@
</div>
<div class="ibox-content">
<h1 class="no-margins"><a href="{% url 'terminal:session-online-list' %}"> <span id="online_hosts"></span>{{ online_asset_count }}</a></h1>
<h1 class="no-margins"><a href="{% url 'terminal:session-online-list' %}"> <span id="total_count_online_assets"></span></a></h1>
<small>Online sessions</small>
</div>
</div>
@ -58,19 +58,11 @@
</div>
<div class="row">
<div class="col-sm-2 border-bottom white-bg dashboard-header" style="margin-left:15px;height: 346px">
<small>{% trans 'In the past week, a total of ' %}<span class="text-info">{{ user_visit_count_weekly }}</span>{% trans ' users have logged in ' %}<span class="text-success">{{ asset_visit_count_weekly }}</span>{% trans ' times asset.' %}</small>
<ul class="list-group clear-list m-t">
{% for data in user_visit_count_top_five %}
<li class="list-group-item fist-item">
<span class="pull-right">
{{ data.total }}{% trans ' times/week' %}
</span>
<span class="label ">{{ forloop.counter }}</span> {{ data.user }}
</li>
{% endfor %}
<small>{% trans 'In the past week, a total of ' %}<span class="text-info" id="week_total_count_login_users"></span>{% trans ' users have logged in ' %}<span class="text-success" id="week_total_count_login_times"></span>{% trans ' times asset.' %}</small>
<ul class="list-group clear-list m-t" id="week_login_times_top5_users">
</ul>
</div>
<div class="col-sm-7" id="top10" style="margin-left: -15px;height: 346px;padding: 15px 0 15px 0;"></div>
<div class="col-sm-7" id="month_metrics_echarts" style="margin-left: -15px;height: 346px;padding: 15px 0 15px 0;"></div>
<div class="col-sm-3 white-bg" id="top1" style="margin-left: -15px;height: 346px">
<div class="statistic-box">
<h4>
@ -81,13 +73,13 @@
</p>
<div class="row text-center">
<div class="col-sm-6">
<div id="activeUser" style="width: 140px; height: 140px;">
<div id="month_total_count_users_pie" style="width: 140px; height: 140px;">
</div>
<h5>{% trans 'User' %}</h5>
</div>
<div class="col-sm-6">
<div id="activeAsset" style="width: 140px; height: 140px;"></div>
<h5>{% trans 'Host' %}</h5>
<div id="month_total_count_assets_pie" style="width: 140px; height: 140px;"></div>
<h5>{% trans 'Asset' %}</h5>
</div>
</div>
<div class="m-t">
@ -120,27 +112,7 @@
<h3><i class="fa fa-inbox"></i>{% trans 'Top 10 assets in a week'%}</h3>
<small><i class="fa fa-map-marker"></i>{% trans 'Login frequency and last login record.' %}</small>
</div>
<div class="ibox-content inspinia-timeline">
{% if week_asset_hot_ten %}
{% for data in week_asset_hot_ten %}
<div class="timeline-item">
<div class="row">
<div class="col-xs-5 date ellipsis">
<i class="fa fa-info-circle"></i>
<strong data-toggle="tooltip" title="{{ data.asset }}">{{ data.asset }}</strong>
<br/>
<small class="text-navy">{{ data.total }}{% trans ' times' %}</small>
</div>
<div class="col-xs-7 content no-top-border">
<p class="m-b-xs">{% trans 'The time last logged in' %}</p>
<p>{% trans 'At' %} {{ data.last|date:"Y-m-d H:i:s" }}</p>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p class="text-center">{% trans '(No)' %}</p>
{% endif %}
<div class="ibox-content inspinia-timeline" id="week_login_times_top10_assets">
</div>
</div>
</div>
@ -158,27 +130,7 @@
</div>
<div class="ibox-content">
<div>
<div class="feed-activity-list">
{% if last_login_ten %}
{% for login in last_login_ten %}
<div class="feed-element">
<a href="#" class="pull-left">
<img alt="image" class="img-circle" src="{% static 'img/avatar/user.png' %}">
</a>
<div class="media-body ">
{% ifequal login.is_finished 0 %}
<small class="pull-right text-navy">{{ login.date_start|timesince }} {% trans 'Before' %}</small>
{% else %}
<small class="pull-right">{{ login.date_start|timesince }} {% trans 'Before' %}</small>
{% endifequal %}
<strong>{{ login.user }}</strong> {% trans 'Login in ' %}{{ login.asset }} <br>
<small class="text-muted">{{ login.date_start }}</small>
</div>
</div>
{% endfor %}
{% else %}
<p class="text-center">{% trans '(No)' %}</p>
{% endif %}
<div class="feed-activity-list" id="week_login_record_top10_sessions">
</div>
</div>
</div>
@ -206,27 +158,7 @@
<h3><i class="fa fa-user"></i>{% trans 'Top 10 users in a week' %}</h3>
<small><i class="fa fa-map-marker"></i>{% trans 'User login frequency and last login record.' %}</small>
</div>
<div class="ibox-content inspinia-timeline">
{% if week_user_hot_ten %}
{% for data in week_user_hot_ten %}
<div class="timeline-item">
<div class="row">
<div class="col-xs-5 date ellipsis">
<i class="fa fa-info-circle"></i>
<strong data-toggle="tooltip" title="{{ data.user }}">{{ data.user }}</strong>
<br/>
<small class="text-navy">{{ data.total }}{% trans ' times' %}</small>
</div>
<div class="col-xs-7 content no-top-border">
<p class="m-b-xs">{% trans 'The time last logged in' %}</p>
<p>{% trans 'At' %} {{ data.last|date:"Y-m-d H:i:s" }}</p>
</div>
</div>
</div>
{% endfor %}
{% else %}
<p class="text-center">{% trans '(No)' %}</p>
{% endif %}
<div class="ibox-content inspinia-timeline" id="week_login_times_top10_users">
</div>
</div>
</div>
@ -238,27 +170,15 @@
{% block custom_foot_js %}
<script src="{% static 'js/plugins/echarts/echarts.js' %}"></script>
<script>
$(document).ready(function(){
$('#show').click(function(){
$('#show').css('display', 'none');
$('#more').css('display', 'block');
});
$("[data-toggle='tooltip']").tooltip();
});
require.config({
paths: {
'echarts': '/static/js/plugins/echarts/chart/',
'echarts/chart/line': '/static/js/plugins/echarts/chart/line',
'echarts/chart/pie': '/static/js/plugins/echarts/chart/pie'
}
});
function requireMonthMetricsECharts(data){
require(
[
'echarts',
'echarts/chart/line'
],
function (ec) {
var top10Chart = ec.init(document.getElementById('top10'));
var monthMetricsECharts = ec.init(document.getElementById('month_metrics_echarts'));
var option = {
title : {
text: "{% trans 'Monthly data overview' %}",
@ -284,7 +204,7 @@ $(document).ready(function(){
{
type : 'category',
boundaryGap : false,
data : {{ month_str|safe}}
data : data['month_metrics_date'],
}
],
yAxis : [
@ -298,38 +218,42 @@ $(document).ready(function(){
type:'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: {{ month_total_visit_count|safe}}
data: data['month_metrics_total_count_login']
},
{
name: "{% trans 'Active users' %}",
type: 'line',
smooth: true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: {{ month_user|safe }}
data: data['month_metrics_total_count_active_users']
},
{
name:"{% trans 'Active assets' %}",
type:'line',
smooth:true,
itemStyle: {normal: {areaStyle: {type: 'default'}}},
data: {{ mouth_asset|safe }}
data: data['month_metrics_total_count_active_assets']
}
]
};
top10Chart.setOption(option);
monthMetricsECharts.setOption(option);
}
);
}
function requireMonthTotalCountUsersPie(data){
require(
[
'echarts',
'echarts/chart/pie'
],
function (ec) {
var auChart = ec.init(document.getElementById('activeUser'));
var monthTotalCountUsersPie = ec.init(document.getElementById('month_total_count_users_pie'));
var option = {
tooltip : {
trigger: 'item',
formatter: "{b} <br> {c} ({d}%)"
formatter: "{b} <br> {c} <br> ({d}%)"
},
legend: {
show: false,
@ -364,6 +288,7 @@ $(document).ready(function(){
name:"{% trans 'Access to the source' %}",
type:'pie',
radius : ['50%', '70%'],
avoidLabelOverlap: false,
itemStyle : {
normal : {
label : {
@ -385,33 +310,36 @@ $(document).ready(function(){
}
},
data:[
{value:{{ month_user_active }}, name:"{% trans 'Monthly active users' %}"},
{value:{{ month_user_disabled }}, name:"{% trans 'Disable user' %}"},
{value:{{ month_user_inactive }}, name:"{% trans 'Month not logged in user' %}"}
{value:data['month_total_count_active_users'], name:"{% trans 'Monthly active users' %}"},
{value:data['month_total_count_disabled_users'], name:"{% trans 'Disable user' %}"},
{value:data['month_total_count_inactive_users'], name:"{% trans 'Month not logged in user' %}"}
]
}
]
};
auChart.setOption(option);
monthTotalCountUsersPie.setOption(option);
}
);
}
function requireMonthTotalCountAssetsPie(data){
require(
[
'echarts',
'echarts/chart/pie'
],
function (ec) {
var aaChart = ec.init(document.getElementById('activeAsset'));
var monthTotalCountAssetsPie = ec.init(document.getElementById('month_total_count_assets_pie'));
var option = {
tooltip : {
trigger: 'item',
formatter: "{b} <br> {c} ({d}%)"
formatter: "{b} <br> {c} <br> ({d}%)"
},
legend: {
show: false,
orient : 'vertical',
x : 'left',
data:["{% trans 'Month is logged into the host' %}", "{% trans 'Disable host' %}", "{% trans 'Month not logged on host' %}"]
data:["{% trans 'Month is logged into the asset' %}", "{% trans 'Disable host' %}", "{% trans 'Month not logged on host' %}"]
},
toolbox: {
show : false,
@ -461,16 +389,230 @@ $(document).ready(function(){
}
},
data:[
{value:{{ month_asset_active }}, name:"{% trans 'Month is logged into the host' %}"},
{value:{{ month_asset_disabled }}, name:"{% trans 'Disable host' %}"},
{value:{{ month_asset_inactive }}, name:"{% trans 'Month not logged on host' %}"}
{value:data['month_total_count_active_assets'], name:"{% trans 'Month is logged into the host' %}"},
{value:data['month_total_count_disabled_assets'], name:"{% trans 'Disable host' %}"},
{value:data['month_total_count_inactive_assets'], name:"{% trans 'Month not logged on host' %}"}
]
}
]
};
aaChart.setOption(option);
monthTotalCountAssetsPie.setOption(option);
}
);
}
var indexUrl = "/api/v1/index/";
function renderRequestApi(query, success, error){
var url = indexUrl + "?" + query;
if (!error){
error = function (){console.log("Request url error: " + url)}
}
requestApi({
url: url,
method: "GET",
success: success,
error: error,
flash_message: false,
})
}
function renderTotalCount(){
var success = function (data) {
$('#total_count_assets').html(data['total_count_assets']);
$('#total_count_users').html(data['total_count_users']);
$('#total_count_online_users').html(data['total_count_online_users']);
$('#total_count_online_assets').html(data['total_count_online_assets']);
};
renderRequestApi('total_count=1', success);
}
function renderMonthMetricsECharts(){
var success = function (data) {
requireMonthMetricsECharts(data)
};
renderRequestApi('month_metrics=1', success)
}
function renderMonthTotalCountUsersPie(){
var success = function (data) {
requireMonthTotalCountUsersPie(data)
};
renderRequestApi('month_total_count_users=1', success)
}
function renderMonthTotalCountAssetsPie(){
var success = function (data) {
requireMonthTotalCountAssetsPie(data)
};
renderRequestApi('month_total_count_assets=1', success)
}
function renderWeekTotalCount(){
var success = function (data) {
$('#week_total_count_login_users').html(data['week_total_count_login_users']);
$('#week_total_count_login_times').html(data['week_total_count_login_times'])
};
renderRequestApi('week_total_count=1', success)
}
function renderWeekLoginTimesTop5Users(){
var success = function (data){
var html = "";
var html_cell = "" +
"<li class=\"list-group-item fist-item\">" +
"<span class=\"pull-right\">" +
"{TOTAL} {% trans ' times/week' %}" +
"</span>" +
"<span class=\"label \">{INDEX}</span> {USER}" +
"</li>";
$.each(data['week_login_times_top5_users'], function(index, value){
html += html_cell.replace('{TOTAL}', value['total'])
.replace('{USER}', value['user'])
.replace('{INDEX}', index+1)
});
$('#week_login_times_top5_users').html(html)
};
renderRequestApi('week_login_times_top5_users=1', success)
}
function renderWeekLoginTimesTop10Assets(){
var success = function (data){
var html = "";
var html_cell = "" +
"<div class=\"timeline-item\">" +
"<div class=\"row\">" +
"<div class=\"col-xs-5 date ellipsis\">" +
"<i class=\"fa fa-info-circle\"></i>" +
"<strong data-toggle=\"tooltip\" title=\"{ASSET}\">{ASSET}</strong>" +
"<br/>" +
"<small class=\"text-navy\">{TOTAL}{% trans ' times' %}</small>" +
"</div>" +
"<div class=\"col-xs-7 content no-top-border\">" +
"<p class=\"m-b-xs\">{% trans 'The time last logged in' %}</p>" +
"<p>{% trans 'At' %} {DATE_LAST}</p>" +
"</div>" +
"</div>" +
"</div>";
var assets = data['week_login_times_top10_assets'];
if (assets.length !== 0){
$.each(assets, function(index, value){
html += html_cell
.replaceAll('{ASSET}', value['asset'])
.replace('{TOTAL}', value['total'])
.replace('{DATE_LAST}', toSafeLocalDateStr(value['last']))
});
}
else{
html += "<p class=\"text-center\">{% trans '(No)' %}</p>"
}
$('#week_login_times_top10_assets').html(html)
};
renderRequestApi('week_login_times_top10_assets=1', success)
}
function renderWeekLoginTimesTop10Users(){
var success = function (data){
var html = "";
var html_cell = "" +
"<div class=\"timeline-item\">" +
"<div class=\"row\">" +
"<div class=\"col-xs-5 date ellipsis\">" +
"<i class=\"fa fa-info-circle\"></i>" +
"<strong data-toggle=\"tooltip\" title=\"{USER}\">{USER}</strong>" +
"<br/>" +
"<small class=\"text-navy\">{TOTAL}{% trans ' times' %}</small>" +
"</div>" +
"<div class=\"col-xs-7 content no-top-border\">" +
"<p class=\"m-b-xs\">{% trans 'The time last logged in' %}</p>" +
"<p>{% trans 'At' %} {DATE_LAST}</p>" +
"</div>" +
"</div>" +
"</div>";
var users = data['week_login_times_top10_users'];
if (users.length !== 0){
$.each(users, function(index, value){
html += html_cell.replaceAll('{USER}', value['user'])
.replace('{TOTAL}', value['total'])
.replace('{DATE_LAST}', toSafeLocalDateStr(value['last']))
});
}
else{
html += "<p class=\"text-center\">{% trans '(No)' %}</p>"
}
$('#week_login_times_top10_users').html(html)
};
renderRequestApi('week_login_times_top10_users=1', success)
}
function renderWeekLoginRecordTop10Sessions(){
var success = function (data){
var html = "";
var html_cell = "" +
"<div class=\"feed-element\">" +
"<a href=\"#\" class=\"pull-left\">" +
"<img alt=\"image\" class=\"img-circle\" src=\"{% static 'img/avatar/user.png' %}\">" +
"</a>" +
"<div class=\"media-body \">" +
"<small class=\"pull-right {TEXT_NAVY}\">{TIMESINCE} {% trans 'Before' %}</small>" +
"<strong>{USER}</strong> {% trans 'Login in ' %}{ASSET} <br>" +
"<small class=\"text-muted\">{DATE_START}</small>" +
"</div>" +
"</div>";
var users = data['week_login_record_top10_sessions'];
if (users.length !== 0){
$.each(users, function(index, value){
console.log(value['is_finished'])
html += html_cell.replaceAll('{USER}', value['user'])
.replace('{ASSET}', value['asset'])
.replace('{DATE_START}', toSafeLocalDateStr(value['date_start']))
.replace('{TEXT_NAVY}', value['is_finished']?'':'text-navy')
.replace('{TIMESINCE}', value['timesince'])
});
}
else{
html += "<p class=\"text-center\">{% trans '(No)' %}</p>"
}
$('#week_login_record_top10_sessions').html(html)
};
renderRequestApi('week_login_record_top10_sessions=1', success)
}
function renderData(){
renderTotalCount();
renderMonthMetricsECharts();
renderMonthTotalCountUsersPie();
renderMonthTotalCountAssetsPie();
renderWeekTotalCount();
renderWeekLoginTimesTop5Users();
renderWeekLoginTimesTop10Assets();
renderWeekLoginRecordTop10Sessions();
renderWeekLoginTimesTop10Users();
}
require.config({
paths: {
'echarts': '/static/js/plugins/echarts/chart/',
'echarts/chart/line': '/static/js/plugins/echarts/chart/line',
'echarts/chart/pie': '/static/js/plugins/echarts/chart/pie'
}
});
$(document).ready(function(){
$('#show').click(function(){
$('#show').css('display', 'none');
$('#more').css('display', 'block');
});
$("[data-toggle='tooltip']").tooltip();
renderData()
});
</script>
{% endblock %}