Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df28af880a | ||
|
|
6c3d301027 | ||
|
|
cd3db4fb86 | ||
|
|
edeb01c889 | ||
|
|
cf3029b545 | ||
|
|
aaa84b8b1a | ||
|
|
e9e5936267 | ||
|
|
788b473c23 | ||
|
|
0853ff0ff4 |
@@ -17,7 +17,7 @@ services:
|
||||
# Use Redis for token storage
|
||||
- REDIS_URI=redis://redis:6379/0
|
||||
# Use PostgreSQL for database
|
||||
- DATABASE_URL=postgresql://baby_monitor:securepassword@postgres:5432/b
|
||||
- DATABASE_URL=postgresql://baby_monitor:securepassword@postgres:5432/baby_monitor_db
|
||||
command: ["--host", "0.0.0.0", "--port", "8000"]
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
|
||||
@@ -14,6 +14,8 @@ from baby_monitor.routers.auth import verify_token
|
||||
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
|
||||
|
||||
@@ -51,6 +53,8 @@ app.include_router(auth_router)
|
||||
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)
|
||||
|
||||
|
||||
@@ -97,6 +101,24 @@ def serve_feedings() -> FileResponse:
|
||||
return FileResponse(static_path / "feedings.html")
|
||||
|
||||
|
||||
@app.get("/diapers.html", include_in_schema=False)
|
||||
def serve_diapers() -> FileResponse:
|
||||
"""Serve the diaper changes overview page."""
|
||||
return FileResponse(static_path / "diapers.html")
|
||||
|
||||
|
||||
@app.get("/log-diaper.html", include_in_schema=False)
|
||||
def serve_log_diaper() -> FileResponse:
|
||||
"""Serve the log diaper change page."""
|
||||
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,30 @@
|
||||
"""Diaper change database model."""
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from sqlalchemy import Column, Integer, DateTime, ForeignKey, String
|
||||
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 DiaperChange(Base):
|
||||
"""Diaper change log database model."""
|
||||
|
||||
__tablename__ = "diaper_changes"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
child_id = Column(Integer, ForeignKey("children.id"), nullable=False)
|
||||
change_time = Column(DateTime, nullable=False)
|
||||
poop_amount = Column(String, nullable=True) # stores PoopAmount enum
|
||||
poop_color = Column(String, nullable=True) # stores PoopColor enum
|
||||
pee_amount = Column(String, nullable=True) # stores PeeAmount enum
|
||||
pee_color = Column(String, nullable=True) # stores PeeColor enum
|
||||
created_at = Column(DateTime, default=datetime.now(UTC), nullable=False)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<DiaperChange(id={self.id}, child_id={self.child_id})>"
|
||||
@@ -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,46 @@
|
||||
"""Diaper change-related request and response models."""
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from baby_monitor.models.enums import (
|
||||
PeeAmount,
|
||||
PeeColor,
|
||||
PoopAmount,
|
||||
PoopColor,
|
||||
)
|
||||
|
||||
|
||||
class CreateDiaperChangeRequest(BaseModel):
|
||||
"""Request model for creating a diaper change log."""
|
||||
|
||||
child_id: int = Field(..., gt=0)
|
||||
change_time: datetime
|
||||
poop_amount: PoopAmount | None = None
|
||||
poop_color: PoopColor | None = None
|
||||
pee_amount: PeeAmount | None = None
|
||||
pee_color: PeeColor | None = None
|
||||
|
||||
|
||||
class UpdateDiaperChangeRequest(BaseModel):
|
||||
"""Request model for updating a diaper change log."""
|
||||
|
||||
change_time: datetime | None = None
|
||||
poop_amount: PoopAmount | None = None
|
||||
poop_color: PoopColor | None = None
|
||||
pee_amount: PeeAmount | None = None
|
||||
pee_color: PeeColor | None = None
|
||||
|
||||
|
||||
class DiaperChangeResponse(BaseModel):
|
||||
"""Response model for diaper change log data."""
|
||||
|
||||
id: int
|
||||
child_id: int
|
||||
change_time: datetime
|
||||
poop_amount: str | None
|
||||
poop_color: str | None
|
||||
pee_amount: str | None
|
||||
pee_color: str | None
|
||||
created_at: datetime
|
||||
child_name: str | None = None # Optional, populated when needed
|
||||
@@ -9,3 +9,36 @@ class FeedingType(StrEnum):
|
||||
LEFT_BREAST = "left_breast"
|
||||
RIGHT_BREAST = "right_breast"
|
||||
BOTTLE = "bottle"
|
||||
|
||||
|
||||
class PoopAmount(StrEnum):
|
||||
"""Enumeration of poop amounts."""
|
||||
|
||||
LIGHT = "light"
|
||||
MEDIUM = "medium"
|
||||
HEAVY = "heavy"
|
||||
|
||||
|
||||
class PoopColor(StrEnum):
|
||||
"""Enumeration of poop colors."""
|
||||
|
||||
BLACK = "black"
|
||||
YELLOW = "yellow"
|
||||
GREEN = "green"
|
||||
BROWN = "brown"
|
||||
|
||||
|
||||
class PeeAmount(StrEnum):
|
||||
"""Enumeration of pee amounts."""
|
||||
|
||||
LIGHT = "light"
|
||||
MEDIUM = "medium"
|
||||
HEAVY = "heavy"
|
||||
|
||||
|
||||
class PeeColor(StrEnum):
|
||||
"""Enumeration of pee colors."""
|
||||
|
||||
CLEAR = "clear"
|
||||
YELLOW = "yellow"
|
||||
RED = "red"
|
||||
|
||||
@@ -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
|
||||
@@ -79,6 +79,8 @@ def init_db() -> None:
|
||||
from baby_monitor.models.db.user import User # noqa: F401
|
||||
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,17 @@
|
||||
"""Dependency for getting diaper change 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.diaper_change.sqlite_diaper_change import (
|
||||
SQLiteDiaperChangeRepository,
|
||||
)
|
||||
|
||||
|
||||
def get_diaper_change_repository(
|
||||
db: Annotated[Session, Depends(get_database)],
|
||||
) -> SQLiteDiaperChangeRepository:
|
||||
"""Get diaper change repository instance."""
|
||||
return SQLiteDiaperChangeRepository(db)
|
||||
@@ -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,133 @@
|
||||
"""SQLite implementation of diaper change repository."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from baby_monitor.repositories.interfaces.diaper_change_repository_interface import ( # noqa: E501
|
||||
DiaperChangeRepositoryInterface,
|
||||
)
|
||||
from baby_monitor.models.db.diaper_change import DiaperChange
|
||||
from baby_monitor.models.db.child import Child
|
||||
|
||||
|
||||
class SQLiteDiaperChangeRepository(DiaperChangeRepositoryInterface):
|
||||
"""SQLite implementation for diaper change log data access."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def create(
|
||||
self,
|
||||
child_id: int,
|
||||
change_time: datetime,
|
||||
poop_amount: str | None = None,
|
||||
poop_color: str | None = None,
|
||||
pee_amount: str | None = None,
|
||||
pee_color: str | None = None,
|
||||
) -> dict:
|
||||
"""Create a new diaper change log entry."""
|
||||
diaper_change = DiaperChange(
|
||||
child_id=child_id,
|
||||
change_time=change_time,
|
||||
poop_amount=poop_amount,
|
||||
poop_color=poop_color,
|
||||
pee_amount=pee_amount,
|
||||
pee_color=pee_color,
|
||||
)
|
||||
self.db.add(diaper_change)
|
||||
self.db.commit()
|
||||
self.db.refresh(diaper_change)
|
||||
|
||||
return self._to_dict(diaper_change)
|
||||
|
||||
def get_by_id(self, diaper_change_id: int) -> dict | None:
|
||||
"""Get a diaper change log by ID."""
|
||||
diaper_change = (
|
||||
self.db.query(DiaperChange)
|
||||
.filter(DiaperChange.id == diaper_change_id)
|
||||
.first()
|
||||
)
|
||||
if not diaper_change:
|
||||
return None
|
||||
return self._to_dict(diaper_change)
|
||||
|
||||
def get_by_child_id(self, child_id: int) -> list[dict]:
|
||||
"""Get all diaper change logs for a specific child."""
|
||||
diaper_changes = (
|
||||
self.db.query(DiaperChange)
|
||||
.filter(DiaperChange.child_id == child_id)
|
||||
.order_by(DiaperChange.change_time.desc())
|
||||
.all()
|
||||
)
|
||||
return [self._to_dict(dc) for dc in diaper_changes]
|
||||
|
||||
def get_by_user_id(self, user_id: int) -> list[dict]:
|
||||
"""Get all diaper change logs for a specific user's children."""
|
||||
diaper_changes = (
|
||||
self.db.query(DiaperChange)
|
||||
.join(Child)
|
||||
.filter(Child.user_id == user_id)
|
||||
.order_by(DiaperChange.change_time.desc())
|
||||
.all()
|
||||
)
|
||||
return [self._to_dict(dc) for dc in diaper_changes]
|
||||
|
||||
def update(
|
||||
self,
|
||||
diaper_change_id: int,
|
||||
change_time: datetime | None = None,
|
||||
poop_amount: str | None = None,
|
||||
poop_color: str | None = None,
|
||||
pee_amount: str | None = None,
|
||||
pee_color: str | None = None,
|
||||
) -> dict | None:
|
||||
"""Update a diaper change log entry."""
|
||||
diaper_change = (
|
||||
self.db.query(DiaperChange)
|
||||
.filter(DiaperChange.id == diaper_change_id)
|
||||
.first()
|
||||
)
|
||||
if not diaper_change:
|
||||
return None
|
||||
|
||||
if change_time is not None:
|
||||
diaper_change.change_time = change_time # type: ignore[assignment]
|
||||
if poop_amount is not None:
|
||||
diaper_change.poop_amount = poop_amount # type: ignore[assignment]
|
||||
if poop_color is not None:
|
||||
diaper_change.poop_color = poop_color # type: ignore[assignment]
|
||||
if pee_amount is not None:
|
||||
diaper_change.pee_amount = pee_amount # type: ignore[assignment]
|
||||
if pee_color is not None:
|
||||
diaper_change.pee_color = pee_color # type: ignore[assignment]
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(diaper_change)
|
||||
return self._to_dict(diaper_change)
|
||||
|
||||
def delete(self, diaper_change_id: int) -> bool:
|
||||
"""Delete a diaper change log entry."""
|
||||
diaper_change = (
|
||||
self.db.query(DiaperChange)
|
||||
.filter(DiaperChange.id == diaper_change_id)
|
||||
.first()
|
||||
)
|
||||
if not diaper_change:
|
||||
return False
|
||||
|
||||
self.db.delete(diaper_change)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
def _to_dict(self, diaper_change: DiaperChange) -> dict:
|
||||
"""Convert DiaperChange model to dictionary."""
|
||||
return {
|
||||
"id": diaper_change.id,
|
||||
"child_id": diaper_change.child_id,
|
||||
"change_time": diaper_change.change_time,
|
||||
"poop_amount": diaper_change.poop_amount,
|
||||
"poop_color": diaper_change.poop_color,
|
||||
"pee_amount": diaper_change.pee_amount,
|
||||
"pee_color": diaper_change.pee_color,
|
||||
"created_at": diaper_change.created_at,
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Interface for diaper change repository operations."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class DiaperChangeRepositoryInterface(ABC):
|
||||
"""Interface for diaper change log data access operations."""
|
||||
|
||||
@abstractmethod
|
||||
def create(
|
||||
self,
|
||||
child_id: int,
|
||||
change_time: datetime,
|
||||
poop_amount: str | None = None,
|
||||
poop_color: str | None = None,
|
||||
pee_amount: str | None = None,
|
||||
pee_color: str | None = None,
|
||||
) -> dict:
|
||||
"""Create a new diaper change log entry."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_id(self, diaper_change_id: int) -> dict | None:
|
||||
"""Get a diaper change log by ID."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_child_id(self, child_id: int) -> list[dict]:
|
||||
"""Get all diaper change logs for a specific child."""
|
||||
|
||||
@abstractmethod
|
||||
def get_by_user_id(self, user_id: int) -> list[dict]:
|
||||
"""Get all diaper change logs for a specific user's children."""
|
||||
|
||||
@abstractmethod
|
||||
def update(
|
||||
self,
|
||||
diaper_change_id: int,
|
||||
change_time: datetime | None = None,
|
||||
poop_amount: str | None = None,
|
||||
poop_color: str | None = None,
|
||||
pee_amount: str | None = None,
|
||||
pee_color: str | None = None,
|
||||
) -> dict | None:
|
||||
"""Update a diaper change log entry."""
|
||||
|
||||
@abstractmethod
|
||||
def delete(self, diaper_change_id: int) -> bool:
|
||||
"""Delete a diaper change log entry."""
|
||||
@@ -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,153 @@
|
||||
"""Diaper change log management router."""
|
||||
|
||||
from typing import Annotated
|
||||
from fastapi import APIRouter, HTTPException, Depends
|
||||
|
||||
from baby_monitor.models.diaper_change import (
|
||||
CreateDiaperChangeRequest,
|
||||
UpdateDiaperChangeRequest,
|
||||
DiaperChangeResponse,
|
||||
)
|
||||
from baby_monitor.routers.auth import verify_token
|
||||
from baby_monitor.repositories.diaper_change.sqlite_diaper_change import (
|
||||
SQLiteDiaperChangeRepository,
|
||||
)
|
||||
from baby_monitor.repositories.dependencies.get_diaper_change_repository import ( # noqa: E501
|
||||
get_diaper_change_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/diaper-changes", tags=["diaper-changes"])
|
||||
|
||||
|
||||
@router.post("", response_model=DiaperChangeResponse, status_code=201)
|
||||
def create_diaper_change(
|
||||
request: CreateDiaperChangeRequest,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
diaper_repo: Annotated[
|
||||
SQLiteDiaperChangeRepository, Depends(get_diaper_change_repository)
|
||||
],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> DiaperChangeResponse:
|
||||
"""Create a new diaper change 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")
|
||||
|
||||
diaper_change = diaper_repo.create(
|
||||
child_id=request.child_id,
|
||||
change_time=request.change_time,
|
||||
poop_amount=request.poop_amount.value if request.poop_amount else None,
|
||||
poop_color=request.poop_color.value if request.poop_color else None,
|
||||
pee_amount=request.pee_amount.value if request.pee_amount else None,
|
||||
pee_color=request.pee_color.value if request.pee_color else None,
|
||||
)
|
||||
|
||||
return DiaperChangeResponse(**diaper_change)
|
||||
|
||||
|
||||
@router.get("", response_model=list[DiaperChangeResponse])
|
||||
def get_user_diaper_changes(
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
diaper_repo: Annotated[
|
||||
SQLiteDiaperChangeRepository, Depends(get_diaper_change_repository)
|
||||
],
|
||||
) -> list[DiaperChangeResponse]:
|
||||
"""Get all diaper change logs for the authenticated user's children."""
|
||||
diaper_changes = diaper_repo.get_by_user_id(user_id)
|
||||
return [DiaperChangeResponse(**dc) for dc in diaper_changes]
|
||||
|
||||
|
||||
@router.get("/{diaper_change_id}", response_model=DiaperChangeResponse)
|
||||
def get_diaper_change(
|
||||
diaper_change_id: int,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
diaper_repo: Annotated[
|
||||
SQLiteDiaperChangeRepository, Depends(get_diaper_change_repository)
|
||||
],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> DiaperChangeResponse:
|
||||
"""Get a specific diaper change log by ID."""
|
||||
diaper_change = diaper_repo.get_by_id(diaper_change_id)
|
||||
|
||||
if not diaper_change:
|
||||
raise HTTPException(status_code=404, detail="Diaper change log not found")
|
||||
|
||||
# Verify the diaper change belongs to user's child
|
||||
child = child_repo.get_by_id(diaper_change["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
return DiaperChangeResponse(**diaper_change)
|
||||
|
||||
|
||||
@router.put("/{diaper_change_id}", response_model=DiaperChangeResponse)
|
||||
def update_diaper_change(
|
||||
diaper_change_id: int,
|
||||
request: UpdateDiaperChangeRequest,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
diaper_repo: Annotated[
|
||||
SQLiteDiaperChangeRepository, Depends(get_diaper_change_repository)
|
||||
],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> DiaperChangeResponse:
|
||||
"""Update an existing diaper change log."""
|
||||
diaper_change = diaper_repo.get_by_id(diaper_change_id)
|
||||
|
||||
if not diaper_change:
|
||||
raise HTTPException(status_code=404, detail="Diaper change log not found")
|
||||
|
||||
# Verify the diaper change belongs to user's child
|
||||
child = child_repo.get_by_id(diaper_change["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
updated = diaper_repo.update(
|
||||
diaper_change_id=diaper_change_id,
|
||||
change_time=request.change_time,
|
||||
poop_amount=request.poop_amount.value if request.poop_amount else None,
|
||||
poop_color=request.poop_color.value if request.poop_color else None,
|
||||
pee_amount=request.pee_amount.value if request.pee_amount else None,
|
||||
pee_color=request.pee_color.value if request.pee_color else None,
|
||||
)
|
||||
|
||||
if not updated:
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Failed to update diaper change log"
|
||||
)
|
||||
|
||||
return DiaperChangeResponse(**updated)
|
||||
|
||||
|
||||
@router.delete("/{diaper_change_id}", status_code=204)
|
||||
def delete_diaper_change(
|
||||
diaper_change_id: int,
|
||||
user_id: Annotated[int, Depends(verify_token)],
|
||||
diaper_repo: Annotated[
|
||||
SQLiteDiaperChangeRepository, Depends(get_diaper_change_repository)
|
||||
],
|
||||
child_repo: Annotated[SQLiteChildRepository, Depends(get_child_repository)],
|
||||
) -> None:
|
||||
"""Delete a diaper change log."""
|
||||
diaper_change = diaper_repo.get_by_id(diaper_change_id)
|
||||
|
||||
if not diaper_change:
|
||||
raise HTTPException(status_code=404, detail="Diaper change log not found")
|
||||
|
||||
# Verify the diaper change belongs to user's child
|
||||
child = child_repo.get_by_id(diaper_change["child_id"])
|
||||
if not child or child["user_id"] != user_id:
|
||||
raise HTTPException(status_code=403, detail="Access denied")
|
||||
|
||||
success = diaper_repo.delete(diaper_change_id)
|
||||
if not success:
|
||||
raise HTTPException(
|
||||
status_code=500, detail="Failed to delete diaper change log"
|
||||
)
|
||||
@@ -0,0 +1,151 @@
|
||||
"""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")
|
||||
File diff suppressed because it is too large
Load Diff
@@ -359,6 +359,8 @@
|
||||
<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="menuDiapers">🧷 Diapers</div>
|
||||
<div class="menu-item" id="menuSleep">😴 Sleep</div>
|
||||
<div class="menu-item logout" id="menuLogout">🚪 Logout</div>
|
||||
</div>
|
||||
|
||||
@@ -410,6 +412,14 @@
|
||||
window.location.href = "/add-child.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuDiapers").addEventListener("click", () => {
|
||||
window.location.href = "/diapers.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
window.location.href = "/sleep.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
@@ -460,7 +470,8 @@
|
||||
}
|
||||
|
||||
function onChildChange(event) {
|
||||
selectedChildId = event.target.value === "all" ? null : parseInt(event.target.value);
|
||||
selectedChildId =
|
||||
event.target.value === "all" ? null : parseInt(event.target.value);
|
||||
displayFeedings(allFeedings);
|
||||
}
|
||||
|
||||
@@ -482,31 +493,34 @@
|
||||
const durationChartData = prepareDurationChartData(feedings);
|
||||
|
||||
// Build child dropdown options
|
||||
const childOptions = allChildren.map(child =>
|
||||
`<option value="${child.id}" ${selectedChildId === child.id ? 'selected' : ''}>${child.name}</option>`
|
||||
).join('');
|
||||
const childOptions = allChildren
|
||||
.map(
|
||||
(child) =>
|
||||
`<option value="${child.id}" ${selectedChildId === child.id ? "selected" : ""}>${child.name}</option>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
content.innerHTML = `
|
||||
<div class="controls">
|
||||
<label for="childFilter">Child:</label>
|
||||
<select id="childFilter" onchange="onChildChange(event)">
|
||||
<option value="all" ${selectedChildId === null ? 'selected' : ''}>All Children</option>
|
||||
<option value="all" ${selectedChildId === null ? "selected" : ""}>All Children</option>
|
||||
${childOptions}
|
||||
</select>
|
||||
|
||||
<label for="daysRange">Time Range:</label>
|
||||
<select id="daysRange" onchange="onDaysRangeChange(event)">
|
||||
<option value="1" ${currentDaysRange === 1 ? 'selected' : ''}>Last 24 Hours</option>
|
||||
<option value="3" ${currentDaysRange === 3 ? 'selected' : ''}>Last 3 Days</option>
|
||||
<option value="7" ${currentDaysRange === 7 ? 'selected' : ''}>Last 7 Days</option>
|
||||
<option value="14" ${currentDaysRange === 14 ? 'selected' : ''}>Last 14 Days</option>
|
||||
<option value="30" ${currentDaysRange === 30 ? 'selected' : ''}>Last 30 Days</option>
|
||||
<option value="90" ${currentDaysRange === 90 ? 'selected' : ''}>Last 90 Days</option>
|
||||
<option value="1" ${currentDaysRange === 1 ? "selected" : ""}>Last 24 Hours</option>
|
||||
<option value="3" ${currentDaysRange === 3 ? "selected" : ""}>Last 3 Days</option>
|
||||
<option value="7" ${currentDaysRange === 7 ? "selected" : ""}>Last 7 Days</option>
|
||||
<option value="14" ${currentDaysRange === 14 ? "selected" : ""}>Last 14 Days</option>
|
||||
<option value="30" ${currentDaysRange === 30 ? "selected" : ""}>Last 30 Days</option>
|
||||
<option value="90" ${currentDaysRange === 90 ? "selected" : ""}>Last 90 Days</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="chart-container">
|
||||
<h2>Feedings Per Day (Last ${currentDaysRange} Day${currentDaysRange !== 1 ? 's' : ''})</h2>
|
||||
<h2>Feedings Per Day (Last ${currentDaysRange} Day${currentDaysRange !== 1 ? "s" : ""})</h2>
|
||||
<div class="chart-wrapper">
|
||||
<canvas id="feedingsChart"></canvas>
|
||||
</div>
|
||||
@@ -533,7 +547,7 @@
|
||||
renderBarChart(barChartData);
|
||||
renderPieChart(pieChartData);
|
||||
renderDurationChart(durationChartData);
|
||||
|
||||
|
||||
// Render feeding list
|
||||
renderFeedingList(feedings);
|
||||
}
|
||||
@@ -553,7 +567,9 @@
|
||||
|
||||
// Filter by selected child if applicable
|
||||
if (selectedChildId !== null) {
|
||||
filteredFeedings = filteredFeedings.filter((f) => f.child_id === selectedChildId);
|
||||
filteredFeedings = filteredFeedings.filter(
|
||||
(f) => f.child_id === selectedChildId,
|
||||
);
|
||||
}
|
||||
|
||||
// Sort by most recent first
|
||||
@@ -561,45 +577,49 @@
|
||||
return new Date(b.start_time) - new Date(a.start_time);
|
||||
});
|
||||
|
||||
const listHtml = filteredFeedings.map((feeding) => {
|
||||
const startTime = new Date(feeding.start_time);
|
||||
const endTime = feeding.end_time ? new Date(feeding.end_time) : null;
|
||||
|
||||
const dateStr = startTime.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const timeStr = startTime.toLocaleTimeString("en-US", {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
const listHtml = filteredFeedings
|
||||
.map((feeding) => {
|
||||
const startTime = new Date(feeding.start_time);
|
||||
const endTime = feeding.end_time
|
||||
? new Date(feeding.end_time)
|
||||
: null;
|
||||
|
||||
const duration = endTime
|
||||
? Math.round((endTime - startTime) / 60000)
|
||||
: null;
|
||||
const dateStr = startTime.toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
});
|
||||
|
||||
const typeClass = feeding.feeding_type.replace("_", "-");
|
||||
const typeLabel = formatFeedingType(feeding.feeding_type);
|
||||
const timeStr = startTime.toLocaleTimeString("en-US", {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
|
||||
// Get child name
|
||||
const child = allChildren.find(c => c.id === feeding.child_id);
|
||||
const childName = child ? child.name : "Unknown";
|
||||
const duration = endTime
|
||||
? Math.round((endTime - startTime) / 60000)
|
||||
: null;
|
||||
|
||||
return `
|
||||
const typeClass = feeding.feeding_type.replace("_", "-");
|
||||
const typeLabel = formatFeedingType(feeding.feeding_type);
|
||||
|
||||
// Get child name
|
||||
const child = allChildren.find((c) => c.id === feeding.child_id);
|
||||
const childName = child ? child.name : "Unknown";
|
||||
|
||||
return `
|
||||
<div class="feeding-item">
|
||||
<div class="feeding-info-left">
|
||||
<div class="feeding-time">${dateStr} at ${timeStr}${selectedChildId === null ? ` - ${childName}` : ''}</div>
|
||||
<div class="feeding-time">${dateStr} at ${timeStr}${selectedChildId === null ? ` - ${childName}` : ""}</div>
|
||||
<div class="feeding-details">
|
||||
<span class="feeding-type-badge ${typeClass}">${typeLabel}</span>
|
||||
${duration !== null ? `${duration} minutes` : 'Ongoing'}
|
||||
${duration !== null ? `${duration} minutes` : "Ongoing"}
|
||||
</div>
|
||||
</div>
|
||||
<button class="edit-button" onclick="editFeeding(${feeding.id})">Edit</button>
|
||||
</div>
|
||||
`;
|
||||
}).join("");
|
||||
})
|
||||
.join("");
|
||||
|
||||
const listContainer = `
|
||||
<div class="feedings-list">
|
||||
@@ -614,7 +634,7 @@
|
||||
`;
|
||||
|
||||
const content = document.getElementById("content");
|
||||
content.insertAdjacentHTML('beforeend', listContainer);
|
||||
content.insertAdjacentHTML("beforeend", listContainer);
|
||||
}
|
||||
|
||||
function formatFeedingType(type) {
|
||||
@@ -650,7 +670,9 @@
|
||||
|
||||
// Filter by selected child if applicable
|
||||
if (selectedChildId !== null) {
|
||||
recentFeedings = recentFeedings.filter((f) => f.child_id === selectedChildId);
|
||||
recentFeedings = recentFeedings.filter(
|
||||
(f) => f.child_id === selectedChildId,
|
||||
);
|
||||
}
|
||||
|
||||
const typeCounts = {
|
||||
@@ -698,7 +720,9 @@
|
||||
|
||||
// Filter by selected child if applicable
|
||||
if (selectedChildId !== null) {
|
||||
completedFeedings = completedFeedings.filter((f) => f.child_id === selectedChildId);
|
||||
completedFeedings = completedFeedings.filter(
|
||||
(f) => f.child_id === selectedChildId,
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate durations in minutes
|
||||
@@ -711,14 +735,14 @@
|
||||
// Find max duration to determine how many bins we need
|
||||
const maxDuration = Math.max(...durations, 0);
|
||||
const maxBin = Math.ceil(maxDuration / 5) * 5; // Round up to nearest 5
|
||||
|
||||
|
||||
// Create 5-minute duration buckets dynamically
|
||||
const buckets = {};
|
||||
for (let i = 0; i < maxBin; i += 5) {
|
||||
const label = `${i}-${i + 5}`;
|
||||
buckets[label] = 0;
|
||||
}
|
||||
|
||||
|
||||
// Add a final bucket for anything over the max
|
||||
if (maxBin > 0) {
|
||||
buckets[`${maxBin}+`] = 0;
|
||||
@@ -728,7 +752,7 @@
|
||||
durations.forEach((duration) => {
|
||||
const binIndex = Math.floor(duration / 5) * 5;
|
||||
const label = `${binIndex}-${binIndex + 5}`;
|
||||
|
||||
|
||||
if (buckets[label] !== undefined) {
|
||||
buckets[label]++;
|
||||
} else {
|
||||
@@ -750,7 +774,9 @@
|
||||
// Filter by selected child if applicable
|
||||
let filteredFeedings = feedings;
|
||||
if (selectedChildId !== null) {
|
||||
filteredFeedings = feedings.filter((f) => f.child_id === selectedChildId);
|
||||
filteredFeedings = feedings.filter(
|
||||
(f) => f.child_id === selectedChildId,
|
||||
);
|
||||
}
|
||||
|
||||
// Create days based on currentDaysRange (including today)
|
||||
@@ -782,7 +808,7 @@
|
||||
|
||||
function renderBarChart(chartData) {
|
||||
const ctx = document.getElementById("feedingsChart").getContext("2d");
|
||||
|
||||
|
||||
new Chart(ctx, {
|
||||
type: "bar",
|
||||
data: {
|
||||
@@ -860,7 +886,7 @@
|
||||
|
||||
function renderPieChart(chartData) {
|
||||
const ctx = document.getElementById("pieChart").getContext("2d");
|
||||
|
||||
|
||||
// Color mapping for each type
|
||||
const colorMap = {
|
||||
"Left Breast": {
|
||||
@@ -871,7 +897,7 @@
|
||||
background: "rgba(118, 75, 162, 0.8)",
|
||||
border: "rgba(118, 75, 162, 1)",
|
||||
},
|
||||
"Bottle": {
|
||||
Bottle: {
|
||||
background: "rgba(255, 159, 64, 0.8)",
|
||||
border: "rgba(255, 159, 64, 1)",
|
||||
},
|
||||
@@ -879,12 +905,12 @@
|
||||
|
||||
// Generate colors based on labels present
|
||||
const backgroundColors = chartData.labels.map(
|
||||
(label) => colorMap[label]?.background || "rgba(200, 200, 200, 0.8)"
|
||||
(label) => colorMap[label]?.background || "rgba(200, 200, 200, 0.8)",
|
||||
);
|
||||
const borderColors = chartData.labels.map(
|
||||
(label) => colorMap[label]?.border || "rgba(200, 200, 200, 1)"
|
||||
(label) => colorMap[label]?.border || "rgba(200, 200, 200, 1)",
|
||||
);
|
||||
|
||||
|
||||
new Chart(ctx, {
|
||||
type: "pie",
|
||||
data: {
|
||||
@@ -923,8 +949,12 @@
|
||||
callbacks: {
|
||||
label: function (context) {
|
||||
const count = context.parsed;
|
||||
const total = context.dataset.data.reduce((a, b) => a + b, 0);
|
||||
const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
|
||||
const total = context.dataset.data.reduce(
|
||||
(a, b) => a + b,
|
||||
0,
|
||||
);
|
||||
const percentage =
|
||||
total > 0 ? ((count / total) * 100).toFixed(1) : 0;
|
||||
return `${context.label}: ${count} (${percentage}%)`;
|
||||
},
|
||||
},
|
||||
@@ -936,7 +966,7 @@
|
||||
|
||||
function renderDurationChart(chartData) {
|
||||
const ctx = document.getElementById("durationChart").getContext("2d");
|
||||
|
||||
|
||||
new Chart(ctx, {
|
||||
type: "bar",
|
||||
data: {
|
||||
|
||||
@@ -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>
|
||||
@@ -217,6 +244,8 @@
|
||||
<div class="menu-overlay" id="menuOverlay">
|
||||
<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>
|
||||
|
||||
@@ -260,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");
|
||||
@@ -290,6 +344,14 @@
|
||||
window.location.href = "/feedings.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuDiapers").addEventListener("click", () => {
|
||||
window.location.href = "/diapers.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuSleep").addEventListener("click", () => {
|
||||
window.location.href = "/sleep.html";
|
||||
});
|
||||
|
||||
document.getElementById("menuLogout").addEventListener("click", () => {
|
||||
closeMenu();
|
||||
logout();
|
||||
@@ -344,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;
|
||||
@@ -374,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() {
|
||||
@@ -401,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) {
|
||||
@@ -408,6 +518,13 @@
|
||||
}
|
||||
}
|
||||
|
||||
function updateSleepTimeDisplay() {
|
||||
const timeElement = document.getElementById("sleepTimeInfo");
|
||||
if (timeElement && activeSleep) {
|
||||
timeElement.textContent = formatTime(activeSleep.start_time);
|
||||
}
|
||||
}
|
||||
|
||||
function renderContent() {
|
||||
const feedingButtonHtml = activeFeeding
|
||||
? `
|
||||
@@ -425,13 +542,32 @@
|
||||
</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}
|
||||
<p>Your session is active.</p>
|
||||
${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>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -583,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,467 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Log Diaper Change - 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, #667eea 0%, #764ba2 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: #667eea;
|
||||
}
|
||||
|
||||
.button {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 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(102, 126, 234, 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;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
color: #666;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.5px;
|
||||
margin: 25px 0 15px 0;
|
||||
padding-top: 15px;
|
||||
border-top: 1px solid #eee;
|
||||
}
|
||||
|
||||
.section-title:first-of-type {
|
||||
border-top: none;
|
||||
margin-top: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<h1 id="pageTitle">🧷 Log Diaper Change</h1>
|
||||
<p class="subtitle">Record a diaper change</p>
|
||||
|
||||
<div id="message" class="message"></div>
|
||||
|
||||
<form id="diaperForm">
|
||||
<div class="form-group">
|
||||
<label for="childSelect">Child *</label>
|
||||
<select id="childSelect" required>
|
||||
<option value="">Select a child</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="changeTime">Change Time *</label>
|
||||
<input type="datetime-local" id="changeTime" required />
|
||||
</div>
|
||||
|
||||
<div class="section-title">💩 Poop Information (Optional)</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="poopAmount">Poop Amount</label>
|
||||
<select id="poopAmount">
|
||||
<option value="">None</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="heavy">Heavy</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="poopColor">Poop Color</label>
|
||||
<select id="poopColor">
|
||||
<option value="">None</option>
|
||||
<option value="black">Black</option>
|
||||
<option value="yellow">Yellow</option>
|
||||
<option value="green">Green</option>
|
||||
<option value="brown">Brown</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="section-title">💧 Pee Information (Optional)</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="peeAmount">Pee Amount</label>
|
||||
<select id="peeAmount">
|
||||
<option value="">None</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="heavy">Heavy</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label for="peeColor">Pee Color</label>
|
||||
<select id="peeColor">
|
||||
<option value="">None</option>
|
||||
<option value="clear">Clear</option>
|
||||
<option value="yellow">Yellow</option>
|
||||
<option value="red">Red</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="button" id="submitBtn">
|
||||
Log Diaper Change
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="button secondary"
|
||||
onclick="window.location.href='/'"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Check if user is authenticated
|
||||
const token = localStorage.getItem("access_token");
|
||||
if (!token) {
|
||||
window.location.href = "/login.html";
|
||||
}
|
||||
|
||||
// Check if we're in edit mode
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const diaperChangeId = urlParams.get("id");
|
||||
const isEditMode = !!diaperChangeId;
|
||||
|
||||
// Update UI for edit mode
|
||||
if (isEditMode) {
|
||||
document.getElementById("pageTitle").textContent =
|
||||
"🧷 Edit Diaper Change";
|
||||
document.getElementById("submitBtn").textContent =
|
||||
"Update Diaper Change";
|
||||
}
|
||||
|
||||
let children = [];
|
||||
|
||||
// Load children when page loads
|
||||
async function loadChildren() {
|
||||
try {
|
||||
const response = await fetch("/api/children", {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
children = await response.json();
|
||||
const select = document.getElementById("childSelect");
|
||||
|
||||
children.forEach((child) => {
|
||||
const option = document.createElement("option");
|
||||
option.value = child.id;
|
||||
option.textContent = child.name;
|
||||
select.appendChild(option);
|
||||
});
|
||||
|
||||
// If editing, load the diaper change data
|
||||
if (isEditMode) {
|
||||
await loadDiaperChangeData();
|
||||
} else {
|
||||
// Set default time to now for new entries
|
||||
const now = new Date();
|
||||
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
|
||||
document.getElementById("changeTime").value = now
|
||||
.toISOString()
|
||||
.slice(0, 16);
|
||||
|
||||
// Load last used child from localStorage
|
||||
const lastDiaperChange = JSON.parse(
|
||||
localStorage.getItem("lastDiaperChange") || "{}",
|
||||
);
|
||||
|
||||
if (lastDiaperChange.child_id) {
|
||||
document.getElementById("childSelect").value =
|
||||
lastDiaperChange.child_id;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
showMessage("Failed to load children", "error");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
showMessage("Network error. Please try again.", "error");
|
||||
}
|
||||
}
|
||||
|
||||
// Load diaper change data for editing
|
||||
async function loadDiaperChangeData() {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`/api/diaper-changes/${diaperChangeId}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
const diaperChange = await response.json();
|
||||
|
||||
// Populate form fields
|
||||
document.getElementById("childSelect").value =
|
||||
diaperChange.child_id;
|
||||
|
||||
// Convert UTC time to local datetime-local format
|
||||
const changeTime = new Date(diaperChange.change_time);
|
||||
changeTime.setMinutes(
|
||||
changeTime.getMinutes() - changeTime.getTimezoneOffset(),
|
||||
);
|
||||
document.getElementById("changeTime").value = changeTime
|
||||
.toISOString()
|
||||
.slice(0, 16);
|
||||
|
||||
document.getElementById("poopAmount").value =
|
||||
diaperChange.poop_amount || "";
|
||||
document.getElementById("poopColor").value =
|
||||
diaperChange.poop_color || "";
|
||||
document.getElementById("peeAmount").value =
|
||||
diaperChange.pee_amount || "";
|
||||
document.getElementById("peeColor").value =
|
||||
diaperChange.pee_color || "";
|
||||
} else {
|
||||
showMessage("Failed to load diaper change data", "error");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
showMessage("Network error. Please try again.", "error");
|
||||
}
|
||||
}
|
||||
|
||||
// Handle form submission
|
||||
document
|
||||
.getElementById("diaperForm")
|
||||
.addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const childId = parseInt(
|
||||
document.getElementById("childSelect").value,
|
||||
);
|
||||
const changeTime = new Date(
|
||||
document.getElementById("changeTime").value,
|
||||
).toISOString();
|
||||
const poopAmount =
|
||||
document.getElementById("poopAmount").value || null;
|
||||
const poopColor = document.getElementById("poopColor").value || null;
|
||||
const peeAmount = document.getElementById("peeAmount").value || null;
|
||||
const peeColor = document.getElementById("peeColor").value || null;
|
||||
|
||||
const submitBtn = document.getElementById("submitBtn");
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = isEditMode ? "Updating..." : "Logging...";
|
||||
|
||||
try {
|
||||
const url = isEditMode
|
||||
? `/api/diaper-changes/${diaperChangeId}`
|
||||
: "/api/diaper-changes";
|
||||
const method = isEditMode ? "PUT" : "POST";
|
||||
|
||||
const body = isEditMode
|
||||
? {
|
||||
change_time: changeTime,
|
||||
poop_amount: poopAmount,
|
||||
poop_color: poopColor,
|
||||
pee_amount: peeAmount,
|
||||
pee_color: peeColor,
|
||||
}
|
||||
: {
|
||||
child_id: childId,
|
||||
change_time: changeTime,
|
||||
poop_amount: poopAmount,
|
||||
poop_color: poopColor,
|
||||
pee_amount: peeAmount,
|
||||
pee_color: peeColor,
|
||||
};
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: method,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
// Save last used child for next time (only for new entries, not edits)
|
||||
if (!isEditMode) {
|
||||
localStorage.setItem(
|
||||
"lastDiaperChange",
|
||||
JSON.stringify({
|
||||
child_id: childId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
showMessage(
|
||||
isEditMode
|
||||
? "Diaper change updated successfully!"
|
||||
: "Diaper change logged successfully!",
|
||||
"success",
|
||||
);
|
||||
setTimeout(() => {
|
||||
window.location.href = "/";
|
||||
}, 1000);
|
||||
} else {
|
||||
const errorData = await response.json();
|
||||
showMessage(
|
||||
errorData.detail || "Failed to log diaper change",
|
||||
"error",
|
||||
);
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = isEditMode
|
||||
? "Update Diaper Change"
|
||||
: "Log Diaper Change";
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
showMessage("Network error. Please try again.", "error");
|
||||
submitBtn.disabled = false;
|
||||
submitBtn.textContent = isEditMode
|
||||
? "Update Diaper Change"
|
||||
: "Log Diaper Change";
|
||||
}
|
||||
});
|
||||
|
||||
function showMessage(text, type) {
|
||||
const messageDiv = document.getElementById("message");
|
||||
messageDiv.textContent = text;
|
||||
messageDiv.className = `message ${type} show`;
|
||||
}
|
||||
|
||||
// Initialize
|
||||
loadChildren();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -231,7 +231,8 @@
|
||||
// Update title and button text if editing
|
||||
if (isEditMode) {
|
||||
document.querySelector("h1").textContent = "🍼 Edit Feeding";
|
||||
document.querySelector(".subtitle").textContent = "Update feeding session details";
|
||||
document.querySelector(".subtitle").textContent =
|
||||
"Update feeding session details";
|
||||
submitBtn.textContent = "Update Feeding";
|
||||
}
|
||||
|
||||
@@ -292,25 +293,29 @@
|
||||
|
||||
if (response.ok) {
|
||||
const feeding = await response.json();
|
||||
|
||||
|
||||
// Populate form with existing data
|
||||
document.getElementById("childId").value = feeding.child_id;
|
||||
|
||||
|
||||
// Format datetime for datetime-local input
|
||||
const startTime = new Date(feeding.start_time);
|
||||
const startLocalDateTime = new Date(
|
||||
startTime.getTime() - startTime.getTimezoneOffset() * 60000
|
||||
).toISOString().slice(0, 16);
|
||||
startTime.getTime() - startTime.getTimezoneOffset() * 60000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 16);
|
||||
document.getElementById("startTime").value = startLocalDateTime;
|
||||
|
||||
|
||||
if (feeding.end_time) {
|
||||
const endTime = new Date(feeding.end_time);
|
||||
const endLocalDateTime = new Date(
|
||||
endTime.getTime() - endTime.getTimezoneOffset() * 60000
|
||||
).toISOString().slice(0, 16);
|
||||
endTime.getTime() - endTime.getTimezoneOffset() * 60000,
|
||||
)
|
||||
.toISOString()
|
||||
.slice(0, 16);
|
||||
document.getElementById("endTime").value = endLocalDateTime;
|
||||
}
|
||||
|
||||
|
||||
document.getElementById("feedingType").value = feeding.feeding_type;
|
||||
} else {
|
||||
showMessage("Failed to load feeding data", "error");
|
||||
@@ -336,9 +341,11 @@
|
||||
messageDiv.classList.remove("show");
|
||||
|
||||
try {
|
||||
const url = isEditMode ? `/api/feedings/${feedingId}` : "/api/feedings";
|
||||
const url = isEditMode
|
||||
? `/api/feedings/${feedingId}`
|
||||
: "/api/feedings";
|
||||
const method = isEditMode ? "PUT" : "POST";
|
||||
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: method,
|
||||
headers: {
|
||||
@@ -357,8 +364,10 @@
|
||||
|
||||
if (response.ok) {
|
||||
showMessage(
|
||||
isEditMode ? "Feeding updated successfully!" : "Feeding logged successfully!",
|
||||
"success"
|
||||
isEditMode
|
||||
? "Feeding updated successfully!"
|
||||
: "Feeding logged successfully!",
|
||||
"success",
|
||||
);
|
||||
// Redirect to feedings page after 1 second
|
||||
setTimeout(() => {
|
||||
@@ -366,7 +375,8 @@
|
||||
}, 1000);
|
||||
} else {
|
||||
showMessage(
|
||||
data.detail || `Failed to ${isEditMode ? 'update' : 'log'} feeding. Please try again.`,
|
||||
data.detail ||
|
||||
`Failed to ${isEditMode ? "update" : "log"} feeding. Please try again.`,
|
||||
"error",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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