code quality fixes
Build and Push Docker Image / build-and-push (pull_request) Successful in 58s
Python Code Quality / python-code-quality (pull_request) Successful in 10s
Python Test / python-test (pull_request) Successful in 18s

This commit is contained in:
Brian Bjarke Jensen
2025-11-11 20:43:47 +01:00
parent 696de14e6b
commit a2b78f7e96
17 changed files with 236 additions and 249 deletions
+8 -8
View File
@@ -81,14 +81,14 @@ uv run uvicorn src.baby_monitor.main:app --reload --host 0.0.0.0 --port 8000
### Environment Variables
| Variable | Default | Description |
| ---------------- | ------------ | --------------------------------------------- |
| `ENVIRONMENT` | `production` | Set to `development` to enable API docs |
| `ADMIN_PASSWORD` | _(required)_ | Admin user password |
| `ADMIN_USERNAME` | `admin` | Admin username |
| `DATA_DIR` | `/data` | Directory for SQLite database (SQLite only) |
| `REDIS_URI` | _(optional)_ | Redis connection URI for distributed tokens |
| `POSTGRES_URI` | _(optional)_ | PostgreSQL connection URI for database storage|
| Variable | Default | Description |
| ---------------- | ------------ | ---------------------------------------------- |
| `ENVIRONMENT` | `production` | Set to `development` to enable API docs |
| `ADMIN_PASSWORD` | _(required)_ | Admin user password |
| `ADMIN_USERNAME` | `admin` | Admin username |
| `DATA_DIR` | `/data` | Directory for SQLite database (SQLite only) |
| `REDIS_URI` | _(optional)_ | Redis connection URI for distributed tokens |
| `POSTGRES_URI` | _(optional)_ | PostgreSQL connection URI for database storage |
### Storage Options
@@ -15,7 +15,7 @@ from baby_monitor.models.db.child_parent import ChildParent
class DatabaseChildRepository(ChildRepositoryInterface):
"""Database implementation for child data access.
Works with both SQLite and PostgreSQL databases.
"""
@@ -15,7 +15,7 @@ from baby_monitor.repositories.interfaces import (
class DatabaseChildInvitationRepository(ChildInvitationRepositoryInterface):
"""Database implementation of child invitation repository.
Works with both SQLite and PostgreSQL databases.
"""
@@ -26,10 +26,10 @@ class DatabaseChildInvitationRepository(ChildInvitationRepositoryInterface):
def _get_now_utc(self, reference_dt: datetime) -> datetime:
"""
Get current UTC time matching the timezone awareness of reference.
Args:
reference_dt: A datetime from DB to match timezone format
Returns:
Current UTC time (naive for SQLite, aware for PostgreSQL)
"""
@@ -84,9 +84,7 @@ class DatabaseChildInvitationRepository(ChildInvitationRepositoryInterface):
def verify_invitation(self, code: str) -> bool:
"""Verify if an invitation code is valid and not expired."""
invitation = (
self.db.query(ChildInvitation)
.filter(ChildInvitation.code == code)
.first()
self.db.query(ChildInvitation).filter(ChildInvitation.code == code).first()
)
if not invitation:
@@ -16,7 +16,7 @@ from baby_monitor.models.db.child_parent import ChildParent
class DatabaseDiaperChangeRepository(DiaperChangeRepositoryInterface):
"""Database implementation for diaper change log data access.
Works with both SQLite and PostgreSQL databases.
"""
@@ -16,7 +16,7 @@ from baby_monitor.models.db.child_parent import ChildParent
class DatabaseFeedingRepository(FeedingRepositoryInterface):
"""Database implementation for feeding log data access.
Works with both SQLite and PostgreSQL databases.
"""
@@ -19,7 +19,7 @@ from baby_monitor.repositories.interfaces import (
class DatabaseInvitationRepository(InvitationRepositoryInterface):
"""Database implementation for managing invitation tokens.
Works with both SQLite and PostgreSQL databases.
"""
@@ -30,10 +30,10 @@ class DatabaseInvitationRepository(InvitationRepositoryInterface):
def _get_now_utc(self, reference_dt: datetime) -> datetime:
"""
Get current UTC time matching the timezone awareness of reference.
Args:
reference_dt: A datetime from DB to match timezone format
Returns:
Current UTC time (naive for SQLite, aware for PostgreSQL)
"""
@@ -82,9 +82,7 @@ class DatabaseInvitationRepository(InvitationRepositoryInterface):
Returns:
True if valid and not consumed, False otherwise
"""
invitation = self.db.query(Invitation).filter(
Invitation.token == token
).first()
invitation = self.db.query(Invitation).filter(Invitation.token == token).first()
if not invitation:
return False
@@ -110,9 +108,7 @@ class DatabaseInvitationRepository(InvitationRepositoryInterface):
Returns:
True if successfully consumed, False if invalid or already used
"""
invitation = self.db.query(Invitation).filter(
Invitation.token == token
).first()
invitation = self.db.query(Invitation).filter(Invitation.token == token).first()
if not invitation:
return False
@@ -143,8 +139,6 @@ class DatabaseInvitationRepository(InvitationRepositoryInterface):
else:
# No invitations, use naive UTC (safe default)
now_utc = datetime.now(UTC).replace(tzinfo=None)
self.db.query(Invitation).filter(
Invitation.expires_at < now_utc
).delete()
self.db.query(Invitation).filter(Invitation.expires_at < now_utc).delete()
self.db.commit()
@@ -16,7 +16,7 @@ from baby_monitor.models.db.child_parent import ChildParent
class DatabaseSleepRepository(SleepRepositoryInterface):
"""Database implementation for sleep log data access.
Works with both SQLite and PostgreSQL databases.
"""
@@ -11,7 +11,7 @@ from baby_monitor.models.db.user import User
class DatabaseUserRepository(UserRepositoryInterface):
"""Database-based user repository.
Works with both SQLite and PostgreSQL databases.
"""
+7 -19
View File
@@ -10,7 +10,7 @@ from baby_monitor.models.child import CreateChildRequest, ChildResponse
from baby_monitor.routers.auth import verify_token
from baby_monitor.repositories.interfaces import (
ChildRepositoryInterface,
ChildInvitationRepositoryInterface
ChildInvitationRepositoryInterface,
)
from baby_monitor.repositories.dependencies import (
get_child_repository,
@@ -45,9 +45,7 @@ class RedeemChildInvitationRequest(BaseModel):
def create_child(
request: CreateChildRequest,
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> ChildResponse:
"""Create a new child for the authenticated user."""
child = child_repo.create(
@@ -63,9 +61,7 @@ def create_child(
@router.get("", response_model=list[ChildResponse])
def get_user_children(
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> list[ChildResponse]:
"""Get all children for the authenticated user."""
children = child_repo.get_by_user_id(user_id)
@@ -76,9 +72,7 @@ def get_user_children(
def get_child(
child_id: int,
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> ChildResponse:
"""Get a specific child by ID."""
child = child_repo.get_by_id(child_id)
@@ -99,9 +93,7 @@ def update_child(
child_id: int,
request: CreateChildRequest,
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> ChildResponse:
"""Update a child's information."""
# First check if child exists and belongs to user
@@ -132,9 +124,7 @@ def update_child(
def create_child_invitation(
request: CreateChildInvitationRequest,
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
invitation_repo: Annotated[
ChildInvitationRepositoryInterface,
Depends(get_child_invitation_repository),
@@ -176,9 +166,7 @@ def create_child_invitation(
def redeem_child_invitation(
request: RedeemChildInvitationRequest,
user_id: Annotated[int, Depends(verify_token)],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
invitation_repo: Annotated[
ChildInvitationRepositoryInterface,
Depends(get_child_invitation_repository),
+4 -12
View File
@@ -29,9 +29,7 @@ def create_diaper_change(
diaper_repo: Annotated[
DiaperChangeRepositoryInterface, Depends(get_diaper_change_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> DiaperChangeResponse:
"""Create a new diaper change log entry."""
# Verify the child belongs to the authenticated user
@@ -68,9 +66,7 @@ def get_diaper_change(
diaper_repo: Annotated[
DiaperChangeRepositoryInterface, Depends(get_diaper_change_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> DiaperChangeResponse:
"""Get a specific diaper change log by ID."""
diaper_change = diaper_repo.get_by_id(diaper_change_id)
@@ -92,9 +88,7 @@ def update_diaper_change(
diaper_repo: Annotated[
DiaperChangeRepositoryInterface, Depends(get_diaper_change_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> DiaperChangeResponse:
"""Update an existing diaper change log."""
diaper_change = diaper_repo.get_by_id(diaper_change_id)
@@ -129,9 +123,7 @@ def delete_diaper_change(
diaper_repo: Annotated[
DiaperChangeRepositoryInterface, Depends(get_diaper_change_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> None:
"""Delete a diaper change log."""
diaper_change = diaper_repo.get_by_id(diaper_change_id)
+6 -18
View File
@@ -29,9 +29,7 @@ def create_feeding(
feeding_repo: Annotated[
FeedingRepositoryInterface, Depends(get_feeding_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> FeedingResponse:
"""Create a new feeding log entry."""
# Verify the child belongs to the authenticated user
@@ -53,9 +51,7 @@ def get_active_feeding(
feeding_repo: Annotated[
FeedingRepositoryInterface, Depends(get_feeding_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> FeedingResponse | None:
"""Get the current active feeding (where end_time is null) for the user."""
feedings = feeding_repo.get_by_user_id(user_id)
@@ -92,9 +88,7 @@ def get_feeding(
feeding_repo: Annotated[
FeedingRepositoryInterface, Depends(get_feeding_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> FeedingResponse:
"""Get a specific feeding log by ID."""
feeding = feeding_repo.get_by_id(feeding_id)
@@ -116,9 +110,7 @@ def update_feeding(
feeding_repo: Annotated[
FeedingRepositoryInterface, Depends(get_feeding_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> FeedingResponse:
"""Update a feeding log entry."""
feeding = feeding_repo.get_by_id(feeding_id)
@@ -130,9 +122,7 @@ def update_feeding(
verify_child_access(child_repo, feeding["child_id"], user_id)
# Update the feeding
feeding_type_value = (
request.feeding_type.value if request.feeding_type else None
)
feeding_type_value = request.feeding_type.value if request.feeding_type else None
updated_feeding = feeding_repo.update(
feeding_id=feeding_id,
start_time=request.start_time,
@@ -153,9 +143,7 @@ def delete_feeding(
feeding_repo: Annotated[
FeedingRepositoryInterface, Depends(get_feeding_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> None:
"""Delete a feeding log entry."""
feeding = feeding_repo.get_by_id(feeding_id)
+11 -33
View File
@@ -26,12 +26,8 @@ router = APIRouter(prefix="/api/sleep", tags=["sleep"])
def create_sleep(
request: CreateSleepRequest,
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, Depends(get_sleep_repository)],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> SleepResponse:
"""Create a new sleep log entry."""
# Verify the child belongs to the authenticated user
@@ -48,12 +44,8 @@ def create_sleep(
@router.get("/active", response_model=SleepResponse | None)
def get_active_sleep(
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, Depends(get_sleep_repository)],
child_repo: Annotated[ChildRepositoryInterface, 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)
@@ -74,9 +66,7 @@ def get_active_sleep(
@router.get("", response_model=list[SleepResponse])
def get_user_sleeps(
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, 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)
@@ -87,12 +77,8 @@ def get_user_sleeps(
def get_sleep(
sleep_id: int,
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, Depends(get_sleep_repository)],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> SleepResponse:
"""Get a specific sleep log by ID."""
sleep = sleep_repo.get_by_id(sleep_id)
@@ -111,12 +97,8 @@ def update_sleep(
sleep_id: int,
request: UpdateSleepRequest,
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, Depends(get_sleep_repository)],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> SleepResponse:
"""Update an existing sleep log."""
sleep = sleep_repo.get_by_id(sleep_id)
@@ -142,12 +124,8 @@ def update_sleep(
def delete_sleep(
sleep_id: int,
user_id: Annotated[int, Depends(verify_token)],
sleep_repo: Annotated[
SleepRepositoryInterface, Depends(get_sleep_repository)
],
child_repo: Annotated[
ChildRepositoryInterface, Depends(get_child_repository)
],
sleep_repo: Annotated[SleepRepositoryInterface, Depends(get_sleep_repository)],
child_repo: Annotated[ChildRepositoryInterface, Depends(get_child_repository)],
) -> None:
"""Delete a sleep log."""
sleep = sleep_repo.get_by_id(sleep_id)
+12 -4
View File
@@ -192,12 +192,20 @@
Cancel
</button>
</form>
<div id="skipOption" style="text-align: center; margin-top: 20px; display: none;">
<p style="color: #666; font-size: 14px; margin-bottom: 10px;">
<div
id="skipOption"
style="text-align: center; margin-top: 20px; display: none"
>
<p style="color: #666; font-size: 14px; margin-bottom: 10px">
Want to accept a child share invitation first?
</p>
<button type="button" class="button secondary" onclick="skipToHome()" style="margin: 0;">
<button
type="button"
class="button secondary"
onclick="skipToHome()"
style="margin: 0"
>
Skip for now
</button>
</div>
+6 -5
View File
@@ -267,7 +267,8 @@
let allDiaperChanges = [];
let allChildren = [];
let currentDaysRange = parseInt(localStorage.getItem("lastDiaperTimeRange")) || 7;
let currentDaysRange =
parseInt(localStorage.getItem("lastDiaperTimeRange")) || 7;
let selectedChildId = null; // null means "All Children"
// Restore last selected child from localStorage
@@ -640,8 +641,8 @@
// Create 8 three-hour buckets
for (let i = 7; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 3), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 3, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 3);
@@ -675,8 +676,8 @@
// Show 8-hour aggregates for 3 days (9 buckets total)
for (let i = 8; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 8), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 8, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 8);
+53 -43
View File
@@ -304,7 +304,8 @@
let allFeedings = [];
let allChildren = [];
let currentDaysRange = parseInt(localStorage.getItem("lastFeedingTimeRange")) || 7;
let currentDaysRange =
parseInt(localStorage.getItem("lastFeedingTimeRange")) || 7;
let selectedChildId = null; // null means "All Children"
let barChartInstance = null;
@@ -672,15 +673,15 @@
}
// Only use completed feedings
const completedFeedings = filteredFeedings.filter(f => f.end_time);
const completedFeedings = filteredFeedings.filter((f) => f.end_time);
// If 24 hours selected, show 3-hour aggregates
if (currentDaysRange === 1) {
// Create 8 three-hour buckets
for (let i = 7; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 3), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 3, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 3);
@@ -699,13 +700,13 @@
const feedingDate = new Date(f.start_time);
return feedingDate >= periodStart && feedingDate < periodEnd;
});
const feedingDurations = periodFeedings.map(feeding => {
const feedingDurations = periodFeedings.map((feeding) => {
const start = new Date(feeding.start_time);
const end = new Date(feeding.end_time);
return (end - start) / 60000; // Convert to minutes
});
durations.push(feedingDurations);
feedingCounts.push(periodFeedings.length);
}
@@ -713,8 +714,8 @@
// Show 8-hour aggregates for 3 days (9 buckets total)
for (let i = 8; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 8), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 8, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 8);
@@ -739,13 +740,13 @@
const feedingDate = new Date(f.start_time);
return feedingDate >= periodStart && feedingDate < periodEnd;
});
const feedingDurations = periodFeedings.map(feeding => {
const feedingDurations = periodFeedings.map((feeding) => {
const start = new Date(feeding.start_time);
const end = new Date(feeding.end_time);
return (end - start) / 60000; // Convert to minutes
});
durations.push(feedingDurations);
feedingCounts.push(periodFeedings.length);
}
@@ -770,13 +771,13 @@
const feedingDate = new Date(f.start_time);
return feedingDate >= date && feedingDate < nextDay;
});
const feedingDurations = dayFeedings.map(feeding => {
const feedingDurations = dayFeedings.map((feeding) => {
const start = new Date(feeding.start_time);
const end = new Date(feeding.end_time);
return (end - start) / 60000; // Convert to minutes
});
durations.push(feedingDurations);
feedingCounts.push(dayFeedings.length);
}
@@ -794,7 +795,10 @@
}
// Find the maximum number of feedings in any period
const maxFeedings = Math.max(...chartData.durations.map(d => d.length), 0);
const maxFeedings = Math.max(
...chartData.durations.map((d) => d.length),
0,
);
// If no feedings at all, show empty chart
if (maxFeedings === 0) {
@@ -802,11 +806,13 @@
type: "bar",
data: {
labels: chartData.labels,
datasets: [{
label: "No Data",
data: new Array(chartData.labels.length).fill(0),
backgroundColor: "rgba(102, 126, 234, 0.3)",
}],
datasets: [
{
label: "No Data",
data: new Array(chartData.labels.length).fill(0),
backgroundColor: "rgba(102, 126, 234, 0.3)",
},
],
},
options: {
responsive: true,
@@ -833,30 +839,32 @@
// Create color palette for different feedings
const colors = [
'rgba(102, 126, 234, 0.8)',
'rgba(118, 75, 162, 0.8)',
'rgba(255, 159, 64, 0.8)',
'rgba(76, 175, 80, 0.8)',
'rgba(244, 67, 54, 0.8)',
'rgba(156, 39, 176, 0.8)',
'rgba(102, 126, 234, 0.6)',
'rgba(118, 75, 162, 0.6)',
'rgba(255, 159, 64, 0.6)',
'rgba(76, 175, 80, 0.6)',
"rgba(102, 126, 234, 0.8)",
"rgba(118, 75, 162, 0.8)",
"rgba(255, 159, 64, 0.8)",
"rgba(76, 175, 80, 0.8)",
"rgba(244, 67, 54, 0.8)",
"rgba(156, 39, 176, 0.8)",
"rgba(102, 126, 234, 0.6)",
"rgba(118, 75, 162, 0.6)",
"rgba(255, 159, 64, 0.6)",
"rgba(76, 175, 80, 0.6)",
];
// Create datasets - one for each feeding position
const datasets = [];
for (let feedingIndex = 0; feedingIndex < maxFeedings; feedingIndex++) {
const dataForFeeding = chartData.durations.map(periodDurations =>
periodDurations[feedingIndex] || 0
const dataForFeeding = chartData.durations.map(
(periodDurations) => periodDurations[feedingIndex] || 0,
);
datasets.push({
label: `Feeding ${feedingIndex + 1}`,
data: dataForFeeding,
backgroundColor: colors[feedingIndex % colors.length],
borderColor: colors[feedingIndex % colors.length].replace('0.8', '1').replace('0.6', '1'),
borderColor: colors[feedingIndex % colors.length]
.replace("0.8", "1")
.replace("0.6", "1"),
borderWidth: 1,
});
}
@@ -897,9 +905,9 @@
font: {
size: 12,
},
callback: function(value) {
return Math.round(value) + 'm';
}
callback: function (value) {
return Math.round(value) + "m";
},
},
grid: {
color: "rgba(0, 0, 0, 0.05)",
@@ -920,17 +928,19 @@
size: 13,
},
callbacks: {
label: function(context) {
label: function (context) {
const minutes = Math.round(context.parsed.y);
return `${context.dataset.label}: ${minutes}m`;
},
footer: function(tooltipItems) {
footer: function (tooltipItems) {
const periodIndex = tooltipItems[0].dataIndex;
const totalMinutes = chartData.durations[periodIndex].reduce((sum, val) => sum + val, 0);
const totalMinutes = chartData.durations[
periodIndex
].reduce((sum, val) => sum + val, 0);
const feedingCount = chartData.feedingCounts[periodIndex];
return `Total: ${Math.round(totalMinutes)}m (${feedingCount} feeding${feedingCount !== 1 ? 's' : ''})`;
}
}
return `Total: ${Math.round(totalMinutes)}m (${feedingCount} feeding${feedingCount !== 1 ? "s" : ""})`;
},
},
},
},
},
+112 -83
View File
@@ -547,15 +547,15 @@
const sessionCounts = []; // For reference
// Only use completed sleep sessions
const completedSessions = sleepSessions.filter(s => s.end_time);
const completedSessions = sleepSessions.filter((s) => s.end_time);
// If 24 hours selected, show 3-hour aggregates
if (timeRange === 1) {
// Create 8 three-hour buckets
for (let i = 7; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 3), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 3, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 3);
@@ -574,11 +574,12 @@
const startDate = new Date(session.start_time);
return startDate >= periodStart && startDate < periodEnd;
});
const sessionDurations = periodSessions.map(session =>
calculateDuration(session.start_time, session.end_time) / 60
const sessionDurations = periodSessions.map(
(session) =>
calculateDuration(session.start_time, session.end_time) / 60,
);
durations.push(sessionDurations);
sessionCounts.push(periodSessions.length);
}
@@ -586,8 +587,8 @@
// Show 8-hour aggregates for 3 days (9 buckets total)
for (let i = 8; i >= 0; i--) {
const periodStart = new Date(now);
periodStart.setHours(periodStart.getHours() - (i * 8), 0, 0, 0);
periodStart.setHours(periodStart.getHours() - i * 8, 0, 0, 0);
const periodEnd = new Date(periodStart);
periodEnd.setHours(periodEnd.getHours() + 8);
@@ -612,11 +613,12 @@
const startDate = new Date(session.start_time);
return startDate >= periodStart && startDate < periodEnd;
});
const sessionDurations = periodSessions.map(session =>
calculateDuration(session.start_time, session.end_time) / 60
const sessionDurations = periodSessions.map(
(session) =>
calculateDuration(session.start_time, session.end_time) / 60,
);
durations.push(sessionDurations);
sessionCounts.push(periodSessions.length);
}
@@ -641,29 +643,39 @@
const startDate = new Date(session.start_time);
return startDate >= date && startDate < nextDay;
});
const sessionDurations = daySessions.map(session => {
const dur = calculateDuration(session.start_time, session.end_time) / 60;
console.log(` Session: ${session.start_time} to ${session.end_time}, duration: ${dur} hours (${calculateDuration(session.start_time, session.end_time)} minutes)`);
const sessionDurations = daySessions.map((session) => {
const dur =
calculateDuration(session.start_time, session.end_time) / 60;
console.log(
` Session: ${session.start_time} to ${session.end_time}, duration: ${dur} hours (${calculateDuration(session.start_time, session.end_time)} minutes)`,
);
return dur;
});
console.log(`${dateStr}: ${daySessions.length} sessions, durations:`, sessionDurations);
console.log(
`${dateStr}: ${daySessions.length} sessions, durations:`,
sessionDurations,
);
durations.push(sessionDurations);
sessionCounts.push(daySessions.length);
}
}
console.log('Final prepareBarChartData result:', { labels, durations, sessionCounts });
console.log("Final prepareBarChartData result:", {
labels,
durations,
sessionCounts,
});
// Log the actual duration values for debugging
durations.forEach((periodDurations, idx) => {
if (periodDurations.length > 0) {
console.log(` ${labels[idx]}: durations =`, periodDurations);
}
});
return { labels, durations, sessionCounts };
}
@@ -699,31 +711,36 @@
function renderBarChart(chartData) {
const ctx = document.getElementById("barChart");
// Destroy existing chart if it exists
if (barChartInstance) {
barChartInstance.destroy();
}
// Debug: Log the data
console.log('Bar chart data:', chartData);
console.log("Bar chart data:", chartData);
// Find the maximum number of sessions in any period
const maxSessions = Math.max(...chartData.durations.map(d => d.length), 0);
console.log('Max sessions:', maxSessions);
const maxSessions = Math.max(
...chartData.durations.map((d) => d.length),
0,
);
console.log("Max sessions:", maxSessions);
// If no sessions at all, show empty chart
if (maxSessions === 0) {
barChartInstance = new Chart(ctx, {
type: "bar",
data: {
labels: chartData.labels,
datasets: [{
label: "No Data",
data: new Array(chartData.labels.length).fill(0),
backgroundColor: "rgba(79, 172, 254, 0.3)",
}],
datasets: [
{
label: "No Data",
data: new Array(chartData.labels.length).fill(0),
backgroundColor: "rgba(79, 172, 254, 0.3)",
},
],
},
options: {
responsive: true,
@@ -747,57 +764,64 @@
});
return;
}
// Create color palette for different sessions
const colors = [
'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)',
'rgba(79, 172, 254, 0.6)',
'rgba(0, 242, 254, 0.6)',
'rgba(58, 155, 232, 0.6)',
'rgba(32, 137, 220, 0.6)',
"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)",
"rgba(79, 172, 254, 0.6)",
"rgba(0, 242, 254, 0.6)",
"rgba(58, 155, 232, 0.6)",
"rgba(32, 137, 220, 0.6)",
];
// Create datasets - one for each session position
const datasets = [];
for (let sessionIndex = 0; sessionIndex < maxSessions; sessionIndex++) {
const dataForSession = chartData.durations.map(periodDurations =>
periodDurations[sessionIndex] || 0
const dataForSession = chartData.durations.map(
(periodDurations) => periodDurations[sessionIndex] || 0,
);
console.log(`Session ${sessionIndex + 1} data:`, dataForSession);
datasets.push({
label: `Session ${sessionIndex + 1}`,
data: dataForSession,
backgroundColor: colors[sessionIndex % colors.length],
borderColor: colors[sessionIndex % colors.length].replace('0.8', '1').replace('0.6', '1'),
borderColor: colors[sessionIndex % colors.length]
.replace("0.8", "1")
.replace("0.6", "1"),
borderWidth: 1,
});
}
console.log('Datasets:', datasets);
console.log("Datasets:", datasets);
// Determine the maximum total duration across all periods (in hours)
const maxDuration = Math.max(...chartData.durations.map(periodDurations =>
periodDurations.reduce((sum, val) => sum + val, 0)
), 0);
console.log('Max duration (hours):', maxDuration);
const maxDuration = Math.max(
...chartData.durations.map((periodDurations) =>
periodDurations.reduce((sum, val) => sum + val, 0),
),
0,
);
console.log("Max duration (hours):", maxDuration);
// Decide whether to use minutes or hours based on max duration
const useMinutes = maxDuration < 2; // Use minutes if max is less than 2 hours
// Convert data to minutes if needed
const finalDatasets = useMinutes ? datasets.map(dataset => ({
...dataset,
data: dataset.data.map(hours => hours * 60) // Convert hours to minutes
})) : datasets;
const finalDatasets = useMinutes
? datasets.map((dataset) => ({
...dataset,
data: dataset.data.map((hours) => hours * 60), // Convert hours to minutes
}))
: datasets;
barChartInstance = new Chart(ctx, {
type: "bar",
data: {
@@ -819,13 +843,13 @@
text: useMinutes ? "Minutes" : "Hours",
},
ticks: {
callback: function(value) {
callback: function (value) {
if (useMinutes) {
return Math.round(value) + 'm';
return Math.round(value) + "m";
} else {
return value.toFixed(1) + 'h';
return value.toFixed(1) + "h";
}
}
},
},
},
},
@@ -835,8 +859,10 @@
},
tooltip: {
callbacks: {
label: function(context) {
const value = useMinutes ? context.parsed.y / 60 : context.parsed.y;
label: function (context) {
const value = useMinutes
? context.parsed.y / 60
: context.parsed.y;
const hours = Math.floor(value);
const minutes = Math.round((value - hours) * 60);
if (hours === 0) {
@@ -844,18 +870,21 @@
}
return `${context.dataset.label}: ${hours}h ${minutes}m`;
},
footer: function(tooltipItems) {
footer: function (tooltipItems) {
const periodIndex = tooltipItems[0].dataIndex;
const totalHours = chartData.durations[periodIndex].reduce((sum, val) => sum + val, 0);
const totalHours = chartData.durations[periodIndex].reduce(
(sum, val) => sum + val,
0,
);
const hours = Math.floor(totalHours);
const minutes = Math.round((totalHours - hours) * 60);
const sessionCount = chartData.sessionCounts[periodIndex];
if (hours === 0) {
return `Total: ${minutes}m (${sessionCount} session${sessionCount !== 1 ? 's' : ''})`;
return `Total: ${minutes}m (${sessionCount} session${sessionCount !== 1 ? "s" : ""})`;
}
return `Total: ${hours}h ${minutes}m (${sessionCount} session${sessionCount !== 1 ? 's' : ''})`;
}
}
return `Total: ${hours}h ${minutes}m (${sessionCount} session${sessionCount !== 1 ? "s" : ""})`;
},
},
},
},
},
@@ -864,12 +893,12 @@
function renderDurationChart(chartData) {
const ctx = document.getElementById("durationChart");
// Destroy existing chart if it exists
if (durationChartInstance) {
durationChartInstance.destroy();
}
durationChartInstance = new Chart(ctx, {
type: "pie",
data: {
@@ -905,7 +934,7 @@
if (avgDurationChartInstance) {
avgDurationChartInstance.destroy();
}
const days = {};
const today = new Date();
today.setHours(0, 0, 0, 0);
+1
View File
@@ -1,4 +1,5 @@
"""Utility functions for the baby monitor application."""
from .hash_password import hash_password
from .verify_child_access import verify_child_access
from .verify_password import verify_password