added sleep logging workflow and overview page
This commit is contained in:
@@ -15,6 +15,7 @@ from baby_monitor.routers.admin import router as admin_router
|
||||
from baby_monitor.routers.child import router as child_router
|
||||
from baby_monitor.routers.feeding import router as feeding_router
|
||||
from baby_monitor.routers.diaper_change import router as diaper_change_router
|
||||
from baby_monitor.routers.sleep import router as sleep_router
|
||||
from baby_monitor.routers.health import router as health_router
|
||||
from baby_monitor.repositories.dependencies.get_database import init_db
|
||||
|
||||
@@ -53,6 +54,7 @@ app.include_router(admin_router)
|
||||
app.include_router(child_router)
|
||||
app.include_router(feeding_router)
|
||||
app.include_router(diaper_change_router)
|
||||
app.include_router(sleep_router)
|
||||
app.include_router(health_router)
|
||||
|
||||
|
||||
@@ -111,6 +113,12 @@ def serve_log_diaper() -> FileResponse:
|
||||
return FileResponse(static_path / "log-diaper.html")
|
||||
|
||||
|
||||
@app.get("/sleep.html", include_in_schema=False)
|
||||
def serve_sleep() -> FileResponse:
|
||||
"""Serve the sleep overview page."""
|
||||
return FileResponse(static_path / "sleep.html")
|
||||
|
||||
|
||||
@app.get("/api/")
|
||||
def read_root(token: Annotated[str, Depends(verify_token)]) -> dict:
|
||||
"""API root endpoint (requires authentication)."""
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Sleep database model."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from sqlalchemy import Column, Integer, DateTime, ForeignKey
|
||||
from datetime import datetime, UTC
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
Base = DeclarativeBase
|
||||
else:
|
||||
from baby_monitor.repositories.dependencies.get_database import Base
|
||||
|
||||
|
||||
class Sleep(Base):
|
||||
"""Sleep log database model."""
|
||||
|
||||
__tablename__ = "sleep_logs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
child_id = Column(Integer, ForeignKey("children.id"), nullable=False)
|
||||
start_time = Column(DateTime, nullable=False)
|
||||
end_time = Column(DateTime, nullable=True)
|
||||
created_at = Column(DateTime, default=datetime.now(UTC), nullable=False)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Sleep(id={self.id}, child_id={self.child_id})>"
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Sleep-related request and response models."""
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class CreateSleepRequest(BaseModel):
|
||||
"""Request model for creating a sleep log."""
|
||||
|
||||
child_id: int = Field(..., gt=0)
|
||||
start_time: datetime
|
||||
|
||||
|
||||
class UpdateSleepRequest(BaseModel):
|
||||
"""Request model for updating a sleep log."""
|
||||
|
||||
end_time: datetime | None = None
|
||||
|
||||
|
||||
class SleepResponse(BaseModel):
|
||||
"""Response model for sleep log data."""
|
||||
|
||||
id: int
|
||||
child_id: int
|
||||
start_time: datetime
|
||||
end_time: datetime | None
|
||||
created_at: datetime
|
||||
child_name: str | None = None # Optional, populated when needed
|
||||
@@ -80,6 +80,7 @@ def init_db() -> None:
|
||||
from baby_monitor.models.db.child import Child # noqa: F401
|
||||
from baby_monitor.models.db.feeding import Feeding # noqa: F401
|
||||
from baby_monitor.models.db.diaper_change import DiaperChange # noqa: F401
|
||||
from baby_monitor.models.db.sleep import Sleep # noqa: F401
|
||||
from baby_monitor.models.invitation import Invitation # noqa: F401
|
||||
|
||||
# Ensure data directory exists
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Dependency for getting sleep repository instance."""
|
||||
|
||||
from typing import Annotated
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from baby_monitor.repositories.dependencies.get_database import get_database
|
||||
from baby_monitor.repositories.sleep.sqlite_sleep import SQLiteSleepRepository
|
||||
|
||||
|
||||
def get_sleep_repository(
|
||||
db: Annotated[Session, Depends(get_database)],
|
||||
) -> SQLiteSleepRepository:
|
||||
"""Get sleep repository instance."""
|
||||
return SQLiteSleepRepository(db)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Interface for sleep repository operations."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class SleepRepositoryInterface(ABC):
|
||||
"""Interface for sleep log data access operations."""
|
||||
|
||||
@abstractmethod
|
||||
def create(
|
||||
self,
|
||||
child_id: int,
|
||||
start_time: datetime,
|
||||
) -> dict:
|
||||
"""Create a new sleep log entry."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_id(self, sleep_id: int) -> dict | None:
|
||||
"""Get a sleep log by ID."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_child_id(self, child_id: int) -> list[dict]:
|
||||
"""Get all sleep logs for a specific child."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_user_id(self, user_id: int) -> list[dict]:
|
||||
"""Get all sleep logs for a specific user's children."""
|
||||
|
||||
@abstractmethod
|
||||
def update(
|
||||
self,
|
||||
sleep_id: int,
|
||||
end_time: datetime | None = None,
|
||||
) -> dict | None:
|
||||
"""Update a sleep log entry."""
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, sleep_id: int) -> bool:
|
||||
"""Delete a sleep log entry."""
|
||||
@@ -0,0 +1,99 @@
|
||||
"""SQLite implementation of sleep repository."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from baby_monitor.repositories.interfaces.sleep_repository_interface import (
|
||||
SleepRepositoryInterface,
|
||||
)
|
||||
from baby_monitor.models.db.sleep import Sleep
|
||||
from baby_monitor.models.db.child import Child
|
||||
|
||||
|
||||
class SQLiteSleepRepository(SleepRepositoryInterface):
|
||||
"""SQLite implementation for sleep log data access."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def create(
|
||||
self,
|
||||
child_id: int,
|
||||
start_time: datetime,
|
||||
) -> dict:
|
||||
"""Create a new sleep log entry."""
|
||||
sleep = Sleep(
|
||||
child_id=child_id,
|
||||
start_time=start_time,
|
||||
end_time=None,
|
||||
)
|
||||
self.db.add(sleep)
|
||||
self.db.commit()
|
||||
self.db.refresh(sleep)
|
||||
|
||||
return self._to_dict(sleep)
|
||||
|
||||
def get_by_id(self, sleep_id: int) -> dict | None:
|
||||
"""Get a sleep log by ID."""
|
||||
sleep = self.db.query(Sleep).filter(Sleep.id == sleep_id).first()
|
||||
if not sleep:
|
||||
return None
|
||||
return self._to_dict(sleep)
|
||||
|
||||
def get_by_child_id(self, child_id: int) -> list[dict]:
|
||||
"""Get all sleep logs for a specific child."""
|
||||
sleeps = (
|
||||
self.db.query(Sleep)
|
||||
.filter(Sleep.child_id == child_id)
|
||||
.order_by(Sleep.start_time.desc())
|
||||
.all()
|
||||
)
|
||||
return [self._to_dict(sleep) for sleep in sleeps]
|
||||
|
||||
def get_by_user_id(self, user_id: int) -> list[dict]:
|
||||
"""Get all sleep logs for a specific user's children."""
|
||||
sleeps = (
|
||||
self.db.query(Sleep)
|
||||
.join(Child)
|
||||
.filter(Child.user_id == user_id)
|
||||
.order_by(Sleep.start_time.desc())
|
||||
.all()
|
||||
)
|
||||
return [self._to_dict(sleep) for sleep in sleeps]
|
||||
|
||||
def update(
|
||||
self,
|
||||
sleep_id: int,
|
||||
end_time: datetime | None = None,
|
||||
) -> dict | None:
|
||||
"""Update a sleep log entry."""
|
||||
sleep = self.db.query(Sleep).filter(Sleep.id == sleep_id).first()
|
||||
if not sleep:
|
||||
return None
|
||||
|
||||
if end_time is not None:
|
||||
sleep.end_time = end_time # type: ignore[assignment]
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(sleep)
|
||||
return self._to_dict(sleep)
|
||||
|
||||
def delete(self, sleep_id: int) -> bool:
|
||||
"""Delete a sleep log entry."""
|
||||
sleep = self.db.query(Sleep).filter(Sleep.id == sleep_id).first()
|
||||
if not sleep:
|
||||
return False
|
||||
|
||||
self.db.delete(sleep)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
def _to_dict(self, sleep: Sleep) -> dict:
|
||||
"""Convert Sleep model to dictionary."""
|
||||
return {
|
||||
"id": sleep.id,
|
||||
"child_id": sleep.child_id,
|
||||
"start_time": sleep.start_time,
|
||||
"end_time": sleep.end_time,
|
||||
"created_at": sleep.created_at,
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Sleep log management router."""
|
||||
|
||||
from typing import Annotated
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from baby_monitor.models.sleep import (
|
||||
CreateSleepRequest,
|
||||
UpdateSleepRequest,
|
||||
SleepResponse,
|
||||
)
|
||||
from baby_monitor.routers.auth import verify_token
|
||||
from baby_monitor.repositories.sleep.sqlite_sleep import SQLiteSleepRepository
|
||||
from baby_monitor.repositories.dependencies.get_sleep_repository import (
|
||||
get_sleep_repository,
|
||||
)
|
||||
from baby_monitor.repositories.child.sqlite_child import SQLiteChildRepository
|
||||
from baby_monitor.repositories.dependencies.get_child_repository import (
|
||||
get_child_repository,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/sleep", tags=["sleep"])
|
||||
|
||||
|
||||
@router.post("", response_model=SleepResponse, status_code=201)
|
||||
def create_sleep(
|
||||
request: CreateSleepRequest,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> SleepResponse:
|
||||
"""Create a new sleep log entry."""
|
||||
# Verify the child belongs to the authenticated user
|
||||
child = child_repo.get_by_id(request.child_id)
|
||||
if not child:
|
||||
raise HTTPException(status_code=404, detail="Child not found")
|
||||
|
||||
if child["user_id"] != user_id:
|
||||
raise HTTPException(
|
||||
status_code=403, detail="Access denied to this child"
|
||||
)
|
||||
|
||||
sleep = sleep_repo.create(
|
||||
child_id=request.child_id,
|
||||
start_time=request.start_time,
|
||||
)
|
||||
|
||||
return SleepResponse(**sleep)
|
||||
|
||||
|
||||
@router.get("/active", response_model=SleepResponse | None)
|
||||
def get_active_sleep(
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> SleepResponse | None:
|
||||
"""Get the current active sleep (where end_time is null) for the user."""
|
||||
sleeps = sleep_repo.get_by_user_id(user_id)
|
||||
|
||||
# Find the first sleep with no end_time
|
||||
for sleep in sleeps:
|
||||
if sleep["end_time"] is None:
|
||||
# Get child info to include in response
|
||||
child = child_repo.get_by_id(sleep["child_id"])
|
||||
response_data = sleep.copy()
|
||||
if child:
|
||||
response_data["child_name"] = child["name"]
|
||||
return SleepResponse(**response_data)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
@router.get("", response_model=list[SleepResponse])
|
||||
def get_user_sleeps(
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
) -> list[SleepResponse]:
|
||||
"""Get all sleep logs for the authenticated user's children."""
|
||||
sleeps = sleep_repo.get_by_user_id(user_id)
|
||||
return [SleepResponse(**sleep) for sleep in sleeps]
|
||||
|
||||
|
||||
@router.get("/{sleep_id}", response_model=SleepResponse)
|
||||
def get_sleep(
|
||||
sleep_id: int,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> SleepResponse:
|
||||
"""Get a specific sleep log by ID."""
|
||||
sleep = sleep_repo.get_by_id(sleep_id)
|
||||
|
||||
if not sleep:
|
||||
raise HTTPException(status_code=404, detail="Sleep log not found")
|
||||
|
||||
# Verify the sleep belongs to user's child
|
||||
child = child_repo.get_by_id(sleep["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
return SleepResponse(**sleep)
|
||||
|
||||
|
||||
@router.put("/{sleep_id}", response_model=SleepResponse)
|
||||
def update_sleep(
|
||||
sleep_id: int,
|
||||
request: UpdateSleepRequest,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> SleepResponse:
|
||||
"""Update an existing sleep log."""
|
||||
sleep = sleep_repo.get_by_id(sleep_id)
|
||||
|
||||
if not sleep:
|
||||
raise HTTPException(status_code=404, detail="Sleep log not found")
|
||||
|
||||
# Verify the sleep belongs to user's child
|
||||
child = child_repo.get_by_id(sleep["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
updated = sleep_repo.update(
|
||||
sleep_id=sleep_id,
|
||||
end_time=request.end_time,
|
||||
)
|
||||
|
||||
if not updated:
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Failed to update sleep log"
|
||||
)
|
||||
|
||||
return SleepResponse(**updated)
|
||||
|
||||
|
||||
@router.delete("/{sleep_id}", status_code=204)
|
||||
def delete_sleep(
|
||||
sleep_id: int,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
sleep_repo: Annotated[SQLiteSleepRepository, Depends(get_sleep_repository)],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> None:
|
||||
"""Delete a sleep log."""
|
||||
sleep = sleep_repo.get_by_id(sleep_id)
|
||||
|
||||
if not sleep:
|
||||
raise HTTPException(status_code=404, detail="Sleep log not found")
|
||||
|
||||
# Verify the sleep belongs to user's child
|
||||
child = child_repo.get_by_id(sleep["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
success = sleep_repo.delete(sleep_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=500, detail="Failed to delete sleep log")
|
||||
@@ -323,6 +323,7 @@
|
||||
<div class="menu-item" id="menuHome">🏠 Home</div>
|
||||
<div class="menu-item" id="menuAddChild">👶 Add Child</div>
|
||||
<div class="menu-item" id="menuFeedings">🍼 Feedings</div>
|
||||
<div class="menu-item" id="menuSleep">😴 Sleep</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
@@ -378,6 +379,10 @@
|
||||
window.location.href = "/feedings.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
window.location.href = "/sleep.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
|
||||
@@ -360,6 +360,7 @@
|
||||
<div class="menu-item" id="menuHome">🏠 Home</div>
|
||||
<div class="menu-item" id="menuAddChild">👶 Add Child</div>
|
||||
<div class="menu-item" id="menuDiapers">🧷 Diapers</div>
|
||||
<div class="menu-item" id="menuSleep">😴 Sleep</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
@@ -415,6 +416,10 @@
|
||||
window.location.href = "/diapers.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
window.location.href = "/sleep.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
|
||||
@@ -203,6 +203,33 @@
|
||||
.cancel-button:hover {
|
||||
background-color: #5a6268;
|
||||
}
|
||||
.sleep-button {
|
||||
width: 100%;
|
||||
padding: 2rem;
|
||||
font-size: 1.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
border-radius: 8px;
|
||||
transition:
|
||||
transform 0.2s,
|
||||
box-shadow 0.2s;
|
||||
}
|
||||
.sleep-button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
|
||||
background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
|
||||
}
|
||||
.sleep-button.active {
|
||||
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
|
||||
}
|
||||
.sleep-button.active:hover {
|
||||
background: linear-gradient(135deg, #00f2fe 0%, #4facfe 100%);
|
||||
}
|
||||
.sleep-info {
|
||||
font-size: 0.9rem;
|
||||
margin-top: 0.5rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -218,6 +245,7 @@
|
||||
<div class="menu-item" id="menuAddChild">👶 Add Child</div>
|
||||
<div class="menu-item" id="menuFeedings">🍼 Feedings</div>
|
||||
<div class="menu-item" id="menuDiapers">🧷 Diapers</div>
|
||||
<div class="menu-item" id="menuSleep">😴 Sleep</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
@@ -261,6 +289,31 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Start Sleep Modal -->
|
||||
<div class="modal" id="startSleepModal">
|
||||
<div class="modal-content">
|
||||
<h2>😴 Start Sleep</h2>
|
||||
<form id="startSleepForm">
|
||||
<div class="form-group">
|
||||
<label for="modalSleepChildId">Child</label>
|
||||
<select id="modalSleepChildId" required>
|
||||
<option value="">Select a child</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="modal-buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="cancel-button"
|
||||
onclick="closeStartSleepModal()"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit">Start</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const token = localStorage.getItem("access_token");
|
||||
const username = localStorage.getItem("username");
|
||||
@@ -295,6 +348,10 @@
|
||||
window.location.href = "/diapers.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
window.location.href = "/sleep.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
@@ -349,6 +406,9 @@
|
||||
let userChildren = [];
|
||||
let lastFeeding = null;
|
||||
let updateTimerInterval = null;
|
||||
let activeSleep = null;
|
||||
let lastSleep = null;
|
||||
let sleepUpdateTimerInterval = null;
|
||||
|
||||
async function loadFeedingStatus(children) {
|
||||
userChildren = children;
|
||||
@@ -379,12 +439,38 @@
|
||||
lastFeeding = feedings[0];
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch active sleep
|
||||
const activeSleepResponse = await fetch("/api/sleep/active", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (activeSleepResponse.ok) {
|
||||
activeSleep = await activeSleepResponse.json();
|
||||
}
|
||||
|
||||
// Fetch all sleep logs to get the last one
|
||||
const sleepResponse = await fetch("/api/sleep", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (sleepResponse.ok) {
|
||||
const sleeps = await sleepResponse.json();
|
||||
if (sleeps.length > 0) {
|
||||
lastSleep = sleeps[0];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error loading feeding status:", error);
|
||||
}
|
||||
|
||||
renderContent();
|
||||
startUpdateTimer();
|
||||
startSleepUpdateTimer();
|
||||
}
|
||||
|
||||
function startUpdateTimer() {
|
||||
@@ -406,6 +492,25 @@
|
||||
}
|
||||
}
|
||||
|
||||
function startSleepUpdateTimer() {
|
||||
// Clear any existing timer
|
||||
if (sleepUpdateTimerInterval) {
|
||||
clearInterval(sleepUpdateTimerInterval);
|
||||
}
|
||||
|
||||
// Update every 30 seconds if there's an active sleep
|
||||
if (activeSleep) {
|
||||
sleepUpdateTimerInterval = setInterval(() => {
|
||||
if (activeSleep) {
|
||||
updateSleepTimeDisplay();
|
||||
} else {
|
||||
clearInterval(sleepUpdateTimerInterval);
|
||||
sleepUpdateTimerInterval = null;
|
||||
}
|
||||
}, 30000); // Update every 30 seconds
|
||||
}
|
||||
}
|
||||
|
||||
function updateFeedingTimeDisplay() {
|
||||
const timeElement = document.getElementById("feedingTimeInfo");
|
||||
if (timeElement && activeFeeding) {
|
||||
@@ -413,6 +518,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
function updateSleepTimeDisplay() {
|
||||
const timeElement = document.getElementById("sleepTimeInfo");
|
||||
if (timeElement && activeSleep) {
|
||||
timeElement.textContent = formatTime(activeSleep.start_time);
|
||||
}
|
||||
}
|
||||
|
||||
function renderContent() {
|
||||
const feedingButtonHtml = activeFeeding
|
||||
? `
|
||||
@@ -430,12 +542,29 @@
|
||||
</button>
|
||||
`;
|
||||
|
||||
const sleepButtonHtml = activeSleep
|
||||
? `
|
||||
<button class="sleep-button active" onclick="stopSleep()">
|
||||
🛑 Stop Sleep
|
||||
<div class="sleep-info">
|
||||
${activeSleep.child_name || "Child"}<br>
|
||||
Started <span id="sleepTimeInfo">${formatTime(activeSleep.start_time)}</span>
|
||||
</div>
|
||||
</button>
|
||||
`
|
||||
: `
|
||||
<button class="sleep-button" onclick="showStartSleepModal()">
|
||||
😴 Start Sleep
|
||||
</button>
|
||||
`;
|
||||
|
||||
document.getElementById("content").innerHTML = `
|
||||
<h1>Welcome to Baby Monitor!</h1>
|
||||
<div class="user-info">
|
||||
<p><strong>Logged in as:</strong> ${username}</p>
|
||||
</div>
|
||||
${feedingButtonHtml}
|
||||
${sleepButtonHtml}
|
||||
<button class="feeding-button" onclick="window.location.href='/log-diaper.html'" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); margin-top: 20px;">
|
||||
🧷 Log Diaper Change
|
||||
</button>
|
||||
@@ -590,6 +719,125 @@
|
||||
}
|
||||
}
|
||||
|
||||
function showStartSleepModal() {
|
||||
const modal = document.getElementById("startSleepModal");
|
||||
const childSelect = document.getElementById("modalSleepChildId");
|
||||
|
||||
// Clear and populate child select
|
||||
childSelect.innerHTML = '<option value="">Select a child</option>';
|
||||
userChildren.forEach((child) => {
|
||||
const option = document.createElement("option");
|
||||
option.value = child.id;
|
||||
option.textContent = child.name;
|
||||
childSelect.appendChild(option);
|
||||
});
|
||||
|
||||
// Set default based on last sleep
|
||||
if (lastSleep) {
|
||||
childSelect.value = lastSleep.child_id;
|
||||
}
|
||||
|
||||
modal.classList.add("show");
|
||||
}
|
||||
|
||||
function closeStartSleepModal() {
|
||||
const modal = document.getElementById("startSleepModal");
|
||||
modal.classList.remove("show");
|
||||
document.getElementById("startSleepForm").reset();
|
||||
}
|
||||
|
||||
document
|
||||
.getElementById("startSleepForm")
|
||||
.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const childId = parseInt(
|
||||
document.getElementById("modalSleepChildId").value,
|
||||
);
|
||||
|
||||
try {
|
||||
const now = new Date();
|
||||
const localDateTime = new Date(
|
||||
now.getTime() - now.getTimezoneOffset() * 60000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 19);
|
||||
|
||||
const response = await fetch("/api/sleep", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
child_id: childId,
|
||||
start_time: localDateTime,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const sleep = await response.json();
|
||||
activeSleep = sleep;
|
||||
lastSleep = sleep;
|
||||
|
||||
// Add child name to active sleep
|
||||
const child = userChildren.find((c) => c.id === childId);
|
||||
if (child) {
|
||||
activeSleep.child_name = child.name;
|
||||
}
|
||||
|
||||
closeStartSleepModal();
|
||||
renderContent();
|
||||
startSleepUpdateTimer();
|
||||
} else {
|
||||
const data = await response.json();
|
||||
alert(data.detail || "Failed to start sleep");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error starting sleep:", error);
|
||||
alert("Network error. Please try again.");
|
||||
}
|
||||
});
|
||||
|
||||
async function stopSleep() {
|
||||
if (!activeSleep) return;
|
||||
|
||||
try {
|
||||
const now = new Date();
|
||||
const localDateTime = new Date(
|
||||
now.getTime() - now.getTimezoneOffset() * 60000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 19);
|
||||
|
||||
const response = await fetch(`/api/sleep/${activeSleep.id}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
end_time: localDateTime,
|
||||
}),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
activeSleep = null;
|
||||
if (sleepUpdateTimerInterval) {
|
||||
clearInterval(sleepUpdateTimerInterval);
|
||||
sleepUpdateTimerInterval = null;
|
||||
}
|
||||
renderContent();
|
||||
} else {
|
||||
const data = await response.json();
|
||||
alert(data.detail || "Failed to stop sleep");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error stopping sleep:", error);
|
||||
alert("Network error. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
|
||||
@@ -0,0 +1,923 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>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;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.burger-menu {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
left: 1rem;
|
||||
cursor: pointer;
|
||||
z-index: 1000;
|
||||
background: white;
|
||||
padding: 0.5rem;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
.burger-menu div {
|
||||
width: 25px;
|
||||
height: 3px;
|
||||
background-color: #333;
|
||||
margin: 5px 0;
|
||||
transition: 0.3s;
|
||||
}
|
||||
.menu-overlay {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: -250px;
|
||||
width: 250px;
|
||||
height: 100vh;
|
||||
background: white;
|
||||
box-shadow: 2px 0 10px rgba(0, 0, 0, 0.1);
|
||||
transition: left 0.3s;
|
||||
z-index: 999;
|
||||
padding: 4rem 1rem 1rem 1rem;
|
||||
}
|
||||
.menu-overlay.open {
|
||||
left: 0;
|
||||
}
|
||||
.menu-backdrop {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
display: none;
|
||||
z-index: 998;
|
||||
}
|
||||
.menu-backdrop.open {
|
||||
display: block;
|
||||
}
|
||||
.menu-item {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #eee;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
.menu-item:hover {
|
||||
background: #f5f5f5;
|
||||
}
|
||||
.menu-item.logout {
|
||||
color: #dc3545;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.container {
|
||||
background: white;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
|
||||
padding: 40px;
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
h1 {
|
||||
color: #333;
|
||||
margin-bottom: 10px;
|
||||
font-size: 28px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #666;
|
||||
margin-bottom: 30px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.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;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.button:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
|
||||
}
|
||||
|
||||
.button.secondary {
|
||||
background: #6c757d;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.button.secondary:hover {
|
||||
box-shadow: 0 4px 12px rgba(108, 117, 125, 0.4);
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 60px 20px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.empty-state-icon {
|
||||
font-size: 64px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.empty-state h2 {
|
||||
color: #333;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.empty-state p {
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.chart-container {
|
||||
margin-bottom: 40px;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.chart-container h2 {
|
||||
color: #333;
|
||||
margin-bottom: 20px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.chart-wrapper {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
}
|
||||
|
||||
.charts-row {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 20px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.charts-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 40px;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: #f8f9fa;
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.stat-card h3 {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.stat-card .value {
|
||||
color: #4facfe;
|
||||
font-size: 32px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.list-container {
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.list-container h2 {
|
||||
color: #333;
|
||||
margin-bottom: 20px;
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.sleep-list {
|
||||
max-height: 500px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sleep-item {
|
||||
background: white;
|
||||
padding: 16px;
|
||||
border-radius: 6px;
|
||||
margin-bottom: 12px;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.sleep-item:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.sleep-info {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sleep-child {
|
||||
font-weight: 600;
|
||||
color: #333;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.sleep-time {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.sleep-duration {
|
||||
color: #4facfe;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sleep-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.edit-button {
|
||||
background: #4facfe;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 8px 16px;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
transition: background 0.2s;
|
||||
}
|
||||
|
||||
.edit-button:hover {
|
||||
background: #3a9be8;
|
||||
}
|
||||
|
||||
.filters {
|
||||
display: flex;
|
||||
gap: 15px;
|
||||
margin-bottom: 30px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.filter-group {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.filter-group label {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.filter-group select {
|
||||
padding: 8px 12px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
font-size: 14px;
|
||||
background: white;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
margin-right: 8px;
|
||||
}
|
||||
|
||||
.badge.ongoing {
|
||||
background: #4facfe;
|
||||
color: white;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="burger-menu" id="burgerMenu">
|
||||
<div></div>
|
||||
<div></div>
|
||||
<div></div>
|
||||
</div>
|
||||
|
||||
<div class="menu-backdrop" id="menuBackdrop"></div>
|
||||
|
||||
<div class="menu-overlay" id="menuOverlay">
|
||||
<div class="menu-item" id="menuHome">🏠 Home</div>
|
||||
<div class="menu-item" id="menuAddChild">👶 Add Child</div>
|
||||
<div class="menu-item" id="menuFeedings">🍼 Feedings</div>
|
||||
<div class="menu-item" id="menuDiapers">🧷 Diapers</div>
|
||||
<div class="menu-item" id="menuSleep">😴 Sleep</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<h1>😴 Sleep Tracking</h1>
|
||||
<p class="subtitle">Monitor your baby's sleep patterns</p>
|
||||
|
||||
<div class="filters">
|
||||
<div class="filter-group">
|
||||
<label for="childFilter">Child</label>
|
||||
<select id="childFilter">
|
||||
<option value="">All Children</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="content" class="loading">
|
||||
<p>Loading sleep data...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
|
||||
<script>
|
||||
const token = localStorage.getItem("access_token");
|
||||
|
||||
// Burger menu functionality
|
||||
const burgerMenu = document.getElementById("burgerMenu");
|
||||
const menuOverlay = document.getElementById("menuOverlay");
|
||||
const menuBackdrop = document.getElementById("menuBackdrop");
|
||||
|
||||
function toggleMenu() {
|
||||
menuOverlay.classList.toggle("open");
|
||||
menuBackdrop.classList.toggle("open");
|
||||
}
|
||||
|
||||
function closeMenu() {
|
||||
menuOverlay.classList.remove("open");
|
||||
menuBackdrop.classList.remove("open");
|
||||
}
|
||||
|
||||
burgerMenu.addEventListener("click", toggleMenu);
|
||||
menuBackdrop.addEventListener("click", closeMenu);
|
||||
|
||||
document.getElementById("menuHome").addEventListener("click", () => {
|
||||
window.location.href = "/";
|
||||
});
|
||||
|
||||
document.getElementById("menuAddChild").addEventListener("click", () => {
|
||||
window.location.href = "/add-child.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuFeedings").addEventListener("click", () => {
|
||||
window.location.href = "/feedings.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuDiapers").addEventListener("click", () => {
|
||||
window.location.href = "/diapers.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
});
|
||||
|
||||
// Check if user is logged in
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
|
||||
let allSleeps = [];
|
||||
let allChildren = [];
|
||||
let selectedChildId = "";
|
||||
|
||||
// Filter change handlers
|
||||
document
|
||||
.getElementById("childFilter")
|
||||
.addEventListener("change", function () {
|
||||
selectedChildId = this.value;
|
||||
// Save selection to localStorage
|
||||
if (selectedChildId) {
|
||||
localStorage.setItem("lastSleepChildFilter", selectedChildId);
|
||||
} else {
|
||||
localStorage.removeItem("lastSleepChildFilter");
|
||||
}
|
||||
renderCharts();
|
||||
});
|
||||
|
||||
document
|
||||
.getElementById("timeRangeFilter")
|
||||
.addEventListener("change", function () {
|
||||
loadData();
|
||||
});
|
||||
|
||||
async function loadData() {
|
||||
try {
|
||||
// Fetch children
|
||||
const childrenResponse = await fetch("/api/children", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!childrenResponse.ok) {
|
||||
throw new Error("Failed to fetch children");
|
||||
}
|
||||
|
||||
allChildren = await childrenResponse.json();
|
||||
|
||||
// Populate child filter
|
||||
const childFilter = document.getElementById("childFilter");
|
||||
childFilter.innerHTML = '<option value="">All Children</option>';
|
||||
allChildren.forEach((child) => {
|
||||
const option = document.createElement("option");
|
||||
option.value = child.id;
|
||||
option.textContent = child.name;
|
||||
childFilter.appendChild(option);
|
||||
});
|
||||
|
||||
// Restore last selected child from localStorage
|
||||
const lastChildId = localStorage.getItem("lastSleepChildFilter");
|
||||
if (lastChildId) {
|
||||
childFilter.value = lastChildId;
|
||||
selectedChildId = lastChildId;
|
||||
}
|
||||
|
||||
// Fetch sleep logs
|
||||
const sleepResponse = await fetch("/api/sleep", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!sleepResponse.ok) {
|
||||
throw new Error("Failed to fetch sleep data");
|
||||
}
|
||||
|
||||
allSleeps = await sleepResponse.json();
|
||||
|
||||
renderCharts();
|
||||
} catch (error) {
|
||||
console.error("Error loading data:", error);
|
||||
document.getElementById("content").innerHTML = `
|
||||
<div class="empty-state">
|
||||
<div class="empty-state-icon">😴</div>
|
||||
<h2>Error Loading Data</h2>
|
||||
<p>${error.message}</p>
|
||||
<button class="button" onclick="window.location.href='/'">Go Home</button>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderCharts() {
|
||||
const timeRange = parseInt(
|
||||
document.getElementById("timeRangeFilter").value,
|
||||
);
|
||||
const cutoffDate = new Date();
|
||||
cutoffDate.setDate(cutoffDate.getDate() - timeRange);
|
||||
|
||||
// Filter sleeps by time range and child
|
||||
let filteredSleeps = allSleeps.filter((sleep) => {
|
||||
const sleepDate = new Date(sleep.start_time);
|
||||
const matchesTimeRange = sleepDate >= cutoffDate;
|
||||
const matchesChild =
|
||||
!selectedChildId ||
|
||||
sleep.child_id === parseInt(selectedChildId);
|
||||
return matchesTimeRange && matchesChild;
|
||||
});
|
||||
|
||||
if (filteredSleeps.length === 0) {
|
||||
document.getElementById("content").innerHTML = `
|
||||
<div class="empty-state">
|
||||
<div class="empty-state-icon">😴</div>
|
||||
<h2>No Sleep Data</h2>
|
||||
<p>Start tracking sleep sessions from the home page.</p>
|
||||
<button class="button" onclick="window.location.href='/'">Go Home</button>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
// Calculate stats
|
||||
const completedSleeps = filteredSleeps.filter(
|
||||
(sleep) => sleep.end_time,
|
||||
);
|
||||
const totalSessions = filteredSleeps.length;
|
||||
const ongoingSessions = filteredSleeps.filter(
|
||||
(sleep) => !sleep.end_time,
|
||||
).length;
|
||||
|
||||
let totalMinutes = 0;
|
||||
let longestMinutes = 0;
|
||||
let shortestMinutes = Infinity;
|
||||
|
||||
completedSleeps.forEach((sleep) => {
|
||||
const duration = calculateDuration(sleep.start_time, sleep.end_time);
|
||||
totalMinutes += duration;
|
||||
if (duration > longestMinutes) longestMinutes = duration;
|
||||
if (duration < shortestMinutes) shortestMinutes = duration;
|
||||
});
|
||||
|
||||
const avgMinutes =
|
||||
completedSleeps.length > 0
|
||||
? Math.round(totalMinutes / completedSleeps.length)
|
||||
: 0;
|
||||
|
||||
if (completedSleeps.length === 0) {
|
||||
shortestMinutes = 0;
|
||||
}
|
||||
|
||||
// Prepare data for charts
|
||||
const barChartData = prepareBarChartData(filteredSleeps, timeRange);
|
||||
const durationDistData = prepareDurationDistributionData(completedSleeps);
|
||||
|
||||
let html = `
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<h3>Total Sessions</h3>
|
||||
<div class="value">${totalSessions}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Ongoing</h3>
|
||||
<div class="value">${ongoingSessions}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Avg Duration</h3>
|
||||
<div class="value">${formatDuration(avgMinutes)}</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<h3>Longest Sleep</h3>
|
||||
<div class="value">${formatDuration(longestMinutes)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<h2>Sleep Sessions per Day</h2>
|
||||
<div class="chart-wrapper">
|
||||
<canvas id="barChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="charts-row">
|
||||
<div class="chart-container">
|
||||
<h2>Duration Distribution</h2>
|
||||
<div class="chart-wrapper">
|
||||
<canvas id="durationChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
<div class="chart-container">
|
||||
<h2>Average Duration by Day</h2>
|
||||
<div class="chart-wrapper">
|
||||
<canvas id="avgDurationChart"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="list-container">
|
||||
<h2>Recent Sleep Sessions</h2>
|
||||
<div class="sleep-list">
|
||||
${filteredSleeps
|
||||
.slice(0, 50)
|
||||
.map((sleep) => renderSleepItem(sleep))
|
||||
.join("")}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById("content").innerHTML = html;
|
||||
|
||||
// Render charts
|
||||
renderBarChart(barChartData);
|
||||
renderDurationChart(durationDistData);
|
||||
renderAvgDurationChart(filteredSleeps, timeRange);
|
||||
}
|
||||
|
||||
function calculateDuration(startTime, endTime) {
|
||||
if (!endTime) return 0;
|
||||
const start = new Date(startTime);
|
||||
const end = new Date(endTime);
|
||||
return Math.round((end - start) / 60000); // minutes
|
||||
}
|
||||
|
||||
function formatDuration(minutes) {
|
||||
if (minutes === 0) return "0m";
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const mins = minutes % 60;
|
||||
if (hours === 0) return `${mins}m`;
|
||||
if (mins === 0) return `${hours}h`;
|
||||
return `${hours}h ${mins}m`;
|
||||
}
|
||||
|
||||
function prepareBarChartData(sleeps, timeRange) {
|
||||
const days = {};
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
// Initialize all days in range
|
||||
for (let i = timeRange - 1; i >= 0; i--) {
|
||||
const date = new Date(today);
|
||||
date.setDate(date.getDate() - i);
|
||||
const dateStr = date.toISOString().split("T")[0];
|
||||
days[dateStr] = 0;
|
||||
}
|
||||
|
||||
// Count sleeps per day
|
||||
sleeps.forEach((sleep) => {
|
||||
const date = new Date(sleep.start_time);
|
||||
date.setHours(0, 0, 0, 0);
|
||||
const dateStr = date.toISOString().split("T")[0];
|
||||
if (days.hasOwnProperty(dateStr)) {
|
||||
days[dateStr]++;
|
||||
}
|
||||
});
|
||||
|
||||
const labels = Object.keys(days).map((date) => {
|
||||
const d = new Date(date);
|
||||
return d.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
labels,
|
||||
data: Object.values(days),
|
||||
};
|
||||
}
|
||||
|
||||
function prepareDurationDistributionData(sleeps) {
|
||||
const ranges = {
|
||||
"0-30m": 0,
|
||||
"30m-1h": 0,
|
||||
"1-2h": 0,
|
||||
"2-3h": 0,
|
||||
"3-4h": 0,
|
||||
"4h+": 0,
|
||||
};
|
||||
|
||||
sleeps.forEach((sleep) => {
|
||||
const duration = calculateDuration(sleep.start_time, sleep.end_time);
|
||||
if (duration < 30) ranges["0-30m"]++;
|
||||
else if (duration < 60) ranges["30m-1h"]++;
|
||||
else if (duration < 120) ranges["1-2h"]++;
|
||||
else if (duration < 180) ranges["2-3h"]++;
|
||||
else if (duration < 240) ranges["3-4h"]++;
|
||||
else ranges["4h+"]++;
|
||||
});
|
||||
|
||||
return {
|
||||
labels: Object.keys(ranges),
|
||||
data: Object.values(ranges),
|
||||
};
|
||||
}
|
||||
|
||||
function renderBarChart(chartData) {
|
||||
const ctx = document.getElementById("barChart");
|
||||
new Chart(ctx, {
|
||||
type: "bar",
|
||||
data: {
|
||||
labels: chartData.labels,
|
||||
datasets: [
|
||||
{
|
||||
label: "Sleep Sessions",
|
||||
data: chartData.data,
|
||||
backgroundColor: "rgba(79, 172, 254, 0.6)",
|
||||
borderColor: "rgba(79, 172, 254, 1)",
|
||||
borderWidth: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderDurationChart(chartData) {
|
||||
const ctx = document.getElementById("durationChart");
|
||||
new Chart(ctx, {
|
||||
type: "pie",
|
||||
data: {
|
||||
labels: chartData.labels,
|
||||
datasets: [
|
||||
{
|
||||
data: chartData.data,
|
||||
backgroundColor: [
|
||||
"rgba(79, 172, 254, 0.8)",
|
||||
"rgba(0, 242, 254, 0.8)",
|
||||
"rgba(58, 155, 232, 0.8)",
|
||||
"rgba(32, 137, 220, 0.8)",
|
||||
"rgba(21, 119, 208, 0.8)",
|
||||
"rgba(11, 101, 196, 0.8)",
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: "bottom",
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderAvgDurationChart(sleeps, timeRange) {
|
||||
const days = {};
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
|
||||
// Initialize all days
|
||||
for (let i = timeRange - 1; i >= 0; i--) {
|
||||
const date = new Date(today);
|
||||
date.setDate(date.getDate() - i);
|
||||
const dateStr = date.toISOString().split("T")[0];
|
||||
days[dateStr] = { total: 0, count: 0 };
|
||||
}
|
||||
|
||||
// Calculate totals
|
||||
sleeps
|
||||
.filter((sleep) => sleep.end_time)
|
||||
.forEach((sleep) => {
|
||||
const date = new Date(sleep.start_time);
|
||||
date.setHours(0, 0, 0, 0);
|
||||
const dateStr = date.toISOString().split("T")[0];
|
||||
if (days.hasOwnProperty(dateStr)) {
|
||||
const duration = calculateDuration(
|
||||
sleep.start_time,
|
||||
sleep.end_time,
|
||||
);
|
||||
days[dateStr].total += duration;
|
||||
days[dateStr].count++;
|
||||
}
|
||||
});
|
||||
|
||||
const labels = Object.keys(days).map((date) => {
|
||||
const d = new Date(date);
|
||||
return d.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
});
|
||||
|
||||
const data = Object.values(days).map((day) =>
|
||||
day.count > 0 ? Math.round(day.total / day.count) : 0,
|
||||
);
|
||||
|
||||
const ctx = document.getElementById("avgDurationChart");
|
||||
new Chart(ctx, {
|
||||
type: "line",
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: "Avg Duration (minutes)",
|
||||
data,
|
||||
borderColor: "rgba(79, 172, 254, 1)",
|
||||
backgroundColor: "rgba(79, 172, 254, 0.1)",
|
||||
fill: true,
|
||||
tension: 0.4,
|
||||
},
|
||||
],
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
callback: function (value) {
|
||||
return value + "m";
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderSleepItem(sleep) {
|
||||
const child = allChildren.find((c) => c.id === sleep.child_id);
|
||||
const childName = child ? child.name : "Unknown";
|
||||
const startDate = new Date(sleep.start_time);
|
||||
const isOngoing = !sleep.end_time;
|
||||
|
||||
let durationText = "";
|
||||
if (isOngoing) {
|
||||
durationText = '<span class="badge ongoing">Ongoing</span>';
|
||||
} else {
|
||||
const duration = calculateDuration(sleep.start_time, sleep.end_time);
|
||||
durationText = `Duration: ${formatDuration(duration)}`;
|
||||
}
|
||||
|
||||
return `
|
||||
<div class="sleep-item">
|
||||
<div class="sleep-info">
|
||||
<div class="sleep-child">${childName}</div>
|
||||
<div class="sleep-time">
|
||||
${startDate.toLocaleString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
${isOngoing ? "" : ` - ${new Date(sleep.end_time).toLocaleString("en-US", { hour: "numeric", minute: "2-digit" })}`}
|
||||
</div>
|
||||
<div class="sleep-duration">${durationText}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await fetch("/api/logout", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Logout error:", error);
|
||||
} finally {
|
||||
localStorage.removeItem("access_token");
|
||||
localStorage.removeItem("username");
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
}
|
||||
|
||||
// Load data on page load
|
||||
loadData();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user