import { ITGlueClient } from '../client'; import { QueryUtilOptions, QueryParams, RequestBody, BaseListResponse, BaseItemResponse, UserResource } from '../types'; /** * Users resource module for IT Glue API * Provides methods to interact with the /users endpoint. * Users represent IT Glue user accounts and their information, including * personal details, roles, permissions, and account status. This resource * manages user accounts within your IT Glue organization, allowing you to * view user information and update certain user attributes. * **Note: This resource has limited operations.** User creation and deletion * are typically managed through the IT Glue web interface or administrative * functions, not through the API. The API provides read access and limited * update capabilities for existing users. * ## Related Resources * Users are commonly used with: * - {@link Groups} - User group memberships and role-based permissions * - {@link UserMetrics} - Activity statistics and usage analytics for users * - {@link Organizations} - Organizations that users have access to manage * - {@link Contacts} - Personal contact information may be linked to user accounts * - {@link Documents} - Documents created, modified, or assigned to users * - {@link Passwords} - Password entries created or managed by users * - {@link Configurations} - IT assets assigned to or managed by users * - {@link FlexibleAssets} - Custom assets created or maintained by users * - {@link RelatedItems} - Cross-resource relationships created by users * - {@link Tags} - Categorization tags applied by users to resources * - {@link Exports} - Data exports requested by users * - {@link Expirations} - Expiring items that users need to monitor or renew * @see {@link Groups#list} for retrieving user groups and permissions * @see {@link UserMetrics#list} for retrieving user activity metrics * @see {@link Organizations#list} for retrieving organizations accessible to users * @see {@link Documents#list} for retrieving documents by user * @example * import { ITGlueClient } from '../client'; * import { Users } from './resources/users'; * const client = new ITGlueClient({ apiKey: 'your-api-key' }); * const users = new Users(client); * // List users * const list = await users.list(); * // Get a single user * const user = await users.get('123'); * // Update a user (JSON:API format) * const updated = await users.update('123', { * data: { * type: 'users', * attributes: { * first_name: 'John', * last_name: 'Doe' * } * } * }); * @category System & Audit */ export declare class Users { private client; private basePath; private paginationUtil; /** * Create a Users resource instance * @param {ITGlueClient} client - ITGlueClient instance */ constructor(client: ITGlueClient); /** * List all users * Retrieves a list of all users in your IT Glue organization. This includes * user account information, roles, status, and basic profile details. Use * filtering options to find specific users by email, role, or status. * @param {QueryUtilOptions} [options] - Optional query parameters (filter, sort, page, etc.) * @param {boolean} [allPages=false] - If true, fetches all pages automatically * @returns {Promise>} List of users and pagination metadata * @example * // Basic usage - get first page of users * const results = await client.users.list(); * console.log(`Found ${results.data.length} users`); * console.log('Total pages:', results.meta.pagination.total_pages); * @example * // Advanced usage with pagination and sorting * const results = await client.users.list({ * page: { number: 2, size: 50 }, * sort: '-last_sign_in_at', // Sort by most recently active * include: ['groups', 'user_metrics'] // Include related data * }); * @example * // Filtering users by role and status * const activeAdmins = await client.users.list({ * filter: { * role: 'Administrator', * status: 'active' * }, * sort: 'last_name' * }); * @example * // Get all users across multiple pages * const allUsers = await client.users.list({}, true); // allPages = true * console.log(`Retrieved all ${allUsers.data.length} users`); * @example * // Manual pagination for user management * async function getAllActiveUsers() { * let page = 1; * let allUsers = []; * let hasMore = true; * while (hasMore) { * const response = await client.users.list({ * filter: { status: 'active' }, * page: { number: page, size: 100 }, * sort: 'email' * }); * allUsers = [...allUsers, ...response.data]; * hasMore = response.meta.pagination.total_pages > page; * page++; * } * return allUsers; * } * @example * // Error handling for list operations * try { * const results = await client.users.list({ * filter: { invalid_field: 'value' } * }); * } catch (error) { * if (error.response?.status === 400) { * console.log('Invalid filter parameters:', error.response.data.errors); * } else if (error.response?.status === 401) { * console.log('Authentication failed - check your API key'); * } else if (error.response?.status === 403) { * console.log('Access denied - insufficient permissions to list users'); * } else { * console.log('Request failed:', error.message); * } * } */ list(options?: QueryUtilOptions, allPages?: boolean): Promise>; /** * Get a single user by ID * Retrieves detailed information about a specific user account, including * personal details, role information, account status, and associated groups. * This is useful for viewing user profiles and checking permissions. * @param {string} id - User ID (required) * @param {QueryParams} [params] - Optional query parameters * @returns {Promise>} User resource * @throws {Error} When user not found (404) or access denied (403) * @example * // Basic usage - get user by ID * const user = await client.users.get('123'); * console.log('User name:', `${user.data.attributes.first_name} ${user.data.attributes.last_name}`); * console.log('Email:', user.data.attributes.email); * console.log('Role:', user.data.attributes.role); * @example * // Get user with related data included * const userWithRelated = await client.users.get('123', { * include: ['groups', 'user_metrics'] * }); * // Access included data * const included = userWithRelated.included || []; * const groups = included.filter(item => item.type === 'groups'); * const metrics = included.find(item => item.type === 'user_metrics'); * @example * // Error handling for get operations * try { * const user = await client.users.get('invalid-id'); * } catch (error) { * if (error.response?.status === 404) { * console.log('User not found'); * } else if (error.response?.status === 403) { * console.log('Access denied - insufficient permissions'); * } else { * console.log('Error retrieving user:', error.message); * } * } * @example * // Safe get with existence check * async function safeGetUser(id) { * try { * const user = await client.users.get(id); * return user.data; * } catch (error) { * if (error.response?.status === 404) { * return null; // User doesn't exist * } * throw error; // Re-throw other errors * } * } * @see * {@link Groups#get} - Get specific group details * {@link Groups#list} - List groups related to users * {@link UserMetrics#get} - Get specific usermetric details * {@link UserMetrics#list} - List usermetrics related to users */ get(id: string, params?: QueryParams): Promise>; /** * Create a new user * **Note: This operation may not be available through the API.** User creation * is typically managed through the IT Glue web interface or administrative * functions. Check your API permissions and IT Glue plan for availability. * @param {RequestBody} data - User data (must be formatted according to JSON:API spec) * @returns {Promise>} Created user resource * @throws {Error} When operation not permitted (403) or validation fails (422) * @example * // Basic user creation (if permitted) * const newUser = await client.users.create({ * data: { * type: 'users', * attributes: { * first_name: 'Jane', * last_name: 'Doe', * email: 'jane.doe@example.com', * role: 'Manager' * } * } * }); * console.log('Created user with ID:', newUser.data.id); * @example * // Advanced user creation with all fields * const newUser = await client.users.create({ * data: { * type: 'users', * attributes: { * first_name: 'John', * last_name: 'Smith', * email: 'john.smith@company.com', * role: 'Administrator', * status: 'active', * phone: '+1-555-0123', * title: 'IT Manager', * notes: 'Primary system administrator' * } * } * }); * @example * // Bulk user creation with error handling * async function createMultipleUsers(userList) { * const results = []; * const errors = []; * for (const userData of userList) { * try { * const created = await client.users.create({ * data: { * type: 'users', * attributes: userData * } * }); * results.push(created.data); * } catch (error) { * errors.push({ userData, error: error.message }); * } * } * return { results, errors }; * } * @example * // Error handling for user creation * try { * const created = await client.users.create({ * data: { * type: 'users', * attributes: { * first_name: 'Test', * // Missing required email field * } * } * }); * } catch (error) { * if (error.response?.status === 403) { * console.log('User creation not permitted through API'); * } else if (error.response?.status === 422) { * console.log('Validation errors:'); * error.response.data.errors.forEach(err => { * console.log(`- ${err.detail} (${err.source?.pointer})`); * }); * } else if (error.response?.status === 409) { * console.log('User with this email already exists'); * } else { * console.log('Creation failed:', error.message); * } * } * @see * {@link Groups#create} - Create new group * {@link Groups#list} - List groups related to users * {@link UserMetrics#list} - List usermetrics related to users */ create(data: RequestBody): Promise>; /** * Update a user by ID * Updates specific attributes of an existing user account. Typically allows * modification of personal information, role assignments, and account status. * Some fields may be restricted based on your permissions and the user's role. * @param {string} id - User ID (required) * @param {RequestBody} data - Updated user data (must be formatted according to JSON:API spec) * @returns {Promise>} Updated user resource * @throws {Error} When user not found (404), access denied (403), or validation fails (422) * @example * // Basic update - modify personal information * const updatedUser = await client.users.update('123', { * data: { * type: 'users', * attributes: { * first_name: 'John', * last_name: 'Doe', * email: 'john.doe@example.com' * } * } * }); * console.log('Updated user:', updatedUser.data.attributes.email); * @example * // Update user role and status * const updatedUser = await client.users.update('123', { * data: { * type: 'users', * attributes: { * role: 'Administrator', * status: 'active', * title: 'Senior IT Administrator' * } * } * }); * @example * // Conditional update based on current state * async function conditionalUpdateUser(id, updates) { * try { * // First, get current state * const current = await client.users.get(id); * // Check if update is needed * const needsUpdate = Object.keys(updates).some( * key => current.data.attributes[key] !== updates[key] * ); * if (!needsUpdate) { * console.log('User is already up to date'); * return current; * } * // Perform update * return await client.users.update(id, { * data: { * type: 'users', * attributes: updates * } * }); * } catch (error) { * console.error('Update failed:', error.message); * throw error; * } * } * @example * // Error handling for user updates * try { * const updated = await client.users.update('123', { * data: { * type: 'users', * attributes: { * role: 'InvalidRole' * } * } * }); * } catch (error) { * if (error.response?.status === 404) { * console.log('User not found'); * } else if (error.response?.status === 403) { * console.log('Insufficient permissions to update user'); * } else if (error.response?.status === 422) { * console.log('Validation failed:', error.response.data.errors); * } else if (error.response?.status === 409) { * console.log('Conflict - user may have been modified by another admin'); * } else { * console.log('Update failed:', error.message); * } * } * @see * {@link Groups#update} - Update group * {@link Groups#get} - Get specific group details * {@link UserMetrics#get} - Get specific usermetric details */ update(id: string, data: RequestBody): Promise>; /** * Delete a user by ID * **Note: This operation may not be available through the API.** User deletion * is typically managed through the IT Glue web interface or administrative * functions for security and audit purposes. Check your API permissions and * IT Glue plan for availability. * @param {string} id - User ID (required) * @returns {Promise} * @throws {Error} When operation not permitted (403), user not found (404), or user has dependencies (409) * @example * // Basic deletion (if permitted) * await client.users.delete('123'); * console.log('User deleted successfully'); * @example * // Safe deletion with confirmation * async function safeDeleteUser(id) { * try { * // First verify the user exists * const user = await client.users.get(id); * console.log(`Deleting user: ${user.data.attributes.email}`); * // Perform deletion * await client.users.delete(id); * console.log('User deleted successfully'); * return true; * } catch (error) { * if (error.response?.status === 404) { * console.log('User not found - may already be deleted'); * return false; * } * throw error; * } * } * @example * // Bulk deletion with error handling * async function deleteMultipleUsers(userIds) { * const results = []; * for (const id of userIds) { * try { * await client.users.delete(id); * results.push({ id, status: 'deleted' }); * } catch (error) { * results.push({ * id, * status: 'error', * error: error.response?.status === 404 ? 'not_found' : error.message * }); * } * } * return results; * } * @example * // Error handling for user deletion * try { * await client.users.delete('123'); * } catch (error) { * if (error.response?.status === 403) { * console.log('User deletion not permitted through API'); * } else if (error.response?.status === 404) { * console.log('User not found - may already be deleted'); * } else if (error.response?.status === 409) { * console.log('Cannot delete user with existing dependencies or active sessions'); * } else { * console.log('Deletion failed:', error.message); * } * } * @see * {@link Groups#list} - List groups related to users * {@link Groups#get} - Get specific group details * {@link UserMetrics#list} - List usermetrics related to users * {@link UserMetrics#get} - Get specific usermetric details */ delete(id: string): Promise; }