����
������������������������������������
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_equipments'],
"data_table_id"=>$this->config['data_table_id_equipments'],
"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($dataId) {
$url='https://datatable-prod.clientpoint.net/api/managedata/'.$dataId.'/'.$this->config['workspaceId'].'/'.$this->config['companyId'].'?apiKey='.$this->config['clientPointApiKey'];
$postFiled=array(
"deleted"=> true
);
$this->executeCurl($url, 'PATCH',$postFiled,'');
}
/**
* @throws Exception
*/
public function syncData() {
$categoriesData=$this->categoriesData;
$page = 1;
$pageSize = 50;
$combinedData = array();
do {
$equipmentUrl = $this->config['base_url']."/pricebook/v2/tenant/".$this->config['tenantId']."/equipment/?page=$page&pageSize=$pageSize";
$equipmentData=$this->executeCurl($equipmentUrl, 'GET',NULL,'serviceTitan');
$equipmentData=json_decode($equipmentData);
foreach ($equipmentData->data as $product) {
$productCategory = "";
if(!empty($product->categories)){
if(is_array($product->categories)){
$categoriesData = array();
/////////////////////////// Get the Category Name from CRM and add them in Data Tables /////////////
foreach($product->categories as $kx=>$categoriesVal){
///////////// HIT the CURL ///////////////
$categoriesUrl = $this->config['base_url']."/pricebook/v2/tenant/".$this->config['tenantId']."/categories/$categoriesVal";
$categoryResponse = json_decode($this->executeCurl($categoriesUrl, 'GET',NULL,'serviceTitan'));
$categoriesData[$kx] = $categoryResponse->name;
}
$productCategory = implode(", ",$categoriesData);
}
else{
$productCategory = $product->categories;
}
}
if(!empty($product->manufacturerWarranty)){
$manufacturerWarranty = json_encode($product->manufacturerWarranty);
}
if(!empty($product->serviceProviderWarranty)){
$serviceProviderWarranty = json_encode($product->serviceProviderWarranty);
}
if(!empty($product->primaryVendor)){
$primaryVendor = json_encode($product->primaryVendor);
}
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->otherVendors)){
$otherVendors = json_encode($product->otherVendors);
}
if(!empty($product->externalData)){
$externalData = json_encode($product->externalData);
}
if(!empty($product->variationsOrConfigurableEquipment)){
$variationsOrConfigurableEquipment = json_encode($product->variationsOrConfigurableEquipment);
}
$productData = array(
'id' => $product->id,
'code' => $product->code,
'name' => $product->displayName,
'description' => html_entity_decode($product->description),
'category' => $productCategory,
'active' => ($product->active==true ? "1" : "0"),
'price' => $product->price,
'memberprice' => $product->memberPrice,
'addOnPrice' => $product->addOnPrice,
'addOnMemberPrice' => $product->addOnMemberPrice,
'manufacturer' => $product->manufacturer,
'model' => $product->model,
'manufacturerWarranty' => $manufacturerWarranty,
'serviceProviderWarranty' => $serviceProviderWarranty,
'categories' => $productCategory,
'assets' => $assets,
'primaryVendor' => $primaryVendor,
'otherVendors' => $otherVendors,
'account' => $product->account,
'costOfSaleAccount' => $product->costOfSaleAccount,
'assetAccount' => $product->assetAccount,
'crossSaleGroup' => $product->crossSaleGroup,
'paysCommission' => $product->paysCommission,
'bonus' => $product->bonus,
'commissionBonus' => $product->commissionBonus,
'hours' => $product->hours,
'taxable' => $product->taxable,
'cost' => $product->cost,
'unitOfMeasure' => $product->unitOfMeasure,
'isInventory' => $product->isInventory,
'modifiedOn' => $product->modifiedOn,
'source' => $product->source,
'externalId' => $product->externalId,
'externalData' => $externalData,
'isConfigurableEquipment' => $product->isConfigurableEquipment,
'variationsOrConfigurableEquipment' => $variationsOrConfigurableEquipment,
'section' => 'Equipments'
);
$combinedData[] = $productData;
}
$page++;
} while ($equipmentData->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_equipments'].'&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{
if(!empty($combinedData) && isset($combinedData)){
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);
}
}
}
}
// At this point, $existingDataMap contains data that should be deleted
}
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 ////////////////////
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.' | Equipments';
$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.' | Equipments';
$dataSync->sendmail($subjectFull, $html,$message['recipients']);
}