Browse Source

Alterações Fly Link e outros

master
Lucas Ayala 3 years ago
parent
commit
5c5e6299c4
  1. 432
      Clientes/Fly Link/Integracao.php
  2. 943
      Clientes/Fly Link/IntegracaoDataBase.php
  3. 661
      Clientes/Fly Link/IxcSoft.php
  4. 157
      Clientes/Fly Link/Logger.php
  5. 258
      Clientes/Fly Link/SimpleMail.php
  6. 19
      Clientes/Fly Link/abreAtendimento.php
  7. 356
      Clientes/Fly Link/bkp/Integracao.php
  8. 426
      Clientes/Fly Link/bkp/IntegracaoDataBase.php
  9. 419
      Clientes/Fly Link/bkp/IxcSoft.php
  10. 157
      Clientes/Fly Link/bkp/Logger.php
  11. 258
      Clientes/Fly Link/bkp/SimpleMail.php
  12. 81
      Clientes/Fly Link/bkp/config.php
  13. 54
      Clientes/Fly Link/bkp/consultaCliente.php
  14. 36
      Clientes/Fly Link/bkp/consultaPendencia.php
  15. 44
      Clientes/Fly Link/bkp/desbloqueiaCliente.php
  16. 33
      Clientes/Fly Link/bkp/email.html
  17. 36
      Clientes/Fly Link/bkp/enviaBoleto.php
  18. 19
      Clientes/Fly Link/bkp/paradaTecnica.php
  19. 356
      Clientes/Fly Link/conf.php
  20. 6
      Clientes/Fly Link/confRotas.php
  21. 99
      Clientes/Fly Link/config.php
  22. 92
      Clientes/Fly Link/consultaCliente.php
  23. 59
      Clientes/Fly Link/consultaClienteTelefone.php
  24. 19
      Clientes/Fly Link/consultaPendencia.php
  25. 32
      Clientes/Fly Link/desbloqueiaCliente.php
  26. 33
      Clientes/Fly Link/email.html
  27. 24
      Clientes/Fly Link/enviaFatura.php
  28. 518
      Clientes/Fly Link/install.php
  29. 57
      Clientes/Fly Link/integracaoTela.php
  30. 18
      Clientes/Fly Link/paradaTecnica.php
  31. 8
      Clientes/Fly Link/reload.php
  32. 11
      Clientes/Fly Link/teste.php
  33. 2
      Clientes/TopNet/EnviaFatura.php
  34. 98
      PlaceholderTest/EnviaBoletoEmail.php
  35. 300
      PlaceholderTest/Integracao.php
  36. 337
      PlaceholderTest/IntegracaoDataBase.php
  37. 147
      PlaceholderTest/Logger.php
  38. 79
      PlaceholderTest/config.php
  39. 25
      PlaceholderTest/consultaCliente.php
  40. 84
      PlaceholderTest/placeHolder.php

432
Clientes/Fly Link/Integracao.php

@ -0,0 +1,432 @@
<?php
require_once 'phpagi/phpagi.php';
require_once 'IntegracaoDataBase.php';
require_once 'Logger.php';
require_once 'SimpleMail.php';
require_once 'conf.php';
// include("util/util.php");
/*
|*************************************************************************
| SISTEMA UNICO DE INTEGRACAO *
|*************************************************************************
*/
/**
* Classe para implementacao das integracoes da Simples IP
* @author Lucas Awade
* @Desenvolvedor
* @SimplesIP
* @version 1.1.1
*/
class Integracao {
protected $log;
protected $mail;
private $agi;
private $db;
########################################################################
## CONSTANTES DA CLASSE ##
########################################################################
const PATH_SOUND = '/var/lib/asterisk/sounds/customizados/';
const AGI_ERROR_HANDLER = false;
########################################################################
## FUNCOES UTILITARIAS ##
########################################################################
/**
* - Retorno é os dados referentes ao retornado da API
* - Params são os dados que serão disponibilizados na tela do agente.
*
* @param array $retorno
* @param array $params
*/
public function integracaoAgente($retorno, $params) {
$registros = 0;
$data = $this->db()->getRegistros();
$retorno_cliente = "{$data['reg_uniqueid']}|{$data['reg_fone']}|{$data['id']}|";
foreach ($retorno as $key => $value) {
if (in_array($key, $params)) {
$registros++;
$retorno_cliente .= sprintf("%s:%s",
strtoupper(str_replace("_", " ", $key)),
strtoupper(str_replace("|", "", $value)));
if (count($params) > $registros) {
$retorno_cliente .= "|";
}
}
}
$this->db()->setRegistros(array('retorno_cliente' => $retorno_cliente));
}
/**
* Converte um CPF ou CNPJ com marcara referente a cada modelo.
*
* @param string $string
* @return boolean|string
*/
protected function mask_cpf_cnpj($string) {
if (!empty($string)) {
if (strlen($string) == 11) {
$mask = "%s%s%s.%s%s%s.%s%s%s-%s%s";
} elseif (strlen($string) == 14) {
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s";
}
return vsprintf($mask, str_split($string));
} else {
return false;
}
}
/**
* Retorna telefone com o (DDD)Numero de acordo com o parametro passado caso nao possua DDD sera o padrao da central.
* @param string $telefone
* @return array
*/
protected function mask_phone_tel($telefone) {
$retorno = array('telefone' => '', 'type' => '');
if (strlen($telefone) == 11) {
$numero_1 = substr($telefone, 2, 5);
$numero_2 = substr($telefone, 7, 4);
$ddd = substr($telefone, 0, 2);
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2;
$retorno['telefone'] = $telefone;
$retorno['type'] = 'celular';
} else if (strlen($telefone) == 12) {
$ddd = substr($telefone, 1, 2);
$numero = substr($telefone, 3, 10);
$telefone = sprintf("(%s) %s", $ddd, $numero);
$retorno['telefone'] = $telefone;
$retorno['type'] = 'telefone';
} else if (strlen($telefone) == 13) {
$ddd = substr($telefone, 2, 2);
$numero = substr($telefone, 4, 10);
$telefone = "(" . $ddd . ") " . $numero;
$retorno['telefone'] = $telefone;
$retorno['type'] = 'celular';
} else if (strlen($telefone) == 10) {
$numero_1 = substr($telefone, 2, 4);
$numero_2 = substr($telefone, 6, 9);
$ddd = substr($telefone, 0, 2);
$telefone = "({$ddd}) " . $numero_1 . '-' . $numero_2;
$retorno['telefone'] = $telefone;
$retorno['type'] = 'fixo';
} else {
return null;
}
return $retorno;
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
protected function getArgs($args) {
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
/**
* Verifica a diferenca em dias entre a data de entrada e a data atual.
*
* @param type $dateParam
* @return type
*/
public function dateDiff($dateParam) {
$dateIni = strtotime(date('Y-m-d'));
if (strstr($dateParam, "/")) {
$dateParam = date(strtotime(str_replace('/', '-', $dateParam)));
} else {
$dateParam = date(strtotime($dateParam));
}
$diff = ($dateIni - $dateParam);
$days = (int) floor($diff / (60 * 60 * 24));
return $days;
}
/**
* Realiza a conversao de datas no formato brasileiro para a Defualt.
* @param string $data
* @return string|boolean
*/
public function convertDateDefault($data) {
if ($data) {
$data = explode('/', $data);
return "{$data[2]}-{$data[1]}-{$data[0]}";
}
return false;
}
/**
* Realiza a validação de pendencia financeira de acordo com a data informada
*
* OBS: O array deve possui nível = array( array('data' => 'yyyy-mm-dd'))
* OBS: O indice deve ser o nome do valor onde se encontra a data.
* @param array $array
* @param string $indice
* @param string $datavalida
* @return boolean
*/
public function verificaDataPendencia($array, $indice, $datavalida = null) {
if (!$datavalida) {
$datavalida = strototime(date('Y-m-d'));
} else {
$datavalida = strtotime($datavalida);
}
foreach ($array as $value) {
if (strtotime($value[$indice]) < $datavalida) {
return false;
}
}
return true;
}
/**
* Adiciona mascara no telefone para realizar a consulta
*
* @param type $value
* @return boolean
*/
protected function phoneMask($value) {
if (!empty($value)) {
if (strlen($value) == 10) {
$mask = '(%s%s)%s%s%s%s-%s%s%s%s';
} elseif (strlen($value) == 11) {
$mask = '(%s%s)%s%s%s%s%s-%s%s%s%s';
}
return vsprintf($mask, str_split($value));
} else {
return false;
}
}
/**
* Verifica se um servidor esta dando resposta de ping
* @param type $ip
* @return boolean
*/
public function verificaLatencia($ip) {
$ping = explode(",", shell_exec("ping -c 4 $ip"));
$latencia = substr($ping[1], 1, 2); //resposta do ping
if ($latencia >= 2) {
return true;
}
return false;
}
/**
* Verbaliza digitos
* @param string|int $string
*/
public function verbaliza($string) {
$vocaliza = str_split($string);
foreach ($vocaliza as $value) {
$this->agi()->say_digits($value);
}
}
/*
* Objetct to array
*/
public function objectToArray($d) {
if (is_object($d)) {
$d = get_object_vars($d);
}
if (is_array($d)) {
return array_map($this->objectToArray(), $d);
} else {
return $d;
}
}
############################################################################
######## CONFIGURACAO DE EMAIL ########
############################################################################
/**
* Inicia a instanciacao da Classe para envio de Email
* @param string $email
* @param string $password
* @param string $subject
*/
public function SimpleMail($email, $password, $subject) {
$this->mail = new SimpleMail($email, $password, $subject);
$this->log->debug("Instanciacao SimpleMail : " . ($this->mail ? "SUCCESS" : "FAIL"), debug_backtrace());
}
/**
* Configura o servidor de Envio dos Emails.
* @param string $host
* @param string|int $port
* @param string $title
* @return boolean
*/
public function confSMTP($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') {
$this->log->debug("Configuracao SMTP", debug_backtrace());
if ($this->mail) {
$this->mail->config($host, $port, $title, $smtpAuth, $smtpSecure, $charset);
} else {
return false;
}
}
public function geraProtocoloSimples($uid){
$connPG = $this->db()->getConnection();
$protoAgente = GeraProtocolo($connPG, $uid);
return $protoAgente;
}
########################################################################
## FUNCOES IMPORTANTES ##
########################################################################
/**
* Instancia um objeto de Logger.
*
* @param Logger $log
*/
protected function setLog($log = false) {
if (!$this->log) {
$this->log = new Logger(CONF_LOGGER_PATH . CONF_NOME_EMPRESA, $log);
}
}
/**
* Retorna o objeto de Log.
* @return string
*/
public function log() {
return $this->log;
}
/**
* Instancia um objeto de AGI para se conectar com as informações do Asterisk.
*
* @return AGI
*/
public function agi() {
if (!$this->agi) {
$data = $this->db()->getAuthAgi();
$config = array();
$config['phpagi']['error_handler'] = self::AGI_ERROR_HANDLER;
$config['asmanager']['server'] = $data['host_sck'];
$config['asmanager']['port'] = $data['porta_sck'];
$config['asmanager']['username'] = $data['usuario_sck'];
$config['asmanager']['secret'] = $data['senha_sck'];
$agi = new AGI('phpagi.conf', $config);
$this->agi = $agi;
return $agi;
}
return $this->agi;
}
private function readAgiVariable() {
ob_implicit_flush(true);
set_time_limit(6);
$in = fopen("php://stdin", "r");
$input = str_replace("\n", "", fgets($in, 4096));
fclose($in);
$this->log->debug("Reading: " . $input);
return $input;
}
public function getAgiVariable($variable = null) {
$this->log->debug("Executing...", debug_backtrace());
while ($env = $this->readAgiVariable()) {
$s = explode(": ", $env);
$agi[str_replace("agi_", "", $s[0])] = trim($s[1]);
$this->log->debug("Data: " . print_r($agi, true), debug_backtrace());
if (($env == "") || ($env == "\n")) {
break;
}
}
$this->log->debug("Reading: " . print_r($agi, true));
if (!$variable || $agi[$variable]) {
return !$variable ? $agi : $agi[$variable];
}
return false;
}
/**
* Instancia um objeto de IntegracaoDataBase para se conectar com dados do
* Banco de dados e credenciais do Manager.
*
* @return IntegracaoDataBase
*/
public function db() {
if (!$this->db) {
$db = new IntegracaoDataBase();
$this->db = $db;
}
return $this->db;
}
protected function audioError() {
$this->log->debug('Audio de error');
$exten = $this->db()->getAnuncio();
$this->log->error('Encaminhando para áudio alternativo de Erros', debug_backtrace());
$this->agi()->exec_goto($exten);
exit();
}
protected function integracaoReg(){
global $ura, $tronco, $uid, $idMetodo, $uidOld, $numero;
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$this->db()->setRegistros($registros);
if (CONF_AUDIO_ERROR) {
$this->db()->setIdAudioError($this->db()->getAnuncioIdByName(strtoupper(CONF_AUDIO_ERROR.CONF_NOME_EMPRESA.CONF_VERSAO)));
}
}
public function executarFluxo($tipo, $nome){
#INEGRACAO DE TELA
if(CONF_INTEGRACAO_TELA){
$parametrosTela = unserialize(CONF_PARAMETROS_TELA);
$itgcTela = array();
$itgcTelaNomes = array();
foreach($parametrosTela as $parametro){
$itgcTela[$parametro] = str_replace(array("|",":"),"-",utf8_decode($this->agi()->get_variable($parametro, true)));
$itgcTelaNomes[] = "$parametro";
}
$this->integracaoAgente($itgcTela, $itgcTelaNomes);
}
$dbFunction = "get".ucfirst(strtolower($tipo));//CONTRUIR NOME FUNCAO BUSCAR ID
$this->agi()->exec_goto($this->db()->$dbFunction(strtoupper($nome)));//REDIRECIONAR FLUXO
$this->db()->atualizaIntegracao();
}
}

943
Clientes/Fly Link/IntegracaoDataBase.php

@ -0,0 +1,943 @@
<?php
require_once 'Logger.php';
// *************************************************************************
// * SISTEMA UNICO DE INTEGRACAO *
// *************************************************************************
/**
* Classe para utilizar os registros do Banco de Dados;
*
* OBS: Deixar como usuario de execucao e acesso pbx:pbx
*
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IntegracaoDataBase {
private $query;
private $connection;
private $registros;
private $log;
private $credentials = array();
private $debug;
private $idAudioError;
/**
* @file
* Arquivo de configuracoes do banco e manager
*/
const FILE_DB = "/var/www/html/include/bd";
public function __construct() {
$this->log = new Logger(CONF_LOGGER_PATH, CONF_LOGGER_DB_ATIVO);
}
/**
* Retorna os registros armazenados na variavel registros pra ser disponibilizado
* no decorrer de uma integracao;
*
* @return array
*/
public function getRegistros() {
return $this->registros;
}
/**
* Informações coletadas do banco de dados para ser escritas no log.
*
* @param array $array
*/
private function logResult($array) {
if ($array) {
$this->log->success(print_r($array, true), $this->debug);
} else {
$this->log->warning('Nenhum resultado encontrado!', $this->debug);
}
}
/**
* Audio de erro padrao
*
* @param string $idAudioError
*/
public function setIdAudioError($idAudioError) {
$this->idAudioError = $idAudioError;
}
########################################################################
## BANCO DE DADOS ##
########################################################################
/**
* Pega as informacoes das credenciais no arquivos padrao "bd";
*/
private function filedb() {
if (file_exists(self::FILE_DB)) {
$contents = fopen(self::FILE_DB, 'r');
while (!feof($contents) && $contents) {
$str = fgets($contents);
$dados = explode('=', $str);
$this->credentials[strtolower($dados[0])] = str_replace('"', '', $dados[1]);
}
fclose($contents);
$this->credentials = array_filter($this->credentials);
$this->log->debug("Credenciais banco de dados: " . print_r($this->credentials, true), debug_backtrace());
} else {
$this->log->error("Nao foi possivel encontrar o arquivo 'bd' em " . self::FILE_DB);
}
}
/**
* Executa as querys da consulta a serem feitas, além de gravar logs de registros de dados,
* e qualquer erro é repassado a classe que está executando para tratar o erro;
*
* @param string $type
* @return boolean|array
*/
private function execute($type = '') {
try {
if (!$this->connection) {
$this->connection = $this->getConnection();
}
$result = pg_query($this->connection, $this->query);
switch (strtolower($type)) {
case 'assoc':
$data = pg_fetch_assoc($result);
break;
case 'row':
$data = pg_fetch_row($result);
break;
case 'array':
$data = pg_fetch_array($result);
break;
case 'all':
$data = pg_fetch_all($result);
break;
}
$this->logResult($data);
return $data;
} catch (Exception $ex) {
$this->log->error("Exception: {$ex->getMessage()} | Postgres : " . pg_last_error(), $this->debug);
}
}
public function getConnection() {
$this->filedb();
$this->connection = pg_connect(sprintf('host=%s port=%s dbname=%s user=%s password=%s', $this->credentials['host_db'], $this->credentials['porta_db'], $this->credentials['base_db'], $this->credentials['usuario'], $this->credentials['senha']));
if (pg_connection_status($this->connection) === 0) {
$this->log->success("Conectado na base {$this->credentials['base_db']}.", debug_backtrace());
return $this->connection;
} else {
throw new Exception('Nao foi possivel conectar na base de dados');
}
}
private function getPDO() {
try {
if (!$this->connection) {
$drive = CONF_DB_DRIVER;
$host = CONF_DB_HOST;
$dbname = CONF_DB_BASE;
$user = CONF_DB_USER;
$pass = CONF_DB_PASSWD;
$this->connection = new pdo("$drive:host=$host;dbname=$dbname", $user, $pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
protected function strquery($stmt, $params) {
foreach ($params as $key => $value) {
if (!$value || $value == "null") {
$value = null;
}
$stmt->bindValue(":{$key}", $value, (is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR));
}
}
public function read($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function create($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$data = $this->connection->lastInsertId();
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function delete($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$count = $stmt->rowCount();
$data = (!$count) ? false : true;
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
public function update($query, $params) {
try{
$this->getPDO();
$stmt = $this->connection->prepare($query);
$this->strquery($stmt, $params);
$stmt->execute();
$count = $stmt->rowCount();
$data = (!$count) ? false : true;
return $data;
} catch (PDOException $ex) {
$this->log->error("Exception: {$ex->getMessage()} ", $this->debug);
}
}
########################################################################
## ASTERISK ##
########################################################################
/**
* Coleta em qual Asterisk a central está rodadando e retorna o modelo padrao
* de configuracao do exten;
*
* @return string
*/
private function getVersionAsterisk() {
$result = array();
exec("asterisk -V", $result);
$this->log->info("Versao Asterisk: " . $result[0], debug_backtrace());
if (strpos($result[0], '1.4') !== false) {
return "|";
} else {
return ",";
}
}
/**
* Transforma uma string exten com "," para "|" de acordo com a versao do Asterisk
*
* @param string $string
* @return string
*/
private function string_exten($string) {
return str_replace(",", $this->getVersionAsterisk(), $string);
}
/**
* Coleta os dados de autenticacao do manager.
*
* @return array
*/
public function getAuthAgi() {
$data = array();
foreach ($this->credentials as $key => $value) {
if (strpos($key, '_sck') !== false) {
$data[$key] = $value;
}
}
return $data;
}
########################################################################
## QUERYS ##
########################################################################
/**
* Inicia um Transacao;
*/
public function beginTransaction() {
$this->debug = debug_backtrace();
$this->query = "BEGIN;";
$this->execute();
}
/**
* Registra uma Transacao.
*/
public function commitTransaction() {
$this->debug = debug_backtrace();
$this->query = "COMMIT;";
$this->execute();
}
/**
* Retorna as informacoes antes da Transacao.
*/
public function rollbackTransaction() {
$this->debug = debug_backtrace();
$this->query = "ROLLBACK;";
$this->execute();
}
/**
* Busca o DDD padrao cadastrado na central.
*
* @param string $name
* @return string
*/
public function getDDD() {
$this->debug = debug_backtrace();
$this->query = "SELECT prm_ddd_padrao FROM pbx_parametros";
return $this->execute('assoc') ? $this->execute('assoc')['prm_ddd_padrao'] : '';
}
/**
* Consulta no banco o nome do Anuncio e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getAnuncio($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-anuncios,a%s,1'), $result);
}
/**
* Consulta no banco o nome do Ura e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getUra($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ura-%s,s,1'), $result);
}
/**
* Consulta no banco a Ura por ID e retorna suas informacoes;
*
* @param string|int $id
* @return string
*/
public function getURAById($id) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_ura WHERE id = '{$id}'";
$result = $this->execute('assoc') ? $this->execute('assoc') : $this->idAudioError;
return $result;
}
/**
* Consulta no banco o nome do Fila e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getFila($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_dacs WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-fila,%s,1'), $result);
}
/**
* Consulta no banco o nome do Ramal e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getRamal($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ramais WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-ramais,%s,1'), $result);
}
public function getAtendimentoLastURA($uniqueid) {
$this->debug = debug_backtrace();
$this->query = "SELECT umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao, umv_opcao, umv_acao "
. "FROM pbx_ura_movimento "
. "WHERE uniqueid = '{$uniqueid}'"
. "AND umv_tipo = 'opc'"
. "ORDER BY data_reg DESC LIMIT 1";
$result = $this->execute('all');
return $result;
}
/**
* Coleta as opcoes que o usuario passou nas uras da sua chamada.
*
* @param string $uniqueid
* @param int $ura_id
* @return boolean|array
*/
public function getOptionsURA($uniqueid, $ura_id) {
$this->debug = debug_backtrace();
$this->query = "SELECT umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao "
. "FROM pbx_ura_movimento WHERE uniqueid = '$uniqueid' "
. "AND umv_ura_opcao IS NOT NULL AND umv_opcao = 'ura' "
. "AND umv_ura_id = $ura_id "
. "ORDER BY umv_id";
return $this->execute('all');
}
/**
* Retorna o ID e Data Hora da primeira entrada da ligacao em um URA de
* acordo com o uniqueid;
* @param string $uniqueid
* @return array
*/
public function getFristURA($uniqueid) {
$this->debug = debug_backtrace();
$this->query = "SELECT destino, min(data_registro) "
. "FROM ast_bilhetes_complemento "
. "WHERE direcao = 'ura' "
. "AND uniqueid2 = '{$uniqueid}' GROUP BY destino LIMIT 1";
$result = $this->execute('assoc');
return $result;
}
public function registraIntegracao() {
$this->debug = debug_backtrace();
/**
* Parametros REGISTROS
*
* id -> Id do qual gerou a integracao para o retorno_cliente
*
* Todos os parametros devem ser igual a da tabela pbx_integracao_reg
*/
$ura = trim($this->registros['reg_ura']) ? trim($this->registros['reg_ura']) : 'null';
$tronco = trim($this->registros['reg_tronco']) ? trim($this->registros['reg_tronco']) : 'null';
$this->query = "INSERT INTO pbx_integracao_reg (reg_id_metodo,reg_uniqueid,reg_uniqueid_old,reg_fone,reg_inicio, reg_tronco, reg_ura)
VALUES('{$this->registros['reg_id_metodo']}','{$this->registros['reg_uniqueid']}','{$this->registros['reg_uniqueid_old']}','{$this->registros['reg_fone']}', now(), '$tronco', '$ura')";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function atualizaIntegracao() {
$this->debug = debug_backtrace();
$tronco = trim($this->registros['reg_tronco']) ? sprintf(",\nreg_tronco='%s'", trim($this->registros['reg_tronco'])) : '';
$ura = trim($this->registros['reg_ura']) ? sprintf(",\nreg_ura='%s'", trim($this->registros['reg_ura'])) : '';
$reg_msg = QuotedStr($this->registros['reg_msg']);
$reg_retorno = QuotedStr($this->registros['reg_fone']);
$retorno_cliente = substr($this->registros['retorno_cliente'], 0, 255);
$this->query = "UPDATE pbx_integracao_reg
SET reg_fim = NOW(),
reg_retorno = $reg_retorno,
reg_msg = $reg_msg,
reg_status_exec = '{$this->registros['reg_status_exec']}',
retorno_cliente = '{$retorno_cliente}'{$tronco}{$ura}
WHERE reg_uniqueid = '{$this->registros['reg_uniqueid']}'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/**
* Informa os dados para ser inseridos na tabela de integracao_reg;
*
* @param array $registros
*/
public function setRegistros($registros) {
if (is_array($registros) && !$this->registros) {
$this->registros = $registros;
$this->registraIntegracao();
} else {
foreach ($registros as $key => $value) {
$this->registros[$key] = $value;
}
}
}
/**
* Retorna todas as informacoes da tabela Supervisor_Dacs
* @param array $dacs
* @return array
*/
public function getSupervisorDAC($dacs = array()) {
$this->query = "SELECT * FROM pbx_supervisor_dacs ";
if ($dacs) {
$this->query .= sprintf("WHERE id IN (%s)", implode(",", $dacs));
}
return $this->execute('all');
}
/**
* Retorna credenciais cadastradas nos metodos de integracao
* @param int $id
* @return array
*/
public function getConexaoAPI($id) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao
WHERE itgc_id = {$id}";
return $this->execute('assoc');
}
public function getScriptCredenciais($script) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao a
INNER JOIN pbx_integracao_metodo b ON a.itgc_id = b.itgc_id
WHERE itgm_comando = '{$script}'";
return $this->execute('assoc');
}
public function getFilaPorNome($name) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_dacs WHERE nome = '$name'";
return $this->execute('assoc');
}
public function getLastUraPorUniqueid($uniqueid) {
$this->query = "SELECT data_reg, umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao
FROM pbx_ura_movimento WHERE uniqueid = '{$uniqueid}'
ORDER BY data_reg DESC
LIMIT 1";
return $this->execute('assoc');
}
public function getUraMovimentoByUniqueid($uniqueid, $orderByAtt = "data_reg", $orderByType = "ASC") {
$this->query = "SELECT data_reg, umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao, umv_opcao
FROM pbx_ura_movimento WHERE uniqueid = '{$uniqueid}'
ORDER BY $orderByAtt $orderByType
LIMIT 1";
return $this->execute('assoc');
}
public function atualizaProtocoloParceiro($uid, $protocoloParceiro) {
$this->debug = debug_backtrace();
$this->query = "UPDATE pbx_protocolo_reg
SET protoparceiro='$protocoloParceiro'
WHERE uniqueid='$uid'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function atualizaDadosAgente($uniqueid, $historico) {
$this->debug = debug_backtrace();
$this->query = "UPDATE pbx_supervisor_agentes "
."SET cont_identificador = cont_identificador || '|HISTORICO:$historico' WHERE uniqueid = '$uniqueid'";
return $this->execute();
}
########################################################################
#### INSTALACAO INTEGRACAO ####
########################################################################
public function findIntegracaoCustom() {
$this->debug = debug_backtrace();
$this->query = "SELECT itgp_id FROM pbx_integracao_protocolo WHERE itgp_descricao = 'Custom'";
$this->log->debug("Query: {$this->query}", $this->debug);
$return = $this->execute('assoc');
if (!$return['itgp_id']) {
$this->query = "INSERT INTO pbx_integracao_protocolo (itgt_id,itgp_id,itgp_descricao,itgp_status,itgp_prefix) VALUES(1,6,'Custom',0,'custom');";
$this->execute('assoc');
}
return 6;
}
public function findVersion($empresa = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT MAX(itgc_status) AS versao FROM pbx_integracao_configuracao where 1=1";
if($empresa){
$this->query .= "AND itgc_nome like '%$empresa%'";
}
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute('assoc');
}
public function createIntegracaoAtiva($nome, $versao, $comando) {
$this->debug = debug_backtrace();
$query = "insert into pbx_integracao_metodo(itgc_id, itgm_nome, itgm_comando, itgm_tipo, itgm_retorno, itgm_status, opcao, evento, stored_params, itgm_id_pai) values(%s,'%s','%s',%s,%s,%s,'%s',%s,'%s',%s) returning itgm_id;";
$this->query = "INSERT INTO pbx_integracao_configuracao "
. "(itgt_id, itgp_id, itgc_nome, itgc_host, itgc_port, itgc_database, itgc_user, itgc_password, itgc_timeout, itgc_status) "
. "VALUES (1, 6, '$nome', '127.0.0.1', '0', '0', '0', '0', '10', '$versao') RETURNING itgc_id; ";
$this->log->debug("Query: {$this->query}", $this->debug);
$return = $this->execute('assoc');
$this->query = sprintf($query, $return['itgc_id'], $nome, $comando, 1, 1, 0, 'anuncios', 'null', 'null', 'null');
$res = $this->execute('assoc');
unset($this->query);
for ($x = 2; $x < 4; $x++) {
$this->query .= sprintf($this->query, $return['itgc_id'], 'NOEXEC', 'NOEXEC', 1, 0, 0, 'null', $x, 'null', $res['itgm_id']);
}
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute('assoc');
}
/* Consulta no banco o nome da integracao metodo e retorna o ID;
*
* @param string $name
* @return string
*/
public function getIntegracaoMetodoByNameIntegracao($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT pim.itgm_id
FROM pbx_integracao_metodo pim INNER JOIN pbx_integracao_configuracao pic on pic.itgc_id = pim.itgc_id
WHERE pim.itgm_retorno = 1 AND pic.itgc_nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
######################### ANUNCIOS #########################
/*
* Inserir Anuncio
*/
public function addAnuncio($nome, $musica, $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_anuncios (nome, musica, opcao, acao)
VALUES('%s','%s','%s', '%s')", $nome, $musica, strtolower($opcao), $acao);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Anuncio e retorna o ID;
*
* @param string $name
* @return string
*/
public function getAnuncioIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o id do Anuncio e retorna o nome;
*
* @param string $name
* @return string
*/
public function getAnuncioNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_anuncios WHERE id = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco a acao e opcao do Anuncio;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateAnuncio($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_anuncios
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
######################### URAS #########################
/*
* Inserir Ura
*/
public function addUra($nome, $som_ura, $tempo_espera = 5, $timeout_digito = 3, $permite_ligacao = 'N', $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_ura (nome, permite_ligacao, tempo_espera, som_ura, opcao, acao, timeout_digito)
VALUES('%s', '%s', %d, '%s', '%s', %d, '%s')", $nome, $permite_ligacao, $tempo_espera, $som_ura, strtolower($opcao), $acao, $timeout_digito);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Ura e retorna o ID;
*
* @param string $name
* @return string
*/
public function getUraIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o ID do Ura e retorna o nome;
*
* @param string $name
* @return string
*/
public function getUraNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ura WHERE id = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco acao e opcao do Ura;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateUra($id, $opcao, $acao) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_ura
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
######################### URAS DESTINO #########################
/*
* Inserir Ura Destino
*/
public function addUraDestino($id_ura, $numero, $tipo, $comando = null, $sequencia, $nome_comando) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_ura_destino
(id_ura, numero, tipo, comando, sequencia, nome_comando)
VALUES(%d, '%s', '%s', '%s', %d, '%s')", $id_ura, $numero, $tipo, $comando, $sequencia, $nome_comando);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute(s);
}
/* Consulta no banco o nome do Ura e retorna os destinos;
*
* @param string $name
* @return string
*/
public function getUraDestinosIdByUraName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT pud.* FROM pbx_ura_destino pud inner join pbx_ura pu on pu.id = pud.id_ura WHERE pu.nome ='$name'";
$result = $this->execute('all');
return $result;
}
/* Atualiza no banco acao e opcao do Ura;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateUraDestino($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_ura
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
######################### HORARIOS #########################
/*
* Inserir Horario
*/
public function addHorario($nome, $opcao = null, $acao = null, $status = 1) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_horarios
(nome, opcao_nao, acao_nao, status)
VALUES('%s', '%s', %d, %d)", $nome, strtolower($opcao), $acao, $status);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Horario e retorna o ID;
*
* @param string $name
* @return string
*/
public function getHorarioIdByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_horarios WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o ID do Horario e retorna o nome;
*
* @param string $name
* @return string
*/
public function getHorarioNameById($id = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_horarios WHERE nome = '$id'";
$result = $this->execute('row')[0];
return $result;
}
/* Atualiza no banco opcao e acao do Horario;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateHorario($id, $opcao, $acao) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_horarios
SET opcao_nao='%s', acao_nao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
######################### HORARIOS ITENS #########################
/*
* Inserir Horario
*/
public function addHorarioItens($id_horario, $horario_ini = '08:00', $horario_fim = '17:59', $dias_semana = 0, $semana = 'mon', $semana_fim = 'fri', $opcao = null, $acao = null) {
$this->debug = debug_backtrace();
$this->query = sprintf("INSERT INTO pbx_horarios_itens
(id_horario, horario_inicio, horario_fim, todos_dias_semana, semana, semana_fim, opcao, acao)
VALUES(%d, '%s', '%s', %d, '%s', '%s', '%s', '%s')", $id_horario, $horario_ini, $horario_fim, $dias_semana, $semana, $semana_fim, $opcao, $acao);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/* Consulta no banco o nome do Horario retornar Horario Itens;
*
* @param string $name
* @return string
*/
public function getHorarioItensByHorarioName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT phi.* FROM pbx_horarios_itens phi INNER JOIN pbx_horarios ph ON ph.id = phi.id_horario WHERE ph.nome = '$name'";
$result = $this->execute('all');
return $result;
}
/* Atualiza no banco a opcao e acao do Horario Item;
*
* @param $opcao $acao Iid
* @return string
*/
public function updateItemHorario($opcao, $acao, $id) {
$this->debug = debug_backtrace();
$this->query = sprintf("UPDATE pbx_horarios_itens
SET opcao='%s', acao='%s'
WHERE id=%d", strtolower($opcao), $acao, $id);
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
######################### FILAS #########################
/* Consulta no banco o nome da Fila e retorna o numero;
*
* @param string $name
* @return string
*/
public function getFilaNumeroByName($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_queues_grupos WHERE nome = '$name'";
$result = $this->execute('row')[0];
return $result;
}
/* Consulta no banco o numero da Fila e retorna o Nome;
*
* @param string $name
* @return string
*/
public function getFilaNameByNumero($numero = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_queues_grupos WHERE numero = '$numero'";
$result = $this->execute('row')[0];
return $result;
}
######################### HELPERS INSTALL ########################
public function getIdDirecionamento($tipo, $nome){
switch ($tipo) {
case CONF_URA:
return $this->getUraIdByName($nome) . "-" . $nome;
break;
case CONF_ANUNCIOS:
return $this->getAnuncioIdByName($nome);
break;
case CONF_HORARIO:
return $this->getHorarioIdByName($nome);
break;
case CONF_INTEGRACAO:
return $this->getIntegracaoMetodoByNameIntegracao($nome);
break;
case CONF_FILAS:
return $this->getFilaNumeroByName($nome);
break;
default:
break;
}
}
public function getNomeDirecionamento($tipo, $id){
$id = intval($id);
switch ($tipo) {
case CONF_URA:
return $this->getUraNameById($id);
break;
case CONF_ANUNCIOS:
return $this->getAnuncioNameById($id);
break;
case CONF_HORARIO:
return $this->getHorarioNameById($id);
break;
case CONF_INTEGRACAO:
return null;
break;
case CONF_FILAS:
return $this->getFilaNameByNumero($id);
break;
default:
break;
}
}
public function redirectUraDestino($ura, $status, $nomenclatura){
$ura_destinos = $this->getUraDestinosIdByUraName($ura.$nomenclatura);
foreach($ura_destinos as $destino){
if($destino['numero'] == strtoupper($status)){
return array(
"TIPO" => str_replace("s","",trim($destino['tipo'])),
"NOME" => $this->getNomeDirecionamento(trim($destino['tipo']), $destino['comando'])
);
}
}
return array("TIPO" => "ANUNCIO", "NOME" => CONF_AUDIO_ERROR.$nomenclatura);//DEFAULT
}
}

661
Clientes/Fly Link/IxcSoft.php

@ -0,0 +1,661 @@
<?php
require_once 'Integracao.php';
include 'config.php';
/**
* Classe para utilizar as API da empresa IXCSoft
*
* @documentation: http://wiki.ixcsoft.com.br/index.php/Recursos_da_API
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IxcSoft extends Integracao
{
private $token;
private $url_api;
private $selfSigned;
private $metodo;
########################################################################
## VARIAVEIS DA CLASSE ##
########################################################################
private $query;
private $curl;
private $post = false;
private $params = array();
private $debug;
private $ssl = false;
########################################################################
## RECURSOS DA API ##
########################################################################
function listarBoleto($codCliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'fn_areceber.id_cliente',
"query" => $codCliente,
"oper" => '=',
"rp" => "2",
"sortname" => 'fn_areceber.data_vencimento',
"sortorder" => 'asc',
"grid_param" => $this->gridParams(
array(
array(
"TB" => "fn_areceber.liberado",
"OP" => "=",
"P" => "S",
"C" => "AND"
),
array(
"TB" => "fn_areceber.status",
"OP" => "!=",
"P" => "C"
),
array(
"TB" => "fn_areceber.status",
"OP" => "!=",
"P" => "R"
)
)
)
);
$this->setMetodo('fn_areceber');
return $this->setParams();
} else {
return false;
}
}
function listarClientes()
{
$this->debug = debug_backtrace();
$this->params = array(
"qtype" => "cliente.id",
"query" => "",
"oper" => "!=",
"page" => "1",
"rp" => "20",
"sortname" => "cliente.id",
"sortorder" => "desc",
);
$this->setMetodo('cliente');
return $this->setParams();
}
public function buscarCliente($cpf_cnpj)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
if (strlen($cpf_cnpj) == 11 || strlen($cpf_cnpj) == 14) {
$this->params = array(
"qtype" => "cliente.cnpj_cpf",
"query" => "{$this->mask_cpf_cnpj($cpf_cnpj)}",
"oper" => "=",
"sortname" => "cliente.id",
"sortorder" => "asc",
);
$this->setMetodo('cliente');
return $this->setParams();
} else {
return false;
}
} else {
return false;
}
}
public function buscarClienteTelefone($tipo, $telefone)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
if (strlen($telefone) == 10 || strlen($telefone) == 11 || strlen($telefone) == 14) {
$this->params = array(
"qtype" => "cliente.$tipo",
"query" => "{$this->mask_phone_tel($telefone)['telefone']}",
"oper" => "=",
"sortname" => "cliente.id",
"sortorder" => "asc"
);
$this->setMetodo('cliente');
return $this->setParams();
} else {
return false;
}
} else {
return false;
}
}
/**
* Status de bloqueio:
* CA - Bloqueio automatico
* CM - Bloqueio Manual
* A - Ativo
* AA - Aguardando assinatura
* D - Desativado
* DE - Data Expirou
*
* @param int $id_cliente
* @return boolean
*/
function listarContrato($id_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'cliente_contrato.id_cliente',
"query" => "$id_cliente",
"oper" => '=',
"sortname" => 'cliente_contrato.id',
"sortorder" => 'asc'
);
$this->setMetodo('cliente_contrato');
return $this->setParams();
} else {
return false;
}
}
/*
* Lista Clientes Conexoes
*/
function listarConexoes($id_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'radusuarios.id_cliente',
"query" => "$id_cliente",
"oper" => '=',
"sortorder" => 'asc'
);
$this->setMetodo('radusuarios');
return $this->setParams();
} else {
return false;
}
}
/*
* Lista Ordens de Servi<EFBFBD>o
*/
function listarOrdensServico($id_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'su_oss_chamado.id_cliente',
"query" => "$id_cliente",
"oper" => '=',
"sortorder" => 'asc'
);
$this->setMetodo('su_oss_chamado');
return $this->setParams();
} else {
return false;
}
}
/*
* Lista Clientes ONLINE
*/
function formaPagamento($id_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'cliente_contrato_tipo.id',
"query" => "$id_cliente",
"oper" => '=',
"sortorder" => 'asc'
);
$this->setMetodo('cliente_contrato_tipo');
return $this->setParams();
} else {
return false;
}
}
/*
* Alterar Status do Acesso
Liberar : cliente_contrato_15464
Aguardando Assinatura: cliente_contrato_23529
Avisar atraso: cliente_contrato_15463
Bloquear: cliente_contrato_15300
Retirar redu<EFBFBD><EFBFBD>o: cliente_contrato_29157
* */
function retirarReducao($contrato)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"id_contrato" => $contrato
);
$this->setMetodo('cliente_contrato_29157');
return $this->setParams();
} else {
return false;
}
}
function desbloqueiaCliente($contrato)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"id" => $contrato
);
$this->setMetodo('desbloqueio_confianca');
return $this->setParams();
} else {
return false;
}
}
/*
* @param codigo_cliente string
*/
function consultaFaturasVencidas($codigo_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$faturas = $this->listarBoleto($codigo_cliente)['registros'];
$faturasVencidas = [];
foreach ($faturas as $invoice) {
if (strtotime($invoice['data_vencimento'] . ' 23:59:59') < time() && $invoice['valor_aberto'] > 0) {
$faturasVencidas[] = $invoice;
}
}
return $faturasVencidas;
} else {
return false;
}
}
function enviaBoleto($type, $codigo_cliente)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$response = false;
$faturas = $this->listarBoleto($codigo_cliente)['registros'];
$this->setMetodo('get_boleto');
foreach ($faturas as $invoice) {
if (strtotime($invoice['data_vencimento'] . ' 23:59:59') < strtotime("+" . CONF_FATURA_DIAS_APOS . " month", time()) && $invoice['valor_aberto'] > 0) {
$this->params = array(
"boletos" => $invoice['id'],
"juro" => "N",
"multa" => "N",
"atualiza_boleto" => "N",
"tipo_boleto" => $type
);
if ($type == 'sms') {
$request = $this->setParamsReturnAll();
} else {
$request = $this->setParams();
}
if ($request['registros'][0]['sucesso'] == 1 || strpos($request, 'sucesso')) {
$response = true;
}
}
}
return $response;
} else {
return false;
}
}
function abrirAtendimento($id_cliente, $titulo, $prioridade, $id_setor, $mensagem, $id_assunto, $id_tecnico = null)
{
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$protocolo = $this->gerarProtocolo();
$this->params = array(
"protocolo" => $protocolo,
"id_cliente" => $id_cliente,
"titulo" => $titulo,
"prioridade" => $prioridade,
"id_ticket_setor" => $id_setor,
"id_ticket_origem" => 'I',
"interacao_pendente" => 'N',
"origem_endereco" => 'M',
"menssagem" => $mensagem,
"su_status" => 'N',
"status" => 'N',
"id_assunto" => $id_assunto,
"id_responsavel_tecnico" => $id_tecnico
);
$this->setMetodo('su_ticket');
$this->getPost();
return $this->setParams();
} else {
return false;
}
}
function gerarProtocolo()
{
$this->debug = debug_backtrace();
$this->setMetodo('gerar_protocolo_atendimento');
return $this->setParams(null, debug_backtrace());
}
function verificaBloqueioInternet($idcliente)
{
$pendencias = array();
$contratos = $this->listarContrato($idcliente);
foreach ($contratos['registros'] as $value) {
if ($value['status_internet'] == 'FA') {
array_push($pendencias, 'INADIMPLENTE');
} else if ($value['status_internet'] == 'CA' || $value['status_internet'] == 'CM') {
array_push($pendencias, 'BLOQUEADO');
} else {
array_push($pendencias, 'ATIVO');
}
}
return $pendencias;
}
function cidadeNome($cod)
{
$this->debug = debug_backtrace();
$this->params = array(
"qtype" => 'cidade.id',
"query" => "$cod",
"oper" => '=',
"sortname" => 'cidade.id',
"sortorder" => 'desc'
);
$this->setMetodo('cidade');
return $this->setParams();
}
function consultaManutencao($latitude, $longitude)
{
$this->debug = debug_backtrace();
$this->params = array(
"latitude" => $latitude,
"longitude" => $longitude,
);
$this->setMetodo('consultar_regiao_manutencao');
return $this->setParams();
}
function listarLogins($cod)
{
$this->debug = debug_backtrace();
$this->params = array(
'qtype' => 'radusuarios.id_cliente',
'query' => $cod,
'oper' => '=',
'page' => '1',
'rp' => '20',
'sortname' => 'radusuarios.id',
'sortorder' => 'desc'
);
$this->setMetodo('cidade');
return $this->setParams();
}
function listarClientesFibra($idContrato)
{
$this->debug = debug_backtrace();
$this->params = array(
'qtype' => 'radpop_radio_cliente_fibra.id_contrato',
'query' => $idContrato,
'oper' => '!=',
'page' => '1',
'rp' => '20',
'sortname' => 'radpop_radio_cliente_fibra.id',
'sortorder' => 'asc',
'grid_param' => 'false',
'grid_param2' => 'false'
);
$this->setMetodo('radpop_radio_cliente_fibra');
return $this->setParams();
}
function infoIdTransmissor($cod)
{
$this->debug = debug_backtrace();
$this->params = array(
'qtype' => 'radpop_radio.id',
'query' => $cod,
'oper' => '=',
'page' => '1',
'rp' => '20',
'sortname' => 'radpop_radio.id',
'sortorder' => 'desc'
);
$this->setMetodo('cidade');
return $this->setParams();
}
function infoIdPop($cod)
{
$this->debug = debug_backtrace();
$this->params = array(
'qtype' => 'radpop.id',
'query' => $cod,
'oper' => '=',
'page' => '1',
'rp' => '20',
'sortname' => 'radpop.id',
'sortorder' => 'desc'
);
$this->setMetodo('cidade');
return $this->setParams();
}
function ordemViaPop($id)
{
$this->debug = debug_backtrace();
$this->params = array(
'qtype' => 'su_oss_chamado.mensagem',
'query' => '',
'oper' => '!=',
'page' => '1',
'rp' => '20',
'sortname' => 'su_oss_chamado.id',
'sortorder' => 'desc',
'grid_param' => $this->gridParams(array(
array('TB' => 'su_oss_chamado.status', 'OP' => '!=', 'P' => 'F'),
array('TB' => 'su_oss_chamado.id_cliente', 'OP' => '=', 'P' => $id)
))
);
$this->setMetodo('su_oss_chamado');
return $this->setParams();
}
########################################################################
## FUNCOES DO SISTEMA ##
########################################################################
function __construct($token = CONF_TOKEN_API, $url_api = CONF_URL_API, $log = CONF_LOGGER_ATIVO, $selfSigned = true)
{
$this->token = base64_encode($token);
if (end(str_split($url_api)) != '/') {
$url_api .= '/';
}
$this->url_api = $url_api . 'webservice/v1/';
if (strpos($url_api, 'https')) {
$this->selfSigned = true;
$this->ssl = true;
} else {
$this->selfSigned = false;
}
$this->setLog($log);
$this->integracaoReg();
$this->log->info("Iniciando integracao com IXCSoft", debug_backtrace());
}
private function setMetodo($metodo)
{
$this->metodo = $metodo;
}
/**
* Escreve a query para ser passada para o curl
*
* @param string $query
*/
private function setQuery($query)
{
return $this->query .= $query;
}
/**
* retorna a string pronta da query do curl e limpa a variavel.
*
* @return string $query
*/
private function getQuery()
{
$query = $this->query;
unset($this->query);
return $query;
}
/**
* Habilita requisicao via POST
*
* @return boolean
*/
private function getPost()
{
return $this->post = true;
}
private function strCurl()
{
$this->curl = "curl -s -k -H \"Authorization:Basic {$this->token}\" ";
$this->curl .= sprintf("-H \"Content-Type: application/json\" -X POST %s %s ", !$this->post ? "-H \"ixcsoft:listar\"" : '', $this->query ? '-d' : '');
$this->curl .= $this->getQuery();
$this->curl .= "{$this->url_api}{$this->metodo}";
$this->log->debug("Curl: {$this->curl}", debug_backtrace());
}
/**
* Recebe array de forma de indice e valor
*
* @example array("qtype" => 'test_api', "query" => '123', "oper" => '=')
*
* @param type $params
*/
private function setParams()
{
$count = 0;
if ($this->params) {
$this->setQuery("'{");
foreach ($this->params as $key => $param) {
$count++;
$this->setQuery("\"{$key}\": \"$param\"");
if ($count == count($this->params)) {
$this->setQuery("}' ");
} else {
$this->setQuery(",");
}
}
}
unset($this->params);
$this->strCurl();
$result = $this->exec();
$ret = json_decode($result, true);
return $ret;
}
private function setParamsReturnAll()
{
$count = 0;
if ($this->params) {
$this->setQuery("'{");
foreach ($this->params as $key => $param) {
$count++;
$this->setQuery("\"{$key}\": \"$param\"");
if ($count == count($this->params)) {
$this->setQuery("}' ");
} else {
$this->setQuery(",");
}
}
}
unset($this->params);
$this->strCurl();
$result = $this->exec();
return $result;
}
private function gridParams($params)
{
$count = 0;
$count1 = 0;
$json = "[";
foreach ($params as $array) {
$count++;
$json .= "{";
foreach ($array as $key => $grid) {
$count1++;
$json .= "\\\"$key\\\": \\\"$grid\\\"";
$json .= $count1 != count($array) ? "," : '';
}
unset($count1);
$json .= "}";
$json .= $count != count($params) ? "," : '';
}
$json .= "]";
if ($params) {
return $json;
} else {
return null;
}
}
function exec()
{
$exec = shell_exec($this->curl);
return $this->response($exec);
}
private function response($data)
{
$this->log->debug("Reponse API: " . print_r(json_decode($data, true), true), $this->debug);
if ($data) {
return $data;
} else {
return false;
}
}
}

157
Clientes/Fly Link/Logger.php

@ -0,0 +1,157 @@
<?php
/**
* Classe para utilizar
*
* @documentation:
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.0
*/
class Logger {
/*
* GENERATE LOG
*/
private $active;
private $log;
private $type;
private $text;
/*
* CONF. FILE LOG
*/
private $file;
private $path;
private $name;
/*
* CONST. MESSAGE TYPE
*/
const LOG_SUCCESS = "SUCCESS";
const LOG_DEBUG = "DEBUG";
const LOG_INFO = "INFO";
const LOG_WARNING = "WARNING";
const LOG_ERROR = "ERROR";
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/") {
$this->name = $nameLog;
$this->path = $path;
$this->active = $active;
$this->config($nameLog);
}
########################################################################
## TYPES ##
########################################################################
public function success($log, $debug_trace = null) {
$this->type = self::LOG_SUCCESS;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace());
$this->write();
}
public function debug($log, $debug_trace = null) {
$this->type = self::LOG_DEBUG;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function info($log, $debug_trace = null) {
$this->type = self::LOG_INFO;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function error($log, $debug_trace = null) {
$this->type = self::LOG_ERROR;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function warning($log, $debug_trace = null) {
$this->type = self::LOG_WARNING;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
########################################################################
## IMPORTANT ##
########################################################################
private function write() {
if ($this->active) {
file_put_contents($this->file, $this->log, FILE_APPEND);
}
}
private function header($log, $debug_trace) {
$this->log = "________________________________________________________________________________________\n";
if(is_array($debug_trace)){
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function'];
$args = null;
if(count($debug_trace[0]['args']) > 0){
foreach($debug_trace[0]['args'] as $key => $arg){
$x++;
$args .= $arg;
if(count($debug_trace[0]['args']) != $x){
$args .= ",";
}
}
}
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type);
} else {
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type);
}
$this->log .= "> " . $log;
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n";
}
public function openLog() {
//$file = fopen($this->file, 'rb');
}
public function locateLog() {
echo "\n\n {$this->file} \n\n";
}
########################################################################
## CONFIGS ##
########################################################################
public function config($name, $exten = ".log", $prefix = null) {
if (file_exists($this->file)) {
$contents = file_get_contents($this->file);
}
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten);
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND);
}
public function getType() {
return $this->type;
}
public function getText(){
return $this->text;
}
public function setLogger($active) {
if ($this->active === true) {
$this->active = $active;
} else if ($active === false) {
$this->active = $active;
} else {
$this->active = true;
}
}
}

258
Clientes/Fly Link/SimpleMail.php

@ -0,0 +1,258 @@
<?php
/**
* Classe para implementacao envio de Emails em Massa ou único!
*
* @author Lucas Awade
* @Desenvolvedor
* @version 1.1.0
*/
require("phpmailer/class.phpmailer.php");
class SimpleMail {
########################################################################
## CONFIGURACOES CLASSE ##
########################################################################
private $log;
private $limit;
private $sended = 0;
private $mailer;
########################################################################
## CONFIGURACOES MAIL ##
########################################################################
private $host;
private $port;
private $smtpAuth;
private $smtpSecure;
private $charset;
private $mail;
private $passwd;
private $title;
private $subject;
########################################################################
## CONFIGURACOES DEFAULT ##
########################################################################
public function __construct($mail, $passwd, $subject, $logger = false) {
$this->log = new Logger('simplesmailer', $logger, "/var/log/");
if ($mail && $passwd && $subject) {
$this->mail = $mail;
$this->passwd = $passwd;
$this->subject = $subject;
$this->phpMailer();
} else {
$this->log->error('Nao foi possivel instanciar a Classe SimplesMail,informacoes incompletas!', debug_backtrace());
}
}
/**
* Metodo de configuração do Host de Envio;
* @param string $host
* @param string|int $port
* @param string $title
* @param boolean $smtpAuth
* @param string $smtpSecure
* @param string $charset
*/
public function config($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') {
$this->host = $host;
$this->port = $port;
$this->title = $title;
$this->smtpAuth = $smtpAuth;
$this->smtpSecure = $smtpSecure;
$this->charset = $charset;
$this->phpMailer();
}
/**
* Informa um limite de email em massa a ser enviado.
*
* @param int $limit
*/
public function limitSend($limit) {
$this->log->debug('Limite de Email: ' . $limit, debug_backtrace());
$this->limit = $limit;
}
/**
* Mensagem escrito em HTML para envio de um email elaborado.
*
* Os dados em $data devem ser em formato array como o exemplo:
* array("MSG_HEADER" => 'Seja Bem vindo', "MSG_FOOTER" => 'Volte Sempre');
*
* @param string $path
* @param array $data
*/
public function pathBodyMail($path, $data) {
$this->log->info('Path HTML Body: ' . $path, debug_backtrace());
$contents = file_get_contents($path);
foreach ($data as $key => $value) {
$contents = str_replace($key, $value, $contents);
}
$this->mailer->Body = $contents;
}
/**
* Mensagem simples para o envio rapido de um email.
*
* @param string $message
*/
public function bodyMessage($message) {
$this->mailer->Body = $message;
}
/**
* Adiciona no email anexos para serem enviados
* @param array|string $files
*/
public function setAddAttachment($files) {
if ($files) {
if (is_array($files)) {
foreach ($files as $name => $file) {
$this->mailer->AddAttachment($file, (is_numeric($name) ? '' : $name));
}
} else {
$this->mailer->AddAttachment($files);
}
}
}
/**
* Adiciona no email imagens para visualizadas.
*
* #=> Caso o paramtro for um array seu corpo deve ser enviado da seguinte forma:
* $cid = array('minha_img_jpg' => 'img/path/mail/header.jpg');
*
* #=> Caso for uma string deve se passar o cid caso contrario gera um cid randomico;
*
* @param array|string $images
*/
public function setAddEmbeddedImage($images, $cid = null) {
if ($images) {
if (is_array($images)) {
foreach ($images as $name => $image) {
$this->mailer->AddEmbeddedImage($image, $name);
}
} else {
$cid = $cid ? $cid : rand(100, 999999);
$this->mailer->AddEmbeddedImage($image, $cid);
}
}
}
/**
* Esta funcao envia os email em massa ou unicos.
*
* Email em massa é necessario passar um array com os emails seu indice que representa o email.
*
* Email unico so é preciso passar o email na variavel $data;
*
* @param array|string $data
* @param string $indice
* @return array|boolean
*/
public function mailing($data, $indice = '') {
if (is_array($data)) {
$invalid = array();
foreach ($data as $mail) {
if ($this->sended <= $this->limit) {
$mail = $indice ? $mail[$indice] : $mail;
$this->setSended();
if (!$this->send($mail)) {
$invalid[] = $mail;
}
}
}
return $invalid;
} else {
if ($this->send($data)) {
$this->setSended();
return true;
} else {
return false;
}
}
}
public function getErrorSend(){
return $this->mailer->ErrorInfo;
}
########################################################################
## ENVIO MAIL ##
########################################################################
/**
* Gerencia a quantidade de email que esta sendo enviado.
*/
private function setSended() {
$this->sended++;
}
/**
* Gerencia o envio do email para estar sempre no limite de envio.
*
* @return boolean
*/
public function getSended() {
$this->log->debug("Sended: " . $this->sended, debug_backtrace());
if ($this->sended < $this->limit) {
return true;
} else {
return false;
}
}
/**
* Metodo responsavel para realizar o envio do email.
*
* @param string $mailFrom
* @return boolean
*/
private function send($mailFrom) {
if (!$this->mailer) {
$this->log->error("Objeto nao criado!", debug_backtrace());
return false;
}
try {
$this->mailer->setFrom($this->mail, $this->title);
$this->mailer->addAddress($mailFrom, $this->title);
$this->mailer->send();
$this->mailer->clearAllRecipients();
$this->log->success("Mail: {$mailFrom} | Send Queue: {$this->sended}", debug_backtrace());
return true;
} catch (Exception $ex) {
if ($this->mailer->ErrorInfo) {
$this->log->error("ErrorInfo Mail: " . $this->mailer->ErrorInfo . " | Exception Mail: {$mailFrom} >> " . $ex->getMessage(), debug_backtrace());
}
}
}
/**
* Cria as configurações e parametros para ser implementado e enviado os emails.
*
* @void null
*/
private function phpMailer() {
$this->log->debug("Instanciando objeto PHPMailer", debug_backtrace());
$this->mailer = new PHPMailer(true);
$this->mailer->isSMTP();
$this->mailer->Host = $this->host;
$this->mailer->SMTPAuth = $this->smtpAuth;
$this->mailer->isHTML(true);
if ($this->smtpAuth) {
$this->mailer->SMTPSecure = $this->smtpSecure;
$this->mailer->Username = $this->mail;
$this->mailer->Password = $this->passwd;
}
$this->mailer->CharSet = $this->charset;
$this->mailer->Port = $this->port;
$this->mailer->Subject = $this->subject;
}
}

19
Clientes/Fly Link/abreAtendimento.php

@ -0,0 +1,19 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$clienteId = $ixc->agi()->get_variable('CODCLIENTE', true);
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$manuntencao = $ixc->consultaManutencao($latitude, $longitude);
$atendimento = $ixc->abrirAtendimento($clienteId, 'ATD Ligacao', 'M', '5', ' ', '98');
if ($atendimento['type'] == 'success' ) {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_ABRE_ATENDIMENTO", "SUCESSO", $nomenclatura); //SUCESSO
}else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_ABRE_ATENDIMENTO", "FALHA", $nomenclatura); //OK
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

356
Clientes/Fly Link/bkp/Integracao.php

@ -0,0 +1,356 @@
<?php
require_once 'phpagi/phpagi.php';
require_once 'IntegracaoDataBase.php';
require_once 'Logger.php';
require_once 'SimpleMail.php';
/* * *************************************************************************
* SISTEMA UNICO DE INTEGRACAO *
* ************************************************************************* */
/**
* Classe para implementacao das integracoes da Simples IP
* @author Lucas Awade
* @Desenvolvedor
* @SimplesIP
* @version 1.1.1
*/
class Integracao {
protected $log;
protected $mail;
private $agi;
private $db;
########################################################################
## CONSTANTES DA CLASSE ##
########################################################################
const PATH_LOG = "/var/log/asterisk/integracao.log";
const PATH_SOUND = '/var/lib/asterisk/sounds/customizados/';
const AGI_ERROR_HANDLER = false;
########################################################################
## FUNCOES UTILITARIAS ##
########################################################################
/**
* - Retorno é os dados referentes ao retornado da API
* - Params são os dados que serão disponibilizados na tela do agente.
*
* @param array $retorno
* @param array $params
*/
public function integracaoAgente($retorno, $params) {
$registros = 0;
$data = $this->db()->getRegistros();
$retorno_cliente = "{$data['reg_uniqueid']}|{$data['reg_fone']}|{$data['id']}|";
foreach ($retorno as $key => $value) {
if (in_array($key, $params)) {
$registros++;
$retorno_cliente .= sprintf("%s:%s",
strtoupper(str_replace("_", " ", $key)),
strtoupper(str_replace("|", "", $value)));
if (count($params) > $registros) {
$retorno_cliente .= "|";
}
}
}
$this->db()->setRegistros(array('retorno_cliente' => $retorno_cliente));
}
/**
* Converte um CPF ou CNPJ com marcara referente a cada modelo.
*
* @param string $string
* @return boolean|string
*/
protected function mask_cpf_cnpj($string) {
if (!empty($string)) {
if (strlen($string) == 11) {
$mask = "%s%s%s.%s%s%s.%s%s%s-%s%s";
} elseif (strlen($string) == 14) {
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s";
}
return vsprintf($mask, str_split($string));
} else {
return false;
}
}
/**
* Retorna telefone com o (DDD)Numero de acordo com o parametro passado caso nao possua DDD sera o padrao da central.
* @param string $telefone
* @return array
*/
protected function mask_phone_tel($telefone) {
$retorno = array('telefone' => '', 'type' => '');
if (strlen($telefone) == 11) {
$numero = substr($telefone, 2, 10);
$ddd = $this->db()->getDDD();
$telefone = "({$ddd})" . $numero;
$retorno['telefone'] = $telefone;
$retorno['type'] = 'celular';
} else if (strlen($telefone) == 12) {
$ddd = substr($telefone, 1, 2);
$numero = substr($telefone, 3, 10);
$telefone = sprintf("(%s)%s", $ddd, $numero);
$retorno['telefone'] = $telefone;
$retorno['type'] = 'telefone';
} else if (strlen($telefone) == 13) {
$ddd = substr($telefone, 2, 2);
$numero = substr($telefone, 4, 10);
$telefone = "(" . $ddd . ")" . $numero;
$retorno['telefone'] = $telefone;
$retorno['type'] = 'celular';
} else {
return null;
}
return $retorno;
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
protected function getArgs($args) {
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
/**
* Verifica a diferenca em dias entre a data de entrada e a data atual.
*
* @param type $dateParam
* @return type
*/
public function dateDiff($dateParam) {
$dateIni = strtotime(date('Y-m-d'));
if (strstr($dateParam, "/")) {
$dateParam = date(strtotime(str_replace('/', '-', $dateParam)));
} else {
$dateParam = date(strtotime($dateParam));
}
$diff = ($dateIni - $dateParam);
$days = (int) floor($diff / (60 * 60 * 24));
return $days;
}
/**
* Realiza a conversao de datas no formato brasileiro para a Defualt.
* @param string $data
* @return string|boolean
*/
public function convertDateDefault($data) {
if ($data) {
$data = explode('/', $data);
return "{$data[2]}-{$data[1]}-{$data[0]}";
}
return false;
}
/**
* Realiza a validação de pendencia financeira de acordo com a data informada
*
* OBS: O array deve possui nível = array( array('data' => 'yyyy-mm-dd'))
* OBS: O indice deve ser o nome do valor onde se encontra a data.
* @param array $array
* @param string $indice
* @param string $datavalida
* @return boolean
*/
public function verificaDataPendencia($array, $indice, $datavalida = null) {
if(!$datavalida){
$datavalida = strototime(date('Y-m-d'));
} else {
$datavalida = strtotime($datavalida);
}
foreach ($array as $value){
if(strtotime($value[$indice]) < $datavalida){
return false;
}
}
return true;
}
/**
* Adiciona mascara no telefone para realizar a consulta
*
* @param type $value
* @return boolean
*/
protected function phoneMask($value) {
if (!empty($value)) {
if (strlen($value) == 10) {
$mask = '(%s%s)%s%s%s%s-%s%s%s%s';
} elseif (strlen($value) == 11) {
$mask = '(%s%s)%s%s%s%s%s-%s%s%s%s';
}
return vsprintf($mask, str_split($value));
} else {
return false;
}
}
/**
* Verifica se um servidor esta dando resposta de ping
* @param type $ip
* @return boolean
*/
public function verificaLatencia($ip) {
$ping = explode(",", shell_exec("ping -c 4 $ip"));
$latencia = substr($ping[1], 1, 2); //resposta do ping
if ($latencia >= 2) {
return true;
}
return false;
}
/**
* Verbaliza digitos
* @param string|int $string
*/
public function verbaliza($string){
$vocaliza = str_split($string);
foreach ($vocaliza as $value) {
$this->agi()->say_digits($value);
}
}
############################################################################
######## CONFIGURACAO DE EMAIL ########
############################################################################
/**
* Inicia a instanciacao da Classe para envio de Email
* @param string $email
* @param string $password
* @param string $subject
*/
public function SimpleMail($email, $password, $subject) {
$this->mail = new SimpleMail($email, $password, $subject);
$this->log->debug("Instanciacao SimpleMail : " . ($this->mail ? "SUCCESS" : "FAIL"), debug_backtrace());
}
/**
* Configura o servidor de Envio dos Emails.
* @param string $host
* @param string|int $port
* @param string $title
* @return boolean
*/
public function confSMTP($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') {
$this->log->debug("Configuracao SMTP", debug_backtrace());
if ($this->mail) {
$this->mail->config($host, $port, $title, $smtpAuth, $smtpSecure, $charset);
} else {
return false;
}
}
########################################################################
## FUNCOES IMPORTANTES ##
########################################################################
/**
* Instancia um objeto de Logger.
*
* @param Logger $log
*/
protected function setLog($log = false) {
if (!$this->log) {
$this->log = new Logger('integracao', $log);
}
}
/**
* Retorna o objeto de Log.
* @return string
*/
public function log() {
return $this->log;
}
/**
* Instancia um objeto de AGI para se conectar com as informações do Asterisk.
*
* @return AGI
*/
public function agi() {
if (!$this->agi) {
$data = $this->db()->getAuthAgi();
$config = array();
$config['phpagi']['error_handler'] = self::AGI_ERROR_HANDLER;
$config['asmanager']['server'] = $data['host_sck'];
$config['asmanager']['port'] = $data['porta_sck'];
$config['asmanager']['username'] = $data['usuario_sck'];
$config['asmanager']['secret'] = $data['senha_sck'];
$agi = new AGI('phpagi.conf', $config);
$this->agi = $agi;
return $agi;
}
return $this->agi;
}
private function readAgiVariable() {
ob_implicit_flush(true);
set_time_limit(6);
$in = fopen("php://stdin", "r");
$input = str_replace("\n", "", fgets($in, 4096));
fclose($in);
$this->log->debug("Reading: " . $input);
return $input;
}
public function getAgiVariable($variable = null) {
$this->log->debug("Executing...", debug_backtrace());
while ($env = $this->readAgiVariable()) {
$s = explode(": ", $env);
$agi[str_replace("agi_", "", $s[0])] = trim($s[1]);
$this->log->debug("Data: " . print_r($agi, true), debug_backtrace());
if (($env == "") || ($env == "\n")) {
break;
}
}
$this->log->debug("Reading: " . print_r($agi, true));
if (!$variable || $agi[$variable]) {
return !$variable ? $agi : $agi[$variable];
}
return false;
}
/**
* Instancia um objeto de IntegracaoDataBase para se conectar com dados do
* Banco de dados e credenciais do Manager.
*
* @return IntegracaoDataBase
*/
public function db() {
if (!$this->db) {
$db = new IntegracaoDataBase();
$this->db = $db;
}
return $this->db;
}
protected function audioError() {
$this->log->debug('Audio de error');
$exten = $this->db()->getAnuncio();
$this->log->error('Encaminhando para áudio alternativo de Erros', debug_backtrace());
$this->agi()->exec_goto($exten);
exit();
}
}

426
Clientes/Fly Link/bkp/IntegracaoDataBase.php

@ -0,0 +1,426 @@
<?php
require_once 'Logger.php';
// *************************************************************************
// * SISTEMA UNICO DE INTEGRACAO *
// *************************************************************************
/**
* Classe para utilizar os registros do Banco de Dados;
*
* OBS: Deixar como usuario de execucao e acesso pbx:pbx
*
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IntegracaoDataBase {
private $query;
private $connection;
private $registros;
private $log;
private $credentials = array();
private $debug;
private $idAudioError;
/**
* @file
* Arquivo de configuracoes do banco e manager
*/
const FILE_DB = "/var/www/html/include/bd";
public function __construct() {
$this->log = new Logger('integracao', CONF_LOGGER_DB_ATIVO);
}
/**
* Retorna os registros armazenados na variavel registros pra ser disponibilizado
* no decorrer de uma integracao;
*
* @return array
*/
public function getRegistros() {
return $this->registros;
}
/**
* Informações coletadas do banco de dados para ser escritas no log.
*
* @param array $array
*/
private function logResult($array) {
if ($array) {
$this->log->success(print_r($array, true), $this->debug);
} else {
$this->log->warning('Nenhum resultado encontrado!', $this->debug);
}
}
/**
* Audio de erro padrao
*
* @param string $idAudioError
*/
public function setIdAudioError($idAudioError) {
$this->idAudioError = $idAudioError;
}
########################################################################
## BANCO DE DADOS ##
########################################################################
/**
* Pega as informacoes das credenciais no arquivos padrao "bd";
*/
private function filedb() {
if (file_exists(self::FILE_DB)) {
$contents = fopen(self::FILE_DB, 'r');
while (!feof($contents) && $contents) {
$str = fgets($contents);
$dados = explode('=', $str);
$this->credentials[strtolower($dados[0])] = str_replace('"', '', $dados[1]);
}
fclose($contents);
$this->credentials = array_filter($this->credentials);
$this->log->debug("Credenciais banco de dados: " . print_r($this->credentials, true), debug_backtrace());
} else {
$this->log->error("Nao foi possivel encontrar o arquivo 'bd' em " . self::FILE_DB);
}
}
/**
* Executa as querys da consulta a serem feitas, além de gravar logs de registros de dados,
* e qualquer erro é repassado a classe que está executando para tratar o erro;
*
* @param string $type
* @return boolean|array
*/
private function execute($type = '') {
try {
if (!$this->connection) {
$this->filedb();
$this->connection = pg_connect(sprintf('host=%s port=%s dbname=%s user=%s password=%s', $this->credentials['host_db'], $this->credentials['porta_db'], $this->credentials['base_db'], $this->credentials['usuario'], $this->credentials['senha']));
if (pg_connection_status($this->connection) === 0) {
$this->log->success("Conectado na base {$this->credentials['base_db']}.", debug_backtrace());
} else {
throw new Exception('Nao foi possivel conectar na base de dados');
}
}
$result = pg_query($this->connection, $this->query);
switch (strtolower($type)) {
case 'assoc':
$data = pg_fetch_assoc($result);
break;
case 'row':
$data = pg_fetch_row($result);
break;
case 'array':
$data = pg_fetch_array($result);
break;
case 'all':
$data = pg_fetch_all($result);
break;
}
$this->logResult($data);
return $data;
} catch (Exception $ex) {
$this->log->error("Exception: {$ex->getMessage()} | Postgres : " . pg_last_error(), $this->debug);
}
}
########################################################################
## ASTERISK ##
########################################################################
/**
* Coleta em qual Asterisk a central está rodadando e retorna o modelo padrao
* de configuracao do exten;
*
* @return string
*/
private function getVersionAsterisk() {
$result = array();
exec("asterisk -V", $result);
$this->log->info("Versao Asterisk: " . $result[0], debug_backtrace());
if (strpos($result[0], '1.4') !== false) {
return "|";
} else {
return ",";
}
}
/**
* Transforma uma string exten com "," para "|" de acordo com a versao do Asterisk
*
* @param string $string
* @return string
*/
private function string_exten($string) {
return str_replace(",", $this->getVersionAsterisk(), $string);
}
/**
* Coleta os dados de autenticacao do manager.
*
* @return array
*/
public function getAuthAgi() {
$data = array();
foreach ($this->credentials as $key => $value) {
if (strpos($key, '_sck') !== false) {
$data[$key] = $value;
}
}
return $data;
}
########################################################################
## QUERYS ##
########################################################################
/**
* Inicia um Transacao;
*/
private function beginTransaction() {
$this->debug = debug_backtrace();
$this->query = "BEGIN;";
$this->execute();
}
/**
* Registra uma Transacao.
*/
private function commitTransaction() {
$this->debug = debug_backtrace();
$this->query = "COMMIT;";
$this->execute();
}
/**
* Retorna as informacoes antes da Transacao.
*/
private function rollbackTransaction() {
$this->debug = debug_backtrace();
$this->query = "ROLLBACK;";
$this->execute();
}
/**
* Busca o DDD padrao cadastrado na central.
*
* @param string $name
* @return string
*/
public function getDDD() {
$this->debug = debug_backtrace();
$this->query = "SELECT prm_ddd_padrao FROM pbx_parametros";
return $this->execute('assoc') ? $this->execute('assoc')['prm_ddd_padrao'] : '';
}
/**
* Consulta no banco o nome do Anuncio e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getAnuncio($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-anuncios,a%s,1'), $result);
}
/**
* Consulta no banco o nome do Ura e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getURA($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ura-%s,s,1'), $result);
}
/**
* Consulta no banco a Ura por ID e retorna suas informacoes;
*
* @param string|int $id
* @return string
*/
public function getURAById($id) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_ura WHERE id = '{$id}'";
$result = $this->execute('assoc') ? $this->execute('assoc') : $this->idAudioError;
return $result;
}
/**
* Consulta no banco o nome do Fila e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getFila($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_dacs WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-fila,%s,1'), $result);
}
/**
* Consulta no banco o nome do Ramal e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getRamal($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ramais WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-ramais,%s,1'), $result);
}
/**
* Coleta as opcoes que o usuario passou nas uras da sua chamada.
*
* @param string $uniqueid
* @param int $ura_id
* @return boolean|array
*/
public function getOptionsURA($uniqueid, $ura_id) {
$this->debug = debug_backtrace();
$this->query = "SELECT umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao "
. "FROM pbx_ura_movimento WHERE uniqueid = '$uniqueid' "
. "AND umv_ura_opcao IS NOT NULL AND umv_opcao = 'ura' "
. "AND umv_ura_id = $ura_id "
. "ORDER BY umv_id";
return $this->execute('all');
}
/**
* Retorna o ID e Data Hora da primeira entrada da ligacao em um URA de
* acordo com o uniqueid;
* @param string $uniqueid
* @return array
*/
public function getFristURA($uniqueid) {
$this->debug = debug_backtrace();
$this->query = "SELECT destino, min(data_registro) "
. "FROM ast_bilhetes_complemento "
. "WHERE direcao = 'ura' "
. "AND uniqueid2 = '{$uniqueid}' GROUP BY destino LIMIT 1";
$result = $this->execute('assoc');
return $result;
}
public function registraIntegracao() {
$this->debug = debug_backtrace();
/**
* Parametros REGISTROS
*
* id -> Id do qual gerou a integracao para o retorno_cliente
*
* Todos os parametros devem ser igual a da tabela pbx_integracao_reg
*/
$ura = trim($this->registros['reg_ura']) ? trim($this->registros['reg_ura']) : 'null';
$tronco = trim($this->registros['reg_tronco']) ? trim($this->registros['reg_tronco']) : 'null';
$this->query = "INSERT INTO pbx_integracao_reg (reg_id_metodo,reg_uniqueid,reg_uniqueid_old,reg_fone,reg_inicio, reg_tronco, reg_ura)
VALUES('{$this->registros['reg_id_metodo']}','{$this->registros['reg_uniqueid']}','{$this->registros['reg_uniqueid_old']}','{$this->registros['reg_fone']}', now(), '$tronco', '$ura')";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function atualizaIntegracao() {
$this->debug = debug_backtrace();
$tronco = trim($this->registros['reg_tronco']) ? sprintf(",\nreg_tronco='%s'", trim($this->registros['reg_tronco'])) : '';
$ura = trim($this->registros['reg_ura']) ? sprintf(",\nreg_ura='%s'", trim($this->registros['reg_ura'])) : '';
$reg_msg = QuotedStr($this->registros['reg_msg']);
$reg_retorno = QuotedStr($this->registros['reg_fone']);
$retorno_cliente = substr($this->registros['retorno_cliente'], 0, 255);
$this->query = "UPDATE pbx_integracao_reg
SET reg_fim = NOW(),
reg_retorno = $reg_retorno,
reg_msg = $reg_msg,
reg_status_exec = '{$this->registros['reg_status_exec']}',
retorno_cliente = '{$retorno_cliente}'{$tronco}{$ura}
WHERE reg_uniqueid = '{$this->registros['reg_uniqueid']}'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/**
* Informa os dados para ser inseridos na tabela de integracao_reg;
*
* @param array $registros
*/
public function setRegistros($registros) {
if (is_array($registros) && !$this->registros) {
$this->registros = $registros;
$this->registraIntegracao();
} else {
foreach ($registros as $key => $value) {
$this->registros[$key] = $value;
}
}
}
/**
* Retorna todas as informacoes da tabela Supervisor_Dacs
* @param array $dacs
* @return array
*/
public function getSupervisorDAC($dacs = array()) {
$this->query = "SELECT * FROM pbx_supervisor_dacs ";
if ($dacs) {
$this->query .= sprintf("WHERE id IN (%s)", implode(",", $dacs));
}
return $this->execute('all');
}
/**
* Retorna credenciais cadastradas nos metodos de integracao
* @param int $id
* @return array
*/
public function getConexaoAPI($id) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao
WHERE itgc_id = {$id}";
return $this->execute('assoc');
}
public function getScriptCredenciais($script) {
$this->query = "SELECT itgc_nome AS name, itgc_port AS id_user, itgc_host AS url,
itgc_database AS token, itgc_user AS user, itgc_password AS password,
itgc_timeout AS timeout
FROM pbx_integracao_configuracao a
INNER JOIN pbx_integracao_metodo b ON a.itgc_id = b.itgc_id
WHERE itgm_comando = '{$script}'";
return $this->execute('assoc');
}
public function getFilaPorNome($name) {
$this->debug = debug_backtrace();
$this->query = "SELECT * FROM pbx_dacs WHERE nome = '$name'";
return $this->execute('assoc');
}
public function getLastUraPorUniqueid($uniqueid) {
$this->query = "SELECT data_reg, umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao
FROM pbx_ura_movimento WHERE uniqueid = '{$uniqueid}'
ORDER BY data_reg DESC
LIMIT 1";
return $this->execute('assoc');
}
}

419
Clientes/Fly Link/bkp/IxcSoft.php

@ -0,0 +1,419 @@
<?php
require_once 'Integracao.php';
include 'config.php';
/**
* Classe para utilizar as API da empresa IXCSoft
*
* @documentation: http://wiki.ixcsoft.com.br/index.php/Recursos_da_API
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IxcSoft extends Integracao {
private $token;
private $url_api;
private $selfSigned;
private $metodo;
########################################################################
## VARIAVEIS DA CLASSE ##
########################################################################
private $query;
private $curl;
private $post = false;
private $params = array();
private $debug;
########################################################################
## RECURSOS DA API ##
########################################################################
function listarBoleto($codCliente) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'fn_areceber.id_cliente',
"query" => $codCliente,
"oper" => '=',
"rp" => "2",
"sortname" => 'fn_areceber.data_vencimento',
"sortorder" => 'asc',
"grid_param" => $this->gridParams(
array(
array(
"TB" => "fn_areceber.liberado",
"OP" => "=",
"P" => "S",
"C" => "AND"),
array(
"TB" => "fn_areceber.status",
"OP" => "!=",
"P" => "C"),
array(
"TB" => "fn_areceber.status",
"OP" => "!=",
"P" => "R")))
);
$this->setMetodo('fn_areceber');
return $this->setParams();
} else {
return false;
}
}
function listarClientes() {
$this->debug = debug_backtrace();
$this->params = array(
"qtype" => "cliente.id",
"query" => "",
"oper" => "!=",
"page" => "1",
"rp" => "20",
"sortname" => "cliente.id",
"sortorder" => "desc",
);
$this->setMetodo('cliente');
return $this->setParams();
}
public function buscarCliente($cpf_cnpj) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
if (strlen($cpf_cnpj) == 11 || strlen($cpf_cnpj) == 14) {
$this->params = array(
"qtype" => "cliente.cnpj_cpf",
"query" => "{$this->mask_cpf_cnpj($cpf_cnpj)}",
"oper" => "=",
"sortname" => "cliente.id",
"sortorder" => "asc",
);
$this->setMetodo('cliente');
return $this->setParams();
} else {
return false;
}
} else {
return false;
}
}
/**
* Status de bloqueio:
* CA - Bloqueio automatico
* CM - Bloqueio Manual
* A - Ativo
* AA - Aguardando assinatura
* D - Desativado
* DE - Data Expirou
*
* @param int $id_cliente
* @return boolean
*/
function listarContrato($id_cliente) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"qtype" => 'cliente_contrato.id_cliente',
"query" => "$id_cliente",
"oper" => '=',
"sortname" => 'cliente_contrato.id',
"sortorder" => 'asc'
);
$this->setMetodo('cliente_contrato');
return $this->setParams();
} else {
return false;
}
}
/*
* Alterar Status do Acesso
Liberar : cliente_contrato_15464
Aguardando Assinatura: cliente_contrato_23529
Avisar atraso: cliente_contrato_15463
Bloquear: cliente_contrato_15300
Retirar redução: cliente_contrato_29157
* */
function retirarReducao($contrato) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"id_contrato" => $contrato
);
$this->setMetodo('cliente_contrato_29157');
return $this->setParams();
} else {
return false;
}
}
function desbloqueiaCliente($contrato) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$this->params = array(
"id" => $contrato
);
$this->setMetodo('desbloqueio_confianca');
return $this->setParams();
} else {
return false;
}
}
function enviaBoleto($type, $codigo_cliente) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$response = false;
$faturas = $this->listarBoleto($codigo_cliente)['registros'];
$this->setMetodo('get_boleto');
foreach ($faturas as $invoice) {
if (strtotime($invoice['data_vencimento'] . ' 23:59:59') < time() && $invoice['valor_aberto'] > 0) {
$this->params = array(
"boletos" => $invoice['id'],
"juro" => "N",
"multa" => "N",
"atualiza_boleto" => "N",
"tipo_boleto" => $type
);
if($type == 'sms'){
$request = $this->setParamsFull();
}else{
$request = $this->setParams();
}
if($request['registros'][0]['sucesso'] == 1 || strpos($request, 'sucesso')){
$response = true;
}
}
}
return $response;
} else {
return false;
}
}
function abrirAtendimento($id_cliente, $titulo, $prioridade, $id_setor, $mensagem, $id_assunto, $id_tecnico = null) {
$this->debug = debug_backtrace();
if ($this->getArgs(func_get_args())) {
$protocolo = $this->gerarProtocolo();
$this->params = array(
"protocolo" => $protocolo,
"id_cliente" => $id_cliente,
"titulo" => $titulo,
"prioridade" => $prioridade,
"id_ticket_setor" => $id_setor,
"id_ticket_origem" => 'I',
"interacao_pendente" => 'N',
"origem_endereco" => 'M',
"menssagem" => $mensagem,
"su_status" => 'N',
"status" => 'N',
"id_assunto" => $id_assunto,
"id_responsavel_tecnico" => $id_tecnico
);
$this->setMetodo('su_ticket');
$this->getPost();
return $this->setParams();
} else {
return false;
}
}
function gerarProtocolo() {
$this->debug = debug_backtrace();
$this->setMetodo('gerar_protocolo_atendimento');
return $this->setParams(null, debug_backtrace());
}
function verificaBloqueioInternet($idcliente) {
$pendencias = array();
$contratos = $this->listarContrato($idcliente);
foreach ($contratos['registros'] as $value) {
if ($value['status_internet'] == 'FA') {
array_push($pendencias, 'INADIMPLENTE');
} else if ($value['status_internet'] == 'CA' || $value['status_internet'] == 'CM') {
array_push($pendencias, 'BLOQUEADO');
} else {
array_push($pendencias, 'ATIVO');
}
}
return $pendencias;
}
function cidadeNome($cod) {
$this->debug = debug_backtrace();
$this->params = array(
"qtype" => 'cidade.id',
"query" => "$cod",
"oper" => '=',
"sortname" => 'cidade.id',
"sortorder" => 'desc'
);
$this->setMetodo('cidade');
return $this->setParams();
}
function consultaManutencao($latitude, $longitude) {
$this->debug = debug_backtrace();
$this->params = array(
"latitude" => $latitude,
"longitude" => $longitude,
);
$this->setMetodo('consultar_regiao_manutencao');
return $this->setParams();
}
########################################################################
## FUNCOES DO SISTEMA ##
########################################################################
function __construct($token, $url_api, $log = false, $selfSigned = true) {
$this->token = base64_encode($token);
$this->url_api = $url_api . "/webservice/v1/";
$this->selfSigned = $selfSigned;
$this->setLog($log);
$this->log->info("Iniciando integracao com IXCSoft", debug_backtrace());
}
private function setMetodo($metodo) {
$this->metodo = $metodo;
}
/**
* Escreve a query para ser passada para o curl
*
* @param string $query
*/
private function setQuery($query) {
return $this->query .= $query;
}
/**
* retorna a string pronta da query do curl e limpa a variavel.
*
* @return string $query
*/
private function getQuery() {
$query = $this->query;
unset($this->query);
return $query;
}
/**
* Habilita requisicao via POST
*
* @return boolean
*/
private function getPost() {
return $this->post = true;
}
private function strCurl() {
$this->curl = "curl -s -k -H \"Authorization:Basic {$this->token}\" ";
$this->curl .= sprintf("-H \"Content-Type: application/json\" -X POST %s %s ", !$this->post ? "-H \"ixcsoft:listar\"" : '', $this->query ? '-d' : '');
$this->curl .= $this->getQuery();
$this->curl .= "{$this->url_api}{$this->metodo}";
$this->log->debug("Curl: {$this->curl}", debug_backtrace());
}
/**
* Recebe array de forma de indice e valor
*
* @example array("qtype" => 'test_api', "query" => '123', "oper" => '=')
*
* @param type $params
*/
private function setParams() {
$count = 0;
if ($this->params) {
$this->setQuery("'{");
foreach ($this->params as $key => $param) {
$count++;
$this->setQuery("\"{$key}\": \"$param\"");
if ($count == count($this->params)) {
$this->setQuery("}' ");
} else {
$this->setQuery(",");
}
}
}
unset($this->params);
$this->strCurl();
$result = $this->exec();
$ret = json_decode($result, true);
return $ret;
}
private function setParamsFull() {
$count = 0;
if ($this->params) {
$this->setQuery("'{");
foreach ($this->params as $key => $param) {
$count++;
$this->setQuery("\"{$key}\": \"$param\"");
if ($count == count($this->params)) {
$this->setQuery("}' ");
} else {
$this->setQuery(",");
}
}
}
unset($this->params);
$this->strCurl();
$result = $this->exec();
return $result;
}
private function gridParams($params) {
$count = 0;
$count1 = 0;
$json = "[";
foreach ($params as $array) {
$count++;
$json .= "{";
foreach ($array as $key => $grid) {
$count1++;
$json .= "\\\"$key\\\": \\\"$grid\\\"";
$json .= $count1 != count($array) ? "," : '';
}
unset($count1);
$json .= "}";
$json .= $count != count($params) ? "," : '';
}
$json .= "]";
if ($params) {
return $json;
} else {
return null;
}
}
function exec() {
$exec = shell_exec($this->curl);
return $this->response($exec);
}
private function response($data) {
$this->log->debug("Reponse API: " . print_r(json_decode($data, true), true), $this->debug);
if ($data) {
return $data;
} else {
return false;
}
}
}

157
Clientes/Fly Link/bkp/Logger.php

@ -0,0 +1,157 @@
<?php
/**
* Classe para utilizar
*
* @documentation:
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.0
*/
class Logger {
/*
* GENERATE LOG
*/
private $active;
private $log;
private $type;
private $text;
/*
* CONF. FILE LOG
*/
private $file;
private $path;
private $name;
/*
* CONST. MESSAGE TYPE
*/
const LOG_SUCCESS = "SUCCESS";
const LOG_DEBUG = "DEBUG";
const LOG_INFO = "INFO";
const LOG_WARNING = "WARNING";
const LOG_ERROR = "ERROR";
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/") {
$this->name = $nameLog;
$this->path = $path;
$this->active = $active;
$this->config($nameLog);
}
########################################################################
## TYPES ##
########################################################################
public function success($log, $debug_trace = null) {
$this->type = self::LOG_SUCCESS;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace());
$this->write();
}
public function debug($log, $debug_trace = null) {
$this->type = self::LOG_DEBUG;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function info($log, $debug_trace = null) {
$this->type = self::LOG_INFO;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function error($log, $debug_trace = null) {
$this->type = self::LOG_ERROR;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function warning($log, $debug_trace = null) {
$this->type = self::LOG_WARNING;
$this->text = $log;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
########################################################################
## IMPORTANT ##
########################################################################
private function write() {
if ($this->active) {
file_put_contents($this->file, $this->log, FILE_APPEND);
}
}
private function header($log, $debug_trace) {
$this->log = "________________________________________________________________________________________\n";
if(is_array($debug_trace)){
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function'];
$args = null;
if(count($debug_trace[0]['args']) > 0){
foreach($debug_trace[0]['args'] as $key => $arg){
$x++;
$args .= $arg;
if(count($debug_trace[0]['args']) != $x){
$args .= ",";
}
}
}
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type);
} else {
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type);
}
$this->log .= "> " . $log;
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n";
}
public function openLog() {
//$file = fopen($this->file, 'rb');
}
public function locateLog() {
echo "\n\n {$this->file} \n\n";
}
########################################################################
## CONFIGS ##
########################################################################
public function config($name, $exten = ".log", $prefix = null) {
if (file_exists($this->file)) {
$contents = file_get_contents($this->file);
}
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten);
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND);
}
public function getType() {
return $this->type;
}
public function getText(){
return $this->text;
}
public function setLogger($active) {
if ($this->active === true) {
$this->active = $active;
} else if ($active === false) {
$this->active = $active;
} else {
$this->active = true;
}
}
}

258
Clientes/Fly Link/bkp/SimpleMail.php

@ -0,0 +1,258 @@
<?php
/**
* Classe para implementacao envio de Emails em Massa ou único!
*
* @author Lucas Awade
* @Desenvolvedor
* @version 1.1.0
*/
require("phpmailer/class.phpmailer.php");
class SimpleMail {
########################################################################
## CONFIGURACOES CLASSE ##
########################################################################
private $log;
private $limit;
private $sended = 0;
private $mailer;
########################################################################
## CONFIGURACOES MAIL ##
########################################################################
private $host;
private $port;
private $smtpAuth;
private $smtpSecure;
private $charset;
private $mail;
private $passwd;
private $title;
private $subject;
########################################################################
## CONFIGURACOES DEFAULT ##
########################################################################
public function __construct($mail, $passwd, $subject, $logger = false) {
$this->log = new Logger('simplesmailer', $logger, "/var/log/");
if ($mail && $passwd && $subject) {
$this->mail = $mail;
$this->passwd = $passwd;
$this->subject = $subject;
$this->phpMailer();
} else {
$this->log->error('Nao foi possivel instanciar a Classe SimplesMail,informacoes incompletas!', debug_backtrace());
}
}
/**
* Metodo de configuração do Host de Envio;
* @param string $host
* @param string|int $port
* @param string $title
* @param boolean $smtpAuth
* @param string $smtpSecure
* @param string $charset
*/
public function config($host, $port, $title, $smtpAuth = true, $smtpSecure = 'TLS', $charset = 'UTF8') {
$this->host = $host;
$this->port = $port;
$this->title = $title;
$this->smtpAuth = $smtpAuth;
$this->smtpSecure = $smtpSecure;
$this->charset = $charset;
$this->phpMailer();
}
/**
* Informa um limite de email em massa a ser enviado.
*
* @param int $limit
*/
public function limitSend($limit) {
$this->log->debug('Limite de Email: ' . $limit, debug_backtrace());
$this->limit = $limit;
}
/**
* Mensagem escrito em HTML para envio de um email elaborado.
*
* Os dados em $data devem ser em formato array como o exemplo:
* array("MSG_HEADER" => 'Seja Bem vindo', "MSG_FOOTER" => 'Volte Sempre');
*
* @param string $path
* @param array $data
*/
public function pathBodyMail($path, $data) {
$this->log->info('Path HTML Body: ' . $path, debug_backtrace());
$contents = file_get_contents($path);
foreach ($data as $key => $value) {
$contents = str_replace($key, $value, $contents);
}
$this->mailer->Body = $contents;
}
/**
* Mensagem simples para o envio rapido de um email.
*
* @param string $message
*/
public function bodyMessage($message) {
$this->mailer->Body = $message;
}
/**
* Adiciona no email anexos para serem enviados
* @param array|string $files
*/
public function setAddAttachment($files) {
if ($files) {
if (is_array($files)) {
foreach ($files as $name => $file) {
$this->mailer->AddAttachment($file, (is_numeric($name) ? '' : $name));
}
} else {
$this->mailer->AddAttachment($files);
}
}
}
/**
* Adiciona no email imagens para visualizadas.
*
* #=> Caso o paramtro for um array seu corpo deve ser enviado da seguinte forma:
* $cid = array('minha_img_jpg' => 'img/path/mail/header.jpg');
*
* #=> Caso for uma string deve se passar o cid caso contrario gera um cid randomico;
*
* @param array|string $images
*/
public function setAddEmbeddedImage($images, $cid = null) {
if ($images) {
if (is_array($images)) {
foreach ($images as $name => $image) {
$this->mailer->AddEmbeddedImage($image, $name);
}
} else {
$cid = $cid ? $cid : rand(100, 999999);
$this->mailer->AddEmbeddedImage($image, $cid);
}
}
}
/**
* Esta funcao envia os email em massa ou unicos.
*
* Email em massa é necessario passar um array com os emails seu indice que representa o email.
*
* Email unico so é preciso passar o email na variavel $data;
*
* @param array|string $data
* @param string $indice
* @return array|boolean
*/
public function mailing($data, $indice = '') {
if (is_array($data)) {
$invalid = array();
foreach ($data as $mail) {
if ($this->sended <= $this->limit) {
$mail = $indice ? $mail[$indice] : $mail;
$this->setSended();
if (!$this->send($mail)) {
$invalid[] = $mail;
}
}
}
return $invalid;
} else {
if ($this->send($data)) {
$this->setSended();
return true;
} else {
return false;
}
}
}
public function getErrorSend(){
return $this->mailer->ErrorInfo;
}
########################################################################
## ENVIO MAIL ##
########################################################################
/**
* Gerencia a quantidade de email que esta sendo enviado.
*/
private function setSended() {
$this->sended++;
}
/**
* Gerencia o envio do email para estar sempre no limite de envio.
*
* @return boolean
*/
public function getSended() {
$this->log->debug("Sended: " . $this->sended, debug_backtrace());
if ($this->sended < $this->limit) {
return true;
} else {
return false;
}
}
/**
* Metodo responsavel para realizar o envio do email.
*
* @param string $mailFrom
* @return boolean
*/
private function send($mailFrom) {
if (!$this->mailer) {
$this->log->error("Objeto nao criado!", debug_backtrace());
return false;
}
try {
$this->mailer->setFrom($this->mail, $this->title);
$this->mailer->addAddress($mailFrom, $this->title);
$this->mailer->send();
$this->mailer->clearAllRecipients();
$this->log->success("Mail: {$mailFrom} | Send Queue: {$this->sended}", debug_backtrace());
return true;
} catch (Exception $ex) {
if ($this->mailer->ErrorInfo) {
$this->log->error("ErrorInfo Mail: " . $this->mailer->ErrorInfo . " | Exception Mail: {$mailFrom} >> " . $ex->getMessage(), debug_backtrace());
}
}
}
/**
* Cria as configurações e parametros para ser implementado e enviado os emails.
*
* @void null
*/
private function phpMailer() {
$this->log->debug("Instanciando objeto PHPMailer", debug_backtrace());
$this->mailer = new PHPMailer(true);
$this->mailer->isSMTP();
$this->mailer->Host = $this->host;
$this->mailer->SMTPAuth = $this->smtpAuth;
$this->mailer->isHTML(true);
if ($this->smtpAuth) {
$this->mailer->SMTPSecure = $this->smtpSecure;
$this->mailer->Username = $this->mail;
$this->mailer->Password = $this->passwd;
}
$this->mailer->CharSet = $this->charset;
$this->mailer->Port = $this->port;
$this->mailer->Subject = $this->subject;
}
}

81
Clientes/Fly Link/bkp/config.php

@ -0,0 +1,81 @@
<?php
###########################################################################
##### #####
##### ARQUIVO PARA A CONFIGURACAO DE ACESSO API #####
##### ----------------------------------------- #####
##### CREDENCIAIS DE ACESSO #####
###########################################################################
define('CONF_ID_CREDENCIAIS', '');
define('CONF_TOKEN_API', '100:3db53fb2e8a4853c85ba0c4f24d2645e9caed232183747ada1d5896eae887c29');
define('CONF_URL_API', 'https://177.66.185.24/');
define('CONF_USER_API', 'simplesip@flylink.com.br');
define('CONF_PASSWORD_API', '@@SIM2022plesIP');
define('CONF_USERID_API', '100');
###########################################################################
##### CONFIGURACAO DE LOG #####
###########################################################################
define('CONF_LOGGER_ATIVO', true);
define('CONF_LOGGER_DB_ATIVO', false);
###########################################################################
##### CONFIGURACAO DE ERROR #####
###########################################################################
define('CONF_AUDIO_ERROR', '');
###########################################################################
##### CONFIGURACAO PDO #####
###########################################################################
define('CONF_DB_DRIVER', "");
define('CONF_DB_HOST', "");
define('CONF_DB_PORT', "");
define('CONF_DB_BASE', "");
define('CONF_DB_USER', "");
define('CONF_DB_PASSWD', "");
define('CONF_DB_OPTIONS', "");
###########################################################################
##### CREDENCIAIS DE ENVIO DE EMAIL #####
###########################################################################
define('CONF_EMAIL_TITLE_INVOICE', '[NO-REPLY] Envio de Fatura');
define('CONF_EMAIL_SUBTITLE_INVOICE', 'Estamos enviando o pedido de Segunda Via da sua Fatura!');
define('CONF_SENDER_EMAIL_USER', '');
define('CONF_SENDER_EMAIL_PASSWORD', '');
define('CONF_SMTP_HOST', '');
define('CONF_SMTP_POST', '587');
###########################################################################
##### CONFIGURACAO GERAÇÃO DE FATURA #####
###########################################################################
define('CONF_FATURA_DIAS_ANTES', 30);
define('CONF_FATURA_DIAS_APOS', 5);
############################################################################
##### CONF. KING CAMPANHA #####
############################################################################
define('CONF_CAMP_LOGIN', "novahelp");
define('CONF_CAMP_DATAINI', date('Y-m-d 08:00:00'));
define('CONF_CAMP_DATAFIM', date('Y-m-d 18:00:00'));
define('CONF_CAMP_RAMAL', "2000");
define('CONF_CAMP_FLUXO', 0);
define('CONF_CAMP_PAUSA', 1);
define('CONF_CAMP_NUMREDISCAGEM', 1);
define('CONF_CAMP_MAXCALL', 10);
define('CONF_CAMP_RINGTIME', 45);
define('CONF_CAMP_INTERVALO', 1);
define('CONF_CAMP_AMD', 0);
define('CONF_CAMP_NDS', 0);
define('CONF_CAMP_PRIOMOVEL', 0);
define('CONF_CAMP_MAXCALLAGENT', 3);

54
Clientes/Fly Link/bkp/consultaCliente.php

@ -0,0 +1,54 @@
<?php
include 'IxcSoft.php';
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$ixc = new IxcSoft(CONF_TOKEN_API, CONF_URL_API, CONF_LOGGER_ATIVO);
$ixc->db()->setRegistros($registros);
if (CONF_AUDIO_ERROR) {
$ixc->db()->setIdAudioError(CONF_AUDIO_ERROR);
}
$documento = $ixc->agi()->get_variable('URA', true);
$retorno = $ixc->buscarCliente($documento);
if ($retorno['total'] >= 1) {
$total = intval($retorno['total']);
$clienteArray = $total - 1;
$cliente = $retorno['registros'][$clienteArray];
if (strtoupper($cliente['ativo']) != 'N') {
$ixc->agi()->set_variable("IDCLIENTE", $cliente['id']);
$ixc->agi()->set_variable("DOCUMENTO", $documento);
}
}
$reg_pass = $ixc->agi()->get_variable("REG_PASS", true);
if ($retorno['registros']) {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('CADASTRO_SUCESSO_INT_V1')); // Sucesso
} else if (is_null($reg_pass) || $reg_pass < 2) {
$reg_pass += 1;
$ixc->agi()->set_variable("REG_PASS", $reg_pass);
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('CADASTRO_FALHA_INT_V1')); //NAO IDENTIFICADO
} else {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('NAO_IDENTIFICADO_INT_V1')); //FALHA
}
$ixc->db()->atualizaIntegracao();
?>

36
Clientes/Fly Link/bkp/consultaPendencia.php

@ -0,0 +1,36 @@
<?php
include 'IxcSoft.php';
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$ixc = new IxcSoft(CONF_TOKEN_API, CONF_URL_API, CONF_LOGGER_ATIVO);
$ixc->db()->setRegistros($registros);
if (CONF_AUDIO_ERROR) {
$ixc->db()->setIdAudioError(CONF_AUDIO_ERROR);
}
$idcliente = $ixc->agi()->get_variable('IDCLIENTE', true);
$pendencias = $ixc->verificaBloqueioInternet($idcliente);
if (in_array('BLOQUEADO', $pendencias)) {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('PENDENCIA_INT_V1')); // Inadimplente
} else {
$ixc->agi()->exec_goto($ixc->db()->getURA('AUTOMATIZADA_INT_V1')); // Cliente OK
}
$ixc->db()->atualizaIntegracao();
?>

44
Clientes/Fly Link/bkp/desbloqueiaCliente.php

@ -0,0 +1,44 @@
<?php
include 'IxcSoft.php';
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$ixc = new IxcSoft(CONF_TOKEN_API, CONF_URL_API, CONF_LOGGER_ATIVO);
$ixc->db()->setRegistros($registros);
if (CONF_AUDIO_ERROR) {
$ixc->db()->setIdAudioError(CONF_AUDIO_ERROR);
}
$idcliente = $ixc->agi()->get_variable('IDCLIENTE', true);
$unlock = false;
$contratos = $ixc->listarContrato($idcliente);
foreach ($contratos['registros'] as $item){
if ($item['status_internet'] == 'CA'){
$ret_unlock = $ixc->desbloqueiaCliente($item['id']);
if ($ret_unlock['tipo'] == 'sucesso'){
$unlock = true;
}
}
}
if(!$unlock){
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('DESBLOQUEIA_SUCESSO_INT_V1'));
}else{
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('DESBLOQUEIA_FALHA_INT_V1'));
}
$ixc->db()->atualizaIntegracao();
?>

33
Clientes/Fly Link/bkp/email.html

@ -0,0 +1,33 @@
<meta charset="UTF-8">
<table align="center" width="60%" style="border: 1px solid #ddd; background-color: #fff;border-radius: 8px;">
<tr>
<td>
<br />
<h2 style="text-align: center;">$titulo</h2>
<hr style="border: 0.05px solid rgb(241, 241, 241);" />
</td>
</tr>
<tr>
<td>
<div style="margin: auto;margin-left: 20px">
<p>Olá $nome, estamos enviando a segunda via de sua fatura,
para mais informação entre em contato com nosso atendimento.
</p>
<p><b>Para visualizar seu Boleto clique em visualizar para abrir ou verique nos anexos!</b></p>
<p>$link</p>
</div>
</td>
</tr>
<tr>
<td>
<br/>
<hr style="border: 0.05px solid rgb(241, 241, 241);" />
<div style="width: 80%; margin: auto;">
<p style="text-align: center;"><b>Este é uma mensagem gerada automaticamente, pedimos que não responda essa mensagem!</b></p>
<p style="text-align: center;"><i><b>A agradeçemos o seu contato!</b></i></p>
</div>
<br/>
</td>
</tr>
</table>

36
Clientes/Fly Link/bkp/enviaBoleto.php

@ -0,0 +1,36 @@
<?php
include 'IxcSoft.php';
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$ixc = new IxcSoft(CONF_TOKEN_API, CONF_URL_API, CONF_LOGGER_ATIVO);
$ixc->db()->setRegistros($registros);
if (CONF_AUDIO_ERROR) {
$ixc->db()->setIdAudioError(CONF_AUDIO_ERROR);
}
$cod_cliente = $ixc->agi()->get_variable('IDCLIENTE', true);
$mail_send = $ixc->enviaBoleto('mail', $cod_cliente);
$sms_send = $ixc->enviaBoleto('sms', $cod_cliente);
if (($mail_send) || ($sms_send)) {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('FATURA_SUCESSO_INT_V1'));
}else {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('FATURA_FALHA_INT_V1'));
}
?>

19
Clientes/Fly Link/bkp/paradaTecnica.php

@ -0,0 +1,19 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$latitude = $ixc->agi()->get_variable('LATITUDE', true);
$longitude = $ixc->agi()->get_variable('LONGITUDE', true);
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$manuntencao = $ixc->consultaManutencao($latitude, $longitude);
if ($manuntencao['em_manutencao'] != 'N' ) {
$ixc->agi()->exec_goto($ixc->db()->getURA('ATENDIMENTO_INT_V1')); // Inadimplente
} else {
$ixc->agi()->exec_goto($ixc->db()->getAnuncio('PARADA_TECNICA_INT_V1')); // Cliente OK
}
$ixc->db()->atualizaIntegracao();
?>

356
Clientes/Fly Link/conf.php

@ -0,0 +1,356 @@
<?php
$provedores = [
##########################
/** @IXCSoftware */
##########################
'IXC' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO']
],
##########################
/** @ISPIntegrator */
##########################
'ISP' => [
'CREDENCIAIS' =>
[
'USER' => '',
'PASSWORD' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO']
],
##########################
/** @HUBSoft */
##########################
'HUBSOFT' => [
'CREDENCIAIS' =>
[
'CLIENT_ID' => '',
'CLIENT_SECRET' => '',
'USERNAME' => '',
'PASSWORD' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO']
],
##########################
/** @MKSolution */
##########################
'MK' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => '',
'CONTRASENHA' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA', 'ABRE_ATENDIMENTO']
],
##########################
/** @SGP */
##########################
'SGP' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => '',
'APP' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE']
],
##########################
/** @CNTSistemas */
##########################
'CNT' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO']
],
##########################
/** @Routerbox */
##########################
'RBX' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO']
],
##########################
/** @TopSapp */
##########################
'TOPSAPP' => [
'CREDENCIAIS' =>
[
'USUARIO' => '',
'SENHA' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'PARADA_TECNICA']
],
##########################
/** @Gerenet */
##########################
'GERENET' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "ENDERECO"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE']
],
##########################
/** @Synsuite */
##########################
'SYNSUITE' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO']
],
##########################
/** @Altarede */
##########################
'ALTAREDE' => [
'CREDENCIAIS' =>
[
'TOKEN' => '',
'URL' => '',
'APPKEY' => ''
],
'INTEGRACAO_TELA' => [
'STATUS' => '1',
'PARAMETROS' => ["DOCUMENTO", "NOME", "PLANO", "ENDERECO", "STATUS", "EMAIL"]
],
'METODOS' => ['CONSULTA_CLIENTE', 'CONSULTA_PENDENCIA', 'ENVIA_FATURA', 'DESBLOQUEIA_CLIENTE', 'ABRE_ATENDIMENTO']
]
];
/**
* Configuracoes do Desenvolvedor
*/
$configs = [
'FATURA' => [
'FATURA_DIAS_ANTES' => 30,
'FATURA_DIAS_APOS' => 5
],
'LOGGER' => [
'LOGGER_PATH' => 'integracao',
'LOGGER_ATIVO' => true,
'LOGGER_DB_ATIVO' => false
],
'EMAIL' => [
'EMAIL_TITLE', '[NO-REPLY] Envio de Fatura',
'EMAIL_SUBTITLE' => 'Estamos enviando o pedido de Segunda Via da sua Fatura!',
'SENDER_EMAIL_USER' => '',
'SENDER_EMAIL_PASSWORD' => '',
'SMTP_HOST' => '',
'SMTP_PORT' => '587',
'SMTP_SECURE' => 'TLS',
'SMTP_AUTH' => true
],
'CONF' => [
'NOMENCLATURA' => 'INT'
]
];
define('CONF_URA', 'ura');
define('CONF_FILAS', 'filas');
define('CONF_ANUNCIOS', 'anuncios');
define('CONF_HORARIO', 'horarios');
define('CONF_INTEGRACAO', 'integativa');
define('CONF_LOGGER_DB_ATIVO', true);
/*
* Cadastro de Anuncios *
*/
$anuncios = [
'SAUDACAO' => [
CONF_URA => 'IDENTIFICACAO'
],
'AGRADECIMENTO' => [],
'CADASTRO_SUCESSO' => [
CONF_INTEGRACAO => 'CONSULTA_PENDENCIA',
CONF_URA => 'AUTOMATIZADA'
],
'CADASTRO_FALHA' => [
CONF_URA => 'IDENTIFICACAO'
],
'NAO_IDENTIFICADO' => [
CONF_ANUNCIOS => 'AGRADECIMENTO'
],
'PENDENCIA' => [
CONF_URA => 'AUTOMATIZADA'
],
'DESBLOQUEIA_SUCESSO' => [
CONF_URA => 'VOLTA_MENU'
],
'DESBLOQUEIA_FALHA' => [
CONF_URA => 'VOLTA_MENU'
],
'FATURA_SUCESSO' => [
CONF_URA => 'VOLTA_MENU'
],
'FATURA_FALHA' => [
CONF_URA => 'VOLTA_MENU'
],
'PRE_SUPORTE' => [
CONF_HORARIO => 'ATENDIMENTO'
],
'TRANSFERE_ATENDENTE' => [],
'PARADA_TECNICA' => [
CONF_URA => 'ATENDIMENTO'
],
'FORA_DE_HORARIO' => [
CONF_ANUNCIOS => 'AGRADECIMENTO'
],
'INTEGRACAO_ERRO' => [
CONF_HORARIO => 'ATENDIMENTO'
]
];
/*
* Configuração de Uras
*/
$ura = [
'AUTOMATIZADA' => [
"ITENS" => [
['numero' => '1', 'sequencia' => '1', 'acao' => [CONF_INTEGRACAO => 'ENVIA_FATURA']],
['numero' => '2', 'sequencia' => '2', 'acao' => [CONF_INTEGRACAO => 'DESBLOQUEIA_CLIENTE']],
['numero' => '3', 'sequencia' => '3', 'acao' => [CONF_INTEGRACAO => 'PARADA_TECNICA', CONF_URA => 'ATENDIMENTO']]
],
"TIMEOUT" => [
]
],
'IDENTIFICACAO' => [
"ITENS" => [
['numero' => '_X.', 'sequencia' => '0', 'acao' => [CONF_INTEGRACAO => 'CONSULTA_CLIENTE']],
['numero' => '9', 'sequencia' => '9', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']]
],
"TIMEOUT" => [
]
],
'VOLTA_MENU' => [
"ITENS" => [
['numero' => '9', 'sequencia' => '9', 'acao' => [CONF_URA => 'AUTOMATIZADA']]
],
"TIMEOUT" => [
CONF_ANUNCIOS => "AGRADECIMENTO"
]
],
'ATENDIMENTO' => [
"ITENS" => [
['numero' => '1', 'sequencia' => '1', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']],
['numero' => '2', 'sequencia' => '2', 'acao' => [CONF_ANUNCIOS => 'PRE_SUPORTE']],
['numero' => '3', 'sequencia' => '3', 'acao' => [CONF_HORARIO => 'ATENDIMENTO']]
],
"TIMEOUT" => [
]
]
];
/*
* Configuração de Uras Redirecionamento
*/
$ura_redir = [
'REDIR_CONSULTA_CLIENTE' => [
'SUCESSO' => [CONF_ANUNCIOS => 'CADASTRO_SUCESSO'],
'FALHA' => [CONF_ANUNCIOS => 'CADASTRO_FALHA'],
'ALTERNATIVO' => [CONF_ANUNCIOS => 'NAO_IDENTIFICADO']
],
'REDIR_CONSULTA_PENDENCIA' => [
'SUCESSO' => [CONF_ANUNCIOS => 'PENDENCIA'],
'FALHA' => [CONF_URA => 'AUTOMATIZADA'],
'ALTERNATIVO' => []
],
'REDIR_ENVIA_FATURA' => [
'SUCESSO' => [CONF_ANUNCIOS => 'FATURA_SUCESSO'],
'FALHA' => [CONF_ANUNCIOS => 'FATURA_FALHA'],
'ALTERNATIVO' => []
],
'REDIR_DESBLOQUEIA_CLIENTE' => [
'SUCESSO' => [CONF_ANUNCIOS => 'DESBLOQUEIA_SUCESSO'],
'FALHA' => [CONF_ANUNCIOS => 'DESBLOQUEIA_FALHA'],
'ALTERNATIVO' => []
],
'REDIR_PARADA_TECNICA' => [
'SUCESSO' => [CONF_ANUNCIOS => 'PARADA_TECNICA'],
'FALHA' => [CONF_URA => 'ATENDIMENTO'],
'ALTERNATIVO' => []
],
'REDIR_ABRE_ATENDIMENTO' => [
'SUCESSO' => [],
'FALHA' => [],
'ALTERNATIVO' => []
]
];
/*
* Configuração de Horario
*/
$horarioPadrao = [
"ATENDIMENTO" => [
"ITENS" => [
["HORARIO_INICIAL" => "08:00", "HORARIO_FINAL" => "18:00", "DIA_SEMANA_INICIO" => "mon", "DIA_SEMANA_FIM" => "fri"],
["HORARIO_INICIAL" => "08:00", "HORARIO_FINAL" => "12:00", "DIA_SEMANA_INICIO" => "sat", "DIA_SEMANA_FIM" => "sat"]
],
"FORA_HORARIO" => [CONF_ANUNCIOS => "FORA_DE_HORARIO"]
]
];

6
Clientes/Fly Link/confRotas.php

@ -0,0 +1,6 @@
<?php
$anuncioos = [
];

99
Clientes/Fly Link/config.php

@ -0,0 +1,99 @@
<?php
###########################################################################
##### #####
##### ARQUIVO PARA A CONFIGURACAO DE ACESSO API #####
##### ----------------------------------------- #####
##### CREDENCIAIS DE ACESSO #####
###########################################################################
define('CONF_ID_CREDENCIAIS', '');
define('CONF_TOKEN_API', '100:3db53fb2e8a4853c85ba0c4f24d2645e9caed232183747ada1d5896eae887c29');
define('CONF_URL_API', 'https://177.66.185.24/');
define('CONF_USER_API', 'simplesip@flylink.com.br');
define('CONF_PASSWORD_API', '@@SIM2022plesIP');
define('CONF_USERID_API', '100');
###########################################################################
##### CONFIGURACAO DE NOME CLOUD #####
###########################################################################
//colocar _EMPRESA
define('CONF_NOME_EMPRESA', '');
###########################################################################
##### CONFIGURACAO DE LOG #####
###########################################################################
define('CONF_LOGGER_PATH', 'integracao');
define('CONF_LOGGER_ATIVO', true);
define('CONF_LOGGER_DB_ATIVO', false);
###########################################################################
##### CONFIGURACAO DE ERROR #####
###########################################################################
define('CONF_AUDIO_ERROR', 'INTEGRACAO_ERRO_INT');
###########################################################################
##### CONFIGURACAO PDO #####
###########################################################################
define('CONF_DB_DRIVER', "");
define('CONF_DB_HOST', "");
define('CONF_DB_PORT', "");
define('CONF_DB_BASE', "");
define('CONF_DB_USER', "");
define('CONF_DB_PASSWD', "");
define('CONF_DB_OPTIONS', "");
###########################################################################
##### CREDENCIAIS DE ENVIO DE EMAIL #####
###########################################################################
define('CONF_EMAIL_TITLE_INVOICE', '[NO-REPLY] Envio de Fatura');
define('CONF_EMAIL_SUBTITLE_INVOICE', 'Estamos enviando o pedido de Segunda Via da sua Fatura!');
define('CONF_SENDER_EMAIL_USER', '');
define('CONF_SENDER_EMAIL_PASSWORD', '');
define('CONF_SMTP_HOST', '');
define('CONF_SMTP_POST', '587');
###########################################################################
##### CONFIGURACAO GERAÇÃO DE FATURA #####
###########################################################################
define('CONF_FATURA_DIAS_ANTES', 30);
define('CONF_FATURA_DIAS_APOS', 5);
############################################################################
##### CONF. KING CAMPANHA #####
############################################################################
define('CONF_CAMP_LOGIN', "novahelp");
define('CONF_CAMP_DATAINI', date('Y-m-d 08:00:00'));
define('CONF_CAMP_DATAFIM', date('Y-m-d 18:00:00'));
define('CONF_CAMP_RAMAL', "2000");
define('CONF_CAMP_FLUXO', 0);
define('CONF_CAMP_PAUSA', 1);
define('CONF_CAMP_NUMREDISCAGEM', 1);
define('CONF_CAMP_MAXCALL', 10);
define('CONF_CAMP_RINGTIME', 45);
define('CONF_CAMP_INTERVALO', 1);
define('CONF_CAMP_AMD', 0);
define('CONF_CAMP_NDS', 0);
define('CONF_CAMP_PRIOMOVEL', 0);
define('CONF_CAMP_MAXCALLAGENT', 3);
############################################################################
##### CONF. INTEGRACAO DE TELA #####
############################################################################
define("CONF_INTEGRACAO_TELA", true);
define("CONF_PARAMETROS_TELA", serialize(array("DOCUMENTO", "NOME", "PLANO", "STATUS", "EMAIL")));
###########################################################################
##### CONFIGURACAO DE PARADA TECNICA HUBSOFT #####
###########################################################################
define('CONF_PARADA_TECNICA_MSG', "PROBLEMA MASSIVO");

92
Clientes/Fly Link/consultaCliente.php

@ -0,0 +1,92 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$documento = $ixc->agi()->get_variable('URA', true);
$retorno = $ixc->buscarCliente($documento);
$reg_pass = $ixc->agi()->get_variable("REG_PASS", true);
$nomenclatura = substr("IDENTIFICACAO", "", $ixc->db()->getUraMovimentoByUniqueid($uid)['umv_ura_nome']);
$ixc->agi()->set_variable("NOMENCLATURA", $nomenclatura);
//Dados:
if ($retorno['total'] >= 1 && strlen($documento)==11) {
$cliente = end($retorno['registros']);
$contrato = $ixc->listarContrato($cliente['id']);
$contratoNome = $contrato['registros'][0]['contrato'];
$contratoId = $contrato['registros'][0]['id'];
$aviso_atraso = 'NAO';
$contrato_bloqueio = 'NAO';
$conexoes = $ixc->listarConexoes($cliente['id']);
$conexaoOnline = '';
$conexaoIP = '';
foreach ($conexoes['registros'] as $item) {
if ($item['online'] == 'S') {
$conexaoOnline.= 'ONLINE ';
}else{
$conexaoOnline.= 'OFFLINE ';
}
if ($item['ip']) {
$conexaoIP.= $item['ip']. ' ';
}
}
foreach ($contrato['registros'] as $item) {
if($item['status'] == 'A'){
$contratoNome = $item['contrato'];
$contratoId = $item['id'];
}
if ($item['aviso_atraso'] == 'S') {
$aviso_atraso = 'SIM';
}
if ($item['status_internet'] == 'CA' || $item['status_internet'] == 'CM') {
$contrato_bloqueio = 'SIM';
}
}
$status = "BLOQUEADO: ".$contrato_bloqueio." ATRASADO: ".$aviso_atraso;
$ixc->agi()->set_variable("CODCLIENTE", $cliente['id']);
$ixc->agi()->set_variable("LATITUDE", $cliente['latitude']);
$ixc->agi()->set_variable("LONGITUDE", $cliente['longitude']);
//INTEGRACAO DE TELA
$ixc->agi()->set_variable("DOCUMENTO", $documento);
$ixc->agi()->set_variable("NOME", $cliente['razao']);
$ixc->agi()->set_variable("PLANO", $contratoNome);
$ixc->agi()->set_variable("ATIVO", $cliente['ativo']);
$ixc->agi()->set_variable("ENDERECO", $cliente['endereco']);
$ixc->agi()->set_variable("EMAIL", $cliente['email']);
$ixc->agi()->set_variable("STATUS", $status);
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_CLIENTE_INT_V1", "SUCESSO", $nomenclatura); //SUCESSO
}else if($retorno['total']>=1 && strlen($documento)==14 ){
$ixc->executarFluxo('ANUNCIO', 'PESSOA_JURIDICA_SUCESSO_INT_V1');
}else if(is_null($reg_pass) || $reg_pass < 2) {
$reg_pass += 1;
$ixc->agi()->set_variable("REG_PASS", $reg_pass);
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_CLIENTE_INT_V1", "FALHA", $nomenclatura); ///NAO IDENTIFICADO
} else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_CLIENTE_INT_V1", "ALTERNATIVO", $nomenclatura); //FALHA
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

59
Clientes/Fly Link/consultaClienteTelefone.php

@ -0,0 +1,59 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$nomenclatura = substr("IDENTIFICACAO", "", $ixc->db()->getUraMovimentoByUniqueid($uid)['umv_ura_nome']);
$ixc->agi()->set_variable("NOMENCLATURA", $nomenclatura);
$telefonesBusca = array(
'telefone_celular',
'fone',
'telefone_comercial',
'whatsapp'
);
$tipo = 0;
$ixc->agi()->set_music(true, 'default');
$retorno = $ixc->buscarClienteTelefone($telefonesBusca[$tipo], $numero);
while(($retorno['total'] == 0) && ($tipo <= intval(sizeof($telefonesBusca)-1))){
$tipo += 1;
$retorno = $ixc->buscarClienteTelefone($telefonesBusca[$tipo], $numero);
};
if ($retorno['total'] == 1){
$cliente = end($retorno['registros']);
$contrato = $ixc->listarContrato($cliente['id']);
$aviso_atraso = 'NAO';
$contrato_bloqueio = 'NAO';
foreach ($contrato['registros'] as $item) {
if ($item['aviso_atraso'] == 'S') {
$aviso_atraso = 'SIM';
}
if ($item['status'] == 'CA' || $item['status'] == 'CM') {
$contrato_bloqueio = 'SIM';
}
}
$ixc->agi()->set_variable("CODCLIENTE", $cliente['id']);
$ixc->agi()->set_variable("DOCUMENTO", $cliente['cnpj_cpf']);
$ixc->agi()->set_variable("NOMECLIENTE", $cliente['razao']);
$ixc->agi()->set_variable("ENDERECO", $cliente['endereco']);
$ixc->agi()->set_variable("SITUACAOCLIENTE", $contrato['registros'][intval($contrato['total']) - 1]['status']);
$ixc->agi()->set_variable("EMAILCLIENTE", $cliente['email']);
$ixc->agi()->set_music(false, 'default');
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_TELEFONE", "SUCESSO", $atendimento); //SUCESSO
}else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_TELEFONE", "FALHA", $nomenclatura); //FALHA
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"])
?>

19
Clientes/Fly Link/consultaPendencia.php

@ -0,0 +1,19 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$idcliente = $ixc->agi()->get_variable('CODCLIENTE', true);
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$pendencias = $ixc->consultaFaturasVencidas($idcliente);
$redirecionamento_dados = array("TIPO" => "ANUNCIO", "NOME" => CONF_AUDIO_ERROR.$nomenclatura);
if ($pendencias) {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_PENDENCIA_INT_V1", "SUCESSO", $nomenclatura); //PENDENTE
} else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_CONSULTA_PENDENCIA_INT_V1", "FALHA", $nomenclatura); //OK
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

32
Clientes/Fly Link/desbloqueiaCliente.php

@ -0,0 +1,32 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$idcliente = $ixc->agi()->get_variable('CODCLIENTE', true);
$unlock = false;
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$contratos = $ixc->listarContrato($idcliente);
foreach ($contratos['registros'] as $item){
if ($item['status_internet'] == 'CA'){
$ret_unlock = $ixc->desbloqueiaCliente($item['id']);
if ($ret_unlock['tipo'] == 'sucesso'){
$unlock = true;
}
}else if ($item['status_internet'] == 'FA'){
$ret_unlock = $ixc->retirarReducao($item['id']);
if ($ret_unlock['type'] == 'success'){
$unlock = true;
}
}
}
if($unlock){
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_DESBLOQUEIA_CLIENTE_INT_V1", "SUCESSO", $nomenclatura); //SUCESSO
}else{
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_DESBLOQUEIA_CLIENTE_INT_V1", "FALHA", $nomenclatura); //FALHA
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

33
Clientes/Fly Link/email.html

@ -0,0 +1,33 @@
<meta charset="UTF-8">
<table align="center" width="60%" style="border: 1px solid #ddd; background-color: #fff;border-radius: 8px;">
<tr>
<td>
<br />
<h2 style="text-align: center;">$titulo</h2>
<hr style="border: 0.05px solid rgb(241, 241, 241);" />
</td>
</tr>
<tr>
<td>
<div style="margin: auto;margin-left: 20px">
<p>Olá $nome, estamos enviando a segunda via de sua fatura,
para mais informação entre em contato com nosso atendimento.
</p>
<p><b>Para visualizar seu Boleto clique em visualizar para abrir ou verifique nos anexos!</b></p>
<p>$link</p>
</div>
</td>
</tr>
<tr>
<td>
<br/>
<hr style="border: 0.05px solid rgb(241, 241, 241);" />
<div style="width: 80%; margin: auto;">
<p style="text-align: center;"><b>Este é uma mensagem gerada automaticamente, pedimos que não responda essa mensagem!</b></p>
<p style="text-align: center;"><i><b>A agradeçemos o seu contato!</b></i></p>
</div>
<br/>
</td>
</tr>
</table>

24
Clientes/Fly Link/enviaFatura.php

@ -0,0 +1,24 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$ura_option = $ixc->agi()->get_variable('EXTEN', true);
$cod_cliente = $ixc->agi()->get_variable('CODCLIENTE', true);
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$mail_send = false;
$sms_send = false;
$mail_send = $ixc->enviaBoleto('mail', $cod_cliente);
$sms_send = $ixc->enviaBoleto('sms', $cod_cliente);
if(($mail_send) || ($sms_send)){
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_ENVIA_FATURA_INT_V1", "SUCESSO", $nomenclatura); //PENDENTE
} else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_ENVIA_FATURA_INT_V1", "FALHA", $nomenclatura); //OK
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

518
Clientes/Fly Link/install.php

@ -0,0 +1,518 @@
#!/usr/bin/php -q
<?php
include_once 'conf.php';
include_once 'config.php';
require_once 'IntegracaoDataBase.php';
include_once("util/util.php");
include_once '/var/www/html/aplicativo/admin/funcoes.php';
include_once 'util/funcoesAmi.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);
/**
* CONEXAO COM BANCO DE DADOS
*/
$db = new IntegracaoDataBase();
/**
* APRESENTA OS PROVEDORES DISPONIVEIS
*/
apresentaProvedoresDisponiveis($provedores);
/**
* AGUARDA O COLABORADOR INFORMAR O SISTEMA A SER USADO!
*/
$provedor = informaSistemaProvedor($provedores);
/**
* INFORMA A EMPRESA CASO FOR CLOUD
*/
$empresa = informaEmpresa();
/**
* INFORMA A FILA A SER INSTALADA
*/
$queue = informaFilas();
$filasInput = explode(",", $queue);
$filas = validaFilas($filasInput);
$horarios = $filas;
/**
* COLETA A VERSAO DO BANCO DE DADOS
*/
$version = installIntegracaoAtiva($provedor, $empresa);
$db->beginTransaction();
if ($version) {
#############CADASTRO################
echo "Integracao install init...\n";
//ANUNCIOS
if(installAnuncio($empresa, $version)){
echo "Anuncio install [ OK ]\n";
} else {
echo "Anuncio install [ FAIL ]\n";
$db->rollbackTransaction();
}
//URAS
if(installURA($empresa, $version)){
echo "URA install [ OK ]\n";
}else{
echo "URA install [ FAIL ]\n";
$db->rollbackTransaction();
}
//HORARIOS
if(installHorario($empresa, $version)){
echo "Horario install [ OK ]\n";
}else{
echo "Horario install [ FAIL ]\n";
$db->rollbackTransaction();
}
//URA REDIR
if(installURARedir($provedor, $empresa, $version)){
echo "URA Redir install [ OK ]\n";
}else{
echo "URA Redir install [ FAIL ]\n";
$db->rollbackTransaction();
}
#########CONFIGURA FLUXO################
echo "Integracao config init...\n";
//ANUNCIO
if(configuraFluxoAnuncio($provedor, $empresa, $version)){
echo "Anuncio fluxo config [ OK ]\n";
}else{
echo "Anuncio fluxo config [ FAIL ]\n";
$db->rollbackTransaction();
}
//URA
if(configuraFluxoUra($provedor, $empresa, $version)){
echo "Ura fluxo config [ OK ]\n";
}else{
echo "Ura fluxo config [ FAIL ]\n";
$db->rollbackTransaction();
}
//HORARIO
if(configuraFluxoHorario($provedor, $empresa, $version)){
echo "Horario fluxo config [ OK ]\n";
}else{
echo "Horario fluxo config [ FAIL ]\n";
$db->rollbackTransaction();
}
//URA REDIR
if(configuraFluxoUraRedir($provedor, $empresa, $version)){
echo "Ura Redir fluxo config [ OK ]\n";
}else{
echo "Ura Redir fluxo config [ FAIL ]\n";
$db->rollbackTransaction();
}
atualizaAsterisk();
$db->commitTransaction();
} else {
$db->rollbackTransaction();
}
############################################################################
#### FUNCOES INSTALACAO ####
############################################################################
function installIntegracaoAtiva($provedor, $empresa) {
global $provedores, $configs, $db;
try {
$db->findIntegracaoCustom();
$versao = $db->findVersion($empresa)['versao'] + 1;
$version = $versao ? $versao : 1;
$metodos = $provedores[$provedor]['METODOS'];
foreach ($metodos as $metodo) {
$nome = $metodo . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$comando = ($empresa ? $empresa . '/' : '') . $provedor . '/' . lcfirst(str_replace(' ', '', ucwords(strtolower(str_replace('_', ' ', $metodo))))) . '.php';
$db->createIntegracaoAtiva($nome, $version, $comando);
}
return $version;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
function installAnuncio($empresa, $version) {
global $anuncios, $configs, $db;
try {
foreach ($anuncios as $key => $val) {
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$musica = strtolower($key . "_" . $configs['CONF']['NOMENCLATURA']) . ".ulaw";
$db->addAnuncio($nome, $musica, null, null);
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
function installURA($empresa, $version) {
global $ura, $configs, $db;
try {
foreach ($ura as $key => $val) {
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$musica = strtolower($key . "_" . $configs['CONF']['NOMENCLATURA']) . ".ulaw";
$db->addUra($nome, $musica);
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
function installHorario($empresa, $version) {
global $horarios, $db, $configs;
try {
foreach ($horarios as $val) {
$nome = $val . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$db->addHorario($nome);
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
function installURARedir($provedor, $empresa, $version) {
global $provedores, $ura_redir, $configs, $db;
$metodos = $provedores[$provedor]['METODOS'];
try {
foreach ($ura_redir as $key => $val) {
if(in_array(str_replace("REDIR_", "", $key), $metodos)){
$nome = $key . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$musica = "silencio_int.ulaw";
$db->addUra($nome, $musica);
}
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
############################################################################
#### FUNCOES CONFIGURA FLUXO ####
############################################################################
/*
* Configuração de Anuncios
*/
function configuraFluxoAnuncio($provedor, $empresa, $version) {
global $provedores, $anuncios, $configs, $db, $horarios;
$metodos = $provedores[$provedor]['METODOS'];
try {
foreach ($anuncios as $key => $val) {
$direcaoTipo = null;
$direcaoNome = null;
foreach($val as $tipo => $nome){
if(in_array($nome, $metodos)){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER
$direcaoTipo = $tipo;
$direcaoNome = $nome;
break;
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE
$direcaoTipo = $tipo;
$direcaoNome = $nome;
if($tipo == CONF_HORARIO){
$direcaoNome = $horarios[0];
}
break;
}
}
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$idAnuncio = $db->getAnuncioIdByName($key);
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome);
$db->updateAnuncio($direcaoTipo, $idAcao, $idAnuncio);
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
/*
* Configuração de Horarios
*/
function configuraFluxoHorario($provedor, $empresa, $version) {
global $filas, $configs, $db, $horarios, $horarioPadrao;
try {
foreach ($horarios as $horarioNome) {
$nome = $horarioNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$horarioId = $db->getHorarioIdByName($nome);
$fila = $filas[0] . ($empresa ? '_'.$empresa: '');
foreach($horarioPadrao as $horarioPadraoItem){
foreach ($horarioPadraoItem as $tipo => $dado){
switch ($tipo) {
case "ITENS":
foreach($dado as $itens){
$horario_ini = $itens['HORARIO_INICIAL'];
$horario_fim = $itens['HORARIO_FINAL'];
$dias_semana = 0;
$semana = $itens['DIA_SEMANA_INICIO'];
$semana_fim = $itens['DIA_SEMANA_FIM'];
$opcao = CONF_FILAS;
$acao = $fila;
$idAcao = $db->getIdDirecionamento($opcao, $acao);
$db->addHorarioItens($horarioId, $horario_ini, $horario_fim, $dias_semana, $semana, $semana_fim, $opcao, $idAcao);
}
break;
case "FORA_HORARIO":
foreach($dado as $tipo => $nome){
$nome = $nome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$idAcao = $db->getIdDirecionamento($tipo, $nome);
$db->updateHorario($horarioId, $tipo, $idAcao);
}
break;
default:
break;
}
}
}
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
/*
* Configuração de Uras
*/
function configuraFluxoUra($provedor, $empresa, $version) {
global $provedores, $ura, $configs, $db, $horarios;
$metodos = $provedores[$provedor]['METODOS'];
try {
foreach ($ura as $key => $val) {
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$uraId = $db->getUraIdByName($key);
foreach($val as $key => $itens){
switch ($key) {
case "ITENS":
foreach ($itens as $item){
$direcaoTipo = null;
$direcaoNome = null;
foreach ($item['acao'] as $tipo => $nome) {
if(in_array($nome, $metodos)){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER
$direcaoTipo = $tipo;
$direcaoNome = $nome;
break;
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE
$direcaoTipo = $tipo;
$direcaoNome = $nome;
if($tipo == CONF_HORARIO){
$direcaoNome = $horarios[0];
}
break;
}
}
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome);
$db->addUraDestino($uraId, $item['numero'], $tipo, $idAcao, $item['sequencia'], $nome) ;
}
break;
case "TIMEOUT":
$direcaoTipo = null;
$direcaoNome = null;
foreach ($itens as $tipo => $nome){//PRIORIZAR INTEGRACAO CASO O PROVEDOR TIVER
if(in_array($nome, $metodos)){
$direcaoTipo = $tipo;
$direcaoNome = $nome;
break;
}else if($tipo != CONF_INTEGRACAO){//CASO NAO EXISTIR INTEGRACAO DO PROVEDOR, NAO PODE PEGAR INTEGRACAO, POIS O PROXIMO PODE SER UMA INTEGRACAO NAO EXISTENTE
$direcaoTipo = $tipo;
$direcaoNome = $nome;
if($tipo == CONF_HORARIO){
$direcaoNome = $horarios[0];
}
break;
}
}
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome);
$db->updateUra($uraId, $direcaoTipo, $idAcao) ;
break;
default:
break;
}
}
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
/*
* Configuração de Uras Redirecionamento
*/
function configuraFluxoUraRedir($provedor, $empresa, $version) {
global $provedores, $ura_redir, $configs, $db, $horarios;
$metodos = $provedores[$provedor]['METODOS'];
try {
foreach ($ura_redir as $key => $val) {
$key .= "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$uraId = $db->getUraIdByName($key);
$sequencia=1;
foreach($val as $key => $item){
$sequencia+=1;
if(!empty($item)){
$direcaoTipo = null;
$direcaoNome = null;
foreach ($item as $tipo => $nome){
if($tipo != CONF_INTEGRACAO){//NAO PODE TER REDIRECIONAMENTO PARA INTEGRACAO
$direcaoTipo = $tipo;
$direcaoNome = $nome;
if($tipo == CONF_HORARIO){
$direcaoNome = $horarios[0];
}
break;
}
}
$nome = $direcaoNome . "_" . $configs['CONF']['NOMENCLATURA'] . "_" . ($empresa ? $empresa . '_' : '') . 'V' . $version;
$idAcao = $db->getIdDirecionamento($direcaoTipo, $nome);
$db->addUraDestino($uraId, $key, $tipo, $idAcao, $sequencia, $nome);
}else{
$db->addUraDestino($uraId, $key, '', null, $sequencia, null);
}
}
}
return true;
} catch (Exception $ex) {
echo $ex->getMessage();
}
return false;
}
############################################################################
#### FUNCOES IMPORTANTES ####
############################################################################
function apresentaProvedoresDisponiveis($provedores, $select = null) {
$prov = "Sistemas de provedores disponiveis: \n\n";
foreach ($provedores as $key => $val) {
$prov .= sprintf(" - [ %s ] \n", $key);
if (strtoupper($select) == $key) {
return true;
}
}
if (!$select) {
echo $prov;
} else {
return false;
}
}
function informaSistemaProvedor($provedores) {
do {
echo "\n --------------------------------- \n";
echo "\nSelecione o sistema de provedor: \n";
echo "\n --------------------------------- \n";
$input = strtoupper(trim(fgets(STDIN)));
$resp = apresentaProvedoresDisponiveis($provedores, $input);
} while (!$resp);
return $input;
}
function informaEmpresa() {
echo "\n --------------------------------- \n";
echo "\nInforme a empresa: \n";
echo "\n OBS: APENAS PARA EMPRESAS NO CLOUD \n";
echo "\n --------------------------------- \n";
$empresa = strtoupper(trim(fgets(STDIN)));
return $empresa;
}
function informaFilas() {
echo "\n --------------------------------- \n";
echo "\nInforme as que seram utilizadas na integracao: \n";
echo "\n OBS: FILAS DEVEM SER SEPADADAS POR Virgulas(,) \n";
echo "\n --------------------------------- \n";
$queue = strtoupper(trim(fgets(STDIN)));
return $queue;
}
function validaFilas($filas){
global $db, $empresa;
$filaValidada = [];
foreach ($filas as $value) {
$fila = $value . ($empresa ? '_'.$empresa: '');
$filaId = $db->getFilaNumeroByName($fila);
if(empty($filaId)){
echo "\n --------------------------------- \n";
echo "\n Fila $value nao existe \n";
echo "\n --------------------------------- \n";
exit();
return null;
}
array_push($filaValidada, $value);
}
return $filaValidada;
}
function atualizaAsterisk(){
global $db;
gera_arquivos($db->getConnection(), 'ANUNCIOS');
gera_arquivos($db->getConnection(), 'TESTES');
gera_arquivos($db->getConnection(), 'URA');
gera_arquivos($db->getConnection(), 'TESTES');
gera_arquivos($db->getConnection(), 'HORARIOS');
gera_arquivos($db->getConnection(), 'TESTES');
}

57
Clientes/Fly Link/integracaoTela.php

@ -0,0 +1,57 @@
<?php
include 'IxcSoft.php';
//$registros = array(
// "id" => '',
// "reg_ura" => $ura,
// "reg_tronco" => $tronco,
// "reg_uniqueid" => $uid,
// "reg_id_metodo" => $idMetodo,
// "reg_uniqueid" => $uid,
// "reg_uniqueid_old" => $uidOld,
/* "reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date()); */
$ixc = new IxcSoft();
//$ixc->db()->setRegistros($registros);
//if (CONF_AUDIO_ERROR) {
// $ixc->db()->setIdAudioError(CONF_AUDIO_ERROR);
//}
$uraAtendimentoFluxo = array_reverse($ixc->db()->getAtendimentoLastURA($uid));
$historicoFluxo = '';
foreach ($uraAtendimentoFluxo as $item) {
/* $nomeSelecao = '';
switch ($item['umv_opcao']) {
case 'anuncios':
$nomeSelecao = $ixc->db()->getAnuncioById($item['umv_acao']);
break;
case 'filas':
$nomeSelecao = $ixc->db()->getFilaById($item['umv_acao']);
break;
case 'ura':
$nomeSelecao = $item['umv_acao'];
break;
case 'horarios':
$nomeSelecao = $ixc->db()->getHorariosById($item['umv_acao']);
break;
case 'integativa':
$nomeSelecao = $ixc->db()->getIntegracaoById($item['umv_acao']);
break;
}*/
$historicoFluxo = "Opcao URA - ". $item['umv_ura_opcao'];
}
$itgcTela['HISTORICO'] = $historicoFluxo;
array_push($params, 'HISTORICO');
$ixc->db()->atualizaDadosAgente($uid, $historicoFluxo);
$ixc->integracaoAgente($itgcTela, $params);
$ixc->db()->atualizaIntegracao();
?>

18
Clientes/Fly Link/paradaTecnica.php

@ -0,0 +1,18 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$latitude = $ixc->agi()->get_variable('LATITUDE', true);
$longitude = $ixc->agi()->get_variable('LONGITUDE', true);
$nomenclatura = $ixc->agi()->get_variable('NOMENCLATURA', true);
$manuntencao = $ixc->consultaManutencao($latitude, $longitude);
if ($manuntencao['em_manutencao'] != 'N' ) {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_PARADA_TECNICA_INT_V1", "SUCESSO", $nomenclatura); //PENDENTE
} else {
$redirecionamento_dados = $ixc->db()->redirectUraDestino("REDIR_PARADA_TECNICA_INT_V1", "FALHA", $nomenclatura); //OK
}
$ixc->executarFluxo($redirecionamento_dados["TIPO"], $redirecionamento_dados["NOME"]);
?>

8
Clientes/Fly Link/reload.php

@ -0,0 +1,8 @@
#!/usr/bin/php -q
<?php
include("util/util.php");
include '/var/www/html/aplicativo/admin/funcoes.php';
gera_arquivos($dbcon, 'ANUNCIOS');
gera_arquivos($dbcon, 'TESTES');

11
Clientes/Fly Link/teste.php

@ -0,0 +1,11 @@
<?php
include 'IxcSoft.php';
$ixc = new IxcSoft();
$retorno = $ixc->buscarCliente('08015285690');
// $listarFibra = $ixc->listarClientesFibra('2356');
// $idCliente = $ixc->listarConexoes($retorno['registros'][0]['id']);
$popOS = $ixc->ordemViaPop($retorno['registros'][0]['id']);
print_r($popOS);

2
Clientes/TopNet/EnviaFatura.php

@ -22,7 +22,7 @@ $registros = array(
$sgp = new SGP(
'90384833-6f95-4970-8bfc-01d8472ad559',
"suporte.topnetbrasil.com:8000",
true);
true);
$sgp->db()->setRegistros($registros);
$sgp->db()->setIdAudioError('79');

98
PlaceholderTest/EnviaBoletoEmail.php

@ -0,0 +1,98 @@
<?php
/*
* Desenvolvido por: Jose Henrique Joanoni
* Programador Jr. | Simples IP.
* Copyright 2020
*/
include 'MKSolutions.php';
$registros = array(
"id" => '',
"reg_ura" => $ura,
"reg_tronco" => $tronco,
"reg_uniqueid" => $uid,
"reg_id_metodo" => $idMetodo,
"reg_uniqueid" => $uid,
"reg_uniqueid_old" => $uidOld,
"reg_fone" => $numero,
"reg_status_exec" => '1',
"reg_inicio" => date());
$mk = new MkSolutions(
'f2e87897171de861c0910342dc166ffe',
"168.121.64.110:60180",
'38861d4be7c3698',
true);
$mk->db()->setRegistros($registros);
$mk->db()->setIdAudioError('');
$client_code = $mk->agi()->get_variable('CODCLIENTE', true);
$client_email = $mk->agi()->get_variable('EMAILCLIENTE', true);
$clientName = $mk->agi()->get_variable('NOMECLIENTE', true);
$invoice = $mk->buscaFatura($client_code);
if (empty($invoice['FaturasPendentes'][0])) {
$mk->agi()->exec_goto($mk->db()->getAnuncio('SEM_FATURAS_PENDENTES'));
} elseif (empty($client_email)) {
$mk->agi()->exec_goto($mk->db()->getFila('FINANCEIRO'));
} else {
$duplicate = $mk->segundaVia($invoice['FaturasPendentes'][0]['codfatura']);
$store_location = __DIR__ . "/boleto_{$duplicate['Fatura']}.pdf";
$file = file_get_contents($duplicate['PathDownload']);
file_put_contents($store_location, $file);
$embeded = __DIR__ . "/assinatura_email.jpeg";
$embeded_name = 'Logomarca';
$attach = array(
$store_location
);
$body = "<p>
Prezado <b>{$client['Nome']}</b>, segue anexo seu boleto com vencimento em: <b>{$duplicate['Vcto']}</b>
</p>
<p>
Se por ventura estiver vencido saiba que podes pagar normalmente em qualquer ponto de recebimento. <br>
Caso prefira, atualize seu código de barras clicando no link abaixo:<br><br>
<a href=\"https://www.santander.com.br/2-via-boleto\">Atualizar código de barras!</a>
</p>
<p>
Quaisquer dúvidas estamos à disposição.<br><br>
<b>0800 8787 985</b><br>
Whatsapp: <b>(11) 98488-0527</b><br>
e-mail: <b>cobranca@starnettelecom.com.br</b>
</p>
<img src=\"cid:{$embeded_name}\" alt=\"Logomarca StarNet\" width=\"600\" heigth=\"168\">";
$mail = $mk->sendMail(
"smtplw.com.br",
"starnettelco",
"44024112s",
"contato@starnettelecom.com.br",
"Atendimento StarNet Telecom",
$client_email,
"[NO-REPLY] Segunda Via StarNet Telecom",
'iso-8859-1',
$body,
$attach,
$embeded,
$embeded_name
);
if ($mail == 200) {
$mk->agi()->exec_goto($mk->db()->getAnuncio('FATURA_ENVIADA_EMAIL')); // Sucesso
} else {
$mk->agi()->exec_goto($mk->db()->getFila('FINANCEIRO')); // Falha
}
unlink($store_location);
}
$mk->db()->atualizaIntegracao();

300
PlaceholderTest/Integracao.php

@ -0,0 +1,300 @@
<?php
require_once 'phpagi/phpagi.php';
require_once 'IntegracaoDataBase.php';
require_once 'Logger.php';
require ("phpmailer/class.phpmailer.php");
/***************************************************************************
* SISTEMA UNICO DE INTEGRACAO *
***************************************************************************/
/**
* Classe para implementacao das integracoes da Simples IP
* @author Lucas Awade
* @Desenvolvedor
* @SimplesIP
* @version 1.1.1
*/
class Integracao {
protected $log;
private $agi;
private $db;
########################################################################
## CONSTANTES DA CLASSE ##
########################################################################
const PATH_LOG = "/var/log/asterisk/integracao.log";
const PATH_SOUND = '/var/lib/asterisk/sounds/customizados/';
const AGI_ERROR_HANDLER = false;
########################################################################
## FUNCOES UTILITARIAS ##
########################################################################
/**
* - Retorno é os dados referentes ao retornado da API
* - Params são os dados que serão disponibilizados na tela do agente.
*
* @param array $retorno
* @param array $params
*/
public function integracaoAgente($retorno, $params) {
$registros = 0;
$data = $this->db()->getRegistros();
$retorno_cliente = "{$data['reg_uniqueid']}|{$data['reg_fone']}|{$data['id']}|";
foreach ($retorno as $key => $value) {
if (in_array($key, $params)) {
$registros++;
$retorno_cliente .= sprintf("%s:%s",
strtoupper(str_replace("_", " ", $key)),
strtoupper(str_replace("|", "", $value)));
if (count($params) > $registros) {
$retorno_cliente .= "|";
}
}
}
$this->db()->setRegistros(array('retorno_cliente' => $retorno_cliente));
}
/**
* Converte um CPF ou CNPJ com marcara referente a cada modelo.
*
* @param string $string
* @return boolean|string
*/
protected function mask_cpf_cnpj($string) {
if (!empty($string)) {
if (strlen($string) == 11) {
$mask = "%s%s%s.%s%s%s.%s%s%s-%s%s";
} elseif (strlen($string) == 14) {
$mask = "%s%s.%s%s%s.%s%s%s/%s%s%s%s-%s%s";
}
return vsprintf($mask, str_split($string));
} else {
return false;
}
}
/**
* Verifica se todos os parametros passados foram completados.
*
* @param array $args
* @return true|false
*/
protected function getArgs($args) {
foreach ($args as $value) {
if (!$value) {
return false;
}
}
return true;
}
/**
* Verifica a diferenca em dias entre a data de entrada e a data atual.
*
* @param type $dateParam
* @return type
*/
public function dateDiff($dateParam)
{
$dateIni = strtotime(date('Y-m-d'));
$dateParam = date(strtotime(str_replace('/', '-', $dateParam)));
$diff = ($dateIni - $dateParam);
$days = (int) floor($diff / (60 * 60 * 24));
return $days;
}
/**
* Adiciona mascara no telefone para realizar a consulta
*
* @param type $value
* @return boolean
*/
protected function phoneMask($value)
{
if(!empty($value)){
if(strlen($value) == 10){
$mask = '(%s%s)%s%s%s%s-%s%s%s%s';
}elseif(strlen($value) == 11){
$mask = '(%s%s)%s%s%s%s%s-%s%s%s%s';
}
return vsprintf($mask, str_split($value));
}else{
return false;
}
}
/**
* Envia a segunda via de fatura para o cliente via email.
*
* @param string $host <p>Endereco do servidor de email</p>
* @param string $username <p>Nome de usuario para acesso ao STMP</p>
* @param string $pass <p>Senha de acesso ao SMTP</p>
* @param string $email_sender <p>Email do destinatario</p>
* @param string $sender_name <p>Nome do destinatario</p>
* @param string $email_receiver <p>Email do recebedor</p>
* @param string $subject <p>Assunto do email</p>
* @param string $charset <p>Encoding do email<p>
* @param string $message_body <p>Corpo do email</p>
* @param string $attachment <p>Anexos (podem ser varios)<p>
* @param string $embeded_img <p>Imagem de rodape</p>
* @param string $embeded_name <p>Nome da imagem de rodape<p>
* @param int $port <p>Porta de conexao ao SMTP</p>
* @param string $secure <p>Define se vai usar TLS, SSL ou nenhum</p>
* @return int
*/
function sendMail($host, $username, $pass, $email_sender, $sender_name,
$email_receiver, $subject, $charset, $message_body, $attachment = '',
$embeded_img = '', $embeded_name = '', $port = 587, $secure = '')
{
$mail = new PHPMailer(true);
//Configurações do Servidor
$mail->SMTPDebug = 0; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = $host; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = $username; // SMTP username
$mail->Password = $pass; // SMTP password
// Enable TLS encryption,`ssl` also accepted
!empty($secure) ? $mail->SMTPSecure = $secure : '';
$mail->Port = $port; // TCP port to connect to
//Remetente
$mail->setFrom($email_sender, $sender_name);
//Recebedores
$mail->addAddress($email_receiver);
//Conteudo
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->CharSet = $charset;
$mail->AddEmbeddedImage($embeded_img, $embeded_name);
// Enviar 1 ou imagens em anexo
if (!empty($attachment)) {
$count = count($attachment);
for ($i = 0; $i < $count; $i++) {
$mail->AddAttachment($attachment[$i]);
}
}
$mail->Body = $message_body;
$mail->send();
if (!empty($attachment)) {
$count = count($attachment);
for ($i = 0; $i < $count; $i++) {
unlink($attachment[$i]);
}
}
if ($mail->ErrorInfo) {
return $mail->ErrorInfo;
}
$success = 200;
return $success;
}
/**
* Verifica se existe o ramal informado pelo cliente na URA.
*
* @param string $numRamal
* @return boolean|string
*/
public function verificaRamal($numRamal)
{
if (strlen($numRamal) > 4) {
return "CPF";
}
$pdo = new PDO($this->db());
$sql = $pdo->prepare("SELECT nome FROM pbx_ramais WHERE nome = :CPF");
$sql->bindValue(":CPF", $numRamal, PDO::PARAM_STR);
$sql->execute();
if ($sql->rowCount() > 0) {
$result = $sql->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return false;
}
}
/**
* retorna o caminho do audio.
*
* @param string $audioName
* @return string
*/
public function pathAudio($audioName)
{
$audio = self::PATH_SOUND.$audioName;
return $audio;
}
########################################################################
## FUNCOES IMPORTANTES ##
########################################################################
/**
* Instancia um objeto de Logger.
*
* @param Logger $log
*/
protected function setLog($log = false) {
if (!$this->log) {
$this->log = new Logger('integracao', $log);
}
}
/**
* Instancia um objeto de AGI para se conectar com as informações do Asterisk.
*
* @return AGI
*/
public function agi() {
if (!$this->agi) {
$data = $this->db()->getAuthAgi();
$config = array();
$config['phpagi']['error_handler'] = self::AGI_ERROR_HANDLER;
$config['asmanager']['server'] = $data['host_sck'];
$config['asmanager']['port'] = $data['porta_sck'];
$config['asmanager']['username'] = $data['usuario_sck'];
$config['asmanager']['secret'] = $data['senha_sck'];
$agi = new AGI('phpagi.conf', $config);
$this->agi = $agi;
return $agi;
}
return $this->agi;
}
/**
* Instancia um objeto de IntegracaoDataBase para se conectar com dados do
* Banco de dados e credenciais do Manager.
*
* @return IntegracaoDataBase
*/
public function db() {
if (!$this->db) {
$db = new IntegracaoDataBase();
$this->db = $db;
}
return $this->db;
}
protected function audioError() {
$this->log->debug('Audio de error');
$exten = $this->db()->getAnuncio();
$this->log->error('Encaminhando para áudio alternativo de Erros',
debug_backtrace());
$this->agi()->exec_goto($exten);
exit();
}
}

337
PlaceholderTest/IntegracaoDataBase.php

@ -0,0 +1,337 @@
<?php
require_once 'Logger.php';
// *************************************************************************
// * SISTEMA UNICO DE INTEGRACAO *
// *************************************************************************
/**
* Classe para utilizar os registros do Banco de Dados;
*
* OBS: Deixar como usuario de execucao e acesso pbx:pbx
*
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.1
*/
class IntegracaoDataBase {
private $query;
private $connection;
private $registros;
private $log;
private $credentials = array();
private $debug;
private $idAudioError;
/**
* @file
* Arquivo de configuracoes do banco e manager
*/
const FILE_DB = "/var/www/html/include/bd";
public function __construct() {
$this->log = new Logger('integracao');
}
/**
* Retorna os registros armazenados na variavel registros pra ser disponibilizado
* no decorrer de uma integracao;
*
* @return array
*/
public function getRegistros() {
return $this->registros;
}
/**
* Informações coletadas do banco de dados para ser escritas no log.
*
* @param array $array
*/
private function logResult($array) {
if ($array) {
$this->log->success(print_r($array, true), $this->debug);
} else {
$this->log->warning('Nenhum resultado encontrado!', $this->debug);
}
}
/**
* Audio de erro padrao
*
* @param string $idAudioError
*/
public function setIdAudioError($idAudioError) {
$this->idAudioError = $idAudioError;
}
########################################################################
## BANCO DE DADOS ##
########################################################################
/**
* Pega as informacoes das credenciais no arquivos padrao "bd";
*/
private function filedb() {
if (file_exists(self::FILE_DB)) {
$contents = fopen(self::FILE_DB, 'r');
while (!feof($contents) && $contents) {
$str = fgets($contents);
$dados = explode('=', $str);
$this->credentials[strtolower($dados[0])] = str_replace('"', '', $dados[1]);
}
fclose($contents);
$this->credentials = array_filter($this->credentials);
$this->log->debug("Credenciais banco de dados: " . print_r($this->credentials, true), debug_backtrace());
} else {
$this->log->error("Nao foi possivel encontrar o arquivo 'bd' em " . self::FILE_DB);
}
}
/**
* Executa as querys da consulta a serem feitas, além de gravar logs de registros de dados,
* e qualquer erro é repassado a classe que está executando para tratar o erro;
*
* @param string $type
* @return boolean|array
*/
private function execute($type = '') {
try {
if (!$this->connection) {
$this->filedb();
$this->connection = pg_connect(sprintf('host=%s port=%s dbname=%s user=%s password=%s', $this->credentials['host_db'], $this->credentials['porta_db'], $this->credentials['base_db'], $this->credentials['usuario'], $this->credentials['senha']));
if (pg_connection_status($this->connection) === 0) {
$this->log->success("Conectado na base {$this->credentials['base_db']}.", debug_backtrace());
} else {
throw new Exception('Nao foi possivel conectar na base de dados');
}
}
$result = pg_query($this->connection, $this->query);
switch (strtolower($type)) {
case 'assoc':
$data = pg_fetch_assoc($result);
break;
case 'row':
$data = pg_fetch_row($result);
break;
case 'array':
$data = pg_fetch_array($result);
break;
case 'all':
$data = pg_fetch_all($result);
break;
}
$this->logResult($data);
return $data;
} catch (Exception $ex) {
$this->log->error("Exception: {$ex->getMessage()} | Postgres : " . pg_last_error(), $this->debug);
}
}
########################################################################
## ASTERISK ##
########################################################################
/**
* Coleta em qual Asterisk a central está rodadando e retorna o modelo padrao
* de configuracao do exten;
*
* @return string
*/
private function getVersionAsterisk() {
$result = array();
exec("asterisk -V", $result);
$this->log->info("Versao Asterisk: " . $result[0], debug_backtrace());
if (strpos($result[0], '1.4') !== false) {
return "|";
} else {
return ",";
}
}
/**
* Transforma uma string exten com "," para "|" de acordo com a versao do Asterisk
*
* @param string $string
* @return string
*/
private function string_exten($string) {
return str_replace(",", $this->getVersionAsterisk(), $string);
}
/**
* Coleta os dados de autenticacao do manager.
*
* @return array
*/
public function getAuthAgi() {
$data = array();
foreach ($this->credentials as $key => $value) {
if (strpos($key, '_sck') !== false) {
$data[$key] = $value;
}
}
return $data;
}
########################################################################
## QUERYS ##
########################################################################
/**
* Inicia um Transacao;
*/
private function beginTransaction() {
$this->debug = debug_backtrace();
$this->query = "BEGIN;";
$this->execute();
}
/**
* Registra uma Transacao.
*/
private function commitTransaction() {
$this->debug = debug_backtrace();
$this->query = "COMMIT;";
$this->execute();
}
/**
* Retorna as informacoes antes da Transacao.
*/
private function rollbackTransaction() {
$this->debug = debug_backtrace();
$this->query = "ROLLBACK;";
$this->execute();
}
/**
* Consulta no banco o nome do Anuncio e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getAnuncio($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_anuncios WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-anuncios,a%s,1'), $result);
}
/**
* Consulta no banco o nome do Ura e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getURA($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT id FROM pbx_ura WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ura-%s,s,1'), $result);
}
/**
* Consulta no banco o nome do Fila e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getFila($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT numero FROM pbx_dacs WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-fila,%s,1'), $result);
}
/**
* Consulta no banco o nome do Ramal e retorna o ID para ser escrito no exten;
*
* @param string $name
* @return string
*/
public function getRamal($name = null) {
$this->debug = debug_backtrace();
$this->query = "SELECT nome FROM pbx_ramais WHERE nome = '$name'";
$result = $this->execute('row')[0] ? $this->execute('row')[0] : $this->idAudioError;
return sprintf($this->string_exten('ext-ramais,%s,1'), $result);
}
/**
* Coleta as opcoes que o usuario passou nas uras da sua chamada.
*
* @param string $uniqueid
* @param int $ura_id
* @return boolean|array
*/
public function getOptionsURA($uniqueid, $ura_id) {
$this->debug = debug_backtrace();
$this->query = "SELECT umv_ura_id,umv_ura_nome,uniqueid,umv_ura_opcao "
. "FROM pbx_ura_movimento WHERE uniqueid = '$uniqueid' "
. "AND umv_ura_opcao IS NOT NULL AND umv_opcao = 'ura' "
. "AND umv_ura_id = $ura_id "
. "ORDER BY umv_id";
return $this->execute('all');
}
public function registraIntegracao() {
$this->debug = debug_backtrace();
/**
* Parametros REGISTROS
*
* id -> Id do qual gerou a integracao para o retorno_cliente
*
* Todos os parametros devem ser igual a da tabela pbx_integracao_reg
*/
$ura = trim($this->registros['reg_ura']) ? trim($this->registros['reg_ura']) : 'null';
$tronco = trim($this->registros['reg_tronco']) ? trim($this->registros['reg_tronco']) : 'null';
$this->query = "INSERT INTO pbx_integracao_reg (reg_id_metodo,reg_uniqueid,reg_uniqueid_old,reg_fone,reg_inicio, reg_tronco, reg_ura)
VALUES('{$this->registros['reg_id_metodo']}','{$this->registros['reg_uniqueid']}','{$this->registros['reg_uniqueid_old']}','{$this->registros['reg_fone']}', now(), '$tronco', '$ura')";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
public function atualizaIntegracao() {
$this->debug = debug_backtrace();
$tronco = trim($this->registros['reg_tronco']) ? sprintf(",\nreg_tronco='%s'", trim($this->registros['reg_tronco'])) : '';
$ura = trim($this->registros['reg_ura']) ? sprintf(",\nreg_ura='%s'", trim($this->registros['reg_ura'])) : '';
$reg_msg = QuotedStr($this->registros['reg_msg']);
$reg_retorno = QuotedStr($this->registros['reg_fone']);
$retorno_cliente = substr($this->registros['retorno_cliente'], 0, 255);
$this->query = "UPDATE pbx_integracao_reg
SET reg_fim = NOW(),
reg_retorno = $reg_retorno,
reg_msg = $reg_msg,
reg_status_exec = '{$this->registros['reg_status_exec']}',
retorno_cliente = '{$retorno_cliente}'{$tronco}{$ura}
WHERE reg_uniqueid = '{$this->registros['reg_uniqueid']}'";
$this->log->debug("Query: {$this->query}", $this->debug);
return $this->execute();
}
/**
* Informa os dados para ser inseridos na tabela de integracao_reg;
*
* @param array $registros
*/
public function setRegistros($registros) {
if (is_array($registros) && !$this->registros) {
$this->registros = $registros;
$this->registraIntegracao();
} else {
foreach ($registros as $key => $value) {
$this->registros[$key] = $value;
}
}
}
public function getClienteNumeroLigacoes($numero) {
$this->debug = debug_backtrace();
$this->query = "select count(*) from ast_bilhetes ab where dcontext != 'ext-transferencia' and calldate >= NOW() - interval '24 hour' and src = '$numero'";
return $this->execute('row')[0];
}
}

147
PlaceholderTest/Logger.php

@ -0,0 +1,147 @@
<?php
/**
* Classe para utilizar
*
* @documentation:
* @author Lucas Awade
* @function developer
* @company SimplesIP
* @version 1.0.0
*/
class Logger {
/*
* GENERATE LOG
*/
private $active;
private $log;
private $type;
/*
* CONF. FILE LOG
*/
private $file;
private $path;
private $name;
/*
* CONST. MESSAGE TYPE
*/
const LOG_SUCCESS = "SUCCESS";
const LOG_DEBUG = "DEBUG";
const LOG_INFO = "INFO";
const LOG_WARNING = "WARNING";
const LOG_ERROR = "ERROR";
public function __construct($nameLog, $active = false, $path = "/var/log/asterisk/") {
$this->name = $nameLog;
$this->path = $path;
$this->active = $active;
$this->config($nameLog);
}
########################################################################
## TYPES ##
########################################################################
public function success($log, $debug_trace) {
$this->type = self::LOG_SUCCESS;
$this->header($log, $debug_trace ? $debug_trace : debug_backtrace());
$this->write();
}
public function debug($log, $debug_trace = null) {
$this->type = self::LOG_DEBUG;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function info($log, $debug_trace = null) {
$this->type = self::LOG_INFO;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function error($log, $debug_trace = null) {
$this->type = self::LOG_ERROR;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
public function warning($log, $debug_trace = null) {
$this->type = self::LOG_WARNING;
$this->header($log, $debug_trace ? $debug_trace : $this->name);
$this->write();
}
########################################################################
## IMPORTANT ##
########################################################################
private function write() {
if ($this->active) {
file_put_contents($this->file, $this->log, FILE_APPEND);
}
}
private function header($log, $debug_trace) {
$this->log = "________________________________________________________________________________________\n";
if(is_array($debug_trace)){
$method = $debug_trace[0]['class'] ? "{$debug_trace[0]['class']}::{$debug_trace[0]['function']}" : $debug_trace[0]['function'];
$args = null;
if(count($debug_trace[0]['args']) > 0){
foreach($debug_trace[0]['args'] as $key => $arg){
$x++;
$args .= $arg;
if(count($debug_trace[0]['args']) != $x){
$args .= ",";
}
}
}
$this->log .= sprintf("\n[ %s ][ LINE %s ][ %s ][ ARGS ($args) ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace[0]['line'], $method, $this->type);
} else {
$this->log .= sprintf("\n[ %s ][ %s ][ %s ]\n\n", date('d/m/Y H:i:s'), $debug_trace, $this->type);
}
$this->log .= "> " . $log;
$this->log .= "\n\n ---------------------------------- [ FINISH LOGGER ] ----------------------------------\n\n";
}
public function openLog() {
//$file = fopen($this->file, 'rb');
}
public function locateLog() {
echo "\n\n {$this->file} \n\n";
}
########################################################################
## CONFIGS ##
########################################################################
public function config($name, $exten = ".log", $prefix = null) {
if (file_exists($this->file)) {
$contents = file_get_contents($this->file);
}
$this->file = trim($this->path . $prefix . ($name ? $name : $this->name) . $exten);
file_put_contents($this->file, $contents ? $contents : "", FILE_APPEND);
}
public function getType() {
return $this->type;
}
public function setLogger($active) {
if ($this->active === true) {
$this->active = $active;
} else if ($active === false) {
$this->active = $active;
} else {
$this->active = true;
}
}
}

79
PlaceholderTest/config.php

@ -0,0 +1,79 @@
<?php
###########################################################################
##### #####
##### ARQUIVO PARA A CONFIGURACAO DE ACESSO API #####
##### ----------------------------------------- #####
##### CREDENCIAIS DE ACESSO #####
###########################################################################
define('CONF_ID_CREDENCIAIS', '');
define('CONF_TOKEN_API', '70cf5d37f9e0ee65252ca63d4b49ff37');
define('CONF_URL_API', 'https://api.tracksale.co/v2/');
define('CONF_USER_API', 'SIMPLESIP');
define('CONF_PASSWORD_API', '25RH0QELJF');
define('CONF_USERID_API', '8');
###########################################################################
##### CONFIGURACAO DE LOG #####
###########################################################################
define('CONF_LOGGER_ATIVO', true);
define('CONF_LOGGER_DB_ATIVO', false);
###########################################################################
##### CONFIGURACAO DE ERROR #####
###########################################################################
define('CONF_AUDIO_ERROR', '');
###########################################################################
##### CONFIGURACAO PDO #####
###########################################################################
define('CONF_DB_DRIVER', "");
define('CONF_DB_HOST', "");
define('CONF_DB_PORT', "");
define('CONF_DB_BASE', "");
define('CONF_DB_USER', "");
define('CONF_DB_PASSWD', "");
define('CONF_DB_OPTIONS', "");
###########################################################################
##### CREDENCIAIS DE ENVIO DE EMAIL #####
###########################################################################
define('CONF_EMAIL_TITLE_INVOICE', '[NO-REPLY] Envio de Fatura');
define('CONF_EMAIL_SUBTITLE_INVOICE', 'Estamos enviando o pedido de Segunda Via da sua Fatura!');
define('CONF_SENDER_EMAIL_USER', '');
define('CONF_SENDER_EMAIL_PASSWORD', '');
define('CONF_SMTP_HOST', '');
define('CONF_SMTP_POST', '587');
###########################################################################
##### CONFIGURACAO GERAÇÃO DE FATURA #####
###########################################################################
define('CONF_FATURA_DIAS_ANTES', 30);
define('CONF_FATURA_DIAS_APOS', 5);
############################################################################
##### CONF. KING CAMPANHA #####
############################################################################
define('CONF_CAMP_LOGIN', "novahelp");
define('CONF_CAMP_DATAINI', date('Y-m-d 08:00:00'));
define('CONF_CAMP_DATAFIM', date('Y-m-d 18:00:00'));
define('CONF_CAMP_RAMAL', "2000");
define('CONF_CAMP_FLUXO', 0);
define('CONF_CAMP_PAUSA', 1);
define('CONF_CAMP_NUMREDISCAGEM', 1);
define('CONF_CAMP_MAXCALL', 10);
define('CONF_CAMP_RINGTIME', 45);
define('CONF_CAMP_INTERVALO', 1);
define('CONF_CAMP_AMD', 0);
define('CONF_CAMP_NDS', 0);
define('CONF_CAMP_PRIOMOVEL', 0);
define('CONF_CAMP_MAXCALLAGENT', 3);

25
PlaceholderTest/consultaCliente.php

@ -0,0 +1,25 @@
<?php
require "placeHolder.php";
$clienteEmail = "lucas_sity@hotmail.com";
$placeholder = new placeHolder();
$idCliente = $placeholder->agi()->get_variable('EXTEN', true);
$reg_pass = $placeholder->agi()->get_variable("REG_PASS", true);
if ($reg_pass < 4) {
$validarCliente = $placeholder->validaCliente($idCliente);
if ($validarCliente == false) {
$placeholder->db()->getAnuncio('NAO_IDENTIFICADO_INT_V2');
exit();
} else {
$placeholder->enviarEmail($clienteEmail, $validarCliente['name']);
}
$placeholder->db()->getFila('SUPORTE');
} else {
$placeholder->db()->getFila('SUPORTE');
}

84
PlaceholderTest/placeHolder.php

@ -0,0 +1,84 @@
<?php
require_once 'Integracao.php';
class placeHolder extends Integracao
{
private $nome;
private $telefone;
private $email;
private $empresa;
private $cidade;
private $rua;
private $id;
private $debug;
private $params = array();
########################################################################
## FUNCOES DA API ##
########################################################################
/**
* @param Type $var Description
* @return type
* @throws conditon
**/
public function validaCliente($id)
{
$url = "https://jsonplaceholder.typicode.com/users/{$id}";
// $url .= "{$id}";
$clienteArquivo = curl_init($url);
curl_setopt($clienteArquivo, CURLOPT_RETURNTRANSFER, true);
curl_setopt($clienteArquivo, CURLOPT_SSL_VERIFYPEER, false);
$clientes = json_decode(curl_exec($clienteArquivo), true);
$arraysum = array_sum($clientes);
if ($arraysum > 0) {
return $clientes;
} else {
return false;
}
$this->log()->debug($clientes);
}
/**
* @param Type $var Description
* @return type
* @throws conditon
**/
public function enviarEmail($clienteEmail, $clienteNome)
{
$host = "smtplw.com.br";
$userName = "lucas.ayala@simplesip.com.br";
$pass = "LucasAyala@2021";
$emailSender = $userName;
$senderName = "Lucas Ayala - Simples IP";
$emailReceiver = $clienteEmail;
$subject = "Ticket Atendimento";
$charset = "iso-8859-1";
$body = "<p>
Prezado <b>{$clienteNome}</b>, segue anexo seu boleto com vencimento em: <b>HOJE!</b>
</p>
<p>
Se por ventura estiver vencido saiba que podes pagar normalmente em qualquer ponto de recebimento. <br>
</p>
<p>
Quaisquer d<EFBFBD>vidas estamos <EFBFBD> disposi<EFBFBD><EFBFBD>o.<br><br>
</p>";
$this->sendMail($host,
$userName,
$pass,
$emailSender,
$senderName,
$emailReceiver,
$subject,
$charset,
$body);
}
}
Loading…
Cancel
Save