15 Commits

Author SHA1 Message Date
a238b7e35f Add comprehensive error handling system
- 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>
2026-01-31 17:43:07 -08:00
184ecbbfcf Add Auth Store with Zustand state management
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>
2026-01-31 17:30:02 -08:00
88bb6d7f8f Configure Root Layout with enhanced redirect logic
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>
2026-01-31 17:20:18 -08:00
dad084c775 Add setup progress indicator to onboarding flow
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>
2026-01-31 17:14:44 -08:00
48019e0b08 Add unsupported browser page for WellNuo Web
Creates a dedicated page to handle browsers that don't support Web Bluetooth API.
The page detects the user's browser and provides appropriate guidance.

Features:
- Automatic browser and platform detection
- User-friendly messages for Safari, Firefox, iOS
- Recommended browsers with download links
- Mobile app alternative suggestion
- Technical details section (expandable)
- Responsive design matching existing pages

Browser detection:
- Chrome 70+ (supported)
- Edge 79+ (supported)
- Opera 57+ (supported)
- Safari (not supported - Apple limitation)
- Firefox (not supported - privacy concerns)
- iOS (not supported - system restrictions)

Files:
- web-pages/unsupported-browser.html - Standalone page with inline detection
- __tests__/web-pages/unsupported-browser.test.ts - Comprehensive test coverage

All tests pass (17/17).
2026-01-31 17:12:35 -08:00
ed6970e67a Add WiFi signal strength indicator component
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>
2026-01-31 17:09:21 -08:00
91e677178e Add offline mode graceful degradation
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>
2026-01-31 16:49:15 -08:00
b5ab28aa3e Add bulk sensor operations API
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>
2026-01-31 16:40:36 -08:00
30df915433 Add comprehensive API error handling for sensor attachment
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>
2026-01-31 16:08:08 -08:00
0cc82b24b0 Add deployment_id lookup mechanism
Implement getDeploymentForBeneficiary() method to resolve beneficiary → deployment_id mapping. This extracts the deployment lookup logic into a reusable, testable method.

Changes:
- Add getDeploymentForBeneficiary() in services/api.ts
  - Fetches beneficiary from WellNuo API
  - Returns deployment_id with proper error handling
  - Returns ApiResponse<number> with typed errors
- Refactor attachDeviceToBeneficiary() to use new method
  - Reduces code duplication
  - Improves separation of concerns
- Add comprehensive test suite
  - Tests successful deployment lookup
  - Tests authentication errors
  - Tests missing deployment scenarios
  - Tests network error handling
  - Tests edge cases (string IDs, 0 values, empty strings)

Benefits:
- Deployment lookup now reusable across codebase
- Better error handling with specific error codes
- Easier to test and maintain
- Follows DRY principle

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-01-31 16:00:11 -08:00
70f9a91be1 Remove console.log statements from codebase
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>
2026-01-29 12:44:16 -08:00
f6ba2a906a Fix race conditions when quickly switching beneficiaries
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>
2026-01-29 12:33:57 -08:00
69c999729f Fix BLE connections not disconnecting on logout
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>
2026-01-29 12:19:46 -08:00
521ff52344 Add comprehensive testing and documentation for role-based UI permissions
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>
2026-01-29 11:39:18 -08:00
88fc9042a7 Add retry button to error states in equipment and subscription screens
- 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>
2026-01-29 11:27:19 -08:00