Merge pull request 'support-add-diaper-entry' (#13) from support-add-diaper-entry into main
Reviewed-on: #13
This commit was merged in pull request #13.
This commit is contained in:
@@ -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,7 @@ 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.health import router as health_router
|
||||
from baby_monitor.repositories.dependencies.get_database import init_db
|
||||
|
||||
@@ -51,6 +52,7 @@ 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(health_router)
|
||||
|
||||
|
||||
@@ -97,6 +99,12 @@ def serve_feedings() -> FileResponse:
|
||||
return FileResponse(static_path / "feedings.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("/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,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"
|
||||
|
||||
@@ -79,6 +79,7 @@ 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.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,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,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"
|
||||
)
|
||||
@@ -431,7 +431,9 @@
|
||||
<p><strong>Logged in as:</strong> ${username}</p>
|
||||
</div>
|
||||
${feedingButtonHtml}
|
||||
<p>Your session is active.</p>
|
||||
<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>
|
||||
`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
<!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>
|
||||
Reference in New Issue
Block a user