| Server IP : 162.214.74.102 / Your IP : 216.73.217.46 Web Server : Apache System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64 User : lrsys ( 1015) PHP Version : 5.6.40 Disable Function : exec,passthru,shell_exec,system MySQL : ON | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : ON | Pkexec : ON Directory : /home/lrsys/www/lrsys_apps/leo/application/plugins/module_imobles/helpers/whats/ |
Upload File : |
<?php
include_once __DIR__ . "/../MyGptHelper.php";
include_once __DIR__ . "/../hubspot/Hubspot.php";
class digisacHelper {
protected $digisac_key = '8cd3c1c07c14c260b98a4f1ee681e024b3945ab1';
public function digisacSendDirectMessage($msg, $digisac_params, $file = null, $delete_file = true, $mimetype = 'image/jpeg'){
if(empty($digisac_params['contact_id']) || empty($digisac_params['service_id'])){
return false;
}
$contact_id = $digisac_params['contact_id'];
$serviceId = $digisac_params['service_id'];
$subject = @$digisac_params['subject'];
$user_id = @$digisac_params['user_id'];
$url = "https://imobles.digisac.co/api/v1/messages";
$data_msg = array(
'text' => $msg,
'type' => 'chat',
'contactId' => $contact_id,
'serviceId' => $serviceId,
'userId' => $user_id,
'subject' => $subject
);
if(!empty($file)){
$imagemData = file_get_contents($file);
if(!empty($imagemData)){
$imagemBase64 = base64_encode($imagemData);
$file_json = array('base64' => $imagemBase64, 'mimetype' => $mimetype, 'name' =>'card');
$data_msg['file'] = $file_json;
}
if($delete_file == true){
unlink($file);
}
}
$postdata = json_encode($data_msg);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
'Content-Type: application/json'
));
$json_response = curl_exec($ch);
$result = json_decode($json_response);
if(isset($result->id)){
$return = array("msg" => "Mensagem enviada com sucesso",
"data" => $result,
"success" => true);
} else {
$return = array("msg" => "erro ao inviar mensagem para o Digisac",
"data" => $result,
"success" => false);
}
return $return;
}
public function getLastUserMessage($ticket_messages) {
$time = 0;
$gpt_last_massage = null;
foreach($ticket_messages->data as $tm){
if($tm->isFromMe === true && $tm->createdAt > $time){
$gpt_last_massage = $tm->text;
$time = $tm->createdAt;
}
}
return $gpt_last_massage;
}
public function getContactDetails($contact_id){
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://imobles.digisac.co/api/v1/contacts/' . $contact_id,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
if(!isset($response->id)){
return false;
}
return $response;
}
public function digisacWebHookIncomeMessage() {
ORM::configure('caching', true);
@ini_set('memory_limit', '4095M');
@ini_set('max_execution_time', 0);
@set_time_limit(0);
ignore_user_abort(true);
try {
$jsonStr = file_get_contents("php://input");
$filter = json_decode($jsonStr, true);
$jsonStr = ""; //LIMPA
} catch (Exception $e) {
$filter = array();
return array('status' => false, 'erro' => array("Paylod com erros " . $e->getMessage()));
}
$data_message = array();
if(is_array($filter['data'])){
$data_message = $filter['data'];
} else {
$data_message[] = $filter['data'];
}
foreach($data_message as $dm){
if ($filter['event'] != 'message.created' && $filter['event'] != 'contact.created') {
// return array('status' => true, "operation" => array("webhook" => array("status" => false, 'erro' => array($filter['event'] . " não implementado"))));
continue;
} elseif($filter['event'] == 'contact.created'){
$dm['contactId'] = $dm['id'];
}
if(isset($dm['isFromMe']) && $dm['isFromMe'] === true)
{
// return array('status' => true, "operation" => array("webhook" => array("status" => false, 'erro' => array("Mensagem enviada pela Imobles"))));
continue;
}
if(isset($dm['isFromMe']) && $dm['type'] == 'ticket')
{
// return array('status' => true, "operation" => array("webhook" => array("status" => false, 'erro' => array("Abertura de Ticket"))));
continue;
}
// START MYGPT
$pw_to_start = true;
$external_user = true;
$gpt_broker = false;
if($dm['serviceId'] == '0d038e4f-61a4-4e5e-9f6f-2714ca154c4b'){
$user_type = 'sys_user';
$pw_to_start = false;
$gpt_broker = true;
} elseif($dm['serviceId'] == 'e44394a5-55de-4f25-b5b8-dcbcb69cf473'){
$user_type = 'sys_user';
$external_user = false;
$gpt_broker = true;
} else {
$user_type = 'crm_account';
// return false;
}
$digisac_params = array("contact_id" => $dm['contactId'], "service_id" => $dm['serviceId'], "subject" => "MYGPT");
$mygptHelper = new MyGptHelper($user_type, $digisac_params, $external_user);
if(isset($dm['text']) && $dm['text'] === "#START_MY_GPT#"){
$mygpt = $mygptHelper->startMyGptChat($dm['contactId']);
return array('status' => true, "operation" => array("mygpt" => array("status" => true, 'erro' => null)));
} else {
if($gpt_broker == true){
$digisac_contact_details = ORM::for_table('module_imobles_mygpt_digisac_contacts')
->where('digisac_contact_id', $dm['contactId'])
->where('user_type', $user_type)->find_one();
if(!empty($digisac_contact_details->id)){
if($digisac_contact_details->user_type == 'sys_user'){
$user_id = $digisac_contact_details->sys_user_id;
$message = ORM::for_table('module_imobles_mygpt_messages')
->where('sys_user_id', $digisac_contact_details->sys_user_id)
->order_by_desc('id')
->find_one();
} else {
$user_id = $digisac_contact_details->crm_account_id;
$message = ORM::for_table('module_imobles_mygpt_messages')
->where('crm_account_id', $user_id)
->order_by_desc('id')
->find_one();
}
if(isset($message->id)){
$date1 = new DateTime();
$date2 = new DateTime($message->created_at);
$interval = $date1->diff($date2);
if($interval->h < 1200){
$return = $mygptHelper->readMessage($dm, $user_id);
return $return;
} else {
$mygpt = $mygptHelper->startMyGptChat($dm['contactId']);
return array('status' => true, "operation" => array("mygpt" => array("status" => true, 'erro' => null)));
}
}
} else {
if($pw_to_start == false){
$mygpt = $mygptHelper->startMyGptChat($dm['contactId']);
return array('status' => true, "operation" => array("mygpt" => array("status" => true, 'erro' => null)));
} else {
return false;
}
}
} else {
// Verifico se é um LEAD que precisa ser movido no pipe de Pre-venda
$digisac_contact_id = $dm['contactId'];
$client_aux = ORM::for_table('module_imobles_digisac_contacts')->where('contact_id', $dm['contactId'])->find_one();
if(!empty($client_aux->crm_account_id)){
$client_details = ORM::for_table('crm_accounts')->find_one($client_aux->crm_account_id);
} else {
$digisac_contact_details = $this->getContactDetails($dm['contactId']);
if(!empty($digisac_contact_details->data->number)){
$digisac_phone = $digisac_contact_details->data->number;
}
$country_code = substr($digisac_phone, 0, 2);
$phone_number = substr($digisac_phone,2);
$phone_number_short = null;
if($country_code == 55)
{
if(strlen($phone_number) <= 10)
{
$ddd = substr($phone_number, 0, 2);
$phone_number = substr($phone_number,2);
if(in_array($phone_number[0],[9,8,7]))
{
$phone_number_short = $country_code.$ddd.$phone_number;
$phone_number = '9'.$phone_number;
}
$phone_number = $ddd.$phone_number;
} else {
$ddd = substr($phone_number, 0, 2);
$phone_number_aux = substr($phone_number,3);
if(in_array($phone_number_aux[0],[9,8,7]))
{
$phone_number_short = $country_code.$ddd.$phone_number_aux;
}
}
}
$phone_number = $country_code.$phone_number;
$client_details = ORM::for_table('crm_accounts')->where('phone', $phone_number)->find_one();
}
if(!empty($client_details)){
$hs_client_details = ORM::for_table('module_imobles_hubspot_contacts')->where('crm_account_id', $client_details->id)->find_one();
if(!empty($hs_client_details->hs_object_id)){
$hs_object_id = $hs_client_details->hs_object_id;
$hsHelper = new hubspotHelper();
$hs_client_details = $hsHelper->getContactDetails($hs_object_id);
$hs_deals = $hsHelper->getDealsByContact($hs_object_id);
$count_open = 0;
$open_deal = null;
$last_deal = null;
/// IMPORTANTE RETIRAR ULTIMA STAGE
$deal_stages = [88315024,88332585, 88332586, 88332587, 88332588, 88332589];
$now = new DateTime('now', new DateTimeZone('America/Sao_Paulo'));
$hour = $now->format('H');
$day_week = $now->format('l');
$labor_day = false;
if($day_week != 'Sunday'){
if($day_week == 'Saturday'){
if(intval($hour) > 9 && intval($hour) < 18){
$labor_day = true;
}
} else {
if(intval($hour) > 9 && intval($hour) < 19){
$labor_day = true;
}
}
}
foreach($hs_deals as $deal){
if(!in_array($deal->properties->dealstage, $deal_stages)){
continue;
}
if($deal->properties->status_do_deal == 'Aberto - Conversando'){
$count_open++;
$open_deal = $deal;
}
if(empty($last_deal) || $deal->id > $last_deal->id){
$last_deal = $deal;
}
}
$deal_to_move = null;
if($count_open == 1){
$deal_to_move = $open_deal;
} elseif($count_open > 1){
$deal_to_move = $open_deal;
// Movo o Deal mais recente e envio um email notificando a duplicação do deal
} else {
// verifico se é pra reabrir o Deal
$deal_to_move = $last_deal;
$close_date = date('Y-m-d H:i:s', strtotime($deal_to_move->properties->closedate));
$close_date = new DateTime($close_date, new DateTimeZone('America/Sao_Paulo'));
$interval = $close_date->diff($now);
if($interval->days < 30){
$data_aux['status_do_deal'] = 'Aberto - Conversando';
$hsHelper->hubspotUpdateDealProperties($deal_to_move->id, $data_aux);
} else {
$deal_to_move = null;
}
}
if(!empty($deal_to_move)){
if($labor_day == true){
$data_aux['dealstage'] = '57109335';
// Pego o usuário
$dono_do_lead__sdr_ = $deal_to_move->properties->dono_do_lead__sdr_;
if(!empty($dono_do_lead__sdr_)){
$owner = $hsHelper->getOwnerById($dono_do_lead__sdr_);
if(!empty($owner->email)){
$userId = $this->getUserId($owner->email);
if(!empty($userId)){
$this->ticketAction($digisac_contact_id, 'transfer', $userId);
}
}
}
} else {
// encerro o chamado no digiscac
$this->ticketAction($digisac_contact_id, 'close');
$data_aux['dealstage'] = '88511750';
}
$hsHelper->hubspotUpdateDealProperties($deal_to_move->id, $data_aux);
}
}
}
}
}
}
}
public function getMessageDetails($digisac_message){
$curl = curl_init();
$url = "https://imobles.digisac.co/api/v1/messages?include%5B0%5D=file&include%5B6%5D%5Binclude%5D%5B0%5D=file&where%5Bid%5D=".$digisac_message->id;
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'GET',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1'
),
));
$response = curl_exec($curl);
curl_close($curl);
$response = json_decode($response);
return $response;
}
public function getServiceId($name = null, $region = null) {
if($name == null)
{
return false;
}
$serviceId = null;
// Pego o ServiceId (Usuario Vinculado ao contato)
$name = urlencode($name);
$url = "https://imobles.digisac.co/api/v1/services?"
. "query=%7B%22"
. "where%22%3A%7B%22"
. "name%22%3A%7B%22%24"
. "iLike%22%3A%22%25"
.$name.
"%25%22%7D%2C%22"
. "isArchived%22%3Afalse%7D%7D";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
'Content-Type: application/json'
));
$json_response = curl_exec($ch);
$result_service = json_decode($json_response);
if(!isset($result_service->total))
{
// Erro na API - Retornar mensagem de erro
$return = array("msg" => "Erro na conxeção com o Mande um Zap | Função: mandeUmZapGetServiceId | Informar Webmaster.",
"success" => false);
return $return;
}
elseif($result_service->total == 1)
{
$serviceId = $result_service->data[0]->id;
}
else
{
foreach($result_service->data as $d){
if(preg_match('/veiga/i',$d->name) && preg_match('/bcu/i',$d->name) && $region == 'BCU'){
$serviceId = $d->id;
} elseif(preg_match('/veiga/i',$d->name) && preg_match('/gyn/i',$d->name) && $region == 'GYN'){
$serviceId = $d->id;
}
}
if(empty($serviceId)){
if($region == 'GYN'){
$serviceId = '6221e13e-ca1f-434d-8656-7cc0bb49425d';
} elseif($region == 'BCU') {
$serviceId = '2822cb6b-d7e2-43f5-a252-f3c9fa3caea0';
} else {
$serviceId = '6221e13e-ca1f-434d-8656-7cc0bb49425d';
}
}
}
return $serviceId;
}
public function getUserId($email = null){
if($email == null)
{
return false;
}
// Pego o ServiceId (Usuario Vinculado ao contato)
$url = "https://imobles.digisac.co/api/v1/users?query=%7B%22where%22%3A+%7B%22email%22%3A+%7B%22%24eq%22%3A+%22".$email."%22%7D%7D%7D";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
'Content-Type: application/json'
));
$json_response = curl_exec($ch);
$result_service = json_decode($json_response);
if(!isset($result_service->total))
{
// Erro na API - Retornar mensagem de erro
$return = array("msg" => "Erro na conxeção com o Mande um Zap | Função: mandeUmZapGetAccountId | Informar Webmaster.",
"success" => false);
return $return;
}
elseif($result_service->total == 1)
{
$accountId = $result_service->data[0]->id;
}
else
{
// Pego o Whats Padrão de Goiânia
$accountId = null;
}
return $accountId;
}
public function createContact($name, $phone, $serviceId, $userId){
// Faço o cadastro do Lead no Mande um Zap
$data_contact = array(
'internalName' => $name,
'number' => preg_replace('/\D/', '', $phone),
'unsubscribed' => false,
'note' => 'CRIADO PELA AUTOMAÇÃO DE PRIMEIRO CONTATO',
'customFields' => [],
'serviceId' => $serviceId,
'personId' => null,
'defaultDepartmentId' => 'bcc09536-028e-44dc-b40e-cdd6249d69fb',
'defaultUserId' => $userId,
'tagIds' => ["1580656b-73ff-4bba-9c8d-2d1fa592c8ca","4f9f72c8-4d18-4548-8543-2ca3c9643060"],
'idFromService' => '',
'mergeRelations' => true
);
$postdata = json_encode($data_contact);
$url = 'https://imobles.digisac.co/api/v1/contacts';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
'Content-Type: application/json'
));
$json_response = curl_exec($ch);
$contact = json_decode($json_response);
if(!empty($contact->id)){
return $contact->id;
} else {
return false;
}
}
public function ticketAction($contactId, $action, $userId = null, $comments = null) {
$postdata = '{
"departmentId": "bcc09536-028e-44dc-b40e-cdd6249d69fb",
"userId": "'.$userId.'",
"comments": "'.$comments.'"
}';
$url = 'https://imobles.digisac.co/api/v1/contacts/'.$contactId.'/ticket/'.$action;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer 8cd3c1c07c14c260b98a4f1ee681e024b3945ab1',
'Content-Type: application/json'
));
$json_response = curl_exec($ch);
$result = json_decode($json_response);
if($result == 'OK')
{
return true;
}
else
{
return false;
}
}
}