Deleting chart.js

Updates to the dashboard html
Test updates
This commit is contained in:
Jonathan Bobel
2024-07-10 10:13:24 -04:00
parent e8f274baa2
commit 7f288598ba
10 changed files with 164 additions and 228 deletions

View File

@@ -1,122 +1,119 @@
(function (window) { (function (window) {
var chartContainer = document.getElementById('chartContainer'); var chartContainer = document.getElementById('chartContainer');
var chartTitle = document.getElementById('chartTitle').textContent; if (chartContainer) {
var sms_sent = 100; var chartTitle = document.getElementById('chartTitle').textContent;
var sms_remaining_messages = 249900;
var totalMessages = sms_sent + sms_remaining_messages;
// Update the message below the chart // Access data attributes from the HTML
document.getElementById('message').innerText = `${sms_sent.toLocaleString()} sent / ${sms_remaining_messages.toLocaleString()} remaining`; var sms_sent = parseInt(chartContainer.getAttribute('data-sms-sent'));
console.log('Message element textContent set to:', document.getElementById('message').innerText); var sms_remaining_messages = parseInt(chartContainer.getAttribute('data-sms-allowance-remaining'));
var totalMessages = sms_sent + sms_remaining_messages;
// Set a minimum value for "Messages Sent" based on a percentage of the remaining messages // Update the message below the chart
var minSentPercentage = 0.01; // Minimum width as a percentage of total messages (1% in this case) document.getElementById('message').innerText = `${sms_sent.toLocaleString()} sent / ${sms_remaining_messages.toLocaleString()} remaining`;
var minSentValue = totalMessages * minSentPercentage;
var displaySent = Math.max(sms_sent, minSentValue);
var displayRemaining = totalMessages - displaySent;
var svg = d3.select("#totalMessageChart"); // Calculate minimum width for "Messages Sent" as 1% of the total chart width
var width = chartContainer.clientWidth; var minSentPercentage = 0.01; // Minimum width as a percentage of total messages (1% in this case)
var height = 64; var minSentValue = totalMessages * minSentPercentage;
svg.attr("width", width).attr("height", height); var displaySent = Math.max(sms_sent, minSentValue);
var displayRemaining = totalMessages - displaySent;
var x = d3.scaleLinear() var svg = d3.select("#totalMessageChart");
.domain([0, totalMessages]) var width = chartContainer.clientWidth;
.range([0, width]); var height = 64;
svg.attr("width", width).attr("height", height);
var tooltip = d3.select(".tooltip"); var x = d3.scaleLinear()
.domain([0, totalMessages])
.range([0, width]);
var data = [ // Create tooltip dynamically
{ label: 'Messages Sent', value: displaySent, actualValue: sms_sent, color: '#0076d6' }, var tooltip = d3.select("body").append("div")
{ label: 'Remaining', value: displayRemaining, actualValue: sms_remaining_messages, color: '#fa9441' } .attr("class", "tooltip")
]; .style("position", "absolute")
.style("background", "#fff")
.style("border", "1px solid #ccc")
.style("padding", "5px")
.style("box-shadow", "0px 0px 10px rgba(0, 0, 0, 0.1)")
.style("pointer-events", "none")
.style("display", "none");
var totalAnimationDuration = 1000; // Total animation duration in milliseconds // Create the initial bars
var sentPercentage = displaySent / totalMessages; var sentBar = svg.append("rect")
var remainingPercentage = displayRemaining / totalMessages; .attr("x", 0)
.attr("y", 0)
.attr("height", height)
.attr("fill", '#0076d6')
.attr("width", 0); // Start with width 0 for animation
var sentDuration = totalAnimationDuration * sentPercentage; var remainingBar = svg.append("rect")
var remainingDuration = totalAnimationDuration * remainingPercentage; .attr("x", 0) // Initially set to 0, will be updated during animation
.attr("y", 0)
.attr("height", height)
.attr("fill", '#fa9441')
.attr("width", 0); // Start with width 0 for animation
var bars = svg.selectAll("rect") // Animate the bars together as a single cohesive line
.data(data) svg.transition()
.enter() .duration(1000) // Total animation duration
.append("rect") .attr("width", width)
.attr("x", (d, i) => i === 0 ? 0 : x(data[0].value)) .tween("resize", function() {
.attr("y", 0) var interpolator = d3.interpolate(0, width);
.attr("width", 0) // Start with width 0 for animation return function(t) {
.attr("height", height) var newWidth = interpolator(t);
.attr("fill", d => d.color) var sentWidth = x(displaySent) / width * newWidth;
.on("mousemove", function (event, d) { var remainingWidth = x(displayRemaining) / width * newWidth;
tooltip.classed("hidden", false) sentBar.attr("width", sentWidth);
.style("left", event.pageX + "px") remainingBar.attr("x", sentWidth).attr("width", remainingWidth);
.style("top", event.pageY - 28 + "px") };
.html(d.label + ": " + d.actualValue.toLocaleString()); });
})
.on("mouseout", function () { // Create and populate the accessible table
tooltip.classed("hidden", true); var tableContainer = document.getElementById('totalMessageTable');
var table = document.createElement('table');
table.className = 'usa-sr-only usa-table';
var caption = document.createElement('caption');
caption.textContent = chartTitle;
table.appendChild(caption);
var thead = document.createElement('thead');
var theadRow = document.createElement('tr');
var thLabel = document.createElement('th');
thLabel.textContent = 'Label';
var thValue = document.createElement('th');
thValue.textContent = 'Value';
theadRow.appendChild(thLabel);
theadRow.appendChild(thValue);
table.appendChild(theadRow);
table.appendChild(thead);
var tbody = document.createElement('tbody');
var tableData = [
{ label: 'Messages Sent', value: sms_sent.toLocaleString() },
{ label: 'Remaining', value: sms_remaining_messages.toLocaleString() }
];
tableData.forEach(function (rowData) {
var row = document.createElement('tr');
var cellLabel = document.createElement('td');
var cellValue = document.createElement('td');
cellLabel.textContent = rowData.label;
cellValue.textContent = rowData.value;
row.appendChild(cellLabel);
row.appendChild(cellValue);
tbody.appendChild(row);
}); });
// Animate "Messages Sent" first table.appendChild(tbody);
bars.filter((d, i) => i === 0) tableContainer.appendChild(table);
.transition()
.duration(sentDuration) // Animation duration for "Messages Sent" // Ensure the chart resizes correctly on window resize
.attr("width", d => x(d.value)) window.addEventListener('resize', function () {
.on("end", function() { width = chartContainer.clientWidth;
// Animate "Remaining" immediately after "Messages Sent" x.range([0, width]);
bars.filter((d, i) => i === 1) svg.attr("width", width);
.transition() sentBar.attr("width", x(displaySent));
.duration(remainingDuration) // Animation duration for "Remaining" remainingBar.attr("x", x(displaySent)).attr("width", x(displayRemaining));
.attr("width", d => x(d.value));
}); });
}
// Create and populate the accessible table
var tableContainer = document.getElementById('totalMessageTable');
var table = document.createElement('table');
table.className = 'usa-sr-only usa-table';
var caption = document.createElement('caption');
caption.textContent = chartTitle;
table.appendChild(caption);
var thead = document.createElement('thead');
var theadRow = document.createElement('tr');
var thLabel = document.createElement('th');
thLabel.textContent = 'Label';
var thValue = document.createElement('th');
thValue.textContent = 'Value';
theadRow.appendChild(thLabel);
theadRow.appendChild(thValue);
thead.appendChild(theadRow);
table.appendChild(thead);
var tbody = document.createElement('tbody');
var tableData = [
{ label: 'Messages Sent', value: sms_sent.toLocaleString() },
{ label: 'Remaining', value: sms_remaining_messages.toLocaleString() }
];
tableData.forEach(function (rowData) {
var row = document.createElement('tr');
var cellLabel = document.createElement('td');
var cellValue = document.createElement('td');
cellLabel.textContent = rowData.label;
cellValue.textContent = rowData.value;
row.appendChild(cellLabel);
row.appendChild(cellValue);
tbody.appendChild(row);
});
table.appendChild(tbody);
tableContainer.appendChild(table);
// Ensure the chart resizes correctly on window resize
window.addEventListener('resize', function () {
width = chartContainer.clientWidth;
x.range([0, width]);
svg.attr("width", width);
svg.selectAll("rect")
.attr("width", d => x(d.value))
.attr("x", (d, i) => i === 0 ? 0 : x(data[0].value));
});
})(window); })(window);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -31,10 +31,14 @@
} }
.tooltip { .tooltip {
position: absolute; position: absolute;
background: #f4f4f4; display: none;
padding: 5px; background: color('ink');
border: 1px solid #d4d4d4; color: #FFF;
border-radius: 3px; border: 1px solid #ccc;
padding: units(1);
border-radius: units(1);
pointer-events: none; pointer-events: none;
font-size: 12px; z-index: 100;
} font-size: size("body", 3);
line-height: 1.3;
}

View File

@@ -36,7 +36,7 @@ from notifications_utils.recipients import format_phone_number_human_readable
@socketio.on("fetch_daily_stats") @socketio.on("fetch_daily_stats")
def handle_fetch_daily_stats(): def handle_fetch_daily_stats():
service_id = session.get('service_id') service_id = session.get("service_id")
if service_id: if service_id:
date_range = get_stats_date_range() date_range = get_stats_date_range()
daily_stats = service_api_client.get_service_notification_statistics_by_day( daily_stats = service_api_client.get_service_notification_statistics_by_day(
@@ -82,6 +82,17 @@ def service_dashboard(service_id):
if not current_user.has_permissions("view_activity"): if not current_user.has_permissions("view_activity"):
return redirect(url_for("main.choose_template", service_id=service_id)) return redirect(url_for("main.choose_template", service_id=service_id))
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"]
job_response = job_api_client.get_jobs(service_id)["data"] job_response = job_api_client.get_jobs(service_id)["data"]
notifications_response = notification_api_client.get_notifications_for_service( notifications_response = notification_api_client.get_notifications_for_service(
service_id service_id
@@ -118,6 +129,8 @@ def service_dashboard(service_id):
partials=get_dashboard_partials(service_id), partials=get_dashboard_partials(service_id),
job_and_notifications=job_and_notifications, job_and_notifications=job_and_notifications,
service_data_retention_days=service_data_retention_days, service_data_retention_days=service_data_retention_days,
sms_sent=sms_sent,
sms_allowance_remaining=sms_allowance_remaining,
) )

View File

@@ -9,7 +9,7 @@
{% block maincolumn_content %} {% block maincolumn_content %}
<div class="dashboard margin-bottom-8"> <div class="dashboard margin-bottom-2">
<h1 class="usa-sr-only">Dashboard</h1> <h1 class="usa-sr-only">Dashboard</h1>
{% if current_user.has_permissions('manage_templates') and not current_service.all_templates %} {% if current_user.has_permissions('manage_templates') and not current_service.all_templates %}
@@ -22,40 +22,29 @@
Messages sent Messages sent
</h2> </h2>
<!-- <button id="sevenDaysButton">7 Days</button>
<canvas id="myChart"></canvas> -->
{{ ajax_block(partials, updates_url, 'inbox') }} {{ ajax_block(partials, updates_url, 'inbox') }}
{{ ajax_block(partials, updates_url, 'totals') }} {{ ajax_block(partials, updates_url, 'totals') }}
{{ ajax_block(partials, updates_url, 'template-statistics') }} <div id="chartContainer" data-sms-sent="{{ sms_sent }}" data-sms-allowance-remaining="{{ sms_allowance_remaining }}">
{% if current_user.has_permissions('manage_service') %} <h2 id="chartTitle" class="margin-top-3 margin-bottom-1">Total Messages</h2>
<!-- <div id="chartContainer" data-sms-sent="{{ sms_sent }}" data-sms-allowance-remaining="{{ sms_allowance_remaining }}">
<h2 class="margin-bottom-1" id="chartTitle">2024 Total message allowance</h2>
<div class="usa-sr-only" id="chartDesc">A bar chart showing the messages sent against the total message allowance for 2024 to date</div>
<canvas id="totalMessageChart" role="img" aria-labelledby="chartTitle chartDesc" height="100"></canvas>
<div id="totalMessageTable"></div>
</div>
<div id="message"></div> -->
<div id="chartContainer">
<h2 id="chartTitle">Total Messages</h2>
<svg id="totalMessageChart"></svg> <svg id="totalMessageChart"></svg>
<div id="message"></div> <div id="message"></div>
</div> </div>
<div id="totalMessageTable"></div> <div id="totalMessageTable" class="margin-0"></div>
<div class="tooltip hidden"></div> <p class="align-with-heading-copy margin-bottom-4">
<p class="align-with-heading-copy">
What counts as 1 text message part?<br /> What counts as 1 text message part?<br />
See <a class="usa-link" href="{{ url_for('.pricing') }}">Tracking usage</a>. See <a class="usa-link" href="{{ url_for('.pricing') }}">Tracking usage</a>.
</p> </p>
<h2>Recent templates</h2>
{{ ajax_block(partials, updates_url, 'template-statistics') }}
{% if current_user.has_permissions('manage_service') %}
{% endif %} {% endif %}
<h2 class="margin-top-4 margin-bottom-1">Recent Batches</h2> <h2 class="margin-top-4">Recent Batches</h2>
<div class="table-wrapper"> <div class="table-wrapper">
<table class="usa-table usa-table--borderless job-table"> <table class="usa-table usa-table--borderless job-table margin-top-0">
<thead class="table-field-headings"> <thead class="table-field-headings">
<tr> <tr>
<th scope="col" class="table-field-heading-first"> <th scope="col" class="table-field-heading-first">

View File

@@ -6,7 +6,7 @@
{% call(item, row_number) list_table( {% call(item, row_number) list_table(
template_statistics, template_statistics,
caption="Messages sent by template", caption="Messages sent by template",
caption_visible=True, caption_visible=False,
empty_message='', empty_message='',
field_headings=[ field_headings=[
'Template', 'Template',

View File

@@ -55,10 +55,6 @@ const copy = {
gtm: () => { gtm: () => {
return src(paths.src + 'js/gtm_head.js') return src(paths.src + 'js/gtm_head.js')
.pipe(dest(paths.dist + 'js/')); .pipe(dest(paths.dist + 'js/'));
},
chart: () => {
return src(paths.src + 'js/chart.umd.js')
.pipe(dest(paths.dist + 'js/'));
} }
}; };
@@ -206,8 +202,7 @@ const defaultTask = parallel(
), ),
uswds.compile, uswds.compile,
uswds.copyAssets, uswds.copyAssets,
copy.gtm, copy.gtm
copy.chart
) )
); );

View File

@@ -1925,14 +1925,14 @@ def test_fetch_daily_stats(
) )
with app.test_client() as client: with app.test_client() as client:
with client.session_transaction() as sess: with client.session_transaction() as sess:
sess['service_id'] = service_id sess["service_id"] = service_id
socketio_client = SocketIOTestClient(app, socketio, flask_test_client=client) socketio_client = SocketIOTestClient(app, socketio, flask_test_client=client)
connected = socketio_client.is_connected() connected = socketio_client.is_connected()
assert connected, "Client should be connected" assert connected, "Client should be connected"
socketio_client.emit('fetch_daily_stats') socketio_client.emit("fetch_daily_stats")
received = socketio_client.get_received() received = socketio_client.get_received()
mock_service_api.assert_called_once_with( mock_service_api.assert_called_once_with(
@@ -1961,8 +1961,13 @@ def test_fetch_daily_stats(
SERVICE_ONE_ID, SERVICE_ONE_ID,
USER_ONE_ID, USER_ONE_ID,
{"start_date": "2024-01-01", "days": 7}, {"start_date": "2024-01-01", "days": 7},
{"service_id": SERVICE_ONE_ID, "user_id": USER_ONE_ID, "start_date": "2024-01-01", "days": 7}, {
{"id": USER_ONE_ID, "name": "Test User"} "service_id": SERVICE_ONE_ID,
"user_id": USER_ONE_ID,
"start_date": "2024-01-01",
"days": 7,
},
{"id": USER_ONE_ID, "name": "Test User"},
), ),
], ],
) )
@@ -1995,15 +2000,15 @@ def test_fetch_daily_stats_by_user(
with app.test_client() as client: with app.test_client() as client:
with client.session_transaction() as sess: with client.session_transaction() as sess:
sess['service_id'] = service_id sess["service_id"] = service_id
sess['user_id'] = user_id sess["user_id"] = user_id
socketio_client = SocketIOTestClient(app, socketio, flask_test_client=client) socketio_client = SocketIOTestClient(app, socketio, flask_test_client=client)
connected = socketio_client.is_connected() connected = socketio_client.is_connected()
assert connected, "Client should be connected" assert connected, "Client should be connected"
socketio_client.emit('fetch_daily_stats_by_user') socketio_client.emit("fetch_daily_stats_by_user")
received = socketio_client.get_received() received = socketio_client.get_received()
mock_service_api.assert_called_once_with( mock_service_api.assert_called_once_with(

View File

@@ -15,7 +15,7 @@ function loadScript(scriptContent) {
beforeAll(done => { beforeAll(done => {
// Set up the DOM with the D3 script included // Set up the DOM with the D3 script included
document.body.innerHTML = ` document.body.innerHTML = `
<div id="chartContainer" data-sms-sent="100" data-sms-allowance-remaining="200" style="width: 600px;"> <div id="chartContainer" data-sms-sent="100" data-sms-allowance-remaining="249900" style="width: 600px;">
<h1 id="chartTitle">Total Messages</h1> <h1 id="chartTitle">Total Messages</h1>
<svg id="totalMessageChart"></svg> <svg id="totalMessageChart"></svg>
</div> </div>
@@ -77,62 +77,23 @@ test('Chart title is correctly set', () => {
expect(chartTitle).toBe('Total Messages'); expect(chartTitle).toBe('Total Messages');
}); });
// Test to mimic the tooltip functionality test('Chart resizes correctly on window resize', done => {
test('Tooltip displays correct content on mouseover', done => {
setTimeout(() => { setTimeout(() => {
const svg = document.getElementById('totalMessageChart'); const svg = document.getElementById('totalMessageChart');
const tooltip = document.querySelector('.tooltip'); const chartContainer = document.getElementById('chartContainer');
const rect = svg.querySelector('rect');
// Simulate mouseover event on the first rect // Initial check
const event = new MouseEvent('mousemove', { expect(svg.getAttribute('width')).toBe(chartContainer.clientWidth.toString());
bubbles: true,
cancelable: true,
view: window,
clientX: 100, // Example x-coordinate
clientY: 50 // Example y-coordinate
});
rect.dispatchEvent(event); // Set new container width
chartContainer.style.width = '800px';
// Check if the tooltip is displayed and has correct content // Trigger resize event
expect(tooltip.classList.contains('hidden')).toBe(false); window.dispatchEvent(new Event('resize'));
expect(tooltip.innerHTML).toBe('Messages Sent: 100');
done();
}, 1000); // Adjust the timeout if necessary
}, 10000); // Adjust the overall test timeout if necessary
// Test to mimic the tooltip functionality on mouseout
test('Tooltip hides on mouseout', done => {
setTimeout(() => {
const svg = document.getElementById('totalMessageChart');
const tooltip = document.querySelector('.tooltip');
const rect = svg.querySelector('rect');
// Simulate mouseover event on the first rect to show the tooltip
const mouseoverEvent = new MouseEvent('mousemove', {
bubbles: true,
cancelable: true,
view: window,
clientX: 100, // Example x-coordinate
clientY: 50 // Example y-coordinate
});
rect.dispatchEvent(mouseoverEvent);
// Simulate mouseout event on the first rect to hide the tooltip
const mouseoutEvent = new MouseEvent('mouseout', {
bubbles: true,
cancelable: true,
view: window
});
rect.dispatchEvent(mouseoutEvent);
// Check if the tooltip is hidden
setTimeout(() => { setTimeout(() => {
expect(tooltip.classList.contains('hidden')).toBe(true); // Check if SVG width is updated
expect(svg.getAttribute('width')).toBe(chartContainer.clientWidth.toString());
done(); done();
}, 500); // Adjust the timeout if necessary }, 500); // Adjust the timeout if necessary
}, 1000); // Initial wait for the chart to render }, 1000); // Initial wait for the chart to render