All files / src/viewmodels/profile useProfileViewModel.ts

55.15% Statements 91/165
49.15% Branches 29/59
60.86% Functions 14/23
56.95% Lines 86/151

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 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 3881x 1x 1x 1x       1x                 1x 1x 1x 1x                                                                                                                                                                                     47x   47x 47x     47x   46x       47x                         11x 11x   11x 33x 36x 35x 35x       11x             12x 35x     1x 28x   28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x   28x   15x 1x 1x 1x 1x 1x 1x 1x 1x 1x     14x 14x   14x             14x             11x 11x 11x 12x   11x             34x 11x 11x 11x         11x         11x           2x 2x 2x 2x 2x 2x 1x   1x     13x           28x 14x     28x 14x 14x         28x 1x     28x                                                                                                                                                                                             28x 28x 28x   28x                                          
import { useState, useCallback, useEffect, useRef } from 'react';
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import { UserProfile } from '@/models/profile';
import type { ProfileEventSummary } from '@/models/profile';
import type { PrivacyLevel } from '@/models/event';
import {
  confirmProfileAvatarUpload,
  getMyCanceledEvents,
  getMyCompletedEvents,
  getMyHostedEvents,
  getMyProfile,
  getProfileAvatarUploadUrl,
  getMyUpcomingEvents,
} from '@/services/profileService';
import { ApiError } from '@/services/api';
import { useAuth } from '@/contexts/AuthContext';
import { uploadFileToPresignedUrl } from '@/services/eventService';
import { shouldShowProfileEvent } from '@/utils/eventStatus';
 
export interface ProfileEventItem {
  id: string;
  title: string;
  start_time: string;
  end_time?: string | null;
  image_url?: string | null;
  category_label: string;
  status: string;
  privacy_level: PrivacyLevel | null;
}
 
export interface ProfileViewModel {
  profile: UserProfile | null;
  isLoading: boolean;
  isUploadingAvatar: boolean;
  apiError: string | null;
  imageError: string | null;
  imageUploadSuccessMessage: string | null;
  primaryName: string;
  secondaryName: string | null;
  avatarInitial: string;
  overallRatingLabel: string;
  hostRatingLabel: string;
  participantRatingLabel: string;
  hostedEvents: ProfileEventItem[];
  attendedEvents: ProfileEventItem[];
  hostedCount: number;
  attendedCount: number;
  pickAvatar: () => Promise<void>;
  refresh: () => Promise<void>;
}
 
function decodeFileUriOnce(uri: string): string {
  if (!uri.startsWith('file://')) {
    return uri;
  }
 
  try {
    return `file://${decodeURIComponent(uri.slice('file://'.length))}`;
  } catch {
    return uri;
  }
}
 
function normalizePickedImageUri(uri: string): string {
  let normalized = uri;
 
  for (let i = 0; i < 3; i += 1) {
    const next = decodeFileUriOnce(normalized);
    if (next === normalized) break;
    normalized = next;
  }
 
  return normalized;
}
 
function getPickedImageUriCandidates(uri: string): string[] {
  return [...new Set([uri, decodeFileUriOnce(uri), normalizePickedImageUri(uri)])];
}
 
async function preparePickedImageUri(uri: string): Promise<string> {
  let lastError: unknown = null;
 
  for (const candidateUri of getPickedImageUriCandidates(uri)) {
    try {
      const preparedImage = await ImageManipulator.manipulateAsync(
        candidateUri,
        [],
        { compress: 0.9, format: ImageManipulator.SaveFormat.JPEG },
      );
      return preparedImage.uri;
    } catch (error) {
      lastError = error;
    }
  }
 
  throw lastError ?? new Error('Could not prepare the selected image');
}
 
async function selectAvatarImage(): Promise<ImagePicker.ImagePickerResult> {
  return ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],
    allowsEditing: true,
    aspect: [1, 1],
    quality: 0.8,
  });
}
 
function normalizeEndTime(value?: string | null): string | null {
  Iif (!value) return null;
 
  const trimmed = value.trim();
  Iif (!trimmed) return null;
 
  // Some profile-event endpoints serialize missing end times as Go's zero time.
  if (trimmed.startsWith('0001-01-01')) return null;
 
  return trimmed;
}
 
function mapProfileEvent(event: ProfileEventSummary): ProfileEventItem {
  return {
    id: event.id,
    title: event.title,
    start_time: event.start_time,
    end_time: normalizeEndTime(event.end_time),
    image_url: event.image_url ?? null,
    category_label: event.category ?? 'Event',
    status: event.status,
    privacy_level: event.privacy_level ?? null,
  };
}
 
function mergeEventsById(...groups: ProfileEventSummary[][]): ProfileEventItem[] {
  const seen = new Set<string>();
  const merged: ProfileEventItem[] = [];
 
  for (const group of groups) {
    for (const event of group) {
      if (seen.has(event.id)) continue;
      seen.add(event.id);
      merged.push(mapProfileEvent(event));
    }
  }
 
  return merged;
}
 
function excludeHostedEvents(
  events: ProfileEventItem[],
  hosted: ProfileEventItem[],
): ProfileEventItem[] {
  const hostedIds = new Set(hosted.map((event) => event.id));
  return events.filter((event) => !hostedIds.has(event.id));
}
 
export function useProfileViewModel(): ProfileViewModel {
  const { token } = useAuth();
 
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [hostedEvents, setHostedEvents] = useState<ProfileEventItem[]>([]);
  const [attendedEvents, setAttendedEvents] = useState<ProfileEventItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);
  const [imageUploadSuccessMessage, setImageUploadSuccessMessage] = useState<string | null>(null);
  const imageUploadSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [overallRatingLabel, setOverallRatingLabel] = useState('New');
  const [hostRatingLabel, setHostRatingLabel] = useState('New');
  const [participantRatingLabel, setParticipantRatingLabel] = useState('New');
 
  const fetchProfile = useCallback(
    async (mode: 'initial' | 'refresh') => {
      if (!token) {
        setProfile(null);
        setHostedEvents([]);
        setAttendedEvents([]);
        setOverallRatingLabel('New');
        setHostRatingLabel('New');
        setParticipantRatingLabel('New');
        setApiError('You must be logged in to view your profile.');
        setIsLoading(false);
        return;
      }
 
      if (mode === 'initial') setIsLoading(true);
      setApiError(null);
 
      try {
        const [
          profileResult,
          hostedResult,
          upcomingResult,
          completedResult,
          canceledResult,
        ] = await Promise.all([
          getMyProfile(token),
          getMyHostedEvents(token),
          getMyUpcomingEvents(token),
          getMyCompletedEvents(token),
          getMyCanceledEvents(token),
        ]);
        setProfile(profileResult);
        const allHostedEvents = hostedResult.events.map(mapProfileEvent);
        const visibleHostedEvents = allHostedEvents.filter((event) =>
          shouldShowProfileEvent(event.status),
        );
        const mergedAttendedEvents = excludeHostedEvents(
          mergeEventsById(
            upcomingResult.events,
            completedResult.events,
            canceledResult.events,
          ),
          allHostedEvents,
        ).filter((event) => shouldShowProfileEvent(event.status));
        setHostedEvents(visibleHostedEvents);
        setAttendedEvents(mergedAttendedEvents);
        setOverallRatingLabel(
          profileResult.final_score != null
            ? profileResult.final_score.toFixed(1)
            : 'New',
        );
        setHostRatingLabel(
          profileResult.host_score?.score != null
            ? profileResult.host_score.score.toFixed(1)
            : 'New',
        );
        setParticipantRatingLabel(
          profileResult.participant_score?.score != null
            ? profileResult.participant_score.score.toFixed(1)
            : 'New',
        );
      } catch (err) {
        setHostedEvents([]);
        setAttendedEvents([]);
        setOverallRatingLabel('New');
        setHostRatingLabel('New');
        setParticipantRatingLabel('New');
        if (err instanceof ApiError) {
          setApiError(err.message);
        } else {
          setApiError('Failed to load profile. Please try again.');
        }
      } finally {
        setIsLoading(false);
      }
    },
    [token],
  );
 
  useEffect(() => {
    void fetchProfile('initial');
  }, [token]);
 
  useEffect(
    () => () => {
      Iif (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
    },
    [],
  );
 
  const refresh = useCallback(async () => {
    await fetchProfile('refresh');
  }, [fetchProfile]);
 
  const pickAvatar = useCallback(async () => {
    if (!token) {
      setImageError('You must be logged in to update your profile photo.');
      return;
    }
 
    setImageError(null);
    if (imageUploadSuccessTimerRef.current) {
      clearTimeout(imageUploadSuccessTimerRef.current);
      imageUploadSuccessTimerRef.current = null;
    }
    setImageUploadSuccessMessage(null);
    try {
      const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
 
      if (permission.status !== 'granted') {
        const message = 'Please allow access to your photo library to add a profile photo.';
        setImageError(message);
        Alert.alert('Permission required', message);
        return;
      }
 
      const result = await selectAvatarImage();
      if (result.canceled) return;
 
      const asset = result.assets[0];
      if (!asset?.uri) {
        setImageError('We could not read the selected image. Please try a different one.');
        return;
      }
 
      let preparedImageUri: string;
      try {
        preparedImageUri = await preparePickedImageUri(asset.uri);
      } catch {
        setImageError('We could not process the selected image. Please try a different one.');
        return;
      }
 
      setIsUploadingAvatar(true);
 
      const original = await ImageManipulator.manipulateAsync(
        preparedImageUri,
        [{ resize: { width: 1200 } }],
        { compress: 0.8, format: ImageManipulator.SaveFormat.JPEG },
      );
 
      const small = await ImageManipulator.manipulateAsync(
        preparedImageUri,
        [{ resize: { width: 400 } }],
        { compress: 0.7, format: ImageManipulator.SaveFormat.JPEG },
      );
 
      const uploadInit = await getProfileAvatarUploadUrl(token);
      const originalUpload = uploadInit.uploads.find((u) => u.variant === 'ORIGINAL');
      const smallUpload = uploadInit.uploads.find((u) => u.variant === 'SMALL');
 
      if (!originalUpload || !smallUpload) {
        throw new Error('Missing upload instructions from server');
      }
 
      await Promise.all([
        uploadFileToPresignedUrl(
          originalUpload.method,
          originalUpload.url,
          originalUpload.headers,
          original.uri,
        ),
        uploadFileToPresignedUrl(
          smallUpload.method,
          smallUpload.url,
          smallUpload.headers,
          small.uri,
        ),
      ]);
 
      await confirmProfileAvatarUpload(uploadInit.confirm_token, token);
      await refresh();
      if (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
      setImageUploadSuccessMessage('Profile photo updated successfully.');
      imageUploadSuccessTimerRef.current = setTimeout(() => {
        setImageUploadSuccessMessage(null);
        imageUploadSuccessTimerRef.current = null;
      }, 5000);
    } catch (error) {
      if (error instanceof ApiError) {
        setImageError(error.message);
      } else {
        setImageError('We could not upload the selected image. Please try again.');
      }
    } finally {
      setIsUploadingAvatar(false);
    }
  }, [refresh, token]);
 
  const primaryName = profile?.display_name ?? profile?.username ?? '';
  const secondaryName = profile?.display_name ? profile.username : null;
  const avatarInitial = primaryName.trim().charAt(0).toUpperCase() || '?';
 
  return {
    profile,
    isLoading,
    isUploadingAvatar,
    apiError,
    imageError,
    imageUploadSuccessMessage,
    primaryName,
    secondaryName,
    avatarInitial,
    overallRatingLabel,
    hostRatingLabel,
    participantRatingLabel,
    hostedEvents,
    attendedEvents,
    hostedCount: hostedEvents.length,
    attendedCount: attendedEvents.length,
    pickAvatar,
    refresh,
  };
}