Resource Management Examples

Overview

These examples demonstrate how to manage resources in the RCAMS system, including districts, schools, groups, and WiFi settings. Resource management forms the foundation of your RCAMS integration, establishing the organizational structure for your emergency notification system.

Note: All resource management operations require proper authentication.

District and School Management

This example demonstrates how to manage districts and schools, including creating, retrieving, and organizing the hierarchical structure.

District and School Management Example (JavaScript)
// RCAMS Resource Management Example

// Helper function for making API requests
async function makeApiRequest(endpoint, params, apiCredentials) {
  const { username, password } = apiCredentials;
  
  // Create json data from params
  const json = {};
    for (const [key, value] of Object.entries(params)) {
      json[key] = value;
    }
    const jsonString = JSON.stringify(json);
  
  try {
    const response = await fetch(`https://rcamsapi.spheronomics.com/api/v2/${endpoint}`, {
      method: 'POST',
      headers: {
        'Authorization': 'Basic ' + btoa(`${username}:${password}`)
      },
      body: jsonString
    });
    
    return await response.json();
  } catch (error) {
    console.error(`API request to ${endpoint} failed:`, error);
    throw error;
  }
}

// District and School Management Example
async function resourceManagementExample() {
  
  // User credentials - replace with actual values
  const userCredentials = {
    email: 'user@example.com',     // Replace with actual user email
    password: 'user_password'      // Replace with actual user password
  };
  
  try {
    
    // Step 1: Create a new district
    console.log('Creating new district...');
    const createDistrictResponse = await makeApiRequest('district.php', {
      action: 'insert',
      district_name: 'Example School District'
    }, userCredentials);
    
    if (createDistrictResponse.status !== 'OK') {
      throw new Error(`Failed to create district: ${createDistrictResponse.message}`);
    }
    
    const districtId = createDistrictResponse.district_id;
    console.log(`District created successfully with ID: ${districtId}`);
    
    // Step 2: Create a new school in the district
    console.log('Creating new school...');
    const createSchoolResponse = await makeApiRequest('school.php', {
      action: 'insert',
      district_id: districtId,
      school_name: 'Example Elementary School',
      school_phone: '555-123-4567',
      school_email: 'info@example-school.edu',
      school_address: '123 Education Blvd'
    }, userCredentials);
    
    if (createSchoolResponse.status !== 'OK') {
      throw new Error(`Failed to create school: ${createSchoolResponse.message}`);
    }
    
    const schoolId = createSchoolResponse.school_id || createSchoolResponse.district_id; // Handle API inconsistency
    console.log(`School created successfully with ID: ${schoolId}`);
    
    // Step 4: Create a group in the school
    console.log('Creating new group...');
    const createGroupResponse = await makeApiRequest('group.php', {
      action: 'insert',
      school_id: schoolId,
      group_name: 'Main Building'
    }, userCredentials);
    
    if (createGroupResponse.status !== 'OK') {
      throw new Error(`Failed to create group: ${createGroupResponse.message}`);
    }
    
    const groupId = createGroupResponse.group_id;
    console.log(`Group created successfully with ID: ${groupId}`);
    
    // Step 5: Create WiFi settings for the school
    console.log('Creating WiFi settings...');
    const createWifiResponse = await makeApiRequest('wifi.php', {
      action: 'insert',
      school_id: schoolId,
      ssid_name: 'School_Staff',
      ssid_pass: 'SecureStaffPassword.123',
      ssid_desc: 'Staff WiFi Network'
    }, userCredentials);
    
    if (createWifiResponse.status !== 'OK') {
      throw new Error(`Failed to create WiFi settings: ${createWifiResponse.message}`);
    }
    
    const wifiId = createWifiResponse.wifi_id;
    console.log(`WiFi settings created successfully with ID: ${wifiId}`);
    
    // Step 6: Retrieve the organizational structure we created
    console.log('Retrieving organizational structure...');
    const userData = await makeApiRequest('userdata.php', {}, userCredentials);
    
    if (userData.status === 'OK') {
      console.log('Organizational structure retrieved successfully.');
      
      // Find our newly created district
      const ourDistrict = userData.districts.find(d => d.district_id == districtId);
      if (ourDistrict) {
        console.log('Our new organizational structure:');
        console.log(`District: ${ourDistrict.district_name} (ID: ${ourDistrict.district_id})`);
        
        ourDistrict.schools.forEach(school => {
          console.log(`  School: ${school.school_name} (ID: ${school.school_id})`);
          
          console.log('    WiFi Networks:');
          school.wifi_ssids.forEach(wifi => {
            console.log(`      - ${wifi.ssid_name} (ID: ${wifi.ssid_id})`);
          });
          
          console.log('    Groups:');
          school.groups.forEach(group => {
            console.log(`      - ${group.group_name} (ID: ${group.group_id})`);
          });
        });
      }
    } else {
      console.error('Failed to retrieve organizational structure:', userData.message);
    }
    
    // Step 7: Cleanup - Note: Commented out to avoid accidental deletion
    // In a real application, you might want to clean up test resources
    /*
    console.log('Cleaning up resources...');
    
    // Delete WiFi settings
    await makeApiRequest('wifi.php', {
      action: 'remove',
      ssid_id: wifiId
    }, userCredentials);
    
    // Delete group
    await makeApiRequest('group.php', {
      action: 'remove',
      group_id: groupId
    }, userCredentials);
    
    // Delete school
    await makeApiRequest('school.php', {
      action: 'remove',
      school_id: schoolId
    }, userCredentials);
    
    // Delete district
    await makeApiRequest('district.php', {
      action: 'remove',
      district_id: districtId
    }, userCredentials);
    
    console.log('Resources cleaned up successfully.');
    */
    
    // Step 8: Logout
    console.log('Logging out...');
    await makeApiRequest('logout.php', {
    }, userCredentials);
    
    console.log('Resource management example completed successfully.');
    
  } catch (error) {
    console.error('Resource management example error:', error);
  }
}

// Run the resource management example
// resourceManagementExample();

User Management

This example demonstrates how to manage users in the RCAMS system, including creating users, setting permissions, and assigning districts.

User Management Example (JavaScript)
// RCAMS User Management Example

// Helper function for making API requests
async function makeApiRequest(endpoint, params, apiCredentials) {
  const { username, password } = apiCredentials;
  
  // Create json data from params
  const json = {};
    for (const [key, value] of Object.entries(params)) {
      json[key] = value;
    }
    const jsonString = JSON.stringify(json);
  
  try {
    const response = await fetch(`https://rcamsapi.spheronomics.com/api/v2/${endpoint}`, {
      method: 'POST',
      headers: {
        'Authorization': 'Basic ' + btoa(`${username}:${password}`)
      },
      body: jsonString
    });
    
    return await response.json();
  } catch (error) {
    console.error(`API request to ${endpoint} failed:`, error);
    throw error;
  }
}

// User Management Example
async function userManagementExample() {
  
  // Admin user credentials - replace with actual values
  const adminCredentials = {
    email: 'admin@example.com',
    password: 'admin_password'
  };
  
  try {
   
    // Step 1: Get list of districts (for assigning to new user)
    console.log('Getting districts...');
    const districtsResponse = await makeApiRequest('district.php', {
      action: 'list'
    }, userCredentials);
    
    if (districtsResponse.status !== 'OK') {
      throw new Error(`Failed to get districts: ${districtsResponse.message}`);
    }
    
    const districts = districtsResponse.districts;
    console.log(`Retrieved ${districts.length} districts.`);
    
    // Step 3: Create a new user
    console.log('Creating new user...');
    const createUserResponse = await makeApiRequest('user.php', {
      action: 'insert',
      first_name: 'John',
      last_name: 'Doe',
      user_name: 'jdoe',
      email: 'john.doe@example.com',
      password: 'SecurePassword123',
      phone: '555-987-6543',
      picture_url: 'https://example.com/profiles/jdoe.jpg',
      notes: 'School safety officer'
    }, userCredentials);
    
    if (createUserResponse.status !== 'OK') {
      throw new Error(`Failed to create user: ${createUserResponse.message}`);
    }
    
    const userToken = createUserResponse.user_token;
    console.log(`User created successfully with token: ${userToken}`);
    
    // Step 4: Assign districts to the new user
    // For this example, we'll assign the first two districts or all if less than two
    const districtIds = districts.slice(0, Math.min(2, districts.length)).map(d => d.district_id);
    const districtList = districtIds.join(',');
    
    console.log(`Assigning districts ${districtList} to new user...`);
    const assignDistrictsResponse = await makeApiRequest('userdistrict.php', {
      usr_tokenid: userToken,
      district_list: districtList
    }, userCredentials);
    
    if (assignDistrictsResponse.status !== 'OK') {
      throw new Error(`Failed to assign districts: ${assignDistrictsResponse.message}`);
    }
    
    console.log('Districts assigned successfully to new user.');
    
    // Step 5: Update user information
    console.log('Updating user information...');
    const updateUserResponse = await makeApiRequest('user.php', {
      action: 'update',
      usr_tokenid: userToken,
      first_name: 'John',
      last_name: 'Doe-Smith',
      phone: '555-123-4567',
      picture_url: 'https://example.com/profiles/jdoe_updated.jpg',
      notes: 'School safety coordinator'
    }, userCredentials);
    
    if (updateUserResponse.status !== 'OK') {
      throw new Error(`Failed to update user: ${updateUserResponse.message}`);
    }
    
    console.log('User information updated successfully.');
    
    // Step 6: List all users
    console.log('Listing all users...');
    const listUsersResponse = await makeApiRequest('user.php', {
      action: 'list'
    }, userCredentials);
    
    if (listUsersResponse.status !== 'OK') {
      throw new Error(`Failed to list users: ${listUsersResponse.message}`);
    }
    
    console.log(`Retrieved ${listUsersResponse.total} users.`);
    
    // Find our newly created user in the list
    const ourUser = listUsersResponse.users.find(u => u.user_token === userToken);
    if (ourUser) {
      console.log('Our new user details:');
      console.log(`  Name: ${ourUser.user_name}`);
      console.log(`  Email: ${ourUser.user_email}`);
      console.log(`  Phone: ${ourUser.user_phone}`);
      console.log(`  Status: ${ourUser.enable === 'yes' ? 'Enabled' : 'Disabled'}`);
    }
    
    // Step 7: Clean up - Remove the user (commented out for safety)
    /*
    console.log('Removing test user...');
    const removeUserResponse = await makeApiRequest('user.php', {
      action: 'remove',
      usr_tokenid: userToken
    }, userCredentials);
    
    if (removeUserResponse.status !== 'OK') {
      throw new Error(`Failed to remove user: ${removeUserResponse.message}`);
    }
    
    console.log('User removed successfully.');
    */
    
    // Step 8: Logout
    console.log('Logging out...');
    await makeApiRequest('logout.php', {}, userCredentials);
    
    console.log('User management example completed successfully.');
    
  } catch (error) {
    console.error('User management example error:', error);
  }
}

// Run the user management example
// userManagementExample();