def administrator(request): staff_netid = request.user.netid now = timezone.now() try: staff = StaffStatus.objects.get(staff_netid=staff_netid) except StaffStatus.DoesNotExist as e: logger.warning(f"Staff {staff_netid} does not exist.") logger.warning(e) return render(request, 'main/404.html') students = StudentChatStatus.objects \ .filter(chat_request_time__gte=day_start()) \ .order_by('chat_request_time') histories = StudentChatHistory.objects \ .filter(chat_request_time__gte=day_start()) \ .order_by('chat_request_time') high_risk_students = ChatBotSession.get_high_risk_student() return render( request, 'main/administrator.html', { 'staff': staff, 'students': students, 'histories': histories, 'high_risk_students': high_risk_students, 'now': now, 'selectable_status': SELECTABLE_STATUS })
def test_statis_overview(self): start_date = timezone.localtime().replace(day=self.days[0], hour=0, minute=0, second=0) end_date = timezone.localtime().replace(day=self.days[-1], hour=23, minute=59, second=59) res = dict() res.update(ChatBotSession.statis_overview(start_date, end_date)) res.update(StudentChatHistory.statis_overview(start_date, end_date)) print('Overview:') print(res) self.assertEqual(res['total_access_count'], 70) self.assertEqual(res['access_office_hr_count'], 27) self.assertEqual(res['polyu_student_count'], 70 / 2) self.assertEqual(res['non_polyu_student_count'], 70 / 2) self.assertListEqual(list(res.keys()), [ 'total_access_count', 'access_office_hr_count', 'polyu_student_count', 'non_polyu_student_count', 'score_green_count', 'score_yellow_count', 'score_red_count', 'mh101_access_count', 'poss_access_count', 'online_chat_access_count', 'successful_chat_count' ]) self.assertEqual( res['score_green_count'] + res['score_yellow_count'] + res['score_red_count'], 70)
def export_red_route(request): data = json.loads(request.body) before_date = data.get('beforeDate') if before_date is None: to_date = timezone.localtime() else: to_date = datetime.strptime(before_date, '%Y-%m-%d') from_date = to_date - timedelta(days=7) data = ChatBotSession.get_red_route(from_date, to_date) output = ChatBotSession.from_red_route_to_excel(data) response = HttpResponse( output, content_type= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename="red_route.xlsx"' return response
def test_get_red_route(self): # 1 Aug is Sun and 7 Aug is Sat start_date = date(2021, 8, 4) start_dt = datetime.combine(start_date, datetime.min.time()) res = ChatBotSession.get_red_route(start_dt) self.assertEqual(len(res), 40) self.assertListEqual( list(res[0].keys()), ['student_netid', 'datetime', 'date', 'start_time', 'end_time'])
def get_red_route(request): data = json.loads(request.body) before_date = data.get('beforeDate') from_date = datetime.strptime(before_date, '%Y-%m-%d') - timedelta(days=7) to_date = datetime.strptime(before_date, '%Y-%m-%d') res = ChatBotSession.get_red_route(from_date, to_date) return JsonResponse(res, safe=False, status=200)
def test_create_chatbot_session(self): session = self.client.session chatbot_session = ChatBotSession.usage_chatbot_connect( student_netid='12345678A', is_ployu_student=True) session['session_id'] = chatbot_session.session_id retrieved_session = ChatBotSession.objects.get( session_id=session['session_id']) self.assertEqual(chatbot_session.session_id, retrieved_session.session_id)
def login_sso_callback(request): try: encoded_jwt = request.POST.get('data') if not encoded_jwt: return render(request, 'main/login_sso.html', {'error_message': "Cannot get JWT"}) decoded_jwt = sso_auth.decode(encoded_jwt) if decoded_jwt['polyuUserType'] == 'Student': try: student_netid = decoded_jwt.get('sub', '').upper() student_user = User.objects.get(netid=student_netid) except User.DoesNotExist: student_user = User.objects.create_user(netid=student_netid, is_active=True) authenticate(requests, netid=student_netid) login(request, student_user, backend='django.contrib.auth.backends.ModelBackend') chatbot_session = ChatBotSession.usage_chatbot_connect( student_netid=student_netid, is_ployu_student=True) request.session['session_id'] = uuid2str( chatbot_session.session_id) return redirect('index') elif decoded_jwt['polyuUserType'] == 'Staff': staff_netid = decoded_jwt['cn'] user = authenticate(requests, netid=staff_netid) user_group = user.get_groups() request.session['user_group'] = user_group login(request, user) return redirect('login_staff') ChatBotSession.usage_chatbot_connect() except (Exception, UnauthorizedException) as e: logger.warning(e) return redirect('login')
def get_statistics(request): data = json.loads(request.body) from_date = data.get('fromDate') to_date = data.get('toDate') f = datetime.strptime(from_date, '%Y-%m-%d') t = datetime.strptime(to_date, '%Y-%m-%d') res = { **ChatBotSession.statis_overview(f, t), **StudentChatHistory.statis_overview(f, t) } return JsonResponse(res, status=200)
def export_statistics(request): data = json.loads(request.body) from_date = data.get('fromDate') to_date = data.get('toDate') f = datetime.strptime(from_date, '%Y-%m-%d') t = datetime.strptime(to_date, '%Y-%m-%d') logger.info('Query from corresponding tables.') chatbot_stat_data = ChatBotSession.objects \ .filter(start_time__range=[f, t]) \ .order_by('start_time') \ .all() online_chat_stat_data = StudentChatHistory.objects \ .filter(chat_request_time__range=[f, t]) \ .order_by('chat_request_time') \ .all() overall_stat = { **ChatBotSession.statis_overview(f, t), **StudentChatHistory.statis_overview(f, t) } chatbot_stat_file = write_chatbot_stat(list(chatbot_stat_data)) online_chat_stat_file = write_online_chat_stat(list(online_chat_stat_data)) overall_stat_file = write_overall_stat(overall_stat, f, t) logger.info('Zip all files.') output = write_zip_files({ 'chatbot_statistics.xlsx': chatbot_stat_file, 'online_chat_statistics.xlsx': online_chat_stat_file, 'overall_statistics.xlsx': overall_stat_file }) response = HttpResponse(output, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="statistics.zip"' return response
def _get_session_id(self, ) -> uuid.UUID: # create a login session and retrieve the chatbot_session = ChatBotSession.usage_chatbot_connect( student_netid='12345678A', is_ployu_student=True) return chatbot_session.session_id