mirror of
https://github.com/GSA/notifications-admin.git
synced 2026-09-04 11:08:25 -04:00
Updates to the js and tests
This commit is contained in:
@@ -34,23 +34,15 @@
|
|||||||
.style('display', 'none');
|
.style('display', 'none');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if there is any data in deliveredData or failedData before creating the legend
|
// Calculate total messages
|
||||||
const totalMessages = d3.sum(deliveredData) + d3.sum(failedData);
|
const totalMessages = d3.sum(deliveredData) + d3.sum(failedData);
|
||||||
|
|
||||||
|
// Create legend only if there are messages
|
||||||
const legendContainer = d3.select('.chart-legend');
|
const legendContainer = d3.select('.chart-legend');
|
||||||
|
legendContainer.selectAll('*').remove(); // Clear any existing legend
|
||||||
if (totalMessages === 0) {
|
|
||||||
legendContainer.style('display', 'none'); // Try manually setting this in the console to see if it hides the legend
|
|
||||||
console.log('Hiding legend'); // Ensure this branch is being hit
|
|
||||||
} else {
|
|
||||||
legendContainer.style('display', 'flex');
|
|
||||||
console.log('Showing legend');
|
|
||||||
}
|
|
||||||
|
|
||||||
if (totalMessages > 0) {
|
if (totalMessages > 0) {
|
||||||
// Create legend only if there is data
|
// Show legend if there are messages
|
||||||
legendContainer.selectAll('*').remove(); // Clear any existing legend
|
|
||||||
|
|
||||||
const legendData = [
|
const legendData = [
|
||||||
{ label: 'Delivered', color: COLORS.delivered },
|
{ label: 'Delivered', color: COLORS.delivered },
|
||||||
{ label: 'Failed', color: COLORS.failed }
|
{ label: 'Failed', color: COLORS.failed }
|
||||||
@@ -72,18 +64,18 @@
|
|||||||
.attr('class', 'legend-label')
|
.attr('class', 'legend-label')
|
||||||
.text(d => d.label);
|
.text(d => d.label);
|
||||||
|
|
||||||
legendContainer.style('display', 'flex'); // Ensure the legend is shown
|
// Ensure the legend is shown
|
||||||
|
legendContainer.style('display', 'flex');
|
||||||
} else {
|
} else {
|
||||||
// Hide legend container if there is no data
|
// Hide the legend if there are no messages
|
||||||
legendContainer.style('display', 'none'); // Hide the legend
|
legendContainer.style('display', 'none');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Proceed with creating the chart as usual
|
|
||||||
const x = d3.scaleBand()
|
const x = d3.scaleBand()
|
||||||
.domain(labels)
|
.domain(labels)
|
||||||
.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
|
||||||
const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0)));
|
const maxY = d3.max(deliveredData.map((d, i) => d + (failedData[i] || 0)));
|
||||||
const y = d3.scaleSqrt()
|
const y = d3.scaleSqrt()
|
||||||
.domain([0, maxY + 2]) // Add 2 units of space at the top
|
.domain([0, maxY + 2]) // Add 2 units of space at the top
|
||||||
@@ -95,20 +87,23 @@
|
|||||||
.attr('transform', `translate(0,${height})`)
|
.attr('transform', `translate(0,${height})`)
|
||||||
.call(d3.axisBottom(x));
|
.call(d3.axisBottom(x));
|
||||||
|
|
||||||
|
// Generate the y-axis with whole numbers
|
||||||
const yAxis = d3.axisLeft(y)
|
const yAxis = d3.axisLeft(y)
|
||||||
.ticks(Math.min(maxY + 2, 10))
|
.ticks(Math.min(maxY + 2, 10)) // Generate up to 10 ticks based on the data
|
||||||
.tickFormat(d3.format('d'));
|
.tickFormat(d3.format('d')); // Ensure whole numbers on the y-axis
|
||||||
|
|
||||||
svg.append('g')
|
svg.append('g')
|
||||||
.attr('class', 'y axis')
|
.attr('class', 'y axis')
|
||||||
.call(yAxis);
|
.call(yAxis);
|
||||||
|
|
||||||
|
// Data for stacking
|
||||||
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 // Ensure there's a value for failed, even if it's 0
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Stack the data
|
||||||
const stack = d3.stack()
|
const stack = d3.stack()
|
||||||
.keys(['delivered', 'failed'])
|
.keys(['delivered', 'failed'])
|
||||||
.order(d3.stackOrderNone)
|
.order(d3.stackOrderNone)
|
||||||
@@ -116,137 +111,203 @@
|
|||||||
|
|
||||||
const series = stack(stackData);
|
const series = stack(stackData);
|
||||||
|
|
||||||
|
// Color scale
|
||||||
const color = d3.scaleOrdinal()
|
const color = d3.scaleOrdinal()
|
||||||
.domain(['delivered', 'failed'])
|
.domain(['delivered', 'failed'])
|
||||||
.range([COLORS.delivered, COLORS.failed]);
|
.range([COLORS.delivered, COLORS.failed]);
|
||||||
|
|
||||||
const barGroups = svg.selectAll('.bar-group')
|
// Create bars with animation
|
||||||
.data(series)
|
const barGroups = svg.selectAll('.bar-group')
|
||||||
.enter()
|
.data(series)
|
||||||
.append('g')
|
.enter()
|
||||||
.attr('class', 'bar-group')
|
.append('g')
|
||||||
.attr('fill', d => color(d.key));
|
.attr('class', 'bar-group')
|
||||||
|
.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]));
|
||||||
};
|
};
|
||||||
|
|
||||||
const fetchData = function(type) {
|
// Function to create an accessible table
|
||||||
const ctx = document.getElementById('weeklyChart');
|
const createTable = function(tableId, chartType, labels, deliveredData, failedData) {
|
||||||
if (!ctx) {
|
const table = document.getElementById(tableId);
|
||||||
return;
|
table.innerHTML = ""; // Clear previous data
|
||||||
}
|
|
||||||
|
|
||||||
const url = type === 'service' ? `/daily_stats.json` : `/daily_stats_by_user.json`;
|
const captionText = document.querySelector(`#${chartType} .chart-subtitle`).textContent;
|
||||||
return fetch(url)
|
const caption = document.createElement('caption');
|
||||||
.then(response => {
|
caption.textContent = captionText;
|
||||||
if (!response.ok) {
|
const thead = document.createElement('thead');
|
||||||
throw new Error('Network response was not ok');
|
const tbody = document.createElement('tbody');
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
})
|
|
||||||
.then(data => {
|
|
||||||
|
|
||||||
let labels = [];
|
// Create table header
|
||||||
let deliveredData = [];
|
const headerRow = document.createElement('tr');
|
||||||
let failedData = [];
|
const headers = ['Day', 'Delivered', 'Failed'];
|
||||||
|
headers.forEach(headerText => {
|
||||||
let totalMessages = 0;
|
const th = document.createElement('th');
|
||||||
|
th.textContent = headerText;
|
||||||
for (var dateString in data) {
|
headerRow.appendChild(th);
|
||||||
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 || 0); // Fallback to 0 if missing
|
|
||||||
failedData.push(data[dateString].sms.failure || 0); // Fallback to 0 if missing
|
|
||||||
|
|
||||||
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
|
|
||||||
const liveRegion = document.getElementById('aria-live-account');
|
|
||||||
|
|
||||||
if (totalMessages === 0) {
|
|
||||||
d3.select('#weeklyChart').selectAll('*').remove();
|
|
||||||
d3.select('#weeklyChart')
|
|
||||||
.append('div')
|
|
||||||
.html(`
|
|
||||||
<div class="usa-alert usa-alert--info usa-alert--slim" aria-live="polite">
|
|
||||||
<div class="usa-alert__body">
|
|
||||||
<p class="usa-alert__text">
|
|
||||||
No messages sent in the last 7 days
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
`);
|
|
||||||
if (subTitle) {
|
|
||||||
subTitle.style.display = 'none';
|
|
||||||
}
|
|
||||||
liveRegion.textContent = `No data available for ${type} - last 7 days.`;
|
|
||||||
|
|
||||||
// Here: Check if the legend exists and remove it if necessary
|
|
||||||
const legendContainer = document.querySelector('.chart-legend');
|
|
||||||
if (legendContainer) {
|
|
||||||
console.log('Legend exists, hiding it...');
|
|
||||||
legendContainer.style.display = 'none'; // Hide the legend
|
|
||||||
} else {
|
|
||||||
console.log('Legend does not exist at this point.');
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
createChart('#weeklyChart', labels, deliveredData, failedData);
|
|
||||||
liveRegion.textContent = `Data updated for ${type} - last 7 days.`;
|
|
||||||
|
|
||||||
// Check if legend should be shown after chart is created
|
|
||||||
const legendContainer = document.querySelector('.chart-legend');
|
|
||||||
if (legendContainer) {
|
|
||||||
console.log('Legend exists, showing it...');
|
|
||||||
legendContainer.style.display = 'flex'; // Show the legend
|
|
||||||
} else {
|
|
||||||
console.log('Legend does not exist at this point.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
})
|
|
||||||
.catch(error => console.error('Error fetching daily stats:', error));
|
|
||||||
};
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
|
||||||
fetchData('service');
|
|
||||||
|
|
||||||
const dropdown = document.getElementById('options');
|
|
||||||
dropdown.addEventListener('change', function(event) {
|
|
||||||
fetchData(event.target.value);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
thead.appendChild(headerRow);
|
||||||
|
|
||||||
|
// Create table body
|
||||||
|
labels.forEach((label, index) => {
|
||||||
|
const row = document.createElement('tr');
|
||||||
|
const cellDay = document.createElement('td');
|
||||||
|
cellDay.textContent = label;
|
||||||
|
row.appendChild(cellDay);
|
||||||
|
|
||||||
|
const cellDelivered = document.createElement('td');
|
||||||
|
cellDelivered.textContent = deliveredData[index];
|
||||||
|
row.appendChild(cellDelivered);
|
||||||
|
|
||||||
|
const cellFailed = document.createElement('td');
|
||||||
|
cellFailed.textContent = failedData[index];
|
||||||
|
row.appendChild(cellFailed);
|
||||||
|
|
||||||
|
tbody.appendChild(row);
|
||||||
|
});
|
||||||
|
|
||||||
|
table.appendChild(caption);
|
||||||
|
table.appendChild(thead);
|
||||||
|
table.append(tbody);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchData = function(type) {
|
||||||
|
var ctx = document.getElementById('weeklyChart');
|
||||||
|
if (!ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var url = type === 'service' ? `/daily_stats.json` : `/daily_stats_by_user.json`;
|
||||||
|
return fetch(url)
|
||||||
|
.then(response => {
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Network response was not ok');
|
||||||
|
}
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then(data => {
|
||||||
|
labels = [];
|
||||||
|
deliveredData = [];
|
||||||
|
failedData = [];
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Calculate the total number of messages
|
||||||
|
totalMessages += data[dateString].sms.delivered + data[dateString].sms.failure;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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>
|
||||||
|
`);
|
||||||
|
// Hide the subtitle
|
||||||
|
if (subTitle) {
|
||||||
|
subTitle.style.display = 'none';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// If there are messages, create the chart and table
|
||||||
|
createChart('#weeklyChart', labels, deliveredData, failedData);
|
||||||
|
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
})
|
||||||
|
.catch(error => console.error('Error fetching daily stats:', error));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDropdownChange = function(event) {
|
||||||
|
const selectedValue = event.target.value;
|
||||||
|
const subTitle = document.querySelector(`#activityChartContainer .chart-subtitle`);
|
||||||
|
const selectElement = document.getElementById('options');
|
||||||
|
const selectedText = selectElement.options[selectElement.selectedIndex].text;
|
||||||
|
|
||||||
|
subTitle.textContent = `${selectedText} - last 7 days`;
|
||||||
|
fetchData(selectedValue);
|
||||||
|
|
||||||
|
// Update ARIA live region
|
||||||
|
const liveRegion = document.getElementById('aria-live-account');
|
||||||
|
liveRegion.textContent = `Data updated for ${selectedText} - last 7 days`;
|
||||||
|
|
||||||
|
// Switch tables based on dropdown selection
|
||||||
|
const selectedTable = selectedValue === "individual" ? "table1" : "table2";
|
||||||
|
const tables = document.querySelectorAll('.table-overflow-x-auto');
|
||||||
|
tables.forEach(function(table) {
|
||||||
|
table.classList.add('hidden'); // Hide all tables by adding the hidden class
|
||||||
|
table.classList.remove('visible'); // Ensure they are not visible
|
||||||
|
});
|
||||||
|
const tableToShow = document.getElementById(selectedTable);
|
||||||
|
tableToShow.classList.remove('hidden'); // Remove hidden class
|
||||||
|
tableToShow.classList.add('visible'); // Add visible class
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
|
// Initialize activityChart 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() {
|
||||||
|
if (labels.length > 0 && deliveredData.length > 0 && failedData.length > 0) {
|
||||||
|
createChart('#weeklyChart', labels, deliveredData, failedData);
|
||||||
|
createTable('weeklyTable', 'activityChart', labels, deliveredData, failedData);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Export functions for testing
|
||||||
|
window.createChart = createChart;
|
||||||
|
window.createTable = createTable;
|
||||||
|
window.handleDropdownChange = handleDropdownChange;
|
||||||
|
window.fetchData = fetchData;
|
||||||
}
|
}
|
||||||
|
|
||||||
})(window);
|
})(window);
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ beforeAll(done => {
|
|||||||
<div id="activityChart" >
|
<div id="activityChart" >
|
||||||
<div class="chart-header">
|
<div class="chart-header">
|
||||||
<div class="chart-subtitle">Service Name - last 7 days</div>
|
<div class="chart-subtitle">Service Name - last 7 days</div>
|
||||||
<div class="chart-legend" aria-label="Legend"></div>
|
<div class="chart-legend" role="region" aria-label="Legend"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="chart-container" id="weeklyChart" data-service-id="12345" style="width: 600px;"></div>
|
<div class="chart-container" id="weeklyChart" data-service-id="12345" style="width: 600px;"></div>
|
||||||
<table id="weeklyTable" class="usa-sr-only usa-table"></table>
|
<table id="weeklyTable" class="usa-sr-only usa-table"></table>
|
||||||
@@ -125,6 +125,37 @@ test('Check HTML content after chart creation', () => {
|
|||||||
expect(container.querySelectorAll('rect').length).toBeGreaterThan(0);
|
expect(container.querySelectorAll('rect').length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Legend is visible when there are delivered or failed messages', () => {
|
||||||
|
// Example data with delivered and failed messages
|
||||||
|
const labels = ['Day 1', 'Day 2'];
|
||||||
|
const deliveredData = [10, 20]; // Mock delivered data
|
||||||
|
const failedData = [5, 0]; // Mock failed data
|
||||||
|
|
||||||
|
// Call the createChart function
|
||||||
|
window.createChart('#weeklyChart', labels, deliveredData, failedData);
|
||||||
|
|
||||||
|
// Check if the legend is displayed using computed style
|
||||||
|
const legendContainer = document.querySelector('.chart-legend');
|
||||||
|
const legendDisplayStyle = window.getComputedStyle(legendContainer).display;
|
||||||
|
expect(legendDisplayStyle).toBe('flex');
|
||||||
|
expect(legendContainer.querySelectorAll('.legend-item').length).toBe(2); // Ensure two legend items
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Legend is hidden when there are no delivered or failed messages', () => {
|
||||||
|
// Example data with no delivered and no failed messages
|
||||||
|
const labels = ['Day 1', 'Day 2'];
|
||||||
|
const deliveredData = [0, 0]; // No delivered messages
|
||||||
|
const failedData = [0, 0]; // No failed messages
|
||||||
|
|
||||||
|
// Call the createChart function
|
||||||
|
window.createChart('#weeklyChart', labels, deliveredData, failedData);
|
||||||
|
|
||||||
|
// Check if the legend is hidden using computed style
|
||||||
|
const legendContainer = document.querySelector('.chart-legend');
|
||||||
|
const legendDisplayStyle = window.getComputedStyle(legendContainer).display;
|
||||||
|
expect(legendDisplayStyle).toBe('none');
|
||||||
|
});
|
||||||
|
|
||||||
test('Fetches data and creates chart and table correctly', async () => {
|
test('Fetches data and creates chart and table correctly', async () => {
|
||||||
const mockResponse = {
|
const mockResponse = {
|
||||||
'2024-07-01': { sms: { delivered: 50, failed: 5 } },
|
'2024-07-01': { sms: { delivered: 50, failed: 5 } },
|
||||||
|
|||||||
Reference in New Issue
Block a user