All files / src/api user-api.ts

83.07% Statements 265/319
57.57% Branches 19/33
100% Functions 7/7
83.07% Lines 265/319

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 3201x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x         2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x             2x 3x 1x 1x 1x 1x 3x         3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x         2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 3x             2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 1x 1x 1x 1x 2x         2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 2x         2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x         2x  
import { USER_ENDPOINT } from "./types/endpoints";
import { User, UserClass, UserSectionStatus, UserStatus } from "./types/user";
 
/**
 * Updates the lock status of a user in the backend.
 *
 * @param userID - The user's unique identifier.
 * @param isLocked - Whether the user should be locked (`true`) or unlocked (`false`).
 * @returns An object indicating success or containing an error message.
 */
export async function updateLockUserInDatabase(
  userID: string,
  isLocked: boolean
): Promise<{ error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userID}/lock`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user_id: userID,
        is_locked: isLocked,
      }),
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to lock user: ${response.status} ${response.statusText}`,
      };
    }
 
    return {};
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
/**
 * Retrieves the user's current class-specific status.
 *
 * @param userId - The user's unique ID.
 * @param classId - (Optional) The class ID to filter status retrieval.
 * @returns An object containing the user's status or an error message.
 */
export async function getUserStatus(
  userId: string,
  classId?: string
): Promise<{ data?: UserStatus; error?: string }> {
  try {
    if (!classId) {
      return { data: UserStatus.ACTIVE };
    }
 
    const url = new URL(`${USER_ENDPOINT}/${userId}/class-status`);
    if (classId) {
      url.searchParams.append("class_id", classId);
    }
 
    const response = await fetch(url.toString(), {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
 
    const data = await response.json();
 
    console.log(data);
 
    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to get user class status: ${response.status} ${response.statusText}`,
      };
    }
 
    if (!data.data || data.data.user_class_status === undefined) {
      return { error: "Invalid response: Missing user status" };
    }
 
    return { data: data.data.user_class_status.user_class_status };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
/**
 * Updates the overall status (e.g., ACTIVE, SUSPENDED) of a user.
 *
 * @param userId - The user's unique ID.
 * @param status - The new status to assign.
 * @param userClassId - (Optional) Class ID if updating class-specific status.
 * @returns An object indicating success or an error message.
 */
export async function updateUserStatus(
  userId: string,
  status: UserStatus,
  userClassId?: string
): Promise<{ success?: boolean; error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userId}/status`, {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ status, userClassId }),
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to update user status: ${response.status} ${response.statusText}`,
      };
    }
 
    return { success: true };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
 
/**
 * Fetches detailed user information by their unique ID.
 *
 * @param userID - The user's unique identifier.
 * @returns An object containing the user data or an error message.
 */
export async function getUserByID(
  userID: string
): Promise<{ user?: User; error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userID}`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to get user: ${response.status} ${response.statusText}`,
      };
    }
 
    if (!data.data) {
      return { error: "Invalid response: Missing user data" };
    }
 
    const userData = data.data;
    console.log(data.data);
    const user: User = {
      id: userData.id,
      email: userData.email,
      first_name: userData.first_name,
      last_name: userData.last_name,
      isLocked: userData.is_locked,
      code_context_id: userData.code_context_id,
      isAuthenticated: true,
      userStatus: userData.status,
      role: userData.role,
      settings: userData.settings,
    };
    return { user: user };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
/**
 * Retrieves the section ID associated with a user.
 *
 * @param userId - The user's unique ID.
 * @param classId - (Optional) Class ID to filter sections.
 * @returns An object containing the user section ID or an error.
 */
export async function getUserSection(
  userId: string,
  classId?: string
): Promise<{ userSectionId?: string; error?: string }> {
  try {
    const url = new URL(`${USER_ENDPOINT}/${userId}/sections`);
    if (classId) {
      url.searchParams.append("class_id", classId);
    }
 
    const response = await fetch(url.toString(), {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.error ||
          `Failed to get user section: ${response.status} ${response.statusText}`,
      };
    }
 
    if (!data.data.user_section_id) {
      return { error: "Invalid response: Missing user_section_id" };
    }
 
    return { userSectionId: data.data.user_section_id };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
/**
 * Updates or creates a user section with a new status.
 *
 * @param userId - The user's unique ID.
 * @param status - The new status to assign to the section.
 * @param userSectionId - (Optional) Specific user section ID to update.
 * @returns An object indicating success or an error message.
 */
export async function updateUserSection(
  userId: string,
  status: UserSectionStatus,
  userSectionId?: string
): Promise<{ newUserSectionID?: string; error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userId}/sections`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        status,
        userSectionId,
      }),
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.error ||
          `Failed to update/create user section: ${response.status} ${response.statusText}`,
      };
    }
 
    return {};
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}
 
 
/**
 * Fetches all classes associated with a given user.
 *
 * @param userId - The user's unique ID.
 * @returns A promise resolving to an array of `UserClass` objects or an error.
 */
export async function getUserClasses(
  userId: string
): Promise<{ data?: UserClass[]; error?: string }> {
  try {
    const response = await fetch(`${USER_ENDPOINT}/${userId}/classes`, {
      method: "GET",
      headers: { "Content-Type": "application/json" },
    });
 
    const data = await response.json();
 
    if (!response.ok) {
      return {
        error:
          data.message ||
          `Failed to get user classes: ${response.status} ${response.statusText}`,
      };
    }
 
    if (!Array.isArray(data.data)) {
      return { error: "Invalid response: expected an array of classes" };
    }
 
    const classes = data.data.map((item: any) => {
      const classItem = item.userClass;
      return {
        id: classItem.id,
        classTitle: classItem.class_title,
        classCode: classItem.class_code,
        instructorId: classItem.instructor_id,
        classHexColor: classItem.class_hex_color,
        classImageCover: classItem.class_image_cover,
        createdAt: classItem.created_at,
      } as UserClass;
    });
 
    return { data: classes };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : "Unknown error occurred",
    };
  }
}