Skip to content

Instantly share code, notes, and snippets.

@JudeRosario
Created February 5, 2015 14:23
Show Gist options
  • Save JudeRosario/4f1ff1df21015350cbaf to your computer and use it in GitHub Desktop.
Save JudeRosario/4f1ff1df21015350cbaf to your computer and use it in GitHub Desktop.
Appointments+ Feature: Select a random service provider
add_filter('app_pre_confirmation_reply', 'select_random_provider');
function select_random_provider($reply_array)
{
// Return if worker is already selected
if(''!==$reply_array['worker'])
return $reply_array;
// Read in the $value params from the $_POST request
global $appointments;
$appointments = new Appointments();
$value = isset($_POST['value']) ? $_POST['value']:"";
$values = explode( ":", $_POST["value"] );
$location = $values[0];
$service = $values[1];
$worker = $values[2];
$start = $values[3];
$end = $values[4];
$post_id = $values[5];
$html = "";
$available_workers = array();
// Get all workers who can perform this service and are available during the current week
$all_workers = $appointments->get_workers_by_service($service);
$week= date( "W", $start );
foreach ($all_workers as $w) {
$available = true;
// Check if this worker has other appointments in this slot
$apps = $appointments->get_reserve_apps_by_worker(" ", $w->ID, $week );
foreach ( $apps as $app ) {
if ( $start >= strtotime( $app->start )
&& $end <= strtotime( $app->end ) )
$available = false;
}
// If the worker is add him to our pool of available workers
if($available)
array_push($available_workers,$w);
}
// Choose a worker randomly from the pool
$worker = array_rand($available_workers);
$worker_id = $available_workers[$worker]->ID;
// A script that handles AJAX responses and injects the random service provider into the final value param
$script = <<<EOT
<script type="text/javascript">
jQuery(document).ready(function($) {
var final_value = $(".appointments-confirmation-final-value")
tmp = final_value.val().split(':')
tmp[2]={$worker_id}
final_value.val(tmp.join(":"))
})
</script>
EOT;
// Add this script to the $reply_array
$html .= $script;
$reply_array['worker'] = $html;
// Hook for further development if needed
apply_filters('random_service_provider',$reply_array)
return $reply_array;
}
@JudeRosario
Copy link
Author

You can just copy/paste the above code into your functions.php or a site specific plugin if you use one

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment