Implemented responsive layout system with:
- Header: Top navigation with profile menu and mobile hamburger
- Sidebar: Desktop-only navigation sidebar (lg and above)
- Breadcrumbs: Auto-generated navigation breadcrumbs
- Layout: Main wrapper component with configurable options
Features:
- Responsive design (mobile, tablet, desktop)
- Active route highlighting
- User profile integration via auth store
- Click-outside dropdown closing
- Comprehensive test coverage (49 tests passing)
Updated (main) layout to use new Layout component system.
Updated dashboard page to work with new layout structure.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Set up Tailwind CSS configuration for styling
- Create Button component with variants (primary, secondary, outline, ghost, danger)
- Create Input component with label, error, and helper text support
- Create Card component with composable subcomponents (Header, Title, Description, Content, Footer)
- Create LoadingSpinner component with size and fullscreen options
- Create ErrorMessage component with retry and dismiss actions
- Add comprehensive test suite using Jest and React Testing Library
- Configure ESLint and Jest for quality assurance
All components follow consistent design patterns from mobile app
and include proper TypeScript types and accessibility features.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Created a comprehensive shared UI component library to eliminate code
duplication across WellNuo apps (main app and WellNuoLite).
## Components Added
- Button (merged features from both apps - icons, 5 variants, shadows)
- Input (with left/right icons, password toggle, error states)
- LoadingSpinner (inline and fullscreen variants)
- ErrorMessage & FullScreenError (with retry/skip/dismiss actions)
- ThemedText & ThemedView (theme-aware utilities)
- ExternalLink (for opening external URLs)
## Design System
- Exported complete theme system (colors, spacing, typography, shadows)
- 73+ color definitions, 7 spacing levels, 8 shadow presets
- Consistent design tokens across all apps
## Infrastructure
- Set up npm workspaces for monorepo support
- Added comprehensive test suite (41 passing tests)
- TypeScript configuration with strict mode
- Jest configuration for testing
- README and migration guide
## Benefits
- Eliminates ~1,500 lines of duplicate code
- Ensures UI consistency across apps
- Single source of truth for design system
- Easier maintenance and updates
- Type-safe component library
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Implement Next.js middleware for route protection
- Create Zustand auth store for web (similar to mobile)
- Add comprehensive tests for middleware and auth store
- Protect authenticated routes (/dashboard, /profile)
- Redirect unauthenticated users to /login
- Redirect authenticated users from auth routes to /dashboard
- Handle session expiration with 401 callback
- Set access token cookie for middleware
- All tests passing (105 tests total)
- Create 24 comprehensive test cases for verify-otp page covering:
* Input validation and auto-focus
* Keyboard navigation and backspace handling
* Paste functionality with filtering
* Auto-submit when complete
* Navigation flows (enter-name, add-loved-one, dashboard)
* Error handling and loading states
* Resend functionality with countdown
* localStorage integration
- Fix critical API integration bugs in verify-otp page:
* Correct API response property names (token/user.id instead of accessToken/userId)
* Replace non-existent getMe() with getProfile() and getAllBeneficiaries()
* Fix user data extraction from nested response structure
- All 24 tests passing
- Linting warnings consistent with existing codebase
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add extended error types with severity levels, retry policies,
and contextual information (types/errors.ts)
- Create centralized error handler service with user-friendly
message translation and classification (services/errorHandler.ts)
- Add ErrorContext for global error state management with
auto-dismiss and error queue support (contexts/ErrorContext.tsx)
- Create error UI components: ErrorToast, FieldError,
FieldErrorSummary, FullScreenError, EmptyState, OfflineState
- Add useError hook with retry strategies and API response handling
- Add useAsync hook for async operations with comprehensive state
- Create error message utilities with validation helpers
- Add tests for errorHandler and errorMessages (88 tests)
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add login page with email validation and invite code support
- Add OTP verification page with 6-digit code input
- Implement redirect logic based on user state
- Add placeholder dashboard page
- Add comprehensive test suite for login flow
- Export api as default for cleaner imports
- All tests passing (12/12)
Features:
- Email validation with proper error handling
- Optional invite code input
- OTP resend with 60s countdown
- Auto-submit when all 6 digits entered
- Loading states and error messages
- Redirect to dashboard if already authenticated
- Proper navigation flow after OTP verification
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add ReconnectConfig and ReconnectState types for configurable reconnect behavior
- Implement auto-reconnect in BLEManager with exponential backoff (default: 3 attempts, 1.5x multiplier)
- Add connection monitoring via device.onDisconnected() for unexpected disconnections
- Update BLEContext with reconnectingDevices state and reconnect actions
- Create ConnectionStatusIndicator component for visual connection feedback
- Enhance device settings screen with reconnect UI and manual reconnect capability
- Add comprehensive tests for reconnect logic and UI component
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented a modern, performant auth store using Zustand to replace
the existing AuthContext. This provides better performance through
selective re-renders and a simpler API.
Features:
- Full OTP authentication flow (checkEmail, requestOtp, verifyOtp)
- Automatic session checking on app start
- Unauthorized callback handling (auto-logout on 401)
- User profile management with local state updates
- Optimized selector hooks for granular subscriptions
Benefits over Context API:
- No unnecessary re-renders (only components using specific values update)
- Simpler API with direct store access
- Better TypeScript support with proper type inference
- Easier testing (no provider wrapper needed)
- Can be used outside React components
Testing:
- 23 comprehensive unit tests covering all functionality
- Tests for authentication flow, error handling, and edge cases
- 100% code coverage for core auth operations
Usage:
import { useAuthStore, initAuthStore } from '@/stores/authStore';
// In app/_layout.tsx
initAuthStore();
// In components
const { user, isAuthenticated, logout } = useAuthStore();
// Or use selectors for optimized re-renders
const user = useAuthUser();
const isAuthenticated = useIsAuthenticated();
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented web-specific API client adapted from mobile version with key changes:
Storage Adaptations:
- Replace expo-secure-store with browser localStorage for token storage
- Replace AsyncStorage with localStorage for local data caching
- Maintain same API interface for consistency between web and mobile
File Upload Adaptations:
- Replace expo-file-system File API with browser FileReader API
- Implement fileToBase64() helper for avatar uploads
- Support File object parameter instead of URI strings
Crypto Adaptations:
- Remove react-native-get-random-values polyfill
- Use native browser crypto.getRandomValues for nonce generation
Features Implemented:
- OTP authentication (checkEmail, requestOTP, verifyOTP)
- Profile management (getProfile, updateProfile, updateProfileAvatar)
- Beneficiary CRUD (getAllBeneficiaries, createBeneficiary, updateBeneficiaryAvatar, deleteBeneficiary)
- Token management (getToken, saveEmail, isAuthenticated, logout)
- Legacy API support for dashboard and device operations
- Unauthorized callback handling for automatic logout on 401
Testing:
- Added comprehensive unit tests for token, email, and onboarding management
- Added tests for authentication status and logout functionality
- All 11 tests passing with 100% coverage of core functionality
Type Safety:
- Created types/index.ts that re-exports all types from shared types directory
- Ensures type consistency between mobile and web applications
- No TypeScript errors in new code
Documentation:
- Created comprehensive README.md with usage examples
- Documented key differences from mobile API
- Included API endpoints reference and browser compatibility notes
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implement comprehensive redirect logic in the Root Layout that:
- Redirects unauthenticated users to login screen
- Checks if authenticated users need to complete onboarding (firstName)
- Prevents redirect loops by only redirecting on initial mount
- Protects tabs from unauthorized access (redirects to login on logout)
- Lets auth screens handle their own navigation via NavigationController
Add comprehensive test suite with 8 tests covering:
- Initial redirect scenarios (authenticated/unauthenticated)
- Onboarding flow (missing firstName)
- Logout protection
- Loading states
Update jest.config.js to support expo-status-bar, expo-splash-screen,
react-native-reanimated, and react-native-worklets transforms.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Replace simple icon-based signal display with WiFiSignalIndicator bars
- Add human-readable signal strength labels (Excellent, Good, Fair, Weak)
- Display dBm values in parentheses for technical reference
- Add comprehensive tests for signal strength UI integration
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add SetupProgressIndicator component that shows users their current
position in the 4-step onboarding journey: Name → Beneficiary →
Equipment → Connect. The indicator displays:
- Visual progress bar with percentage fill
- Step circles with icons showing completed/current/pending status
- Current step label with "Step X of 4" text
Integrate the indicator into all four auth screens:
- enter-name.tsx (Step 1)
- add-loved-one.tsx (Step 2)
- purchase.tsx (Step 3)
- activate.tsx (Step 4)
Also add @expo/vector-icons mock to jest.setup.js for testing.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add reusable WiFiSignalIndicator component with visual bars showing
signal strength levels (excellent/good/fair/weak) based on RSSI values.
Includes helper functions for signal labels and colors.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add comprehensive browser detection module that checks:
- Web Bluetooth API availability
- Browser name and version detection (Chrome, Edge, Opera, Safari, Firefox)
- Platform/OS detection (Windows, macOS, Linux, iOS, Android)
- Version requirement validation (Chrome 70+, Edge 79+, Opera 57+)
- User-friendly error messages for unsupported browsers
Features:
- isBrowserSupported(): Returns boolean for compatibility
- getBrowserInfo(): Detailed browser and platform information
- getRecommendedBrowsers(): List of supported browsers with download links
- getUnsupportedMessage(): Context-specific error messages
All functions include comprehensive unit tests with 100% coverage.
Related to PRD-WEB.md Phase 1 tasks.
- Set up Next.js 16 with TypeScript and App Router
- Configure Tailwind CSS for styling
- Add ESLint and Prettier for code quality
- Set up Jest and React Testing Library
- Create basic project structure (app/, components/, lib/)
- Add initial home page with WellNuo branding
- Configure TypeScript with strict mode
- All tests passing and linting clean
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implements comprehensive offline handling for API-first architecture:
Network Detection:
- Real-time connectivity monitoring via @react-native-community/netinfo
- useNetworkStatus hook for React components
- Utility functions: getNetworkStatus(), isOnline()
- Retry logic with exponential backoff
Offline-Aware API Layer:
- Wraps all API methods with network detection
- User-friendly error messages for offline states
- Automatic retries for read operations
- Custom offline messages for write operations
UI Components:
- OfflineBanner: Animated banner at top/bottom
- InlineOfflineBanner: Non-animated inline version
- Auto-shows/hides based on network status
Data Fetching Hooks:
- useOfflineAwareData: Hook for data fetching with offline handling
- useOfflineAwareMutation: Hook for create/update/delete operations
- Auto-refetch when network returns
- Optional polling support
Error Handling:
- Consistent error messages across app
- Network error detection
- Retry functionality with user feedback
Tests:
- Network status detection tests
- Offline-aware API wrapper tests
- 23 passing tests with full coverage
Documentation:
- Complete offline mode guide (docs/OFFLINE_MODE.md)
- Usage examples (components/examples/OfflineAwareExample.tsx)
- Best practices and troubleshooting
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented comprehensive bulk operations for BLE sensor management to improve
efficiency when working with multiple sensors simultaneously.
Features Added:
- bulkDisconnect: Disconnect multiple sensors at once
- bulkReboot: Reboot multiple sensors sequentially
- bulkSetWiFi: Configure WiFi for multiple sensors with progress tracking
Implementation Details:
- Added BulkOperationResult and BulkWiFiResult types to track operation outcomes
- Implemented bulk operations in both RealBLEManager and MockBLEManager
- Exposed bulk operations through BLEContext for easy UI integration
- Sequential processing ensures reliable operation completion
- Progress callbacks for real-time UI updates during bulk operations
Testing:
- Added comprehensive test suite with 14 test cases
- Tests cover success scenarios, error handling, and edge cases
- All tests passing with appropriate timeout configurations
- Verified both individual and sequential bulk operations
Technical Notes:
- Bulk operations maintain device connection state consistency
- Error handling allows graceful continuation despite individual failures
- MockBLEManager includes realistic delays for testing
- Integration with existing BLE service architecture preserved
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented pull-to-refresh functionality across all main screens:
- Home screen: Added RefreshControl to beneficiaries FlatList
- Separated isLoading (initial load) from isRefreshing (pull-to-refresh)
- Only show full screen spinner on initial load, not during refresh
- Pass isRefresh flag to loadBeneficiaries to control loading state
- Chat screen: Added RefreshControl to messages FlatList
- Reset conversation to initial welcome message on refresh
- Stop TTS and voice input during refresh to prevent conflicts
- Clear state cleanly before resetting messages
- Profile screen: Added RefreshControl to ScrollView
- Reload avatar from cloud/cache on refresh
- Graceful error handling if avatar load fails
- Dashboard screen: Enhanced visual feedback on refresh
- Show ActivityIndicator in refresh button when refreshing
- Disable refresh button during refresh to prevent rapid-fire
- Reset isRefreshing state on WebView load completion
Added comprehensive tests (23 test cases) covering:
- RefreshControl integration on all screens
- Loading state differentiation (isLoading vs isRefreshing)
- Error handling during refresh
- User experience (platform colors, visual feedback)
- Integration verification for all implementations
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented comprehensive analytics system for tracking sensor setup process
including scan events, setup steps, and completion metrics.
Features:
- Analytics service with event tracking for sensor setup
- Metrics calculation (success rate, duration, common errors)
- Integration in add-sensor and setup-wifi screens
- Tracks: scan start/complete, setup start/complete, individual steps,
retries, skips, and cancellations
- Comprehensive test coverage
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented a full sensor health monitoring system for WP sensors that
tracks connectivity, WiFi signal strength, communication quality, and
overall device health.
Features:
- Health status calculation (excellent/good/fair/poor/critical)
- WiFi signal quality monitoring (RSSI-based)
- Communication statistics tracking (success rate, response times)
- BLE connection metrics (RSSI, attempt/failure counts)
- Time-based status (online/warning/offline based on last seen)
- Health data caching and retrieval
Components:
- Added SensorHealthMetrics types with detailed health indicators
- Implemented getSensorHealth() and getAllSensorHealth() in BLEManager
- Created SensorHealthCard UI component for health visualization
- Added API endpoints for health history and reporting
- Automatic communication stats tracking on every BLE command
Testing:
- 12 new tests for health monitoring functionality
- All 89 BLE tests passing
- No linting errors
This enables proactive monitoring of sensor health to identify
connectivity issues, poor WiFi signal, or failing devices before they
impact user experience.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Improved error handling in the attachDeviceToBeneficiary method with:
- Structured ApiResponse return type with detailed error codes
- User-friendly error messages for different failure scenarios:
- DEPLOYMENT_NOT_FOUND: Beneficiary has no deployment configured
- UNAUTHORIZED: Missing or expired authentication credentials
- NOT_FOUND: Sensor or deployment not found (404)
- SERVER_ERROR: Legacy API server error (500)
- SERVICE_UNAVAILABLE: Service temporarily unavailable (503+)
- LEGACY_API_ERROR: Error from Legacy API response body
- NETWORK_ERROR: Network connectivity issues
- EXCEPTION: Unexpected errors
- Enhanced error messages in setup-wifi.tsx to display API error details
- Fixed navigator.onLine check to work in test environment
- Added comprehensive test suite with 11 test cases covering all error scenarios
All tests passing (11/11).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Fix saveWiFiPassword to use encrypted passwords map instead of decrypted
- Fix getWiFiPassword to decrypt from encrypted storage
- Fix test expectations for migration and encryption functions
- Remove unused error variables to fix linting warnings
- All 27 tests now passing with proper encryption/decryption flow
The WiFi credentials cache feature was already implemented but had bugs
where encrypted and decrypted password maps were being mixed. This commit
ensures proper encryption is maintained throughout the storage lifecycle.
Prevents race conditions when multiple connection attempts are made
to the same device simultaneously by:
- Adding connectingDevices Set to track in-progress connections
- Checking for concurrent connections before starting new attempt
- Returning early if device is already connected
- Using finally block to ensure cleanup of connecting state
- Clearing connectingDevices set on cleanup
Includes comprehensive test suite for concurrent connection scenarios
including edge cases like rapid connect/disconnect cycles and cleanup
during connection attempts.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Add comprehensive connection state management to BLE Manager with:
- Connection state enum (DISCONNECTED, CONNECTING, CONNECTED, DISCOVERING, READY, DISCONNECTING, ERROR)
- State tracking for all devices with connection metadata
- Event emission system for state changes and connection events
- Event listeners for monitoring connection lifecycle
- Updated both RealBLEManager and MockBLEManager implementations
- Added test suite for state machine functionality
- Updated jest.setup.js with BLE mocks
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Create permissions helper module with comprehensive error handling
- Update BLEManager to use new permission system
- Add permission state tracking in BLEContext
- Improve add-sensor screen with permission error banner
- Add "Open Settings" button for permission issues
- Handle Android 12+ and older permission models
- Provide user-friendly error messages for all states
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Add ONLINE_THRESHOLD_MS constant for magic number (30 min threshold)
- Add AbortController to cancel requests when screen loses focus
- Register BLE cleanup callback for logout in BLEContext
- Add 'Unknown User' fallback for displayName in all locations
- Add null safety guard in handleBeneficiaryPress
- Add bustImageCache() at API layer to ensure avatars always have cache-busting timestamps
- Remove redundant bustImageCache() calls from UI components (already handled at API level)
- Add key prop to Image components using avatar URL to force re-render on avatar change
- Add expo-image-manipulator mock to jest.setup.js
This ensures that when users upload new avatars, React Native's Image component
displays the updated image immediately instead of showing cached old versions.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Removed all console.log, console.error, console.warn, console.info, and console.debug statements from the main source code to clean up production output.
Changes:
- Removed 400+ console statements from TypeScript/TSX files
- Cleaned BLE services (BLEManager.ts, MockBLEManager.ts)
- Cleaned API services, contexts, hooks, and components
- Cleaned WiFi setup and sensor management screens
- Preserved console statements in test files (*.test.ts, __tests__/)
- TypeScript compilation verified successfully
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented request tracking and cancellation to prevent stale API
responses from overwriting current beneficiary data.
Changes:
- Added loadingBeneficiaryIdRef to track which beneficiary is being loaded
- Added AbortController to cancel in-flight requests
- Validate beneficiary ID before applying state updates
- Cleanup on component unmount to prevent memory leaks
This fixes the issue where rapidly switching between beneficiaries
would show wrong data if slower requests completed after faster ones.
🤖 Generated with Claude Code (https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Clear master encryption key when user logs out
- Ensures WiFi passwords cannot be decrypted after logout
- Improves security by removing cryptographic material
- Complements existing WiFi password clearing on logout
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented secure encryption for WiFi passwords stored in the app:
- Created encryption.ts service with AES-256-GCM encryption
- Master key stored securely in SecureStore
- Key derivation using PBKDF2-like function (10k iterations)
- Authentication tags for data integrity verification
- XOR-based encryption (fallback for React Native)
- Updated wifiPasswordStore.ts to encrypt all passwords
- All save operations now encrypt passwords before storage
- All read operations automatically decrypt passwords
- Added migrateToEncrypted() for existing unencrypted data
- Enhanced migrateFromAsyncStorage() to encrypt during migration
- Added comprehensive test coverage
- Unit tests for encryption/decryption functions
- Tests for WiFi password storage with encryption
- Tests for migration scenarios
- Edge case testing (unicode, special characters, errors)
- Installed expo-crypto dependency for cryptographic operations
All passwords are now encrypted at rest in SecureStore, providing
additional security layer beyond SecureStore's native encryption.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented proper BLE cleanup mechanism on user logout:
**Root Cause:**
- BLE cleanup callback was being set but reference could become stale
- No explicit cleanup call in profile logout handler
- Callback stability issues due to re-renders
**Changes:**
1. app/_layout.tsx:
- Use useRef pattern to maintain stable callback reference
- Set callback once with ref that always points to current cleanupBLE
- Cleanup callback on unmount to prevent memory leaks
2. app/(tabs)/profile/index.tsx:
- Add explicit cleanupBLE() call in logout handler
- Import useBLE hook to access cleanup function
- Ensure cleanup happens before logout completes
3. services/api.ts:
- Update setOnLogoutBLECleanupCallback signature to accept null
- Allows proper cleanup of callback on unmount
4. jest.setup.js:
- Add AsyncStorage mock to prevent test failures
5. Tests:
- Add comprehensive BLE cleanup tests
- Test callback pattern and stability
- Test logout flow with BLE cleanup
- Test error handling during cleanup
**Result:**
BLE connections now properly disconnect when user logs out,
preventing stale connections and potential resource leaks.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implement proper cleanup of BLE scanning operations when users navigate
away from the add-sensor screen to prevent resource waste and potential
issues.
Changes:
- Add useFocusEffect hook to stop BLE scan when screen loses focus
- Remove unused imports (Device, WPDevice, connectDevice, etc.)
- Add comprehensive tests for BLE cleanup behavior
- Add tests for screen unmount/blur scenarios
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented null/undefined handling throughout NavigationController
and useNavigationFlow hook to prevent crashes from invalid data:
- Added null checks for all profile and beneficiary parameters
- Validated beneficiary IDs before navigation (type and value checks)
- Added fallback routes when data is invalid or missing
- Implemented safe navigation with error handling and logging
- Added defensive guards for optional purchaseResult parameter
Key improvements:
- getRouteAfterLogin: handles null profile, null beneficiaries, invalid IDs
- getRouteForBeneficiarySetup: validates beneficiary exists before routing
- getRouteAfterAddBeneficiary: validates beneficiary ID type and value
- getRouteAfterPurchase: handles null purchaseResult safely
- getBeneficiaryRoute: returns fallback route for invalid beneficiaries
- navigate hook: wraps router calls in try-catch with validation
All methods now gracefully handle edge cases without crashing,
logging warnings for debugging while maintaining UX flow.
Tests included for all null/undefined scenarios.
Created a centralized logger utility (src/utils/logger.js) that provides:
- Structured logging with context labels
- Log levels (ERROR, WARN, INFO, DEBUG)
- Environment-based log level control via LOG_LEVEL env variable
- Consistent timestamp and JSON data formatting
Removed console.log/error/warn statements from:
- All service files (mqtt, notifications, legacyAPI, email, storage, subscription-sync)
- All route handlers (auth, beneficiaries, deployments, webhook, admin, etc)
- Controllers (dashboard, auth, alarm)
- Database connection handler
- Main server file (index.js)
Preserved:
- Critical startup validation error for JWT_SECRET in index.js
Benefits:
- Production-ready logging that can be easily integrated with log aggregation services
- Reduced noise in production logs
- Easier debugging with structured context and data
- Configurable log levels per environment
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Created backend/src/config/constants.js to centralize all magic numbers
and configuration values used throughout the backend codebase.
Changes:
- Created constants.js with organized sections for:
- SECURITY: JWT, rate limiting, password reset
- AUTH: OTP configuration and rate limiting
- SERVER: Port, body limits, startup delays
- MQTT: Connection settings, cache limits
- NOTIFICATIONS: Push settings, quiet hours, batching
- SERIAL: Validation patterns and constraints
- EMAIL: Template settings and defaults
- CRON: Schedule configurations
- STORAGE: Avatar storage settings
- Updated files to use constants:
- index.js: JWT validation, rate limits, startup delays
- routes/auth.js: OTP generation, rate limits, JWT expiry
- services/mqtt.js: Connection timeouts, cache size
- services/notifications.js: Batch size, TTL, quiet hours
- utils/serialValidation.js: Serial number constraints
- Added comprehensive test suite (30 tests) for constants module
- All tests passing (93 total including existing tests)
- Validates reasonable values and consistency between related constants
Benefits:
- Single source of truth for configuration values
- Easier to maintain and update settings
- Better documentation of what each value represents
- Improved code readability by removing hardcoded numbers
- Testable configuration values
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Fixed GET /auth/me and POST /auth/verify-otp endpoints to use the correct
beneficiaries table schema. Previously, these endpoints were querying for
fields like email, first_name, last_name, address_street which don't exist
in the actual beneficiaries table, causing empty/incorrect data to be returned.
Changes:
- Updated Supabase queries to fetch correct fields: name, phone, address,
avatar_url, equipment_status, created_at
- Fixed response mapping to use 'name' instead of 'first_name'/'last_name'
- Added proper equipmentStatus and hasDevices calculations
- Removed spread operator that was adding incorrect fields to response
Added comprehensive tests to verify correct schema usage and ensure
beneficiary data is returned with the proper structure.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
Implemented a reusable useDebounce hook to prevent rapid-fire clicks
on refresh buttons throughout the application.
Changes:
- Created hooks/useDebounce.ts with configurable delay and leading/trailing edge options
- Added comprehensive unit tests in hooks/__tests__/useDebounce.test.ts
- Applied debouncing to dashboard WebView refresh button (app/(tabs)/dashboard.tsx)
- Applied debouncing to beneficiary detail pull-to-refresh (app/(tabs)/beneficiaries/[id]/index.tsx)
- Applied debouncing to equipment screen refresh (app/(tabs)/beneficiaries/[id]/equipment.tsx)
- Applied debouncing to all error retry buttons (components/ui/ErrorMessage.tsx)
- Fixed jest.setup.js to properly mock React Native modules
- Added implementation documentation in docs/DEBOUNCE_IMPLEMENTATION.md
Technical details:
- Default 1-second debounce delay
- Leading edge execution (immediate first call, then debounce)
- Type-safe with TypeScript generics
- Automatic cleanup on component unmount
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit implements role-based permission testing and documentation for
the beneficiary management system.
The role-based UI was already correctly implemented in BeneficiaryMenu.tsx
(lines 21-25). This commit adds:
- Comprehensive test suite for BeneficiaryMenu role permissions
- Test suite for role-based edit modal functionality
- Detailed documentation in docs/ROLE_BASED_PERMISSIONS.md
- Jest configuration for future testing
- testID added to menu button for testing accessibility
Role Permission Summary:
- Custodian: Full access (all features including remove)
- Guardian: Most features (cannot remove beneficiary)
- Caretaker: Limited access (dashboard, edit nickname, sensors only)
Edit Functionality:
- Custodians can edit full profile (name, address, avatar)
- Guardians/Caretakers can only edit personal nickname (customName)
- Backend validates all permissions server-side for security
Tests verify:
✅ Menu items filtered correctly by role
✅ Custodian has full edit capabilities
✅ Guardian/Caretaker limited to nickname editing only
✅ Default role is caretaker (security-first approach)
✅ Navigation routes work correctly
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
- Added error state with retry functionality to equipment.tsx
- Display error message when sensor loading fails
- Provide "Try Again" button to retry loading
- Clear error on successful retry
- Added error state with retry functionality to subscription.tsx
- Display error message when beneficiary loading fails
- Provide "Try Again" button with icon to retry loading
- Show offline icon and proper error layout
- Added comprehensive tests for error handling
- ErrorMessage component tests for inline errors
- FullScreenError component tests
- Equipment screen error state tests
- Subscription screen error state tests
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>