From 20cb8021b84dd7158c1226356ff453c9d4480076 Mon Sep 17 00:00:00 2001 From: Jonathan Bobel Date: Thu, 20 Jun 2024 11:16:46 -0400 Subject: [PATCH] Update for a second pair of eyes --- .../javascripts/dashboardVisualization.js | 70 +++++++------------ app/main/views/dashboard.py | 23 +++++- app/notify_client/service_api_client.py | 14 +++- poetry.lock | 1 - 4 files changed, 61 insertions(+), 47 deletions(-) diff --git a/app/assets/javascripts/dashboardVisualization.js b/app/assets/javascripts/dashboardVisualization.js index 53a3ce1a3..d83c63b35 100644 --- a/app/assets/javascripts/dashboardVisualization.js +++ b/app/assets/javascripts/dashboardVisualization.js @@ -179,21 +179,22 @@ table.append(tbody); } - function fetchServiceData() { + function fetchData(type) { var ctx = document.getElementById('weeklyChart'); if (!ctx) { return; } var socket = io(); - var serviceId = ctx.getAttribute('data-service-id'); + var eventType = type === 'service' ? 'fetch_daily_stats' : 'fetch_daily_stats_by_user'; socket.on('connect', function() { - socket.emit('fetch_daily_stats', serviceId); - // socket.emit('fetch_daily_stats_by_user', serviceId); + socket.emit(eventType); }); socket.on('daily_stats_update', function(data) { + console.log('Received data:', data); // Log the received data + var labels = []; var deliveredData = []; var failedData = []; @@ -201,13 +202,17 @@ for (var dateString in data) { // Parse the date string (assuming format YYYY-MM-DD) const dateParts = dateString.split('-'); - const formattedDate = `${dateParts[1]}/${dateParts[2]}/${dateParts[0]}`; // Format to MM/DD/YYYY + const formattedDate = `${dateParts[1]}/${dateParts[2]}/${dateParts[0].slice(2)}`; // Format to MM/DD/YY labels.push(formattedDate); deliveredData.push(data[dateString].sms.delivered); failedData.push(data[dateString].sms.failed !== undefined ? data[dateString].sms.failed : 0); } + console.log('Formatted labels:', labels); // Log the formatted labels + console.log('Delivered data:', deliveredData); // Log the delivered data + console.log('Failed data:', failedData); // Log the failed data + createChart('#weeklyChart', labels, deliveredData, failedData); createTable('weeklyTable', 'Weekly', labels, deliveredData, failedData); }); @@ -217,55 +222,34 @@ }); } - // Function to handle dropdown change function handleDropdownChange(event) { - const selectedValue = event.target.value; - const subTitle = document.querySelector(`#chartsArea .chart-subtitle`); - const selectElement = document.getElementById('options'); - const selectedText = selectElement.options[selectElement.selectedIndex].text; + const selectedValue = event.target.value; + const subTitle = document.querySelector(`#chartsArea .chart-subtitle`); + const selectElement = document.getElementById('options'); + const selectedText = selectElement.options[selectElement.selectedIndex].text; - if (selectedValue === "individual") { - // Get today's date - const today = new Date(); - - // Function to generate labels for the last 7 days (including today) - function getLabelsForLast7Days() { - const labels = []; - for (let i = 6; i >= 0; i--) { - const pastDate = new Date(today.getTime() - (i * 24 * 60 * 60 * 1000)); // Subtract i days from today - const day = pastDate.getDate(); - const month = pastDate.getMonth() + 1; // Months are 0-indexed - labels.push(`${month}/${day}/${pastDate.getFullYear()}`); - } - - return labels; - } - - const labels = getLabelsForLast7Days(); - const deliveredData = labels.map(() => Math.floor(Math.random() * 5) + 1); // Random between 1 and 5 - const failedData = [0, 1, 0, 0, 1, 2, 1]; - subTitle.textContent = selectedText + " - Last 7 Days"; - createChart('#weeklyChart', labels, deliveredData, failedData); - createTable('weeklyTable', 'Weekly', labels, deliveredData, failedData); + if (selectedValue === "individual") { + subTitle.textContent = selectedText + " - Last 7 Days"; + fetchData('individual'); } else if (selectedValue === "service") { subTitle.textContent = selectedText + " - Last 7 Days"; - // Fetch and use real service data - fetchServiceData(); + fetchData('service'); } } + document.addEventListener('DOMContentLoaded', function() { + // Initialize weekly chart and table with service data by default + fetchData('service'); + + // Add event listener to the dropdown + const dropdown = document.getElementById('options'); + dropdown.addEventListener('change', handleDropdownChange); + }); + // Resize chart on window resize window.addEventListener('resize', function() { const selectedValue = document.getElementById('options').value; handleDropdownChange({ target: { value: selectedValue } }); }); - document.addEventListener('DOMContentLoaded', function() { - // Initialize weekly chart and table with service data by default - fetchServiceData(); - - // Add event listener to the dropdown - const dropdown = document.getElementById('options'); - dropdown.addEventListener('change', handleDropdownChange); - }); })(window); diff --git a/app/main/views/dashboard.py b/app/main/views/dashboard.py index a64444dc2..ae58ff226 100644 --- a/app/main/views/dashboard.py +++ b/app/main/views/dashboard.py @@ -35,7 +35,8 @@ from notifications_utils.recipients import format_phone_number_human_readable @socketio.on("fetch_daily_stats") -def handle_fetch_daily_stats(service_id): +def handle_fetch_daily_stats(): + service_id = session.get('service_id') if service_id: date_range = get_stats_date_range() daily_stats = service_api_client.get_service_notification_statistics_by_day( @@ -46,6 +47,25 @@ def handle_fetch_daily_stats(service_id): emit("error", {"error": "No service_id provided"}) +@socketio.on("fetch_daily_stats_by_user") +def handle_fetch_daily_stats_by_user(): + service_id = session.get("service_id") + user_id = session.get("user_id") + if service_id and user_id: + date_range = get_stats_date_range() + daily_stats_by_user = ( + service_api_client.get_user_service_notification_statistics_by_day( + service_id, + user_id, + start_date=date_range["start_date"], + days=date_range["days"], + ) + ) + emit("daily_stats_by_user_update", daily_stats_by_user) + else: + emit("error", {"error": "No service_id or user_id provided"}) + + @main.route("/services//dashboard") @user_has_permissions("view_activity", "send_messages") def old_service_dashboard(service_id): @@ -98,7 +118,6 @@ def service_dashboard(service_id): partials=get_dashboard_partials(service_id), job_and_notifications=job_and_notifications, service_data_retention_days=service_data_retention_days, - service_id=service_id, ) diff --git a/app/notify_client/service_api_client.py b/app/notify_client/service_api_client.py index 42f54572f..3a0655d9e 100644 --- a/app/notify_client/service_api_client.py +++ b/app/notify_client/service_api_client.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, timezone from app.extensions import redis_client from app.notify_client import NotifyAdminAPIClient, _attach_current_user, cache @@ -53,6 +53,18 @@ class ServiceAPIClient(NotifyAdminAPIClient): "/service/{0}/statistics/{1}/{2}".format(service_id, start_date, days), )["data"] + def get_user_service_notification_statistics_by_day( + self, service_id, user_id, start_date=None, days=None + ): + if start_date is None: + start_date = datetime.now(timezone.utc).strftime("%Y-%m-%d") + + return self.get( + "/service/{0}/statistics/user/{1}/{2}/{3}".format( + service_id, user_id, start_date, days + ), + )["data"] + def get_services(self, params_dict=None): """ Retrieve a list of services. diff --git a/poetry.lock b/poetry.lock index b13267749..b5ffdb0cb 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1681,7 +1681,6 @@ files = [ {file = "msgpack-1.0.8-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5fbb160554e319f7b22ecf530a80a3ff496d38e8e07ae763b9e82fadfe96f273"}, {file = "msgpack-1.0.8-cp39-cp39-win32.whl", hash = "sha256:f9af38a89b6a5c04b7d18c492c8ccf2aee7048aff1ce8437c4683bb5a1df893d"}, {file = "msgpack-1.0.8-cp39-cp39-win_amd64.whl", hash = "sha256:ed59dd52075f8fc91da6053b12e8c89e37aa043f8986efd89e61fae69dc1b011"}, - {file = "msgpack-1.0.8-py3-none-any.whl", hash = "sha256:24f727df1e20b9876fa6e95f840a2a2651e34c0ad147676356f4bf5fbb0206ca"}, {file = "msgpack-1.0.8.tar.gz", hash = "sha256:95c02b0e27e706e48d0e5426d1710ca78e0f0628d6e89d5b5a5b91a5f12274f3"}, ]