All files / contexts BeneficiaryContext.tsx

0% Statements 0/80
0% Branches 0/42
0% Functions 0/13
0% Lines 0/77

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211                                                                                                                                                                                                                                                                                                                                                                                                                                     
import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import type { Beneficiary, BeneficiarySubscription } from '@/types';
 
const LOCAL_BENEFICIARIES_KEY = 'wellnuo_local_beneficiaries';
 
interface AddBeneficiaryData {
  name: string;
  address?: string;
  avatar?: string;
  subscription?: BeneficiarySubscription;
}
 
interface BeneficiaryContextType {
  currentBeneficiary: Beneficiary | null;
  setCurrentBeneficiary: (beneficiary: Beneficiary | null) => void;
  clearCurrentBeneficiary: () => void;
  // Local beneficiaries management (for users without API deployments)
  localBeneficiaries: Beneficiary[];
  addLocalBeneficiary: (data: string | AddBeneficiaryData) => Promise<Beneficiary>;
  updateLocalBeneficiary: (id: number, data: Partial<Beneficiary>) => Promise<Beneficiary | null>;
  removeLocalBeneficiary: (id: number) => Promise<void>;
  // Clear all data (used on logout)
  clearAllBeneficiaryData: () => Promise<void>;
  // Helper to format beneficiary context for AI
  getBeneficiaryContext: () => string;
}
 
const BeneficiaryContext = createContext<BeneficiaryContextType | undefined>(undefined);
 
export function BeneficiaryProvider({ children }: { children: React.ReactNode }) {
  const [currentBeneficiary, setCurrentBeneficiary] = useState<Beneficiary | null>(null);
  const [localBeneficiaries, setLocalBeneficiaries] = useState<Beneficiary[]>([]);
 
  // Load local beneficiaries on mount
  useEffect(() => {
    loadLocalBeneficiaries();
  }, []);
 
  const loadLocalBeneficiaries = async () => {
    try {
      const stored = await AsyncStorage.getItem(LOCAL_BENEFICIARIES_KEY);
      if (stored) {
        setLocalBeneficiaries(JSON.parse(stored));
      }
    } catch (error) {
      // Failed to load local beneficiaries
    }
  };
 
  const saveLocalBeneficiaries = async (beneficiaries: Beneficiary[]) => {
    try {
      await AsyncStorage.setItem(LOCAL_BENEFICIARIES_KEY, JSON.stringify(beneficiaries));
    } catch (error) {
      // Failed to save local beneficiaries
    }
  };
 
  const addLocalBeneficiary = useCallback(async (data: string | AddBeneficiaryData): Promise<Beneficiary> => {
    // Support both string (legacy) and object format
    const beneficiaryData: AddBeneficiaryData = typeof data === 'string'
      ? { name: data }
      : data;
 
    const newBeneficiary: Beneficiary = {
      id: Date.now(), // Use timestamp as unique ID
      name: beneficiaryData.name.trim(),
      displayName: beneficiaryData.name.trim(), // For UI display
      address: beneficiaryData.address?.trim(),
      avatar: beneficiaryData.avatar,
      status: 'offline',
      last_activity: 'Just added',
      subscription: beneficiaryData.subscription,
    };
 
    const updated = [...localBeneficiaries, newBeneficiary];
    setLocalBeneficiaries(updated);
    await saveLocalBeneficiaries(updated);
 
    // Auto-select if first beneficiary
    if (localBeneficiaries.length === 0) {
      setCurrentBeneficiary(newBeneficiary);
    }
 
    return newBeneficiary;
  }, [localBeneficiaries]);
 
  const updateLocalBeneficiary = useCallback(async (id: number, data: Partial<Beneficiary>): Promise<Beneficiary | null> => {
    const index = localBeneficiaries.findIndex(b => b.id === id);
    if (index === -1) return null;
 
    const updatedBeneficiary = { ...localBeneficiaries[index], ...data };
    const updated = [...localBeneficiaries];
    updated[index] = updatedBeneficiary;
 
    setLocalBeneficiaries(updated);
    await saveLocalBeneficiaries(updated);
 
    // Update current if it's the same beneficiary
    if (currentBeneficiary?.id === id) {
      setCurrentBeneficiary(updatedBeneficiary);
    }
 
    return updatedBeneficiary;
  }, [localBeneficiaries, currentBeneficiary]);
 
  const removeLocalBeneficiary = useCallback(async (id: number) => {
    const updated = localBeneficiaries.filter(b => b.id !== id);
    setLocalBeneficiaries(updated);
    await saveLocalBeneficiaries(updated);
 
    // Clear current if removed
    if (currentBeneficiary?.id === id) {
      setCurrentBeneficiary(updated[0] || null);
    }
  }, [localBeneficiaries, currentBeneficiary]);
 
  const clearCurrentBeneficiary = useCallback(() => {
    setCurrentBeneficiary(null);
  }, []);
 
  // Clear all beneficiary data (called on logout)
  const clearAllBeneficiaryData = useCallback(async () => {
    setCurrentBeneficiary(null);
    setLocalBeneficiaries([]);
    await AsyncStorage.removeItem(LOCAL_BENEFICIARIES_KEY);
  }, []);
 
  const getBeneficiaryContext = useCallback(() => {
    if (!currentBeneficiary) {
      return '';
    }
 
    const b = currentBeneficiary;
    const contextParts: string[] = [];
 
    // Basic info
    contextParts.push(`Person: ${b.name}`);
 
    if (b.address) {
      contextParts.push(`Address: ${b.address}`);
    }
 
    // Current status
    if (b.last_location) {
      contextParts.push(`Current location: ${b.last_location}`);
    }
 
    if (b.before_last_location) {
      contextParts.push(`Previous location: ${b.before_last_location}`);
    }
 
    // Health metrics
    if (b.wellness_score !== undefined) {
      contextParts.push(`Wellness score: ${b.wellness_score}% (${b.wellness_descriptor || 'N/A'})`);
    }
 
    // Temperature
    if (b.temperature !== undefined) {
      const unit = b.units || '°F';
      contextParts.push(`Room temperature: ${b.temperature.toFixed(1)}${unit}`);
    }
 
    if (b.bedroom_temperature !== undefined) {
      const unit = b.units || '°F';
      contextParts.push(`Bedroom temperature: ${b.bedroom_temperature.toFixed(1)}${unit}`);
    }
 
    // Sleep data
    if (b.sleep_hours !== undefined) {
      contextParts.push(`Sleep hours: ${b.sleep_hours.toFixed(1)} hours`);
    }
 
    // Activity time
    if (b.last_detected_time) {
      contextParts.push(`Last detected: ${b.last_detected_time}`);
    }
 
    // Status
    contextParts.push(`Status: ${b.status === 'online' ? 'Active' : 'Inactive'}`);
 
    return `[SENSOR DATA FOR ${b.name.toUpperCase()}: ${contextParts.join('. ')}]`;
  }, [currentBeneficiary]);
 
  return (
    <BeneficiaryContext.Provider
      value={{
        currentBeneficiary,
        setCurrentBeneficiary,
        clearCurrentBeneficiary,
        localBeneficiaries,
        addLocalBeneficiary,
        updateLocalBeneficiary,
        removeLocalBeneficiary,
        clearAllBeneficiaryData,
        getBeneficiaryContext,
      }}
    >
      {children}
    </BeneficiaryContext.Provider>
  );
}
 
export function useBeneficiary() {
  const context = useContext(BeneficiaryContext);
  if (context === undefined) {
    throw new Error('useBeneficiary must be used within a BeneficiaryProvider');
  }
  return context;
}