����
������������������������������������
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 => 36000, // 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 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 insertData($data) {
$url='https://datatable-prod.clientpoint.net/api/managedata/?apiKey='.$this->config['clientPointApiKey'];
$postFiled=array(
"companyId"=>$this->config['companyId'],
"workspace"=>$this->config['workspaceId'],
"unique_identifier"=>$this->config['unique_identifier_tag'],
"data_table_id"=>$this->config['data_table_id_tag'],
"meta"=>$data
);
$this->executeCurl($url, 'POST',$postFiled,'');
}
private function updateData($id,$data) {
$url='https://datatable-prod.clientpoint.net/api/managedata/'.$id.'/'.$this->config['workspaceId'].'/'.$this->config['companyId'].'?apiKey='.$this->config['clientPointApiKey'];
$postFiled=array(
"meta"=>$data
);
$this->executeCurl($url, 'PATCH',$postFiled,'');
}
/**
* @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() {
$page = 1;
$pageSize = 50;
$combinedData = array();
do {
$tagsUrl = $this->config['base_url']."/settings/v2/tenant/".$this->config['tenantId']."/tag-types/?page=$page&pageSize=$pageSize";
$tagsData=$this->executeCurl($tagsUrl, 'GET',NULL,'serviceTitan');
$tagsData=json_decode($tagsData);
echo "
";
print_r($tagsData);
echo "
";
foreach ($tagsData->data as $kx=>$product) {
$productData = array(
'id' => $product->id,
'name' => $product->name,
'color' => $product->color,
'code' => $product->code,
'importance' => $product->importance,
'isConversionOpportunity' => ($product->isConversionOpportunity==true ? "1" : "0"),
'active' => ($product->active==true ? "1" : "0"),
'createdOn' => $product->createdOn,
'modifiedOn' => $product->modifiedOn,
'section' => 'Tags'
);
$combinedData[] = $productData;
}
$page++;
} while ($tagsData->hasMore);
//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'].'&apiKey='.$this->config['clientPointApiKey'], 'GET',null,'');
$datatableResponse=json_decode($datatableResponse);
$existingDataMap = [];
$udid = array();
$dataResponseV = array();
$dataResponseids = array();
$serviceTitanId = array();
foreach ($datatableResponse as $kx=>$db) {
$dataResponseV[$kx]["udid"] = $db->_id;
$dataResponseids[] = $db->meta->id;
$udid[$kx] = $db->meta->id;
$existingDataMap[$db->meta->udid][$kx] = $db;
}
if(empty($datatableResponse) && count($datatableResponse)==0){
foreach ($combinedData as $data) {
$this->insertData($data);
}
}
else{
foreach($combinedData as $km=>$data){
$serviceTitanId[$km] = $data["id"];
if(in_array($data["id"],$udid)){
$key = array_search ($data["id"], $udid);
$this->updateData($dataResponseV[$key]["udid"],$data);
}
else{
$this->insertData($data);
}
}
///////// HERE Please check the both arrays difference if any differnce then delete that from data table //////
if(!empty($dataResponseids) && count($dataResponseids)>0 && count($serviceTitanId)>0){
$resultdiff = array_diff($dataResponseids,$serviceTitanId);
if(!empty($resultdiff) && count($resultdiff)>0){
$array_keys = array_keys($resultdiff);
foreach($array_keys as $arrayKeyValues){
$this->deleteData($datatableResponse[$arrayKeyValues]->_id);
}
}
}
}
$dataToDelete = array_values($existingDataMap);
foreach($dataToDelete as $data){
$this->deleteData($data);
}
}
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 Air Works Live Configration ////////////////////
// $service_titan_config = array(
// 'clientId' => 'cid.pvzp7dh6vlllpzliyhzbjo3io',
// 'clientSecret' => 'cs1.9ywkcudixkz9bbh8pvvpo5qhcrsufkyljjc17n8mepbucuy7oe',
// 'appKey' => 'ak1.enw7rcl42u5ykch9tkasdv44y',
// 'auth_url' => 'https://auth.servicetitan.io/connect/token',
// 'base_url' => 'https://api.servicetitan.io',
// 'tenantId' => '1033273639',
// 'clientPointApiKey' => 'b6ad5af9ec6d1ed5c05ec9bbc7a0a2ab9a954962',
// 'data_table_id' => '669e6f4842e7b03ca0426615',
// 'unique_identifier' => 'tag_service_titan',
// 'companyId' => "3314",
// 'workspaceId' => '0',
// );
//////////////// Service Titan Sandbox Configration ////////////////////
if(file_exists('ServiceTitanConfig_Live.php')){
include('ServiceTitanConfig_Live.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']);
$subjectFull = $message['subject'].' - Dated: '.$dateInCustomFormat.' | Tags';
$dataSync->sendmail($subjectFull,$html,$message['recipients']);
echo "PHP Version: " . phpversion();
} catch (Exception $e) {
$message = $dataSync->getMessage('error');
$html = $dataSync->email_template($message['message']);
$subjectFull = $message['subject'].' - Dated: '.$dateInCustomFormat.' | Tags';
$dataSync->sendmail($subjectFull, $html,$message['recipients']);
}