����
������������������������������������
config = $config;
$this->accessToken = $this->getAccessToken();
$this->categoriesData = $this->fetchCategories();
}
/**
* @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 fetchCategories() {
$categoriesUrl = $this->config['base_url'] . "/pricebook/v2/tenant/" . $this->config['tenantId'] . "/categories";
$categoriesResponse = $this->executeCurl($categoriesUrl, 'GET', null, 'serviceTitan');
$categoriesResponse = json_decode($categoriesResponse);
$filteredCategories = [];
foreach ($categoriesResponse->data as $category) {
$filteredCategories[] = $category;
}
return $filteredCategories;
}
private function getImage($assets) {
if(count($assets)>0){
$imageUrl=$this->getImageUrl($assets[0]->url);
$imageResponse = $this->executeCurl($imageUrl, 'GET',null,'serviceTitan');
if (!empty($imageResponse) && is_string($imageResponse)) {
return base64_encode($imageResponse);
}
}
}
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_service'],
"data_table_id"=>$this->config['data_table_id_service'],
"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.'/'.$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() {
$categoriesData=$this->categoriesData;
$page = 1;
$pageSize = 50;
$combinedData = array();
do {
$servicesUrl = $this->config['base_url']."/pricebook/v2/tenant/".$this->config['tenantId']."/services/?page=$page&pageSize=$pageSize";
$servicesData=$this->executeCurl($servicesUrl, 'GET',NULL,'serviceTitan');
$servicesData=json_decode($servicesData);
foreach ($servicesData->data as $product) {
//foreach ($product->categories as $productCategory) {
//foreach ($categoriesData as $category) {
//if ($category->id === $productCategory) {
$categoriesName = "";
if(!empty($product->warranty)){
$warranty = json_encode($product->warranty);
}
if(!empty($product->categories)){
$categories = $product->categories;
}
if(!empty($product->recommendations)){
if(is_array($product->recommendations)){
$recommendations = implode(", ", $product->recommendations);
}
else{
$recommendations = $product->recommendations;
}
}
else{
$recommendations = "";
}
if(!empty($product->assets)){
$assets = !empty($product->assets[0]->url) ? $product->assets[0]->url : '';
}
else{
$assets = '';
}
if(!empty($product->serviceMaterials)){
$serviceMaterials = json_encode($product->serviceMaterials);
}
else{
$serviceMaterials = "";
}
if(!empty($product->serviceEquipment)){
$serviceEquipment = json_encode($product->serviceEquipment);
}
else{
$serviceEquipment = "";
}
if(!empty($product->externalData)){
$externalData = json_encode($product->externalData);
}
if(!empty($categories) && is_array($categories)){
foreach($categories as $kx=>$categoriesData){
$categoriesName .= $categoriesData->name.",";
}
}
$productData = array(
'id' => $product->id,
'code' => $product->code,
'displayName' => $product->displayName,
'description' => html_entity_decode($product->description),
'warranty' => $warranty,
'categories' => rtrim($categoriesName,","),
'price' => $product->price,
'memberprice' => $product->memberPrice,
'addOnPrice' => $product->addOnPrice,
'addOnMemberPrice' => $product->addOnMemberPrice,
'taxable' => ($product->taxable==true ? "1" : "0"),
'account' => $product->account,
'hours' => $product->hours,
'isLabor' => ($product->isLabor==true ? "1" : "0"),
'recommendations' => $recommendations,
'upgrades' => implode(",",$product->upgrades),
'assets' => $assets,
'serviceMaterials' => $serviceMaterials,
'serviceEquipment' => $serviceEquipment,
'active' => ($product->active==true ? "1" : "0"),
'crossSaleGroup' => $product->crossSaleGroup,
'paysCommission' => $product->paysCommission,
'bonus' => $product->bonus,
'commissionBonus' => $product->commissionBonus,
'modifiedOn' => $product->modifiedOn,
'source' => $product->source,
'externalId' => $product->externalId,
'externalData' => $externalData,
'section' => 'Services'
);
$combinedData[] = $productData;
//}
//}
//}
}
$page++;
} while ($servicesData->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_service'].'&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 data tables are empty then insert ////////////////////////
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 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.' | Services';
$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.' | Services';
$dataSync->sendmail($subjectFull, $html,$message['recipients']);
}