This commit is contained in:
Beverly Nguyen
2025-01-13 15:54:04 -08:00
parent 30293d9774
commit 6d008d4e45
9 changed files with 195 additions and 230 deletions

View File

@@ -13,7 +13,7 @@
const FONT_WEIGHT = 'bold'; const FONT_WEIGHT = 'bold';
const MAX_Y = 120; const MAX_Y = 120;
const createChart = function(containerId, labels, deliveredData, failedData) { const createChart = function(containerId, labels, deliveredData, failedData, pendingData) {
const container = d3.select(containerId); const container = d3.select(containerId);
container.selectAll('*').remove(); // Clear any existing content container.selectAll('*').remove(); // Clear any existing content
@@ -36,7 +36,7 @@
} }
// Calculate total messages // Calculate total messages
const totalMessages = d3.sum(deliveredData) + d3.sum(failedData); const totalMessages = d3.sum(deliveredData) + d3.sum(failedData) + d3.sum(pendingData);
// Create legend only if there are messages // Create legend only if there are messages
const legendContainer = d3.select('.chart-legend'); const legendContainer = d3.select('.chart-legend');
@@ -78,8 +78,9 @@
.range([0, width]) .range([0, width])
.padding(0.1); .padding(0.1);
// Adjust the y-axis domain to add some space above the tallest bar // Adjust the y-axis domain to add some space above the tallest bar
const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0))); const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0) + (pendingData[i] || 0)));
const y = d3.scaleSqrt()
const y = d3.scaleSymlog()
.domain([0, maxY + 2]) // Add 2 units of space at the top .domain([0, maxY + 2]) // Add 2 units of space at the top
.nice() .nice()
.range([height, 0]); .range([height, 0]);
@@ -91,7 +92,7 @@
// Generate the y-axis with whole numbers // Generate the y-axis with whole numbers
const yAxis = d3.axisLeft(y) const yAxis = d3.axisLeft(y)
.ticks(Math.min(maxY + 2, 10)) // Generate up to 10 ticks based on the data .ticks(Math.min(maxY + 2, 3))
.tickFormat(d3.format('d')); // Ensure whole numbers on the y-axis .tickFormat(d3.format('d')); // Ensure whole numbers on the y-axis
svg.append('g') svg.append('g')
@@ -102,7 +103,7 @@
const stackData = labels.map((label, i) => ({ const stackData = labels.map((label, i) => ({
label: label, label: label,
delivered: deliveredData[i], delivered: deliveredData[i],
failed: failedData[i] || 0, // Ensure there's a value for failed, even if it's 0 failed: failedData[i] || 0,
pending: pendingData[i] || 0 pending: pendingData[i] || 0
})); }));
@@ -119,149 +120,150 @@
.domain(['delivered', 'failed', 'pending']) .domain(['delivered', 'failed', 'pending'])
.range([COLORS.delivered, COLORS.failed, COLORS.pending]); .range([COLORS.delivered, COLORS.failed, COLORS.pending]);
// Create bars with animation // Create bars with animation
const barGroups = svg.selectAll('.bar-group') const barGroups = svg.selectAll('.bar-group')
.data(series) .data(series)
.enter() .enter()
.append('g') .append('g')
.attr('class', 'bar-group') .attr('class', 'bar-group')
.attr('fill', d => color(d.key)); .attr('fill', d => color(d.key));
barGroups.selectAll('rect') barGroups.selectAll('rect')
.data(d => d) .data(d => d)
.enter() .enter()
.append('rect') .append('rect')
.attr('x', d => x(d.data.label)) .attr('x', d => x(d.data.label))
.attr('y', height) .attr('y', height)
.attr('height', 0) .attr('height', 0)
.attr('width', x.bandwidth()) .attr('width', x.bandwidth())
.on('mouseover', function(event, d) { .on('mouseover', function(event, d) {
const key = d3.select(this.parentNode).datum().key; const key = d3.select(this.parentNode).datum().key;
const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1); const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
tooltip.style('display', 'block') tooltip.style('display', 'block')
.html(`${d.data.label}<br>${capitalizedKey}: ${d.data[key]}`); .html(`${d.data.label}<br>${capitalizedKey}: ${d.data[key]}`);
}) })
.on('mousemove', function(event) { .on('mousemove', function(event) {
tooltip.style('left', `${event.pageX + 10}px`) tooltip.style('left', `${event.pageX + 10}px`)
.style('top', `${event.pageY - 20}px`); .style('top', `${event.pageY - 20}px`);
}) })
.on('mouseout', function() { .on('mouseout', function() {
tooltip.style('display', 'none'); tooltip.style('display', 'none');
}) })
.transition() .transition()
.duration(1000) .duration(1000)
.attr('y', d => y(d[1])) .attr('y', d => y(d[1]))
.attr('height', d => y(d[0]) - y(d[1])); .attr('height', d => y(d[0]) - y(d[1]));
}; };
// Function to create an accessible table // Function to create an accessible table
const createTable = function(tableId, chartType, labels, deliveredData, failedData) { const createTable = function(tableId, chartType, labels, deliveredData, failedData, pendingData) {
const table = document.getElementById(tableId); const table = document.getElementById(tableId);
table.innerHTML = ""; // Clear previous data table.innerHTML = ""; // Clear previous data
const captionText = document.querySelector(`#${chartType} .chart-subtitle`).textContent; const captionText = document.querySelector(`#${chartType} .chart-subtitle`).textContent;
const caption = document.createElement('caption'); const caption = document.createElement('caption');
caption.textContent = captionText; caption.textContent = captionText;
const thead = document.createElement('thead'); const thead = document.createElement('thead');
const tbody = document.createElement('tbody'); const tbody = document.createElement('tbody');
// Create table header // Create table header
const headerRow = document.createElement('tr'); const headerRow = document.createElement('tr');
const headers = ['Day', 'Delivered', 'Failed', 'Pending']; const headers = ['Day', 'Delivered', 'Failed', 'Pending'];
headers.forEach(headerText => { headers.forEach(headerText => {
const th = document.createElement('th'); const th = document.createElement('th');
th.textContent = headerText; th.textContent = headerText;
headerRow.appendChild(th); headerRow.appendChild(th);
}); });
thead.appendChild(headerRow); thead.appendChild(headerRow);
// Create table body // Create table body
labels.forEach((label, index) => { labels.forEach((label, index) => {
const row = document.createElement('tr'); const row = document.createElement('tr');
const cellDay = document.createElement('td'); const cellDay = document.createElement('td');
cellDay.textContent = label; cellDay.textContent = label;
row.appendChild(cellDay); row.appendChild(cellDay);
const cellDelivered = document.createElement('td'); const cellDelivered = document.createElement('td');
cellDelivered.textContent = deliveredData[index]; cellDelivered.textContent = deliveredData[index];
row.appendChild(cellDelivered); row.appendChild(cellDelivered);
const cellFailed = document.createElement('td'); const cellFailed = document.createElement('td');
cellFailed.textContent = failedData[index]; cellFailed.textContent = failedData[index];
row.appendChild(cellFailed); row.appendChild(cellFailed);
const cellPending = document.createElement('td'); const cellPending = document.createElement('td');
cellPending.textContent = pendingData[index]; cellPending.textContent = pendingData[index];
row.appendChild(cellPending); row.appendChild(cellPending);
tbody.appendChild(row); tbody.appendChild(row);
}); });
table.appendChild(caption); table.appendChild(caption);
table.appendChild(thead); table.appendChild(thead);
table.append(tbody); table.append(tbody);
}; };
const fetchData = function(type) { const fetchData = function(type) {
var ctx = document.getElementById('weeklyChart'); var ctx = document.getElementById('weeklyChart');
if (!ctx) { if (!ctx) {
return; return;
} }
var url = type === 'service' ? `/daily_stats.json` : `/daily_stats_by_user.json`; var url = type === 'service' ? `/daily_stats.json` : `/daily_stats_by_user.json`;
return fetch(url) return fetch(url)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
labels = [];
deliveredData = [];
failedData = [];
pendingData = [];
let totalMessages = 0;
for (var dateString in data) {
if (data.hasOwnProperty(dateString)) {
const dateParts = dateString.split('-');
const formattedDate = `${dateParts[1]}/${dateParts[2]}/${dateParts[0].slice(2)}`;
labels.push(formattedDate);
deliveredData.push(data[dateString].sms.delivered);
failedData.push(data[dateString].sms.failure);
pendingData.push(data[dateString].sms.pending || 0);
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure + data[dateString].sms.pending;
// Calculate the total number of messages
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure;
} }
return response.json(); }
})
.then(data => {
labels = [];
deliveredData = [];
failedData = [];
pendingData = [];
let totalMessages = 0; // Check if there are no messages sent
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
for (var dateString in data) { if (totalMessages === 0) {
if (data.hasOwnProperty(dateString)) { // Remove existing chart and render the alert message
const dateParts = dateString.split('-'); d3.select('#weeklyChart').selectAll('*').remove();
const formattedDate = `${dateParts[1]}/${dateParts[2]}/${dateParts[0].slice(2)}`; d3.select('#weeklyChart')
.append('div')
labels.push(formattedDate); .html(`
deliveredData.push(data[dateString].sms.delivered); <div class="usa-alert usa-alert--info usa-alert--slim">
failedData.push(data[dateString].sms.failure); <div class="usa-alert__body">
pendingData.push(data[dateString].sms.pending || 0); <p class="usa-alert__text">
// Calculate the total number of messages No messages sent in the last 7 days
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure; </p>
}
}
// Check if there are no messages sent
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
if (totalMessages === 0) {
// Remove existing chart and render the alert message
d3.select('#weeklyChart').selectAll('*').remove();
d3.select('#weeklyChart')
.append('div')
.html(`
<div class="usa-alert usa-alert--info usa-alert--slim">
<div class="usa-alert__body">
<p class="usa-alert__text">
No messages sent in the last 7 days
</p>
</div>
</div> </div>
`); </div>
// Hide the subtitle `);
if (subTitle) { // Hide the subtitle
subTitle.style.display = 'none'; if (subTitle) {
} subTitle.style.display = 'none';
} else { }
// If there are messages, create the chart and table } else {
createChart('#weeklyChart', labels, deliveredData, failedData); // If there are messages, create the chart and table
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData); createChart('#weeklyChart', labels, deliveredData, failedData, pendingData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData, pendingData);
} }
return data; return data;
@@ -269,53 +271,53 @@
.catch(error => console.error('Error fetching daily stats:', error)); .catch(error => console.error('Error fetching daily stats:', error));
}; };
setInterval(() => fetchData('service'), 10000); setInterval(() => fetchData('service'), 10000);
const handleDropdownChange = function(event) { const handleDropdownChange = function(event) {
const selectedValue = event.target.value; const selectedValue = event.target.value;
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`); const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
const selectElement = document.getElementById('options'); const selectElement = document.getElementById('options');
const selectedText = selectElement.options[selectElement.selectedIndex].text; const selectedText = selectElement.options[selectElement.selectedIndex].text;
subTitle.textContent = `${selectedText} - last 7 days`; subTitle.textContent = `${selectedText} - last 7 days`;
fetchData(selectedValue); fetchData(selectedValue);
// Update ARIA live region // Update ARIA live region
const liveRegion = document.getElementById('aria-live-account'); const liveRegion = document.getElementById('aria-live-account');
liveRegion.textContent = `Data updated for ${selectedText} - last 7 days`; liveRegion.textContent = `Data updated for ${selectedText} - last 7 days`;
// Switch tables based on dropdown selection // Switch tables based on dropdown selection
const selectedTable = selectedValue === "individual" ? "table1" : "table2"; const selectedTable = selectedValue === "individual" ? "table1" : "table2";
const tables = document.querySelectorAll('.table-overflow-x-auto'); const tables = document.querySelectorAll('.table-overflow-x-auto');
tables.forEach(function(table) { tables.forEach(function(table) {
table.classList.add('hidden'); // Hide all tables by adding the hidden class table.classList.add('hidden'); // Hide all tables by adding the hidden class
table.classList.remove('visible'); // Ensure they are not visible table.classList.remove('visible'); // Ensure they are not visible
}); });
const tableToShow = document.getElementById(selectedTable); const tableToShow = document.getElementById(selectedTable);
tableToShow.classList.remove('hidden'); // Remove hidden class tableToShow.classList.remove('hidden'); // Remove hidden class
tableToShow.classList.add('visible'); // Add visible class tableToShow.classList.add('visible'); // Add visible class
}; };
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
// Initialize activityChart chart and table with service data by default // Initialize activityChart chart and table with service data by default
fetchData('service'); fetchData('service');
// Add event listener to the dropdown // Add event listener to the dropdown
const dropdown = document.getElementById('options'); const dropdown = document.getElementById('options');
dropdown.addEventListener('change', handleDropdownChange); dropdown.addEventListener('change', handleDropdownChange);
});
// Resize chart on window resize
window.addEventListener('resize', function() {
if (labels.length > 0 && deliveredData.length > 0 && failedData.length > 0 && pendingData.length > 0) {
createChart('#weeklyChart', labels, deliveredData, failedData, pendingData);
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData, pendingData);
}
}); });
// Resize chart on window resize // Export functions for testing
window.addEventListener('resize', function() { window.createChart = createChart;
if (labels.length > 0 && deliveredData.length > 0 && failedData.length > 0) { window.createTable = createTable;
createChart('#weeklyChart', labels, deliveredData, failedData); window.handleDropdownChange = handleDropdownChange;
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData); window.fetchData = fetchData;
} }
});
// Export functions for testing
window.createChart = createChart;
window.createTable = createTable;
window.handleDropdownChange = handleDropdownChange;
window.fetchData = fetchData;
}
})(window); })(window);

View File

@@ -94,8 +94,19 @@ def service_dashboard(service_id):
) )
@main.route("/services/<uuid:service_id>/daily_stats_by_user.json") @main.route("/daily_stats.json")
def get_daily_stats_by_user(service_id): def get_daily_stats():
service_id = session.get("service_id")
date_range = get_stats_date_range()
stats = service_api_client.get_service_notification_statistics_by_day(
service_id, start_date=date_range["start_date"], days=date_range["days"]
)
return jsonify(stats)
@main.route("/daily_stats_by_user.json")
def get_daily_stats_by_user():
service_id = session.get("service_id") service_id = session.get("service_id")
date_range = get_stats_date_range() date_range = get_stats_date_range()
user_id = current_user.id user_id = current_user.id
@@ -349,35 +360,7 @@ def aggregate_notifications_stats(template_statistics):
return notifications return notifications
def fetch_daily_stats(service_id):
date_range = get_stats_date_range()
stats = service_api_client.get_service_notification_statistics_by_day(
service_id, start_date='2025-01-09', days=date_range["days"]
)
return stats
# Route using the helper
@main.route("/daily_stats.json")
def get_daily_stats():
service_id = session.get("service_id")
stats = fetch_daily_stats(service_id) # Use the helper
return jsonify(stats)
def get_dashboard_partials(service_id): def get_dashboard_partials(service_id):
date_range = get_stats_date_range()
yearly_usage = billing_api_client.get_annual_usage_for_service(
service_id,
get_current_financial_year(),
)
free_sms_allowance = billing_api_client.get_free_sms_fragment_limit_for_year(
current_service.id,
)
usage_data = get_annual_usage_breakdown(yearly_usage, free_sms_allowance)
sms_sent = usage_data["sms_sent"]
sms_allowance_remaining = usage_data["sms_allowance_remaining"]
activityStats = fetch_daily_stats
all_statistics = template_statistics_client.get_template_statistics_for_service( all_statistics = template_statistics_client.get_template_statistics_for_service(
service_id, limit_days=7 service_id, limit_days=7
) )
@@ -401,12 +384,6 @@ def get_dashboard_partials(service_id):
get_current_financial_year(), get_current_financial_year(),
) )
return { return {
"activity": render_template(
"views/dashboard/_activity.html",
activityStats=activityStats,
sms_sent=sms_sent,
sms_allowance_remaining=sms_allowance_remaining,
),
"upcoming": render_template( "upcoming": render_template(
"views/dashboard/_upcoming.html", "views/dashboard/_upcoming.html",
), ),

View File

@@ -334,18 +334,6 @@ def get_status_filters(service, message_type, statistics):
def _get_job_counts(job): def _get_job_counts(job):
print('''
job
''', dir(job))
print(job.notification_count)
job_type = job.template_type job_type = job.template_type
return [ return [
( (
@@ -362,7 +350,7 @@ def _get_job_counts(job):
for label, query_param, count in [ for label, query_param, count in [
[ [
Markup( Markup(
f"""total notification_count<span class="usa-sr-only"> f"""total<span class="usa-sr-only">
{"text message" if job_type == "sms" else job_type}s</span>""" {"text message" if job_type == "sms" else job_type}s</span>"""
), ),
"", "",
@@ -370,7 +358,7 @@ def _get_job_counts(job):
], ],
[ [
Markup( Markup(
f"""pending notifications_sending<span class="usa-sr-only"> f"""pending<span class="usa-sr-only">
{message_count_noun(job.notifications_sending, job_type)}</span>""" {message_count_noun(job.notifications_sending, job_type)}</span>"""
), ),
"pending", "pending",

View File

@@ -28,7 +28,7 @@ class JobApiClient(NotifyAdminAPIClient):
def get_job(self, service_id, job_id): def get_job(self, service_id, job_id):
params = {} params = {}
job = self.get(url=f"/service/{service_id}/job/{job_id}", params=params) job = self.get(url=f"/service/{service_id}/job/{job_id}", params=params)
# comment
return job return job
def get_jobs(self, service_id, *, limit_days=None, statuses=None, page=1): def get_jobs(self, service_id, *, limit_days=None, statuses=None, page=1):

View File

@@ -2,7 +2,6 @@
{% if link %} {% if link %}
<a class="usa-link display-flex" href="{{ link }}"> <a class="usa-link display-flex" href="{{ link }}">
{% endif %} {% endif %}
big number
<span class="big-number{% if smaller %}-smaller{% endif %}{% if smallest %}-smallest{% endif %}"> <span class="big-number{% if smaller %}-smaller{% endif %}{% if smallest %}-smallest{% endif %}">
<span class="big-number-number"> <span class="big-number-number">
{% if number is number %} {% if number is number %}

View File

@@ -8,7 +8,6 @@
) %} ) %}
<nav aria-labelledby='page-header'> <nav aria-labelledby='page-header'>
<ul class='pill'> <ul class='pill'>
Pill
{% for label, option, link, count in items %} {% for label, option, link, count in items %}
<li class="pill-item__container"> <li class="pill-item__container">
{% if current_value == option %} {% if current_value == option %}

View File

@@ -2,7 +2,6 @@
<div class="ajax-block-container"> <div class="ajax-block-container">
<div class="tabs"> <div class="tabs">
count
{{ pill(counts, request.args.get('status', '')) }} {{ pill(counts, request.args.get('status', '')) }}
</div> </div>
</div> </div>

View File

@@ -16,7 +16,7 @@
</ul> </ul>
</div> </div>
{% endif %} {% endif %}
<h2>Delivery Stadsadatus</h2> <h2>Delivery Status</h2>
{% endset %} {% endset %}
<div class="ajax-block-container"> <div class="ajax-block-container">

View File

@@ -33,6 +33,7 @@
</div> </div>
<div id="totalMessageTable" class="margin-0"></div> <div id="totalMessageTable" class="margin-0"></div>
<h2 class="line-height-sans-2 margin-bottom-0 margin-top-4">Recent activity</h2> <h2 class="line-height-sans-2 margin-bottom-0 margin-top-4">Recent activity</h2>
<div id="activityChartContainer"> <div id="activityChartContainer">
<form class="usa-form"> <form class="usa-form">