All files / services pushNotifications.ts

0% Statements 0/59
0% Branches 0/26
0% Functions 0/10
0% Lines 0/59

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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
/**
 * Push Notifications Service
 *
 * Handles:
 * - Requesting push notification permissions
 * - Getting Expo Push Token
 * - Registering/unregistering token on server
 * - Handling incoming notifications
 */
 
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import { Platform } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import Constants from 'expo-constants';
 
const WELLNUO_API_URL = 'https://wellnuo.smartlaunchhub.com/api';
const PUSH_TOKEN_KEY = 'expoPushToken';
 
// Configure notification handler for foreground notifications
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
    shouldShowBanner: true,
    shouldShowList: true,
  }),
});
 
/**
 * Register for push notifications and get Expo Push Token
 * Returns the token or null if not available
 */
export async function registerForPushNotificationsAsync(): Promise<string | null> {
  let token: string | null = null;
 
  // Must be a physical device for push notifications
  if (!Device.isDevice) {
    // For simulator, return a fake token for testing
    if (__DEV__) {
      return 'ExponentPushToken[SIMULATOR_TEST_TOKEN]';
    }
    return null;
  }
 
  // Check/request permissions
  const { status: existingStatus } = await Notifications.getPermissionsAsync();
  let finalStatus = existingStatus;
 
  if (existingStatus !== 'granted') {
    const { status } = await Notifications.requestPermissionsAsync();
    finalStatus = status;
  }
 
  if (finalStatus !== 'granted') {
    return null;
  }
 
  // Get Expo Push Token
  try {
    const projectId = Constants.expoConfig?.extra?.eas?.projectId;
 
    const pushTokenResponse = await Notifications.getExpoPushTokenAsync({
      projectId: projectId,
    });
 
    token = pushTokenResponse.data;
 
    // Store locally
    await SecureStore.setItemAsync(PUSH_TOKEN_KEY, token);
  } catch (error) {
    return null;
  }
 
  // Android needs notification channel
  if (Platform.OS === 'android') {
    await Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });
 
    // Emergency alerts channel
    await Notifications.setNotificationChannelAsync('emergency', {
      name: 'Emergency Alerts',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 500, 200, 500],
      lightColor: '#FF0000',
      sound: 'default',
    });
  }
 
  return token;
}
 
/**
 * Register push token on WellNuo backend
 */
export async function registerTokenOnServer(token: string): Promise<boolean> {
  try {
    const accessToken = await SecureStore.getItemAsync('accessToken');
 
    if (!accessToken) {
      return false;
    }
 
    const response = await fetch(`${WELLNUO_API_URL}/push-tokens`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`,
      },
      body: JSON.stringify({
        token,
        platform: Platform.OS,
        deviceName: Device.deviceName || `${Device.brand} ${Device.modelName}`,
      }),
    });
 
    if (!response.ok) {
      const error = await response.json();
      return false;
    }
 
    return true;
  } catch (error) {
    return false;
  }
}
 
/**
 * Unregister push token from server (call on logout)
 */
export async function unregisterToken(): Promise<boolean> {
  try {
    const token = await SecureStore.getItemAsync(PUSH_TOKEN_KEY);
    const accessToken = await SecureStore.getItemAsync('accessToken');
 
    if (!token || !accessToken) {
      return true; // Nothing to unregister
    }
 
    const response = await fetch(`${WELLNUO_API_URL}/push-tokens`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${accessToken}`,
      },
      body: JSON.stringify({ token }),
    });
 
    // Clear local storage regardless of server response
    await SecureStore.deleteItemAsync(PUSH_TOKEN_KEY);
 
    if (!response.ok) {
      return false;
    }
 
    return true;
  } catch (error) {
    // Still clear local storage
    await SecureStore.deleteItemAsync(PUSH_TOKEN_KEY);
    return false;
  }
}
 
/**
 * Full registration flow: get token + register on server
 * Call this after successful login
 */
export async function setupPushNotifications(): Promise<string | null> {
 
  const token = await registerForPushNotificationsAsync();
 
  if (token) {
    await registerTokenOnServer(token);
  }
 
  return token;
}
 
/**
 * Get stored push token (if any)
 */
export async function getStoredPushToken(): Promise<string | null> {
  try {
    return await SecureStore.getItemAsync(PUSH_TOKEN_KEY);
  } catch {
    return null;
  }
}
 
/**
 * Add listener for received notifications (while app is open)
 */
export function addNotificationReceivedListener(
  callback: (notification: Notifications.Notification) => void
): Notifications.EventSubscription {
  return Notifications.addNotificationReceivedListener(callback);
}
 
/**
 * Add listener for notification response (user tapped notification)
 */
export function addNotificationResponseListener(
  callback: (response: Notifications.NotificationResponse) => void
): Notifications.EventSubscription {
  return Notifications.addNotificationResponseReceivedListener(callback);
}
 
/**
 * Get last notification response (if app was opened from notification)
 */
export async function getLastNotificationResponse(): Promise<Notifications.NotificationResponse | null> {
  return await Notifications.getLastNotificationResponseAsync();
}
 
/**
 * Parse notification data to determine navigation target
 */
export function parseNotificationData(data: Record<string, unknown>): {
  type: string;
  deploymentId?: number;
  beneficiaryId?: number;
  alertId?: string;
} {
  return {
    type: (data.type as string) || 'unknown',
    deploymentId: data.deploymentId as number | undefined,
    beneficiaryId: data.beneficiaryId as number | undefined,
    alertId: data.alertId as string | undefined,
  };
}