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
+45 -48
View File
@@ -1,15 +1,17 @@
(function (window) { (function (window) {
var chartContainer = document.getElementById('chartContainer'); var chartContainer = document.getElementById('chartContainer');
if (chartContainer) {
var chartTitle = document.getElementById('chartTitle').textContent; var chartTitle = document.getElementById('chartTitle').textContent;
var sms_sent = 100;
var sms_remaining_messages = 249900; // Access data attributes from the HTML
var sms_sent = parseInt(chartContainer.getAttribute('data-sms-sent'));
var sms_remaining_messages = parseInt(chartContainer.getAttribute('data-sms-allowance-remaining'));
var totalMessages = sms_sent + sms_remaining_messages; var totalMessages = sms_sent + sms_remaining_messages;
// Update the message below the chart // Update the message below the chart
document.getElementById('message').innerText = `${sms_sent.toLocaleString()} sent / ${sms_remaining_messages.toLocaleString()} remaining`; document.getElementById('message').innerText = `${sms_sent.toLocaleString()} sent / ${sms_remaining_messages.toLocaleString()} remaining`;
console.log('Message element textContent set to:', document.getElementById('message').innerText);
// Set a minimum value for "Messages Sent" based on a percentage of the remaining messages // Calculate minimum width for "Messages Sent" as 1% of the total chart width
var minSentPercentage = 0.01; // Minimum width as a percentage of total messages (1% in this case) var minSentPercentage = 0.01; // Minimum width as a percentage of total messages (1% in this case)
var minSentValue = totalMessages * minSentPercentage; var minSentValue = totalMessages * minSentPercentage;
var displaySent = Math.max(sms_sent, minSentValue); var displaySent = Math.max(sms_sent, minSentValue);
@@ -24,50 +26,45 @@
.domain([0, totalMessages]) .domain([0, totalMessages])
.range([0, width]); .range([0, width]);
var tooltip = d3.select(".tooltip"); // Create tooltip dynamically
var tooltip = d3.select("body").append("div")
.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 data = [ // Create the initial bars
{ label: 'Messages Sent', value: displaySent, actualValue: sms_sent, color: '#0076d6' }, var sentBar = svg.append("rect")
{ label: 'Remaining', value: displayRemaining, actualValue: sms_remaining_messages, color: '#fa9441' } .attr("x", 0)
];
var totalAnimationDuration = 1000; // Total animation duration in milliseconds
var sentPercentage = displaySent / totalMessages;
var remainingPercentage = displayRemaining / totalMessages;
var sentDuration = totalAnimationDuration * sentPercentage;
var remainingDuration = totalAnimationDuration * remainingPercentage;
var bars = svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", (d, i) => i === 0 ? 0 : x(data[0].value))
.attr("y", 0) .attr("y", 0)
.attr("width", 0) // Start with width 0 for animation
.attr("height", height) .attr("height", height)
.attr("fill", d => d.color) .attr("fill", '#0076d6')
.on("mousemove", function (event, d) { .attr("width", 0); // Start with width 0 for animation
tooltip.classed("hidden", false)
.style("left", event.pageX + "px")
.style("top", event.pageY - 28 + "px")
.html(d.label + ": " + d.actualValue.toLocaleString());
})
.on("mouseout", function () {
tooltip.classed("hidden", true);
});
// Animate "Messages Sent" first var remainingBar = svg.append("rect")
bars.filter((d, i) => i === 0) .attr("x", 0) // Initially set to 0, will be updated during animation
.transition() .attr("y", 0)
.duration(sentDuration) // Animation duration for "Messages Sent" .attr("height", height)
.attr("width", d => x(d.value)) .attr("fill", '#fa9441')
.on("end", function() { .attr("width", 0); // Start with width 0 for animation
// Animate "Remaining" immediately after "Messages Sent"
bars.filter((d, i) => i === 1) // Animate the bars together as a single cohesive line
.transition() svg.transition()
.duration(remainingDuration) // Animation duration for "Remaining" .duration(1000) // Total animation duration
.attr("width", d => x(d.value)); .attr("width", width)
.tween("resize", function() {
var interpolator = d3.interpolate(0, width);
return function(t) {
var newWidth = interpolator(t);
var sentWidth = x(displaySent) / width * newWidth;
var remainingWidth = x(displayRemaining) / width * newWidth;
sentBar.attr("width", sentWidth);
remainingBar.attr("x", sentWidth).attr("width", remainingWidth);
};
}); });
// Create and populate the accessible table // Create and populate the accessible table
@@ -87,7 +84,7 @@
thValue.textContent = 'Value'; thValue.textContent = 'Value';
theadRow.appendChild(thLabel); theadRow.appendChild(thLabel);
theadRow.appendChild(thValue); theadRow.appendChild(thValue);
thead.appendChild(theadRow); table.appendChild(theadRow);
table.appendChild(thead); table.appendChild(thead);
var tbody = document.createElement('tbody'); var tbody = document.createElement('tbody');
@@ -115,8 +112,8 @@
width = chartContainer.clientWidth; width = chartContainer.clientWidth;
x.range([0, width]); x.range([0, width]);
svg.attr("width", width); svg.attr("width", width);
svg.selectAll("rect") sentBar.attr("width", x(displaySent));
.attr("width", d => x(d.value)) remainingBar.attr("x", x(displaySent)).attr("width", x(displayRemaining));
.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
+10 -6
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;
}
+14 -1
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,
) )
+11 -22
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">
@@ -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',
+1 -6
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
) )
); );
+12 -7
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(
+11 -50
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(() => { setTimeout(() => {
const svg = document.getElementById('totalMessageChart'); // Check if SVG width is updated
const tooltip = document.querySelector('.tooltip'); expect(svg.getAttribute('width')).toBe(chartContainer.clientWidth.toString());
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(() => {
expect(tooltip.classList.contains('hidden')).toBe(true);
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