9 Commits
Author SHA1 Message Date
brian 1887de14e0 Merge pull request 'Improved single child UX' (#29) from improve-single-child-UX into main
Build and Push Docker Image / build-and-push (push) Successful in 25s
Python Code Quality / python-code-quality (push) Successful in 9s
Python Test / python-test (push) Successful in 18s
Reviewed-on: #29
2025-11-12 16:42:30 +01:00
Brian Bjarke Jensen 28a5df4f12 changed dropdown to read-only textfield when only 1 associated child and fixed redirects after manual entries
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-12 16:39:16 +01:00
brian 9d1ca55905 Merge pull request 'streamlined manual entry redirects back to related overview page' (#28) from ensure-manual-logs-go-back-to-overview-page into main
Build and Push Docker Image / build-and-push (push) Successful in 25s
Python Code Quality / python-code-quality (push) Successful in 9s
Python Test / python-test (push) Successful in 18s
Reviewed-on: #28
2025-11-12 15:58:31 +01:00
Brian Bjarke Jensen 5b8a19b2ad streamlined manual entry redirects back to related overview 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-12 15:53:35 +01:00
brian 4f3bc36168 Merge pull request 'Support sliding login token expiration' (#27) from support-sliding-login-token-expiration into main
Build and Push Docker Image / build-and-push (push) Successful in 26s
Python Code Quality / python-code-quality (push) Successful in 10s
Python Test / python-test (push) Successful in 18s
Reviewed-on: #27
2025-11-12 15:43:01 +01:00
Brian Bjarke Jensen a302dc51c6 CQ fixes
Build and Push Docker Image / build-and-push (pull_request) Successful in 1m0s
Python Code Quality / python-code-quality (pull_request) Successful in 10s
Python Test / python-test (pull_request) Successful in 18s
2025-11-12 15:34:10 +01:00
Brian Bjarke Jensen d46fd51aa0 added reset of TTL for login tokens when user is active
Build and Push Docker Image / build-and-push (pull_request) Successful in 58s
Python Code Quality / python-code-quality (pull_request) Failing after 10s
Python Test / python-test (pull_request) Successful in 17s
2025-11-12 15:31:06 +01:00
brian 6e402cb1df Merge pull request 'added support for manual sleep logging' (#26) from support-manually-adding-sleep-entries into main
Build and Push Docker Image / build-and-push (push) Successful in 25s
Python Code Quality / python-code-quality (push) Successful in 9s
Python Test / python-test (push) Successful in 18s
Reviewed-on: #26
2025-11-12 15:27:51 +01:00
Brian Bjarke Jensen 1e93fb8783 added support for manual sleep logging
Build and Push Docker Image / build-and-push (pull_request) Successful in 1m6s
Python Code Quality / python-code-quality (pull_request) Successful in 11s
Python Test / python-test (pull_request) Successful in 18s
2025-11-12 15:23:51 +01:00
14 changed files with 704 additions and 89 deletions
+6
View File
@@ -119,6 +119,12 @@ def serve_sleep() -> FileResponse:
return FileResponse(static_path / "sleep.html") return FileResponse(static_path / "sleep.html")
@app.get("/log-sleep.html", include_in_schema=False)
def serve_log_sleep() -> FileResponse:
"""Serve the log sleep page."""
return FileResponse(static_path / "log-sleep.html")
@app.get("/settings.html", include_in_schema=False) @app.get("/settings.html", include_in_schema=False)
def serve_settings() -> FileResponse: def serve_settings() -> FileResponse:
"""Serve the settings page.""" """Serve the settings page."""
+1
View File
@@ -9,6 +9,7 @@ class CreateSleepRequest(BaseModel):
child_id: int = Field(..., gt=0) child_id: int = Field(..., gt=0)
start_time: datetime start_time: datetime
end_time: datetime | None = None
class UpdateSleepRequest(BaseModel): class UpdateSleepRequest(BaseModel):
@@ -12,6 +12,7 @@ class SleepRepositoryInterface(ABC):
self, self,
child_id: int, child_id: int,
start_time: datetime, start_time: datetime,
end_time: datetime | None = None,
) -> dict: ) -> dict:
"""Create a new sleep log entry.""" """Create a new sleep log entry."""
@@ -27,12 +27,13 @@ class DatabaseSleepRepository(SleepRepositoryInterface):
self, self,
child_id: int, child_id: int,
start_time: datetime, start_time: datetime,
end_time: datetime | None = None,
) -> dict: ) -> dict:
"""Create a new sleep log entry.""" """Create a new sleep log entry."""
sleep = Sleep( sleep = Sleep(
child_id=child_id, child_id=child_id,
start_time=start_time, start_time=start_time,
end_time=None, end_time=end_time,
) )
self.db.add(sleep) self.db.add(sleep)
self.db.commit() self.db.commit()
@@ -16,6 +16,7 @@ class InMemoryTokenRepository(TokenRepositoryInterface):
def __init__(self) -> None: def __init__(self) -> None:
# token -> (user_id, expiry_time) # token -> (user_id, expiry_time)
self._tokens: dict[str, tuple[int, datetime]] = {} self._tokens: dict[str, tuple[int, datetime]] = {}
self._default_ttl = 3600 # Store default TTL for sliding expiration
def store(self, token: str, user_id: int, ttl: int = 3600) -> None: def store(self, token: str, user_id: int, ttl: int = 3600) -> None:
"""Store a token with TTL (time to live in seconds).""" """Store a token with TTL (time to live in seconds)."""
@@ -23,7 +24,10 @@ class InMemoryTokenRepository(TokenRepositoryInterface):
self._tokens[token] = (user_id, expiry) self._tokens[token] = (user_id, expiry)
def verify(self, token: str) -> int | None: def verify(self, token: str) -> int | None:
"""Verify token and return user_id if valid, None otherwise.""" """Verify token and return user_id if valid, None otherwise.
Implements sliding expiration: extends token lifetime on each verification.
"""
if token not in self._tokens: if token not in self._tokens:
return None return None
@@ -34,6 +38,10 @@ class InMemoryTokenRepository(TokenRepositoryInterface):
del self._tokens[token] del self._tokens[token]
return None return None
# Sliding expiration: extend the token lifetime
new_expiry = datetime.now(UTC) + timedelta(seconds=self._default_ttl)
self._tokens[token] = (user_id, new_expiry)
return user_id return user_id
def invalidate(self, token: str) -> None: def invalidate(self, token: str) -> None:
@@ -21,6 +21,7 @@ class RedisTokenRepository(TokenRepositoryInterface):
redis_client: Redis client instance from redis.from_url() redis_client: Redis client instance from redis.from_url()
""" """
self.redis = redis_client self.redis = redis_client
self.default_ttl = 3600 # Store default TTL for sliding expiration
def store(self, token: str, user_id: int, ttl: int = 3600) -> None: def store(self, token: str, user_id: int, ttl: int = 3600) -> None:
"""Store a token with TTL (time to live in seconds).""" """Store a token with TTL (time to live in seconds)."""
@@ -28,10 +29,15 @@ class RedisTokenRepository(TokenRepositoryInterface):
self.redis.setex(key, ttl, str(user_id)) self.redis.setex(key, ttl, str(user_id))
def verify(self, token: str) -> int | None: def verify(self, token: str) -> int | None:
"""Verify token and return user_id if valid, None otherwise.""" """Verify token and return user_id if valid, None otherwise.
Implements sliding expiration: extends token lifetime on verification.
"""
key = f"token:{token}" key = f"token:{token}"
user_id_str = self.redis.get(key) user_id_str = self.redis.get(key)
if user_id_str: if user_id_str:
# Sliding expiration: extend the token lifetime
self.redis.expire(key, self.default_ttl)
return int(user_id_str) return int(user_id_str)
return None return None
+1
View File
@@ -36,6 +36,7 @@ def create_sleep(
sleep = sleep_repo.create( sleep = sleep_repo.create(
child_id=request.child_id, child_id=request.child_id,
start_time=request.start_time, start_time=request.start_time,
end_time=request.end_time,
) )
return SleepResponse(**sleep) return SleepResponse(**sleep)
+18 -4
View File
@@ -280,7 +280,7 @@
let allChildren = []; let allChildren = [];
let currentDaysRange = let currentDaysRange =
parseInt(localStorage.getItem("lastDiaperTimeRange")) || 7; parseInt(localStorage.getItem("lastDiaperTimeRange")) || 7;
let selectedChildId = null; // null means "All Children" let selectedChildId = null; // null means show first/only child
// Restore last selected child from localStorage // Restore last selected child from localStorage
const lastChildId = localStorage.getItem("lastDiaperChildFilter"); const lastChildId = localStorage.getItem("lastDiaperChildFilter");
@@ -321,6 +321,11 @@
if (response.ok) { if (response.ok) {
allChildren = await response.json(); allChildren = await response.json();
// Auto-select first child if no selection exists
if (selectedChildId === null && allChildren.length > 0) {
selectedChildId = allChildren[0].id;
}
} }
} catch (error) { } catch (error) {
console.error("Error loading children:", error); console.error("Error loading children:", error);
@@ -334,8 +339,7 @@
} }
function onChildChange(event) { function onChildChange(event) {
selectedChildId = selectedChildId = parseInt(event.target.value);
event.target.value === "all" ? null : parseInt(event.target.value);
localStorage.setItem("lastDiaperChildFilter", event.target.value); localStorage.setItem("lastDiaperChildFilter", event.target.value);
displayDiaperChanges(allDiaperChanges); displayDiaperChanges(allDiaperChanges);
} }
@@ -367,11 +371,21 @@
content.innerHTML = ` content.innerHTML = `
<div class="controls"> <div class="controls">
${allChildren.length === 1 ? `
<label for="childDisplay">Child:</label>
<input
type="text"
id="childDisplay"
value="${allChildren[0].name}"
readonly
style="background-color: #f5f5f5; cursor: default; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;"
/>
` : `
<label for="childFilter">Child:</label> <label for="childFilter">Child:</label>
<select id="childFilter" onchange="onChildChange(event)"> <select id="childFilter" onchange="onChildChange(event)">
<option value="all" ${selectedChildId === null ? "selected" : ""}>All Children</option>
${childOptions} ${childOptions}
</select> </select>
`}
<label for="daysRange">Time Range:</label> <label for="daysRange">Time Range:</label>
<select id="daysRange" onchange="onDaysRangeChange(event)"> <select id="daysRange" onchange="onDaysRangeChange(event)">
+18 -4
View File
@@ -317,7 +317,7 @@
let allChildren = []; let allChildren = [];
let currentDaysRange = let currentDaysRange =
parseInt(localStorage.getItem("lastFeedingTimeRange")) || 7; parseInt(localStorage.getItem("lastFeedingTimeRange")) || 7;
let selectedChildId = null; // null means "All Children" let selectedChildId = null; // null means show first/only child
let barChartInstance = null; let barChartInstance = null;
// Restore last selected child from localStorage // Restore last selected child from localStorage
@@ -359,6 +359,11 @@
if (response.ok) { if (response.ok) {
allChildren = await response.json(); allChildren = await response.json();
// Auto-select first child if no selection exists
if (selectedChildId === null && allChildren.length > 0) {
selectedChildId = allChildren[0].id;
}
} }
} catch (error) { } catch (error) {
console.error("Error loading children:", error); console.error("Error loading children:", error);
@@ -372,8 +377,7 @@
} }
function onChildChange(event) { function onChildChange(event) {
selectedChildId = selectedChildId = parseInt(event.target.value);
event.target.value === "all" ? null : parseInt(event.target.value);
localStorage.setItem("lastFeedingChildFilter", event.target.value); localStorage.setItem("lastFeedingChildFilter", event.target.value);
displayFeedings(allFeedings); displayFeedings(allFeedings);
} }
@@ -405,11 +409,21 @@
content.innerHTML = ` content.innerHTML = `
<div class="controls"> <div class="controls">
${allChildren.length === 1 ? `
<label for="childDisplay">Child:</label>
<input
type="text"
id="childDisplay"
value="${allChildren[0].name}"
readonly
style="background-color: #f5f5f5; cursor: default; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;"
/>
` : `
<label for="childFilter">Child:</label> <label for="childFilter">Child:</label>
<select id="childFilter" onchange="onChildChange(event)"> <select id="childFilter" onchange="onChildChange(event)">
<option value="all" ${selectedChildId === null ? "selected" : ""}>All Children</option>
${childOptions} ${childOptions}
</select> </select>
`}
<label for="daysRange">Time Range:</label> <label for="daysRange">Time Range:</label>
<select id="daysRange" onchange="onDaysRangeChange(event)"> <select id="daysRange" onchange="onDaysRangeChange(event)">
+42 -2
View File
@@ -510,7 +510,24 @@
const childSelect = document.getElementById("modalChildId"); const childSelect = document.getElementById("modalChildId");
const typeSelect = document.getElementById("modalFeedingType"); const typeSelect = document.getElementById("modalFeedingType");
// Clear and populate child select // Clear and populate child select or show single child
if (userChildren.length === 1) {
// Single child: replace dropdown with text display
const child = userChildren[0];
const formGroup = childSelect.parentElement;
formGroup.innerHTML = `
<label for="modalChildName">Child</label>
<input
type="text"
id="modalChildName"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default;"
/>
<input type="hidden" id="modalChildId" value="${child.id}" />
`;
} else {
// Multiple children: show dropdown
childSelect.innerHTML = '<option value="">Select a child</option>'; childSelect.innerHTML = '<option value="">Select a child</option>';
userChildren.forEach((child) => { userChildren.forEach((child) => {
const option = document.createElement("option"); const option = document.createElement("option");
@@ -522,6 +539,11 @@
// Set defaults based on last feeding // Set defaults based on last feeding
if (lastFeeding) { if (lastFeeding) {
childSelect.value = lastFeeding.child_id; childSelect.value = lastFeeding.child_id;
}
}
// Set default feeding type based on last feeding
if (lastFeeding) {
typeSelect.value = lastFeeding.feeding_type; typeSelect.value = lastFeeding.feeding_type;
} }
@@ -633,7 +655,24 @@
const modal = document.getElementById("startSleepModal"); const modal = document.getElementById("startSleepModal");
const childSelect = document.getElementById("modalSleepChildId"); const childSelect = document.getElementById("modalSleepChildId");
// Clear and populate child select // Clear and populate child select or show single child
if (userChildren.length === 1) {
// Single child: replace dropdown with text display
const child = userChildren[0];
const formGroup = childSelect.parentElement;
formGroup.innerHTML = `
<label for="modalSleepChildName">Child</label>
<input
type="text"
id="modalSleepChildName"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default;"
/>
<input type="hidden" id="modalSleepChildId" value="${child.id}" />
`;
} else {
// Multiple children: show dropdown
childSelect.innerHTML = '<option value="">Select a child</option>'; childSelect.innerHTML = '<option value="">Select a child</option>';
userChildren.forEach((child) => { userChildren.forEach((child) => {
const option = document.createElement("option"); const option = document.createElement("option");
@@ -646,6 +685,7 @@
if (lastSleep) { if (lastSleep) {
childSelect.value = lastSleep.child_id; childSelect.value = lastSleep.child_id;
} }
}
modal.classList.add("show"); modal.classList.add("show");
} }
+35 -3
View File
@@ -235,7 +235,7 @@
<button <button
type="button" type="button"
class="button secondary" class="button secondary"
onclick="window.location.href='/'" onclick="window.location.href=getReturnUrl()"
> >
Cancel Cancel
</button> </button>
@@ -249,6 +249,16 @@
window.location.href = "/login.html"; window.location.href = "/login.html";
} }
// Determine return URL based on referrer
function getReturnUrl() {
const referrer = document.referrer;
if (referrer.includes('/diapers.html')) {
return '/diapers.html';
}
// Default to home page
return '/';
}
// Check if we're in edit mode // Check if we're in edit mode
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const diaperChangeId = urlParams.get("id"); const diaperChangeId = urlParams.get("id");
@@ -277,12 +287,32 @@
children = await response.json(); children = await response.json();
const select = document.getElementById("childSelect"); const select = document.getElementById("childSelect");
// Populate select dropdown or show single child
if (children.length === 1) {
// Single child: replace dropdown with text display
const child = children[0];
const formGroup = select.parentElement;
formGroup.innerHTML = `
<label for="childName">Child *</label>
<input
type="text"
id="childName"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default;"
/>
<input type="hidden" id="childSelect" name="childSelect" value="${child.id}" />
`;
} else {
// Multiple children: show dropdown (clear the placeholder first)
select.innerHTML = '';
children.forEach((child) => { children.forEach((child) => {
const option = document.createElement("option"); const option = document.createElement("option");
option.value = child.id; option.value = child.id;
option.textContent = child.name; option.textContent = child.name;
select.appendChild(option); select.appendChild(option);
}); });
}
// If editing, load the diaper change data // If editing, load the diaper change data
if (isEditMode) { if (isEditMode) {
@@ -295,7 +325,8 @@
.toISOString() .toISOString()
.slice(0, 16); .slice(0, 16);
// Load last used child from localStorage // Load last used child from localStorage (only for multiple children)
if (children.length > 1) {
const lastDiaperChange = JSON.parse( const lastDiaperChange = JSON.parse(
localStorage.getItem("lastDiaperChange") || "{}", localStorage.getItem("lastDiaperChange") || "{}",
); );
@@ -305,6 +336,7 @@
lastDiaperChange.child_id; lastDiaperChange.child_id;
} }
} }
}
} else { } else {
showMessage("Failed to load children", "error"); showMessage("Failed to load children", "error");
} }
@@ -431,7 +463,7 @@
"success", "success",
); );
setTimeout(() => { setTimeout(() => {
window.location.href = "/"; window.location.href = getReturnUrl();
}, 1000); }, 1000);
} else { } else {
const errorData = await response.json(); const errorData = await response.json();
+33 -4
View File
@@ -206,6 +206,16 @@
window.location.href = "/login.html"; window.location.href = "/login.html";
} }
// Determine return URL based on referrer
function getReturnUrl() {
const referrer = document.referrer;
if (referrer.includes('/feedings.html')) {
return '/feedings.html';
}
// Default to home page
return '/';
}
const form = document.getElementById("logFeedingForm"); const form = document.getElementById("logFeedingForm");
const messageDiv = document.getElementById("message"); const messageDiv = document.getElementById("message");
const submitBtn = document.getElementById("submitBtn"); const submitBtn = document.getElementById("submitBtn");
@@ -259,13 +269,32 @@
return; return;
} }
// Populate select dropdown // Populate select dropdown or show single child
if (children.length === 1) {
// Single child: replace dropdown with text display
const child = children[0];
const formGroup = childSelect.parentElement;
formGroup.innerHTML = `
<label for="childName">Child</label>
<input
type="text"
id="childName"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default;"
/>
<input type="hidden" id="childId" name="childId" value="${child.id}" />
`;
} else {
// Multiple children: show dropdown (clear placeholder first)
childSelect.innerHTML = '';
children.forEach((child) => { children.forEach((child) => {
const option = document.createElement("option"); const option = document.createElement("option");
option.value = child.id; option.value = child.id;
option.textContent = child.name; option.textContent = child.name;
childSelect.appendChild(option); childSelect.appendChild(option);
}); });
}
// Show form, hide loading // Show form, hide loading
loadingDiv.style.display = "none"; loadingDiv.style.display = "none";
@@ -369,9 +398,9 @@
: "Feeding logged successfully!", : "Feeding logged successfully!",
"success", "success",
); );
// Redirect to feedings page after 1 second // Redirect to appropriate page after 1 second
setTimeout(() => { setTimeout(() => {
window.location.href = "/feedings.html"; window.location.href = getReturnUrl();
}, 1000); }, 1000);
} else { } else {
showMessage( showMessage(
@@ -394,7 +423,7 @@
} }
function goBack() { function goBack() {
window.location.href = "/"; window.location.href = getReturnUrl();
} }
</script> </script>
</body> </body>
+414
View File
@@ -0,0 +1,414 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Log Sleep - Baby Monitor</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family:
-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu,
Cantarell, sans-serif;
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 12px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
padding: 40px;
max-width: 500px;
width: 100%;
}
h1 {
color: #333;
margin-bottom: 10px;
font-size: 28px;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 600;
font-size: 14px;
}
input,
select {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.2s;
}
input:focus,
select:focus {
outline: none;
border-color: #4facfe;
}
.button {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
color: white;
border: none;
padding: 12px 24px;
border-radius: 6px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition:
transform 0.2s,
box-shadow 0.2s;
width: 100%;
margin-top: 10px;
}
.button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}
.button:active {
transform: translateY(0);
}
.button:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.button.secondary {
background: #6c757d;
margin-top: 10px;
}
.button.secondary:hover {
box-shadow: 0 4px 12px rgba(108, 117, 125, 0.4);
}
.message {
padding: 12px;
border-radius: 6px;
margin-bottom: 20px;
display: none;
}
.message.show {
display: block;
}
.message.error {
background: #ffebee;
border-left: 4px solid #f44336;
color: #c62828;
}
.message.success {
background: #e8f5e9;
border-left: 4px solid #4caf50;
color: #2e7d32;
}
.help-text {
font-size: 12px;
color: #666;
margin-top: 4px;
}
.loading {
text-align: center;
padding: 20px;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<h1>😴 Log Sleep</h1>
<p class="subtitle">Record a sleep session</p>
<div id="message" class="message"></div>
<div id="loadingChildren" class="loading">Loading children...</div>
<form id="logSleepForm" style="display: none">
<div class="form-group">
<label for="childId">Child *</label>
<select id="childId" name="childId" required>
<option value="">Select a child</option>
</select>
</div>
<div class="form-group">
<label for="startTime">Start Time *</label>
<input
type="datetime-local"
id="startTime"
name="startTime"
required
/>
<p class="help-text">Defaults to current time</p>
</div>
<div class="form-group">
<label for="endTime">End Time</label>
<input type="datetime-local" id="endTime" name="endTime" />
<p class="help-text">Leave empty if sleep is ongoing</p>
</div>
<button type="submit" class="button" id="submitBtn">Log Sleep</button>
<button type="button" class="button secondary" onclick="goBack()">
Cancel
</button>
</form>
</div>
<script>
// Check if user is authenticated
const token = localStorage.getItem("access_token");
if (!token) {
window.location.href = "/login.html";
}
// Determine return URL based on referrer
function getReturnUrl() {
const referrer = document.referrer;
if (referrer.includes('/sleep.html')) {
return '/sleep.html';
}
// Default to home page
return '/';
}
const form = document.getElementById("logSleepForm");
const messageDiv = document.getElementById("message");
const submitBtn = document.getElementById("submitBtn");
const loadingDiv = document.getElementById("loadingChildren");
const childSelect = document.getElementById("childId");
// Check if we're editing an existing sleep session
const urlParams = new URLSearchParams(window.location.search);
const sleepId = urlParams.get("id");
const isEditMode = !!sleepId;
// Set default start time to now (only for new sleep sessions)
if (!isEditMode) {
const now = new Date();
const localDateTime = new Date(
now.getTime() - now.getTimezoneOffset() * 60000,
)
.toISOString()
.slice(0, 16);
document.getElementById("startTime").value = localDateTime;
}
// Update title and button text if editing
if (isEditMode) {
document.querySelector("h1").textContent = "😴 Edit Sleep";
document.querySelector(".subtitle").textContent =
"Update sleep session details";
submitBtn.textContent = "Update Sleep";
}
// Load user's children
async function loadChildren() {
try {
const response = await fetch("/api/children", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const children = await response.json();
if (children.length === 0) {
showMessage(
"No children found. Please add a child first.",
"error",
);
setTimeout(() => {
window.location.href = "/add-child.html";
}, 2000);
return;
}
// Populate select dropdown or show single child
if (children.length === 1) {
// Single child: replace dropdown with text display
const child = children[0];
const formGroup = childSelect.parentElement;
formGroup.innerHTML = `
<label for="childName">Child</label>
<input
type="text"
id="childName"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default;"
/>
<input type="hidden" id="childId" name="childId" value="${child.id}" />
`;
} else {
// Multiple children: show dropdown (clear placeholder first)
childSelect.innerHTML = '';
children.forEach((child) => {
const option = document.createElement("option");
option.value = child.id;
option.textContent = child.name;
childSelect.appendChild(option);
});
}
// Show form, hide loading
loadingDiv.style.display = "none";
form.style.display = "block";
// If editing, load the sleep data
if (isEditMode) {
loadSleepData();
}
} else {
showMessage("Failed to load children", "error");
}
} catch (error) {
showMessage("Network error loading children", "error");
}
}
async function loadSleepData() {
try {
const response = await fetch(`/api/sleep/${sleepId}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.ok) {
const sleep = await response.json();
// Populate form with existing data
document.getElementById("childId").value = sleep.child_id;
// Format datetime for datetime-local input
const startTime = new Date(sleep.start_time);
const startLocalDateTime = new Date(
startTime.getTime() - startTime.getTimezoneOffset() * 60000,
)
.toISOString()
.slice(0, 16);
document.getElementById("startTime").value = startLocalDateTime;
if (sleep.end_time) {
const endTime = new Date(sleep.end_time);
const endLocalDateTime = new Date(
endTime.getTime() - endTime.getTimezoneOffset() * 60000,
)
.toISOString()
.slice(0, 16);
document.getElementById("endTime").value = endLocalDateTime;
}
} else {
showMessage("Failed to load sleep data", "error");
}
} catch (error) {
showMessage("Network error loading sleep", "error");
}
}
loadChildren();
form.addEventListener("submit", async (e) => {
e.preventDefault();
const childId = parseInt(document.getElementById("childId").value);
const startTime = document.getElementById("startTime").value;
const endTimeValue = document.getElementById("endTime").value;
// Disable button during request
submitBtn.disabled = true;
submitBtn.textContent = isEditMode ? "Updating..." : "Logging...";
messageDiv.classList.remove("show");
try {
const url = isEditMode ? `/api/sleep/${sleepId}` : "/api/sleep";
const method = isEditMode ? "PUT" : "POST";
const response = await fetch(url, {
method: method,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
child_id: childId,
start_time: startTime,
end_time: endTimeValue || null,
}),
});
const data = await response.json();
if (response.ok) {
showMessage(
isEditMode
? "Sleep updated successfully!"
: "Sleep logged successfully!",
"success",
);
// Redirect to appropriate page after 1 second
setTimeout(() => {
window.location.href = getReturnUrl();
}, 1000);
} else {
showMessage(
data.detail ||
`Failed to ${isEditMode ? "update" : "log"} sleep. Please try again.`,
"error",
);
}
} catch (error) {
showMessage("Network error. Please try again.", "error");
} finally {
submitBtn.disabled = false;
submitBtn.textContent = isEditMode ? "Update Sleep" : "Log Sleep";
}
});
function showMessage(text, type) {
messageDiv.textContent = text;
messageDiv.className = `message ${type} show`;
}
function goBack() {
window.location.href = getReturnUrl();
}
</script>
</body>
</html>
+56 -8
View File
@@ -328,10 +328,11 @@
let allChildren = []; let allChildren = [];
let selectedChildId = ""; let selectedChildId = "";
// Filter change handlers // Filter change handlers (will be attached after children are loaded)
document function attachChildFilterListener() {
.getElementById("childFilter") const childFilter = document.getElementById("childFilter");
.addEventListener("change", function () { if (childFilter) {
childFilter.addEventListener("change", function () {
selectedChildId = this.value; selectedChildId = this.value;
// Save selection to localStorage // Save selection to localStorage
if (selectedChildId) { if (selectedChildId) {
@@ -341,6 +342,8 @@
} }
renderCharts(); renderCharts();
}); });
}
}
document document
.getElementById("timeRangeFilter") .getElementById("timeRangeFilter")
@@ -365,19 +368,52 @@
allChildren = await childrenResponse.json(); allChildren = await childrenResponse.json();
// Populate child filter // Auto-select first child if available
if (allChildren.length > 0 && !selectedChildId) {
selectedChildId = allChildren[0].id;
}
// Populate child filter or show single child
const childFilterContainer = document.querySelector('.controls');
if (allChildren.length === 1) {
// Single child: show as read-only text
const child = allChildren[0];
childFilterContainer.innerHTML = `
<label for="childDisplay">Child:</label>
<input
type="text"
id="childDisplay"
value="${child.name}"
readonly
style="background-color: #f5f5f5; cursor: default; padding: 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px;"
/>
<label for="timeRangeFilter">Time Range:</label>
<select id="timeRangeFilter">
<option value="1">Last 24 hours</option>
<option value="3">Last 3 days</option>
<option value="7" selected>Last 7 days</option>
<option value="14">Last 14 days</option>
<option value="30">Last 30 days</option>
<option value="90">Last 90 days</option>
</select>
`;
} else {
// Multiple children: show dropdown
const childFilter = document.getElementById("childFilter"); const childFilter = document.getElementById("childFilter");
childFilter.innerHTML = '<option value="">All Children</option>'; childFilter.innerHTML = '';
allChildren.forEach((child) => { allChildren.forEach((child) => {
const option = document.createElement("option"); const option = document.createElement("option");
option.value = child.id; option.value = child.id;
option.textContent = child.name; option.textContent = child.name;
childFilter.appendChild(option); childFilter.appendChild(option);
}); });
}
// Restore last selected child from localStorage // Restore last selected child from localStorage
const lastChildId = localStorage.getItem("lastSleepChildFilter"); const lastChildId = localStorage.getItem("lastSleepChildFilter");
if (lastChildId) { if (lastChildId && allChildren.length > 1) {
const childFilter = document.getElementById("childFilter");
childFilter.value = lastChildId; childFilter.value = lastChildId;
selectedChildId = lastChildId; selectedChildId = lastChildId;
} }
@@ -402,6 +438,11 @@
allSleeps = await sleepResponse.json(); allSleeps = await sleepResponse.json();
// Attach event listener for child filter if multiple children
if (allChildren.length > 1) {
attachChildFilterListener();
}
renderCharts(); renderCharts();
} catch (error) { } catch (error) {
console.error("Error loading data:", error); console.error("Error loading data:", error);
@@ -517,7 +558,10 @@
</div> </div>
<div class="list-container"> <div class="list-container">
<h2>Recent Sleep Sessions</h2> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
<h2 style="margin: 0;">Recent Sleep Sessions</h2>
<button class="button" onclick="addManualSleep()" style="padding: 8px 16px; font-size: 14px;"> Add Manual Entry</button>
</div>
<div class="sleep-list"> <div class="sleep-list">
${filteredSleeps ${filteredSleeps
.slice(0, 50) .slice(0, 50)
@@ -1058,6 +1102,10 @@
`; `;
} }
function addManualSleep() {
window.location.href = `/log-sleep.html`;
}
async function logout() { async function logout() {
try { try {
await fetch("/api/logout", { await fetch("/api/logout", {