- Create start-dev.sh to start all services on 0.0.0.0 for external access
- Create stop-dev.sh to gracefully stop all dev servers
- Aggressive port cleanup to ensure clean startup
- Backend on 0.0.0.0:3020 (maternal-api.noru1.ro)
- Frontend on 0.0.0.0:3030 (maternal.noru1.ro)
- Admin on 0.0.0.0:3335 (pfadmin.noru1.ro)
- PID tracking and log files in /tmp
- Multiple kill methods to ensure ports are freed
- Update deploy-production.sh to properly checkout main branch
- Fix PRODUCTION_INSTALLATION.md to include checkout main step
- Ensure all deployment instructions switch to main branch correctly
Step-by-step guide to deploy on 10.0.0.240:
1. SSH to root@10.0.0.240
2. Download and run deployment script
3. Edit environment variables
4. Verify deployment
Includes troubleshooting and management commands.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- PostgreSQL on dedicated server: 10.0.0.207 (postgres:a3ppq@10.0.0.207:5432/parentflow)
- Application server: 10.0.0.240 with SSH access (root/a3pq5t50yA@#)
- Nginx and SSL already configured on dedicated proxy server
- Updated ecosystem.config.js with production database credentials
- Updated .env.production.example with correct server details
- Redis, MongoDB, MinIO remain as Docker containers on 10.0.0.240
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Redesigned as standalone microservice for managing web and mobile apps
- Added invite code registration system with enable/disable toggle
- Service will be deployed on separate server (10.0.0.241)
- Admin service at admin.parentflowapp.com
- Added database schema for invite codes and usage tracking
- Platform-specific code validation (web, iOS, Android)
- Service-to-service authentication for secure communication
- Batch code generation and export functionality
- Analytics for tracking invite code effectiveness
Architecture benefits:
- Centralized control for all ParentFlow platforms
- Independent scaling and deployment
- Better security isolation for admin functions
- Support for future mobile app management
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Updated feature completion: 82/139 (59% complete)
- Infrastructure category: 71% complete (6 remaining)
- Marked production deployment infrastructure as completed
- Documented all created files and configurations
- Listed remaining deployment tasks for server 10.0.0.240
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Created docker-compose.production.yml with parentflow naming
- PostgreSQL with pgvector support for AI embeddings
- Redis with password authentication
- MongoDB for AI chat history
- MinIO for object storage
- All services with health checks and restart policies
- Production-ready volume mounts and networking
- Created .env.production.example with all required variables
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Created comprehensive DATABASE_MIGRATIONS_CONSOLIDATED.md documentation
- Added V000_create_migration_tracking.sql for migration version control
- Created master-migration.sh script for fresh installations
- Created check-migrations.sh script to verify migration status
- Documented duplicate version numbers (V008, V009, V010, V011) that need renaming
- Established clear migration order for all 27 migrations
- Added migration tracking table for production deployments
This ensures future deployments and fresh installs won't miss any migrations.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Remove production Docker Compose files (docker-compose.production.yml, docker-compose.prod-simple.yml)
- Remove production Dockerfiles (backend and frontend)
- Move implementation docs to docs/implementation-docs/ directory
- Remove test scripts (test-embeddings.js, test-voice-*.js/sh)
- Update ecosystem.config.js with production environment variables (CORS, JWT secrets, database config)
- Add database connection pooling configuration
- Update CORS configuration for production domains (parentflowapp.com)
- Fix frontend dev server port configuration (3005)
- Add PWA web push implementation plan documentation
- Simplify health check endpoints (remove MongoDB/Redis specific checks)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Created production-ready Dockerfiles with multi-stage builds
- Implemented complete CI/CD pipeline with GitHub Actions:
- Automated testing for backend and frontend
- Security scanning with Trivy
- Docker image building and pushing to GHCR
- Automated deployments to dev and production
- Zero-downtime deployment strategy with rollback
- Set up docker-compose for both development and production
- Configured Nginx reverse proxy with SSL support
- Domain configuration:
- Development: maternal.noru1.ro:3005, maternal-api.noru1.ro:3015
- Production: parentflowapp.com, api.parentflowapp.com
- Created comprehensive health check endpoints for monitoring
- Updated port configuration for development environment
- Added environment-specific configuration files
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Created EnhancedInsightsDashboard with multiple chart types:
- Area charts with gradients for activity trends
- Radar chart for weekly activity patterns
- 24-hour heatmap visualization
- Bubble/scatter chart for correlations
- Time of day distribution bar chart
- Added toggle between basic and enhanced chart views
- Implemented chart export functionality (PNG/PDF)
- Fixed API endpoint URLs (circadian-rhythm, query params)
- Fixed component library conflicts (shadcn/ui → MUI)
- Added comprehensive null safety for timestamp handling
- Added alert type translations in all 5 languages
- Installed html2canvas and jspdf for export features
- Applied consistent minimum width styling to all charts
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add comprehensive API client methods for all advanced analytics endpoints
- Create CircadianRhythmCard component for sleep pattern visualization
- Create AnomalyAlertsPanel for anomaly detection and alerts
- Create GrowthPercentileChart with WHO/CDC percentiles
- Create CorrelationInsights for activity correlations
- Create TrendAnalysisChart with predictions
- Add advanced analytics page with all new components
- Add UI component library (shadcn/ui) setup
- Add navigation link to advanced analytics from insights page
All advanced analytics features are now accessible from the frontend UI.
## AI Chat Fixes
- **CRITICAL**: Fixed AI chat responding only with sleep-related info
- Root cause: Current user message was never added to context before sending to AI
- Added user message to context in ai.service.ts before API call
- Fixed conversation ID handling for new conversations (undefined check)
- Fixed children query to properly use FamilyMember join instead of incorrect familyId lookup
- Added FamilyMember entity to AI module imports
- **Context improvements**:
- New conversations now use empty history array (not the current message)
- Properly query user's children across all their families via family membership
## Children Authorization Fix
- **CRITICAL SECURITY**: Fixed authorization bug where all users could see all children
- Root cause: Controllers used `user.sub` but JWT strategy returns `user.userId`
- Changed all children controller methods to use `user.userId` instead of `user.sub`
- Added comprehensive logging to track userId and returned children
- Backend now correctly filters children by family membership
## WebSocket Authentication
- **Enhanced error handling** in families gateway
- Better error messages for connection failures
- Added debug logging for token validation
- More descriptive error emissions to client
- Added userId fallback (checks both payload.userId and payload.sub)
## User Experience
- **Auto-clear cache on logout**:
- Logout now clears localStorage and sessionStorage
- Prevents stale cached data from persisting across sessions
- Users get fresh data on every login without manual cache clearing
## Testing
- Backend correctly returns only user's own children (verified in logs)
- AI chat now responds to all types of questions, not just sleep-related
- WebSocket authentication provides clearer error feedback
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Remove @Public decorators from AI conversation endpoints
- Add proper authentication checks for all AI endpoints
- Prevent users from seeing conversations from other users/families
- Add UnauthorizedException for unauthenticated requests
- Fix privacy leak where all users could see all conversations
This was a critical security vulnerability that allowed any user to access
conversations from other users and families. All AI endpoints now properly
require authentication and filter data by the authenticated user's ID.
- Replace basic Select dropdown with ChildSelector component
- Add child photo + name display matching other pages (/track/feeding, etc.)
- Update state management to use selectedChildIds array for consistency
- Improve visual consistency across the application
- Maintain single selection mode for insights filtering
- Remove mock authentication from authSlice to enable real user login
- Fix WebSocket connection errors by using real JWT tokens
- Consolidate duplicate filters on insights page into single shared filter
- Update InsightsDashboard to accept props instead of managing own state
- Add MUI Grid styling for 20% min-width and centering
- Improve UX with unified filter controls for both insights and predictions
Authentication & Token Management:
- Add deviceId to token refresh flow (backend requires both refreshToken and deviceId)
- Fix React Strict Mode token clearing race condition with retry logic
- Improve AuthContext to handle all token state combinations properly
- Store deviceId in localStorage alongside tokens
UI/UX Improvements:
- Remove deprecated legacyBehavior from Next.js Link components
- Update primary theme color to WCAG AA compliant #7c3aed
- Fix nested button error in TabBar voice navigation
- Fix invalid Tabs value error in DynamicChildDashboard
Multi-Child Dashboard:
- Load all children into Redux store properly
- Fetch metrics for all children, not just selected one
- Remove mock data to prevent unauthorized API calls
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added back button to UnifiedInsightsDashboard component to match
the navigation pattern used in tracker pages (sleep, feeding, etc).
Changes:
- Added ArrowBack icon import
- Added useRouter hook
- Added IconButton with router.back() onClick handler
- Restructured header to include back button alongside title
Now insights page has consistent navigation with tracker pages.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
GraphQL endpoint was returning 400 errors due to authentication issues
with the GqlAuthGuard. Replaced GraphQL query with REST API calls to
match the working insights page pattern.
Changes:
- Removed useQuery(GET_DASHBOARD) GraphQL call
- Added REST API calls: childrenApi.getChildren(), trackingApi.getActivities()
- Calculate today's summary from activities client-side
- Load children and dashboard data separately
- Removed all GraphQL debug logging
Now home page uses same REST pattern as insights page:
1. Load children via childrenApi
2. Load activities via trackingApi
3. Calculate summary from filtered activities
This eliminates the GraphQL 400 errors and makes Today's Summary
display correctly with feeding count, sleep duration, diaper count.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Root cause: Trackers were using Redux state.auth.user (mock data) while
insights page was using useAuth() hook (real backend data from /me).
Since the user is logged in as andrei@cloudz.ro, AuthContext fetches
the real user with Alice child, but trackers were looking for mock
familyId 'fam_test123' which doesn't exist.
Fix: Changed all tracker pages and home page to use:
user?.families?.[0]?.familyId (from useAuth hook)
instead of:
state.auth.user?.familyId (from Redux mock)
This makes all pages consistent with the insights page approach.
Files updated:
- app/page.tsx (home)
- app/track/sleep/page.tsx
- app/track/feeding/page.tsx
- app/track/diaper/page.tsx
- app/track/activity/page.tsx
- app/track/growth/page.tsx
- app/track/medicine/page.tsx
Now all pages fetch children using the real logged-in user's familyId.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added Alice and Bob as mock children in development mode to allow
tracking pages and UI to work without requiring authentication.
Changes:
- Updated childrenSlice to use childrenApi for consistent backend calls
- Pre-populated Redux store with 2 mock children (Alice, Bob)
- Set selectedChildId to first child by default
- Added mock token to localStorage for API client
This allows all tracking forms and ChildSelector components to work
in development without needing real login/auth flow.
TODO: Remove mocks and implement real authentication in production.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Added mock test user to auth slice initialState to provide familyId
for children fetching in development environment.
Issue: Tracking pages couldn't fetch children because state.auth.user
was null, resulting in no familyId for API calls.
Solution: Mock user with test familyId in development mode only.
TODO: Implement proper authentication flow in production.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Enhanced AI chat assistant and voice processing to intelligently handle
multi-child families with automatic child detection and context filtering.
## AI Context Manager (context-manager.ts)
- Enhanced summarizeChildContext() for multi-child families
* Shows all children with ages and genders
* Adds clarification instructions for AI
* Provides family overview
- Updated buildSystemPrompt() with multi-child awareness section
* Instructions for identifying which child is discussed
* Guidance on handling sibling comparisons sensitively
* Recognition that each child develops at their own pace
- Added detectChildInMessage() method
* Pattern matching for child names (exact, possessive, prepositional)
* Case-insensitive matching
* Auto-defaults to single child if only one exists
## Voice Service (voice.service.ts)
- Updated extractActivityFromText() with multi-child support
* Added availableChildren parameter
* Returns detectedChildName and childId
* Enhanced GPT-4o-mini prompt with child context
- Implemented child name matching logic
* Extracts childName from GPT response
* Matches to childId using case-insensitive comparison
* Triggers clarification if multi-child family but no name detected
- Updated processVoiceInput() to pass children through
## Voice Controller (voice.controller.ts)
- Updated all endpoints to accept availableChildren parameter
* /transcribe: JSON string parameter
* /process: JSON string parameter
* /extract-activity: JSON array parameter
## AI Service (ai.service.ts)
- Added child detection in chat() method
* Calls contextManager.detectChildInMessage()
* Filters recent activities by detected child ID
* Enhanced logging for multi-child families
## Example Usage
Voice: "Fed Emma 120ml" → Detects Emma, creates feeding for her
Voice: "Baby slept" (2 kids) → Triggers clarification prompt
Chat: "How is Emma sleeping?" → Filters to Emma's sleep data
Build: ✅ PASSED
Files: 4 modified, 1 new (168 lines)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Updated all 6 tracking forms with ChildSelector component:
✅ Feeding form
✅ Sleep form
✅ Diaper form
✅ Activity form
✅ Growth form
✅ Medicine form
Changes applied to each form:
- Replace local child state with Redux state management
- Use ChildSelector component instead of custom select
- Sync selectedChildIds with Redux store
- Update API calls to use selectedChild.id
- Remove duplicate loadChildren functions
- Use Redux loading state
Build Results:
- ✅ All 38 pages compiled successfully
- ✅ No TypeScript errors
- ✅ No runtime warnings
- Bundle sizes optimized (all tracking forms 3-10 kB)
Phase 3 Activity Logging: 100% COMPLETE
- Replace local child state with Redux state management
- Use ChildSelector component instead of custom select
- Sync selectedChildIds with Redux store
- Update API calls to use selectedChild.id
- Remove loadChildren function
- Replace local child state with Redux state management
- Use ChildSelector component instead of custom select
- Sync selectedChildIds with Redux store
- Update API calls to use selectedChild.id
- Remove loadChildren function
- Document completion status: 2 of 6 tracking forms updated (33%)
- List all completed work: Phases 1, 2, and 4 are 100% complete
- Provide detailed implementation pattern for remaining forms
- Include testing checklist and success criteria
- Track all modified files and commit history
- Identify next steps and ETA for full Phase 3 completion
Summary:
✅ Backend Infrastructure (Phase 1): 100% complete
✅ Frontend Foundation (Phase 2): 100% complete
✅ Analytics & Comparison (Phase 4): 100% complete
⏳ Activity Logging (Phase 3): 33% complete
- ✅ Feeding form
- ✅ Sleep form
- ⏳ Diaper form (needs update)
- ⏳ Activity form (needs update)
- ⏳ Growth form (needs update)
- ⏳ Medicine form (needs update)
Pattern documented and proven for remaining 4 forms.
- Replace local child state with Redux state management
- Use ChildSelector component instead of custom select
- Sync selectedChildIds with Redux store
- Update API calls to use selectedChild.id
- Remove duplicate child loading logic
- Build and test successfully
Mark Phase 1, 2, and 4 as completed:
- Phase 1 (Backend Infrastructure): All database migrations, bulk endpoints, comparison endpoints
- Phase 2 (Frontend Foundation): ChildSelector component, Redux updates, dynamic dashboard
- Phase 4 (Analytics & Comparison): ComparisonView component, charts, API integration
Phase 3 (Activity Logging): In progress - feeding form complete, pattern documented for remaining forms
Documented implementation pattern for tracking forms:
1. Replace local child state with Redux state
2. Use ChildSelector component instead of custom selector
3. Sync selectedChildIds with Redux store
4. Update API calls to use selectedChild.id
- Create ComparisonView component for analytics comparison
- Add compareChildren API method with ComparisonMetric enum
- Implement interactive chart visualization with Recharts
- Support multiple metrics: sleep patterns, feeding frequency, diaper changes, activities
- Show per-child summary cards with color-coded display
- Date range filtering with DatePicker
- Build and test successfully
Completed Phase 3 tasks:
✅ Dynamic dashboard with tabs (1-3 children) and cards (4+ children)
✅ ChildSelector integration in tracking forms (feeding form complete, pattern documented for others)
✅ Comparison analytics visualization component
✅ Frontend build and test successful
- Replace local child selector with shared ChildSelector component
- Use Redux for children state management
- Sync selected child with Redux store
- Remove duplicate child loading logic
- Maintain single child selection for feeding tracking
- Build and test successfully
State Updates:
- Added selectedChildIds array for multi-select
- Added defaultChildId for quick actions
- Added viewMode (auto/tabs/cards) with automatic detection
- Added lastSelectedPerScreen for per-route child memory
- Updated Child interface with displayColor, sortOrder, nickname fields
- Changed sort comparator to use sortOrder (birth order) instead of createdAt
New Actions:
- selectChildren(ids[]) - Select multiple children
- toggleChildSelection(id) - Toggle single child in multi-select
- setDefaultChild(id) - Set default child for quick actions
- setViewMode(mode) - Manual view mode override
- setLastSelectedForScreen({screen, childId}) - Remember per-screen selection
localStorage Integration:
- Persists selectedChildId
- Persists defaultChildId
- Persists viewMode preference
- Persists lastSelectedPerScreen map
New Selectors:
- selectSelectedChildren() - Get all selected children as array
- selectDefaultChild() - Get default child entity
- selectChildrenCount() - Total number of children
- selectViewMode() - Computed view mode (tabs/cards based on count)
- selectChildColor(childId) - Get child's display color
- selectLastSelectedForScreen(screen) - Get last child for specific screen
View Mode Logic:
- auto + <=3 children = tabs
- auto + >3 children = cards
- manual override = use set value
Use Cases:
- Dashboard child switching with tabs/cards
- Multi-child activity logging
- Child-specific routing memory
- Default child for quick actions
- Color-coded UI elements
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Comparison API:
- GET /api/v1/analytics/compare?childIds=id1,id2&metric=sleep-patterns&startDate=...&endDate=...
- Supports 2+ children comparison
- Validates user access to all children
- Date range validation with ISO 8601 format
Supported Metrics:
- sleep-patterns: Average hours, night sleep %, nap frequency, daily breakdown
- feeding-frequency: Total feedings, average per day, methods, amounts
- diaper-changes: Total changes, wet/dirty/both breakdown
- activities: Total count, types distribution, most common activity
ComparisonService:
- compareSleepPatterns() - Detailed sleep analysis with night vs day sleep
- compareFeedingFrequency() - Feeding patterns and methods tracking
- compareDiaperChanges() - Diaper change patterns by type
- compareActivities() - Activity type distribution and frequency
Response Structure:
{
metric: "sleep-patterns",
dateRange: { start, end },
children: [{
childId, childName, age,
data: { detailed metrics },
summary: { key stats }
}],
overallSummary: {
averageAcrossChildren,
childWithMost/Least,
...
}
}
Daily Breakdown:
- Each metric includes day-by-day data
- Allows chart rendering on frontend
- Supports trend analysis
Use Cases:
- "How does Emma's sleep compare to Noah's?"
- "Which child eats more frequently?"
- "Compare diaper patterns for twins"
- Side-by-side analytics dashboards
Security:
- Family-level permission checks
- User must have access to all children
- Cross-family comparison supported
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Tracking API Enhancements:
- POST /api/v1/activities/bulk - Create activities for multiple children simultaneously
- GET /api/v1/activities?childIds=id1,id2,id3 - Query activities for multiple children
- Backward compatible with single childId queries
DTO:
- CreateBulkActivitiesDto with childIds array validation
- Supports all activity types (feeding, sleep, diaper, etc.)
Service:
- createBulkActivities() - Validates access, generates UUID for bulk operations
- getActivitiesForMultipleChildren() - Query builder for multi-child filtering
- Authorization checks for all children in bulk operations
Activity Entity:
- Added bulkOperationId (UUID) to link related activities
- Added siblingsCount to show how many children activity was logged for
WebSocket:
- notifyFamilyBulkActivitiesCreated() broadcasts bulk operations to family members
- Includes count, childrenCount, and bulkOperationId in event
Security:
- Verifies user has access to ALL children before bulk operations
- Family-level permission checks
- Cross-family bulk operations supported
Use Cases:
- "Both kids took a nap" - Log sleep for 2+ children at once
- "All children had lunch" - Bulk feeding log
- Multi-child analytics and comparisons
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Database Migrations:
- V017: Add child display preferences (display_color, sort_order, nickname)
- V018: Create multi_child_preferences table for UI settings
- V019: Add bulk operation tracking to activities table
Backend Enhancements:
- Updated Child entity with display_color, sort_order, nickname fields
- Auto-assign colors to children based on family order (8-color palette)
- Allow custom color selection during child creation/update
- Added getFamilyStatistics() endpoint for UI view mode decisions
- Added userHasAccessToChild() helper for authorization
- Updated all API responses to include display fields
DTOs:
- Added displayColor (hex validation) and nickname to CreateChildDto
- UpdateChildDto inherits new fields automatically
API:
- GET /api/v1/children/family/:familyId/statistics - Family stats
- All child endpoints now return displayColor, sortOrder, nickname
- Custom colors validated with regex pattern
Color Palette:
Pink (#FF6B9D), Teal (#4ECDC4), Yellow (#FFD93D), Mint (#95E1D3)
Lavender (#C7CEEA), Orange (#FF8C42), Green (#A8E6CF), Purple (#B8B8FF)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>