����
������������������������������������
config = $config;
$this->accessToken = $this->getAccessToken();
}
/**
* @throws Exception
*/
private function executeCurl($url, $method, $data = null, $for) {
$headers = array(
"Authorization: Bearer " . $this->accessToken,
"ST-App-Key: " . $this->config['appKey']
);
$curlOptions = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0, // Increase the timeout if needed
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => $method,
);
if($for=='serviceTitan'){
$curlOptions[CURLOPT_HTTPHEADER] = $headers;
}
if ($data !== null) {
$curlOptions[CURLOPT_POSTFIELDS] = json_encode($data);
$curlOptions[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
}
$curl = curl_init();
curl_setopt_array($curl, $curlOptions);
$response = curl_exec($curl);
if ($response === false) {
throw new Exception("cURL error: " . curl_error($curl));
}
curl_close($curl);
return $response;
}
private function getImageUrl($url) {
return $this->config['base_url'] . '/pricebook/v2/tenant/' . $this->config['tenantId'] . '/images?path=' . $url;
}
private function getAccessToken() {
$authUrl = $this->config['auth_url'];
$authData = array(
'grant_type' => 'client_credentials',
'client_id' => $this->config['clientId'],
'client_secret' => $this->config['clientSecret']
);
$authOptions = array(
CURLOPT_URL => $authUrl,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($authData),
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded')
);
$authCh = curl_init();
curl_setopt_array($authCh, $authOptions);
$authResponse = curl_exec($authCh);
curl_close($authCh);
$authData = json_decode($authResponse);
return $authData->access_token;
}
private function resizeBase64Image($base64Image) {
// Decode the base64 image
$imageData = base64_decode($base64Image);
if ($imageData === false) {
return false; // Unable to decode the base64 image
}
// Create an image from the decoded data
$image = imagecreatefromstring($imageData);
if ($image === false) {
return false; // Unable to create an image from the decoded data
}
// Get the original dimensions of the image
$originalWidth = imagesx($image);
$originalHeight = imagesy($image);
// Set the new width to 400px and calculate the height to maintain the aspect ratio
$newWidth = 100;
$newHeight = intval($originalHeight * ($newWidth / $originalWidth));
// Create a new image with the desired dimensions
$resizedImage = imagecreatetruecolor($newWidth, $newHeight);
// Copy and resize the original image to the new image
imagecopyresampled($resizedImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);
// Capture the image data in a buffer
ob_start();
imagejpeg($resizedImage);
$resizedImageData = ob_get_clean();
// Encode the resized image data as base64
$base64ResizedImage = base64_encode($resizedImageData);
// Free up memory
imagedestroy($image);
imagedestroy($resizedImage);
return $base64ResizedImage;
}
/**
* @throws Exception
*/
private function deleteData($data) {
$url='https://datatable-prod.clientpoint.net/api/managedata/'.$data->_id.'/'.$this->config['workspaceId'].'/'.$this->config['companyId'].'?apiKey='.$this->config['clientPointApiKey'];
$postFiled=array(
"deleted"=> true
);
$this->executeCurl($url, 'PATCH',$postFiled,'');
}
private function deleteOldData($dataToDelete) {
foreach ($dataToDelete as $data) {
$this->deleteData($data);
}
}
/**
* @throws Exception
*/
public function syncData() {
//GET all products in datatable
$datatableResponse=$this->executeCurl('https://datatable-prod.clientpoint.net/api/managedata/data/?companyId='.$this->config['companyId'].'&workspace='.$this->config['workspaceId'].'&unique_identifier='.$this->config['unique_identifier_material'].'&apiKey='.$this->config['clientPointApiKey'], 'GET',null,'');
$datatableResponse=json_decode($datatableResponse);
foreach($datatableResponse as $index => $response){
if(!empty($response->meta->assets) && (strpos($response->meta->assets, ".jpg") || strpos($response->meta->assets, ".png") || strpos($response->meta->assets, ".jpeg")) == true){
$imageUrl=$this->getImageUrl($response->meta->assets);
$imageResponse = $this->executeCurl($imageUrl, 'GET',null,'serviceTitan');
$image=base64_encode($imageResponse);
$image = $this->resizeBase64Image($image);
$url='https://datatable-prod.clientpoint.net/api/managedata/'.$response->_id.'/'.$this->config['workspaceId'].'/'.$this->config['companyId'].'?apiKey='.$this->config['clientPointApiKey'];
$postFiled=array(
"meta"=>array (
'id' => $response->meta->id,
'code' => $response->meta->code,
'name' => $response->meta->name,
'description' => html_entity_decode($response->meta->description),
'category' => $response->meta->category,
'active' => $response->meta->active,
'price' => $response->meta->price,
'memberprice' => $response->meta->memberPrice,
'addOnPrice' => $response->meta->addOnPrice,
'addOnMemberPrice' => $response->meta->addOnMemberPrice,
'bonus' => $response->meta->bonus,
'hours' => $response->meta->hours,
'commissionBonus' => $response->meta->commissionBonus,
'account' => $response->meta->account,
'primaryVendor' => $response->meta->primaryVendor,
'otherVendors' => $response->meta->otherVendors,
'categories' => $response->meta->categories,
'assets' => $image,
'modifiedOn' => $response->meta->modifiedOn,
'externalData' => $response->meta->externalData,
'isConfigurableMaterial' => $response->meta->isConfigurableMaterial,
'chargeableByDefault' => $response->meta->chargeableByDefault,
'variationsOrConfigurableMaterials' => $response->meta->variationsOrConfigurableMaterials,
'section' => 'Materials'
)
);
echo $this->executeCurl($url, 'PATCH',$postFiled,'');
}
}
}
public function email_template($message){
$html=
'
|
|
Email Notification
|
'.$message.'
|
|
';
return $html;
}
//send mail
public function sendmail($subject, $html, $reps)
{
$emailContent = $html;
try {
$url = 'https://darcop1.dreamhosters.com/SendGrid/sendEmail.php';
$postData = [
'toEmail' => $reps,
'subject' => $subject,
'emailContent' => $emailContent
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo "cURL error: " . curl_error($ch);
} else {
echo "Email sent successfully. Response: " . $response;
}
curl_close($ch);
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
}
public function getMessage($result){
$datatableResponse=$this->executeCurl('https://datatable-prod.clientpoint.net/api/managedata/data/?companyId='.$this->config['companyId'].'&workspace='.$this->config['workspaceId'].'&unique_identifier='.$this->config['unique_identifier_email'].'&apiKey='.$this->config['clientPointApiKey'], 'GET',null,'');
$datatableResponse=json_decode($datatableResponse);
$datatableResponse=$datatableResponse[0]->meta;
if($result=='success'){
$message=array(
'recipients'=>$datatableResponse->recipients,
'subject'=>$datatableResponse->success_subject,
'message'=>$datatableResponse->success_message,
);
}else{
$message=array(
'recipients'=>$datatableResponse->recipients,
'subject'=>$datatableResponse->failed_subject,
'message'=>$datatableResponse->failed_message,
);
}
return $message;
}
}
//////////////// Service Titan Sandbox Configration for Air Works ////////////////////
// Configuration for using Sandbox for testing purposes
if(file_exists('ServiceTitanConfig.php')){
include('ServiceTitanConfig.php');
}
else{
die("Configuration File does not exists");
}
$dataSync = new DataSync($config);
$dateInCustomFormat = date("F j, Y");
try {
$dataSync->syncData();
$message=$dataSync->getMessage('success');
$html=$dataSync->email_template($message['message']);
$subject = $message['subject'].' - Dated: '.$dateInCustomFormat.' | Images';
$dataSync->sendmail( $subject,$html,$message['recipients']);
} catch (Exception $e) {
$message = $dataSync->getMessage('error');
$html = $dataSync->email_template($message['message']);
$subject = $message['subject'].' - Dated: '.$dateInCustomFormat.' | Images';
$dataSync->sendmail( $subject, $html,$message['recipients']);
}