Home / Admin / Consultants
Duplicate Snippet

Embed Snippet on Your Site

Consultants

It'll create profiles based on the API data using Pods.

Code Preview
php
<?php
function create_consultant_logs_entry($log_content) {
	// Check if Pods is active
	if (!function_exists('pods')) {
		error_log('Pods is not active.');
		return false;
	}
	$logs_pod_name = 'logs'; // The name of the Pod
	$log_entry_field = 'log'; // The field in the Pod to store the content
	$log_title = 'Log Entry'; // Unique title for the log post
	// Query for an existing post with the exact title "Log Entry"
	$existing_posts = get_posts([
		'post_type'   => $logs_pod_name,
		'meta_query'  => [], // Ensures no extra filters affect the query
		'title'       => $log_title,
		'post_status' => 'any', // Search across all statuses
		'numberposts' => 1,
	]);
	// If a post exists, update it
	if (!empty($existing_posts)) {
		$existing_post_id = $existing_posts[0]->ID;
		$logs_pod = pods($logs_pod_name, $existing_post_id);
		if ($logs_pod) {
			$updated = $logs_pod->save($log_entry_field, $log_content);
			if ($updated) {
				return $existing_post_id; // Return the updated post ID
			} else {
				error_log('Failed to update the existing log entry.');
				return false;
			}
		} else {
			error_log('Failed to initialize Pods object for existing log.');
			return false;
		}
	}
	// If no post exists, create a new log entry
	$logs_pod = pods($logs_pod_name);
	if ($logs_pod) {
		$new_log_id = $logs_pod->add([
			'post_title'   => $log_title,   // Set the title for the log post
			$log_entry_field => $log_content, // Set the content for the 'log' field
			'post_status'  => 'publish',   // Ensure the post is published
		]);
		if (is_wp_error($new_log_id)) {
			error_log('Error creating logs entry: ' . $new_log_id->get_error_message());
			return false;
		}
		return $new_log_id; // Return the new log post ID
	} else {
		error_log('Failed to initialize Pods object for logs.');
		return false;
	}
}
function fetch_all_publications_from_api($discoveryUrlId) {
	$url = 'https://website.com/api/publications/linkedTo';
	$all_publications = [];
	$body = [
		"objectId" => $discoveryUrlId,
		"objectType" => "user",
		"pagination" => [
			"perPage" => 999,
			"startFrom" => 0,
		],
		"sort" => "dateDesc",
		"favouritesFirst" => true,
	];
	$args = [
		'method'      => 'POST',
		'body'        => json_encode($body),
		'headers'     => [
			'Content-Type' => 'application/json',
			'Accept'       => 'application/json',
		],
		'timeout'     => 50,
	];
	$response = wp_remote_post($url, $args);
	//     if (is_wp_error($response)) {
	//         error_log('API Request Error: ' . $response->get_error_message());
	//         return [];
	//     }
	$response_body = wp_remote_retrieve_body($response);
	//     if (!$response_body) {
	//         error_log('Empty response body from API.');
	//         return [];
	//     }
	$response_data = json_decode($response_body, true);
	//     if (json_last_error() !== JSON_ERROR_NONE) {
	//         error_log('JSON Decode Error: ' . json_last_error_msg());
	//         return [];
	//     }
	//     if (!isset($response_data['resource']) || empty($response_data['resource'])) {
	//         error_log('No "resource" key or empty data in API response.');
	//         return [];
	//     }
	$all_publications = $response_data['resource'];
	//     error_log('Fetched publications: ' . print_r($all_publications, true));
	return $all_publications;
}
function fetch_all_contributions_from_api($discoveryUrlId) {
	$url = 'https://website.com/api/professionalActivities/linkedTo';
	$body = [
		"objectId" => $discoveryUrlId,
		"objectType" => "user",
		"pagination" => [
			"perPage" => 999,
			"startFrom" => 0,
		],
		"sort" => "dateDesc",
		"favouritesFirst" => true,
	];
	$args = [
		'method'      => 'POST',
		'body'        => json_encode($body),
		'headers'     => [
			'Content-Type' => 'application/json',
			'Accept'       => 'application/json',
		],
		'timeout'     => 50
	];
	$response = wp_remote_post($url, $args);
	//     if (is_wp_error($response)) {
	//         error_log('API Request Error: ' . $response->get_error_message());
	//         return [];
	//     }
	$response_body = wp_remote_retrieve_body($response);
	$response_data = json_decode($response_body, true);
	$all_contributions = $response_data['resource'];
	return $all_contributions;
}
function fetch_user_from_api($discoveryUrlId) {
	$url = 'https://website.com/api/users/' . $discoveryUrlId;
	$response = wp_remote_get($url);
	// Get the response body
	$body = wp_remote_retrieve_body($response);
	// Optionally decode the JSON response
	$data = json_decode($body, true);
	return $data;
}
function fetch_all_users_from_api() {
	$langsArray = [];
	$url = 'https://website.com/api/users';
	$per_page = 100; 
	$start_from = 0; 
	$all_users = []; 
	do {
		$body = [
			"params" => [
				"by" => "text",
				"type" => "user",
				"text" => ""
			],
			"pagination" => [
				"startFrom" => $start_from,
				"perPage" => $per_page
			],
			"sort" => "lastNameAsc",
			"filters" => [
				[
					"name" => "customFilterOne",
					"matchDocsWithMissingValues" => true,
					"useValuesToFilter" => false
				],
				[
					"name" => "tags",
					"matchDocsWithMissingValues" => true,
					"useValuesToFilter" => false
				],
				[
					"name" => "customFilterThree",
					"matchDocsWithMissingValues" => false,
					"useValuesToFilter" => true,
					"values" => ["Industry Projects"]
				],
				[
					"name" => "department",
					"matchDocsWithMissingValues" => true,
					"useValuesToFilter" => false
				]
			]
		];
		$args = [
			'method'      => 'POST',
			'body'        => json_encode($body),
			'headers'     => [
				'Content-Type' => 'application/json',
			],
			'timeout'     => 50,
		];
		$response = wp_remote_post($url, $args);
		if (is_wp_error($response)) {
			error_log('Request failed: ' . $response->get_error_message());
			return [];
		}
		$response_body = wp_remote_retrieve_body($response);
		if (is_array($response_body)) {
			error_log('Raw API Response (Array): ' . print_r($response_body, true));
		}
		$response_data = json_decode($response_body, true);
		if (!isset($response_data['resource']) || empty($response_data['resource'])) {
			error_log('No data found or \"data\" key missing in API response.');
			break; 
		}
		$all_users = array_merge($all_users, $response_data['resource']);
		$start_from += $per_page; 
	} while (count($response_data['resource']) === $per_page);
	//     error_log('Total users fetched: ' . gettype($all_users));
	return $all_users;
}
$users = fetch_all_users_from_api();
$post_type = 'consultant';
$all_logs = '';
foreach ($users as $consultant) {
	$unique_id = $consultant['discoveryUrlId']; // Use a unique identifier
	$data = fetch_user_from_api($unique_id);
	$is_any_field_changed = false;
	$post_exists = get_posts([
		'post_type'   => $post_type, 
		'meta_key'    => 'consultant_discovery_id',
		'meta_value'  => $unique_id,
		'numberposts' => 1
	]);
	$post_id = null;
	if (!$post_exists) {
		// Create the post if it doesn't exist
		$post_id = wp_insert_post([
			'post_title'    => $consultant['firstNameLastName'],
			'post_content'  => '',
			'post_status'   => 'publish',
			'post_author'   => 1,
			'post_type'     => $post_type,
		]);
		// 			if (is_wp_error($post_id)) {
		// 				error_log('Error creating consultant: ' . $post_id->get_error_message());
		// 				continue;
		// 			}
		// Save the unique identifier for future lookups
		update_post_meta($post_id, 'consultant_discovery_id', $unique_id);
	} else {
		// If the post exists, get its ID
		$post_id = $post_exists[0]->ID;
	}
	// Update consultant data using Pods
	if ($post_id && function_exists('pods')) {
		$pod = pods($post_type, $post_id);
		if ($pod) {
			// Check if 'consultant_manual_update' field is enabled
			$consultant_manual_update = $pod->field('consultant_manual_update');
			if ($consultant_manual_update) {
				// Skip updates for this consultant
				continue;
			}
			$bio = isset($consultant['tabSummaryAbout']['value']) && $consultant['tabSummaryAbout']['value'] 
				? $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s bio: \n" . $consultant['tabSummaryAbout']['value'] 
				: "No biography is available!";
			if (!empty(fetch_all_publications_from_api($unique_id))) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s publications: " . "\n";
				$publications = fetch_all_publications_from_api($unique_id);
				foreach ($publications as $publication) {
					$bio .= $publication['title'] . "\n";
				}
			}
			$contributions = fetch_all_contributions_from_api($unique_id);
			if (!empty($contributions)) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s contributions: " . "\n";
				foreach ($contributions as $contribution) {
					$bio .= $contribution['title'] . "\n";
				}
			}
			if (!empty($consultant['positions'][0])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s positions: " . "\n";
				foreach ($consultant['positions'][0] as $position) {
					$bio .= $position . "\n";
				}
			}
			if (!empty($data['academicAppointments'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s academic positions: " . "\n";
				foreach ($data['academicAppointments'] as $position) {
					$bio .= $position['position'] . "\n";
				}
			}
			if (!empty($consultant['customFilterOne'][0])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s faculty: " . $consultant['customFilterOne'][0] . "\n";
			}
			if (!empty($consultant['customFilterThree'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s availability: " . "\n";
				foreach ($consultant['customFilterThree'] as $availability) {
					$bio .= $availability . "\n";
				}
			}
			if (!empty($consultant['tags']['explicit'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s fields of research: " . "\n";
				foreach ($consultant['tags']['explicit'] as $field) {
					$bio .= $field['value'] . "\n";
				}
			}
			if (!empty($data['nonAcademicAppointments'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s non-academic positions: " . "\n";
				foreach ($data['nonAcademicAppointments'] as $naa) {
					$bio .= $naa['position'] . "\n";
				}
			}
			if (!empty($data['degrees'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s degrees: " . "\n";
				foreach ($data['degrees'] as $degree) {
					$bio .= $degree['name'] . "\n";
				}
			}
			if (!empty($data['languageCompetencies'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s languages: " . "\n";
				$langNames = [];
				foreach ($data['languageCompetencies'] as $lang) {
					$bio .= $lang['displayName'] . "\n";
					$langNames[] = $lang['displayName'];
				}
				$langs = implode(', ', $langNames);
				$langsArray = $langNames;
			}
			else {
				$langs = implode(', ', ['English']);
				$langsArray = ['English'];
			}
			if (!empty($data['certifications'])) {
				$bio .= "\n" . $consultant['firstName'] . ' ' . $consultant['lastName'] . "'s certifications: " . "\n";
				foreach ($data['certifications'] as $certification) {
					$bio .= $certification['title'] . "\n";
				}
			}
			$fields = [
				'consultant_name' => $consultant['firstName'] . ' ' . $consultant['lastName'],
				'consultant_email_address' => isset($data['emailAddress']) ? 'mailto:' . $data['emailAddress']['address'] : '',
				'consultant_academic_profile_url' => 'https://website.com/' . $consultant['discoveryUrlId'],
				'consultant_image' => 'https://website.com/' . $consultant['discoveryUrlId'] . '/thumbnail',
				'consultant_department' => $consultant['positions'][0]['department'] ?? '',
				'consultant_position' => $consultant['positions'][0]['position'] ?? '',
				'consultant_faculty' => $consultant['customFilterOne'][0] ?? '',
				'consultant_title' => $consultant['title'] ?? '-',
				'consultant_language' => $langsArray,
			];
			foreach ($fields as $field => $new_value) {
				$existing_value = $pod->field($field);
				// Compare old and new values, log if different
				if ($existing_value !== $new_value) {
					$is_any_field_changed = true;
					// Log the change into the 'expert_sync_logs' field (WYSIWYG type)
					$existing_logs = $pod->field('expert_sync_logs'); // Get the current WYSIWYG content
					$change_log = sprintf(
						"Field '%s' changed from '%s' to '%s'.\n\n",
						$field,
						is_array($existing_value) ? json_encode($existing_value) : $existing_value,
						is_array($new_value) ? json_encode($new_value) : $new_value
					);
					// Append the change to the existing log
					$new_logs = $change_log . $existing_logs;
					// Save the updated log back to the 'expert_sync_logs' field
					$pod->save('expert_sync_logs', $new_logs);
					// Save the new value in the consultant Pod
					$pod->save($field, $new_value);
				}
			}
			// Additional field updates with specific comparisons
			$existing_bio = $pod->field('consultant_actual_bio');
			$new_bio = $bio;
			$cab_log = '';
			$bio_log = '';
			$actual_bio_log = '';
			if ($existing_bio !== $new_bio || $existing_bio === '') {
				// summarize
				$con_bio = use_chatgpt($new_bio, "summarize");
				$bio_log .= sprintf(
					"Field '%s' changed from '%s' to '%s'.\n\n",
					"consultant_bio",
					$pod->field('consultant_bio'),
					$con_bio
				);
				$pod->save('consultant_bio', $con_bio);
				// capabilities
				$con_cab = json_decode(use_chatgpt($new_bio, "capabilities"));
				$cab_log .= sprintf(
					"Field '%s' changed from '%s' to '%s'.\n\n",
					"consultant_capabilities_text",
					$pod->field('consultant_capabilities_text'),
					json_encode($con_cab)
				);
				$pod->save('consultant_capabilities', $con_cab);
				$pod->save('consultant_capabilities_text', json_encode($con_cab));
				$actual_bio_log .= sprintf(
					"Field '%s' changed from '%s' to '%s'.\n\n",
					"consultant_actual_bio",
					$pod->field('consultant_actual_bio'),
					$new_bio
				);
				$pod->save('consultant_actual_bio', $new_bio);
			}
			$existing_department = $pod->field('consultant_department');
			$new_department = $consultant['positions'][0]['department'];
			if ($existing_department !== $new_department) {
				$pod->save('consultant_department', $new_department);
			}
			$existing_position = $pod->field('consultant_position');
			$new_position = $consultant['positions'][0]['position'];
			if ($existing_position !== $new_position) {
				$pod->save('consultant_position', $new_position);
			}
			$existing_faculty = $pod->field('consultant_faculty');
			$new_faculty = $consultant['customFilterOne'][0];
			if ($existing_faculty !== $new_faculty) {
				$pod->save('consultant_faculty', $new_faculty);
			}
			$existing_title = $pod->field('consultant_title');
			$new_title = $consultant['title'] ?? '-';
			if ($existing_title !== $new_title) {
				$pod->save('consultant_title', $new_title);
			}
			$existing_email_address = $pod->field('consultant_email_address');
			$new_email_address = isset($data['emailAddress']) ? 'mailto:' . $data['emailAddress']['address'] : '';
			if ($existing_email_address !== $new_email_address) {
				$pod->save('consultant_email_address', $new_email_address);
			}
			$existing_academic_profile_url = $pod->field('consultant_academic_profile_url');
			$new_academic_profile_url = 'https://website.com/' . $consultant['discoveryUrlId'];
			if ($existing_academic_profile_url !== $new_academic_profile_url) {
				$pod->save('consultant_academic_profile_url', $new_academic_profile_url);
			}
			$existing_image = $pod->field('consultant_image');
			$new_image = 'https://website.com/' . $consultant['discoveryUrlId'] . '/thumbnail';
			if ($existing_image !== $new_image) {
				$pod->save('consultant_image', $new_image);
			}
			if ($is_any_field_changed) {
				$log_date = date("Y/m/d") . ' ' . date('H:i') . " Log:\n";
				$existing_logs = $pod->field('expert_sync_logs');
				$logs_info = $log_date . $existing_logs . $bio_log . $cab_log . $actual_bio_log;
				$pod->save('expert_sync_logs', $logs_info);
			}
			$all_logs .= $consultant['firstName'] . ' ' . $consultant['lastName'] . " Logs:\n" . $pod->field('expert_sync_logs');
			$log_date = '';
			create_consultant_logs_entry($all_logs);
		}
	}
}	

Comments

Add a Comment