Author SHA1 Message Date
brian 320696c57c Merge pull request 'added recent activity cards to home page' (#37) from add-most-recent-entries-to-home-page into main
Python Code Quality / python-code-quality (push) Successful in 9s
Python Test / python-test (push) Successful in 18s
Build and Push Docker Image / build-and-push (push) Successful in 28s
Refresh Showcase Data / refresh-data (push) Successful in 17s
Reviewed-on: #37
2025-11-13 22:57:07 +01:00
Brian Bjarke Jensen e26c53456f fixed chart destruction and recreation
Build and Push Docker Image / build-and-push (pull_request) Successful in 58s
Python Code Quality / python-code-quality (pull_request) Successful in 11s
Python Test / python-test (pull_request) Successful in 18s
2025-11-13 22:55:06 +01:00
Brian Bjarke Jensen 1eeb8ad148 added recent activity cards to home page
Build and Push Docker Image / build-and-push (pull_request) Successful in 58s
Python Code Quality / python-code-quality (pull_request) Successful in 10s
Python Test / python-test (pull_request) Successful in 18s
2025-11-13 22:44:41 +01:00
13 changed files with 285 additions and 138 deletions
-6
View File
@@ -143,12 +143,6 @@ def serve_menu_js() -> FileResponse:
return FileResponse(static_path / "menu.js")
@app.get("/auth-utils.js", include_in_schema=False)
def serve_auth_utils_js() -> FileResponse:
"""Serve the shared auth utilities JavaScript."""
return FileResponse(static_path / "auth-utils.js")
@app.get("/api/")
def read_root(token: Annotated[str, Depends(verify_token)]) -> dict:
"""API root endpoint (requires authentication)."""
+4 -2
View File
@@ -211,10 +211,12 @@
</div>
</div>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Get child ID from URL if editing
const urlParams = new URLSearchParams(window.location.search);
+5 -3
View File
@@ -424,15 +424,17 @@
</div>
</div>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated and is admin
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
let allUsers = [];
let userToDelete = null;
// Load data
// Verify user is admin and load data
fetch("/api/me", {
headers: {
Authorization: `Bearer ${token}`,
-21
View File
@@ -1,21 +0,0 @@
/**
* Redirect to login page with return URL
* @param {string} returnUrl - The URL to return to after login (defaults to current page)
*/
function redirectToLogin(returnUrl) {
const url = returnUrl || window.location.pathname + window.location.search;
window.location.href = `/login.html?return=${encodeURIComponent(url)}`;
}
/**
* Check if user has valid token, redirect to login if not
* @returns {string|null} - Returns token if valid, redirects to login if not
*/
function getToken() {
const token = localStorage.getItem("access_token");
if (!token) {
redirectToLogin();
return null;
}
return token;
}
+25 -5
View File
@@ -266,10 +266,12 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script src="/menu.js"></script>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Initialize burger menu
initBurgerMenu({ includeHome: true });
@@ -279,6 +281,9 @@
let currentDaysRange =
parseInt(localStorage.getItem("lastDiaperTimeRange")) || 7;
let selectedChildId = null; // null means show first/only child
let barChartInstance = null; // Track chart instance for proper cleanup
let poopPieChartInstance = null;
let peePieChartInstance = null;
// Restore last selected child from localStorage
const lastChildId = localStorage.getItem("lastDiaperChildFilter");
@@ -780,7 +785,12 @@
function renderBarChart(chartData) {
const ctx = document.getElementById("diaperChart").getContext("2d");
new Chart(ctx, {
// Destroy existing chart instance if it exists
if (barChartInstance) {
barChartInstance.destroy();
}
barChartInstance = new Chart(ctx, {
type: "bar",
data: {
labels: chartData.labels,
@@ -873,6 +883,11 @@
function renderPoopPieChart(chartData) {
const ctx = document.getElementById("poopPieChart").getContext("2d");
// Destroy existing chart instance if it exists
if (poopPieChartInstance) {
poopPieChartInstance.destroy();
}
const colors = {
Light: {
bg: "rgba(139, 69, 19, 0.5)",
@@ -899,7 +914,7 @@
(label) => colors[label]?.border || "rgba(200, 200, 200, 1)",
);
new Chart(ctx, {
poopPieChartInstance = new Chart(ctx, {
type: "pie",
data: {
labels: chartData.labels,
@@ -955,6 +970,11 @@
function renderPeePieChart(chartData) {
const ctx = document.getElementById("peePieChart").getContext("2d");
// Destroy existing chart instance if it exists
if (peePieChartInstance) {
peePieChartInstance.destroy();
}
const colors = {
Light: {
bg: "rgba(255, 215, 0, 0.5)",
@@ -981,7 +1001,7 @@
(label) => colors[label]?.border || "rgba(200, 200, 200, 1)",
);
new Chart(ctx, {
peePieChartInstance = new Chart(ctx, {
type: "pie",
data: {
labels: chartData.labels,
+18 -4
View File
@@ -303,10 +303,12 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script src="/menu.js"></script>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Initialize burger menu
initBurgerMenu({ includeHome: true });
@@ -317,6 +319,8 @@
parseInt(localStorage.getItem("lastFeedingTimeRange")) || 7;
let selectedChildId = null; // null means show first/only child
let barChartInstance = null;
let pieChartInstance = null;
let durationChartInstance = null;
// Restore last selected child from localStorage
const lastChildId = localStorage.getItem("lastFeedingChildFilter");
@@ -977,6 +981,11 @@
function renderPieChart(chartData) {
const ctx = document.getElementById("pieChart").getContext("2d");
// Destroy existing chart instance if it exists
if (pieChartInstance) {
pieChartInstance.destroy();
}
// Color mapping for each type
const colorMap = {
"Left Breast": {
@@ -1001,7 +1010,7 @@
(label) => colorMap[label]?.border || "rgba(200, 200, 200, 1)",
);
new Chart(ctx, {
pieChartInstance = new Chart(ctx, {
type: "pie",
data: {
labels: chartData.labels,
@@ -1057,7 +1066,12 @@
function renderDurationChart(chartData) {
const ctx = document.getElementById("durationChart").getContext("2d");
new Chart(ctx, {
// Destroy existing chart instance if it exists
if (durationChartInstance) {
durationChartInstance.destroy();
}
durationChartInstance = new Chart(ctx, {
type: "bar",
data: {
labels: chartData.labels,
+167 -5
View File
@@ -167,6 +167,52 @@
margin-top: 0.5rem;
opacity: 0.9;
}
.recent-activity {
margin-top: 2rem;
padding: 1.5rem;
background: #f8f9fa;
border-radius: 8px;
}
.recent-activity h3 {
margin-top: 0;
margin-bottom: 1rem;
color: #333;
font-size: 1.1rem;
}
.activity-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.activity-card {
background: white;
padding: 1rem;
border-radius: 6px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
.activity-card .icon {
font-size: 1.5rem;
margin-bottom: 0.5rem;
}
.activity-card .type {
font-weight: 600;
color: #333;
margin-bottom: 0.25rem;
}
.activity-card .time {
font-size: 0.85rem;
color: #666;
}
.activity-card .details {
font-size: 0.85rem;
color: #888;
margin-top: 0.5rem;
}
.activity-card.empty {
opacity: 0.5;
font-style: italic;
color: #999;
}
</style>
</head>
<body>
@@ -236,21 +282,32 @@
</div>
<script src="/menu.js"></script>
<script src="/auth-utils.js"></script>
<script>
const token = getToken();
const token = localStorage.getItem("access_token");
const username = localStorage.getItem("username");
// Check if user is logged in
if (!token) {
window.location.href = "/login.html";
} else {
// Fetch current user info including admin status
fetch("/api/me", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => response.json())
.then((response) => {
if (response.ok) {
return response.json();
} else {
// Token invalid, redirect to login
localStorage.removeItem("access_token");
localStorage.removeItem("username");
window.location.href = "/login.html";
throw new Error("Authentication failed");
}
})
.then((user) => {
if (!user) return; // Early exit if redirected
// Initialize burger menu
initBurgerMenu({
includeHome: true,
@@ -277,6 +334,7 @@
.catch((error) => {
console.error("Error:", error);
});
}
function showNoChildrenMessage() {
const content = document.getElementById("content");
@@ -309,6 +367,7 @@
let activeSleep = null;
let lastSleep = null;
let sleepUpdateTimerInterval = null;
let lastDiaperChange = null;
async function loadFeedingStatus(children) {
userChildren = children;
@@ -364,6 +423,20 @@
lastSleep = sleeps[0];
}
}
// Fetch all diaper changes to get the last one
const diaperResponse = await fetch("/api/diaper-changes", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (diaperResponse.ok) {
const diapers = await diaperResponse.json();
if (diapers.length > 0) {
lastDiaperChange = diapers[0];
}
}
} catch (error) {
console.error("Error loading feeding status:", error);
}
@@ -466,9 +539,98 @@
</button>
${feedingButtonHtml}
${sleepButtonHtml}
${buildRecentActivitySection()}
`;
}
function buildRecentActivitySection() {
// Build diaper card
const diaperCard = lastDiaperChange
? `
<div class="activity-card">
<div class="icon">🧷</div>
<div class="type">Last Diaper</div>
<div class="time">${formatTime(lastDiaperChange.change_time)}</div>
<div class="details">
${lastDiaperChange.poop_amount ? `💩 ${lastDiaperChange.poop_amount}` : ""}
${lastDiaperChange.poop_amount && lastDiaperChange.pee_amount ? " • " : ""}
${lastDiaperChange.pee_amount ? `💧 ${lastDiaperChange.pee_amount}` : ""}
</div>
</div>
`
: `
<div class="activity-card empty">
<div class="icon">🧷</div>
<div class="type">No diaper changes yet</div>
</div>
`;
// Build feeding card
const feedingCard = lastFeeding
? `
<div class="activity-card">
<div class="icon">🍼</div>
<div class="type">Last Feeding</div>
<div class="time">${formatTime(lastFeeding.start_time)}</div>
<div class="details">
${formatFeedingType(lastFeeding.feeding_type)}
${lastFeeding.end_time ? `${calculateDuration(lastFeeding.start_time, lastFeeding.end_time)}` : " (ongoing)"}
</div>
</div>
`
: `
<div class="activity-card empty">
<div class="icon">🍼</div>
<div class="type">No feedings yet</div>
</div>
`;
// Build sleep card
const sleepCard = lastSleep
? `
<div class="activity-card">
<div class="icon">😴</div>
<div class="type">Last Sleep</div>
<div class="time">${formatTime(lastSleep.start_time)}</div>
<div class="details">
${lastSleep.end_time ? calculateDuration(lastSleep.start_time, lastSleep.end_time) : "ongoing"}
</div>
</div>
`
: `
<div class="activity-card empty">
<div class="icon">😴</div>
<div class="type">No sleep sessions yet</div>
</div>
`;
return `
<div class="recent-activity">
<h3>📊 Recent Activity</h3>
<div class="activity-grid">
${diaperCard}
${feedingCard}
${sleepCard}
</div>
</div>
`;
}
function calculateDuration(startTime, endTime) {
const start = new Date(startTime);
const end = new Date(endTime);
const diffMs = end - start;
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 60) {
return `${diffMins} min`;
}
const hours = Math.floor(diffMins / 60);
const mins = diffMins % 60;
return `${hours}h ${mins}m`;
}
function formatFeedingType(type) {
const types = {
left_breast: "Left Breast",
+4 -2
View File
@@ -242,10 +242,12 @@
</form>
</div>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Determine return URL based on referrer
function getReturnUrl() {
+4 -2
View File
@@ -199,10 +199,12 @@
</form>
</div>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Determine return URL based on referrer
function getReturnUrl() {
+4 -2
View File
@@ -189,10 +189,12 @@
</form>
</div>
<script src="/auth-utils.js"></script>
<script>
// Check if user is authenticated
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Determine return URL based on referrer
function getReturnUrl() {
+2 -38
View File
@@ -82,36 +82,10 @@
</div>
<script>
// Check if redirected due to expired session
const params = new URLSearchParams(window.location.search);
const returnUrl = params.get("return");
const form = document.getElementById("loginForm");
const messageDiv = document.getElementById("message");
const loginButton = document.getElementById("loginButton");
// Show session expired message if redirected from another page
if (returnUrl) {
showMessage("Your session has expired. Please log in again.", "error");
}
// Clear user-specific cache data on login
function clearUserCache() {
const keysToRemove = [
'lastDiaperChildFilter',
'lastFeedingChildFilter',
'lastSleepChildFilter',
'lastDiaperTimeRange',
'lastFeedingTimeRange'
];
keysToRemove.forEach(key => {
localStorage.removeItem(key);
});
console.log('Cleared user cache on login');
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
@@ -135,23 +109,13 @@
if (response.ok) {
showMessage(data.message, "success");
// Store token in localStorage
localStorage.setItem("access_token", data.access_token);
localStorage.setItem("username", data.username);
// Clear stale user preferences from previous sessions
clearUserCache();
// Check for return URL parameter
const params = new URLSearchParams(window.location.search);
const returnUrl = params.get("return");
// Redirect based on return URL or is_admin from login response
// Redirect based on is_admin from login response
setTimeout(() => {
if (returnUrl) {
window.location.href = returnUrl;
} else if (data.is_admin === true) {
if (data.is_admin === true) {
window.location.href = "/admin.html";
} else {
window.location.href = "/";
+6 -6
View File
@@ -469,9 +469,11 @@
</div>
<script src="/menu.js"></script>
<script src="/auth-utils.js"></script>
<script>
const token = getToken();
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Initialize burger menu
initBurgerMenu({ includeHome: true });
@@ -493,7 +495,7 @@
currentUser = await userResponse.json();
document.getElementById("username").value = currentUser.username;
} else {
redirectToLogin();
window.location.href = "/login.html";
return;
}
@@ -850,10 +852,8 @@
}
});
// Load data on page load (only if authenticated)
if (token) {
// Load data on page load
loadData();
}
</script>
</body>
</html>
+6 -2
View File
@@ -313,9 +313,13 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
<script src="/menu.js"></script>
<script src="/auth-utils.js"></script>
<script>
const token = getToken();
const token = localStorage.getItem("access_token");
// Check if user is logged in
if (!token) {
window.location.href = "/login.html";
}
// Initialize burger menu
initBurgerMenu({ includeHome: true });