PABX da Simples IP
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6487 lines
253 KiB

<?php
//caso o display errors for ativo pode impactar no funcionamento de algumas chamadas da api.
error_reporting(0);
ini_set('display_errors', 0);
$docApi = [];
$obsConectaAgente = "<br/> Obs: <EFBFBD> necess<EFBFBD>rio ter autenticado(\"ConectaAgente(...)\") o agente e informar o \"SIPID\" na url.";
$log = array();
$docApi['Ping'] = MetodoApi('Informa<EFBFBD><EFBFBD>es sobre o servidor de socket.');
function Ping()
{
try {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = "Servidor Ativo!";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("Ping", $ex);
}
}
$docApi['MeuIP'] = MetodoApi('Retorna o IP.');
function MeuIP()
{
try {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $_SERVER["SERVER_ADDR"];
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("Ping", $ex);
}
}
/*
* Metodos de Usuarios
*/
$docApi['ListaDacs'] = MetodoApi('Retorna uma lista com os Dacs dispon<EFBFBD>veis.');
function ListaDacs()
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select 'Receptivo' as tipo, id, nome, numero from pbx_dacs_api d where status = 'A' order by nome";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaDacs", $ex);
}
}
/**
* ListaAbandonadas -> Lista todas as chamadas abandonadas em tempo real da fila informada.
* @param string $dac
* @return JSON/XML
* @throws Exception
*/
$docApi['ListaAbandonadas'] = MetodoApi(
'Lista todas as chamadas abandonadas em tempo real da fila informada.',
[
["DAC-SUPORT", "STRING", "REQUIRED", 'Informe um DAC a ser monitorado.']
]
);
function ListaAbandonadas($dac)
{
$dbcon = $GLOBALS['dbcon'];
try {
$sql = "drop table if exists tmp_abandonadas_sr;
create temporary table tmp_abandonadas_sr
(
calldate timestamp,
src varchar(80),
fila varchar(80),
param3 varchar(50),
status varchar(2)
);
insert into tmp_abandonadas_sr (calldate,src,fila,param3)
select b.calldate, b.src , c.fila,c.param3
from ast_bilhetes b, ast_eventos_dacs c
where c.uid2 = b.uniqueid
and b.data_bilhete = now()::date
and c.evento = 'ABANDON'
and upper(c.fila) = upper('$dac')
and 1 = CASE WHEN(c.evento = 'ABANDON')then
(case when(not exists(select '' from ast_eventos_dacs where uid2 = c.uid2 and evento = 'TRANSBORDANDO' and fila = c.fila))
then 1 else 0 end) else 1 end ;
update tmp_abandonadas_sr a set status = 'F'
from ast_bilhetes b
inner join ast_eventos_dacs c on c.uid2 = b.uniqueid
where c.evento in('COMPLETEAGENT','COMPLETECALLER','COMPLETECALLERRAMAL','COMPLETEAGENTRAMAL',
'COMPLETAAGENT','COMPLETACALLER','COMPLETACALLERRAMAL','COMPLETAAGENTRAMAL')
and c.fila = a.fila
and (a.src = b.src or a.src = b.dst)
and b.lastapp <> 'Transferred Call'
and b.calldate > a.calldate;
select fila, cast(calldate as date) as data, src as origem, count(src) as qtde,
sum(param3::integer) as tempo, max(calldate) as ult_abandono
from tmp_abandonadas_sr where status is null and upper(fila) = upper('$dac') group by 1,2,3 order by 3";
$result = pg_query($dbcon, $sql);
if (!$result) {
throw new Exception("<b>N<EFBFBD>o foi poss<EFBFBD>vel consultar as abandonadas</b>");
} elseif (pg_num_rows($result) == 0) {
throw new Exception("<b>N<EFBFBD>o h<EFBFBD> chamadas abandonadas na fila especificada.</b>");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaAbandonadas", $ex);
}
}
$docApi['ListaAbandonadasPeriodo'] = MetodoApi(
'Retorna uma listagem das chamadas abandonadas por per<EFBFBD>odo.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa'],
["DAC-SUPORT", "STRING", "REQUIRED", 'Informe a fila que gostaria de consultar']
]
);
function ListaAbandonadasPeriodo($dataInicial, $dataFinal, $dac)
{
try {
//TRATAMENTO DA DATA INICIAL
$date = soNumero($dataInicial);
if (strlen($date) > 8) {
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
}
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date)) {
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
}
//TRATAMENTO DA DATA FINAL
$date = soNumero($dataFinal);
if (strlen($date) > 8) {
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
}
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date)) {
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
}
$dbcon = $GLOBALS['dbcon'];
$sql = "select b.fila, a.data_bilhete as data, date_part('hour', calldate) as hora,
a.src as origem, count(*) as qtde, sum(strtoint(param3)) as tempo
from pbx_bilhetes a, pbx_eventos_dacs b
where b.uid2 = a.uniqueid
and b.evento = 'ABANDON'
and a.lastapp <> 'Transferred Call'
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and b.fila = upper('$dac')
group by b.fila, a.data_bilhete, date_part('hour', calldate), a.src
order by 2,3";
$result = pg_query($dbcon, $sql);
if (!$result) {
throw new Exception("<b>N<EFBFBD>o foi poss<EFBFBD>vel realizar a consulta!</b>");
} elseif (pg_num_rows($result) == 0) {
throw new Exception("<b>N<EFBFBD>o existem registros para a fila informada! </b>");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaAbandonadasPeriodo", $ex);
}
}
$docApi['ListaChamadasGeral'] = MetodoApi(
'Retorna lista das chamadas Entrantes/Saintes por per<EFBFBD>odo.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa.']
]
);
function ListaChamadasGeral($dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = " drop table if exists tmp_listachamadas;
create temporary table tmp_listachamadas
(tipo varchar(25), data date,data_hora timestamp, agente varchar(50), ramal varchar(25), fone varchar(100),uniqueid varchar(32),
transferencia varchar(32),status varchar(45),duracao varchar(25), tempo_atend varchar(25), id_fila varchar(25), nome_fila varchar(50));
--PBX - saintes ramal
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select 'S' as tipo, a.data_bilhete as data, a.calldate as data_hora, '' as agente, a.src as ramal, c.destino as fone, a.uniqueid, '' as transferencia, a.disposition as status,
(case when a.lastdata like ('CONTASENHA%') then 0 else (a.billsec) end) as duracao,'' as tempo_atend, '' as id_fila, '' nome_fila
from pbx_bilhetes a, pbx_bilhetes_complemento c
where c.uniqueid2 = a.uniqueid
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and c.direcao in ('saida-pstn','interna')
and coalesce(trim(c.dac), '') = ''
and not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call' )
and exists(select '' from pbx_ramais where nome = a.src);
--PBX - Entrantes ramal
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select 'E' as tipo, a.data_bilhete as data, a.calldate as data_hora, '' as agente, a.dst as ramal, a.src as fone, a.uniqueid, '' as transferencia, a.disposition as status,
(case when a.lastdata like ('CONTASENHA%') then 0 else (a.billsec) end) as duracao,'' as tempo_atend, '' as id_fila, '' nome_fila
from pbx_bilhetes a
inner join pbx_bilhetes_complemento e on e.uniqueid2 = a.uniqueid
where cast(a.calldate as date) >= '$dataInicial'
and cast(a.calldate as date) <= '$dataFinal'
and e.direcao in ('entrada-pstn','externa')
and length(a.src) >= 8
and exists(select '' from pbx_ramais where nome = (a.dst))
and not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call' )
and not exists(select '' from tmp_listachamadas where uniqueid = a.uniqueid);
--CallCenter - Originadas
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select 'S' as tipo, a.data_bilhete as data, a.calldate as data_hora, c.matricula as agente, a.src as ramal,
a.dst as fone, a.uniqueid,
'' as transferencia, a.disposition as status, a.billsec as duracao,
case b.evento when 'TRANSFERORIG' then b.param4 else b.param2 end as tempo_atend,
d.id as id_fila, d.nome as nome_fila
from pbx_bilhetes a, pbx_eventos_dacs b, pbx_usuarios c, pbx_dacs d
where b.uid2 = a.uniqueid
and d.nome = b.fila
and c.matricula = substring(b.agente,7 ,4)
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call' )
and b.evento in('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG')
and not exists(select '' from tmp_listachamadas where uniqueid = a.uniqueid);
--CallCenter - Recebidas
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select 'E' as tipo, a.data_bilhete as data, a.calldate as data_hora, c.matricula as agente, d.destino as ramal,
a.src as fone, a.uniqueid,'' as transferencia,
case when a.channel like ('%SMS%') then 'SMS' else a.disposition end as status, a.billsec as duracao,
case b.evento when 'TRANSFER' then b.param4 else b.param2 end as tempo_atend,
e.id as id_fila, e.nome as nome_fila
from pbx_bilhetes a
inner join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento in('COMPLETEAGENT','COMPLETECALLER','TRANSFER')
inner join pbx_bilhetes_complemento d on d.uniqueid2 = a.uniqueid and d.direcao = 'fila-ramal'
inner join pbx_dacs e on e.nome = b.fila
left join pbx_usuarios c on c.matricula = substring(b.agente,7 ,4)
where a.billsec > 3
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call' )
and not exists(select '' from tmp_listachamadas where uniqueid = a.uniqueid);
--Abandonada fila
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select 'E' as tipo, a.data_bilhete as data, a.calldate as data_hora, '' as agente, a.dst as ramal,
a.src as fone, a.uniqueid, '' as transferencia,
b.evento as status, a.billsec as duracao, '' as tempo_atend, c.id as id_fila, c.nome as nome_fila
from pbx_bilhetes a, pbx_eventos_dacs b, pbx_dacs c
where b.uid2 = a.uniqueid
and c.nome = b.fila
and b.evento = 'ABANDON'
and a.lastapp <> 'Transferred Call'
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call' )
and not exists(select '' from tmp_listachamadas where uniqueid = a.uniqueid);
-- transferencias
insert into tmp_listachamadas(tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia, status, duracao, tempo_atend, id_fila, nome_fila)
select distinct 'S' as tipo, a.data_bilhete as data, a.calldate as data_hora, d.matricula as agente, c.destino as ramal, a.src as fone,
a.uniqueid, a.accountcode as transferencia, a.disposition as status, a.billsec as duracao,'' as tempo_atend, e.id as id_fila, e.nome as nome_fila
from pbx_bilhetes a
inner join pbx_bilhetes_complemento c on c.uniqueid2 = a.uniqueid
left join pbx_eventos_dacs b on a.uniqueid = b.uid2 and b.evento in('COMPLETEAGENT','COMPLETECALLER','TRANSFER','COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG','COMPLETEAGENTRAMAL','COMPLETAAGENTRAMAL')
left join pbx_usuarios d on d.matricula = substring(b.agente,7 ,4)
left join pbx_dacs e on e.nome = b.fila
where a.accountcode <> ''
and a.data_bilhete >= '$dataInicial'
and a.data_bilhete <= '$dataFinal'
and lastapp <> 'Transferred Call'
and a.accountcode <> a.uniqueid
and not exists(select '' from tmp_listachamadas where uniqueid = a.uniqueid);
select distinct tipo, data, data_hora, agente, ramal, fone, uniqueid, transferencia,
case status
when 'ABANDON' then 'ABANDONADA'
when 'ANSWERED' then 'ATENDIDA'
when 'SMS' then 'SMS'
when 'NO ANSWER' then 'N<EFBFBD>O ATENDIDA'
when 'BUSY' then 'OCUPADO'
when 'FAILED' then 'TRONCO INDISPONIVEL'
else '-' end as status
, duracao, tempo_atend, id_fila, nome_fila
from tmp_listachamadas order by 3";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaChamadasGeral", $ex);
}
}
$docApi['ListaChamadas'] = MetodoApi(
'Retorna informa<EFBFBD><EFBFBD>es de origem/destino das chamadas de acordo com o per<EFBFBD>odo.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa']
]
);
function ListaChamadas($dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = "drop table if exists ast_complemento;
create temporary table ast_complemento as
select min(b.id)as id from pbx_bilhetes a
inner join pbx_bilhetes_complemento b on b.uniqueid2 = a.uniqueid
where not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
and a.lastapp <> 'Transferred Call'
group by uniqueid2;
drop table if exists ast_audio_pbx;
create temporary table ast_audio_pbx as
select a.id,a.direcao,a.uniqueid2 from pbx_bilhetes_complemento a
inner join ast_complemento b on b.id=a.id;
select uniqueid, data, src, dst, dac, agente, direcao,
CASE evento
WHEN 'COMPLETARAMAL' THEN 'ATENDIDA'
WHEN 'COMPLETEAGENTRAMAL' THEN 'ATENDIDA'
WHEN 'COMPLETEAGENT' THEN 'ATENDIDA'
WHEN 'COMPLETAAGENT' THEN 'ATENDIDA'
WHEN 'COMPLETACALLER' THEN 'ATENDIDA'
WHEN 'COMPLETECALLER' THEN 'ATENDIDA'
WHEN 'ABANDON' THEN 'ABANDONADA'
WHEN 'NO ANSWER' THEN 'ABANDONADA'
WHEN 'ANSWERED' THEN 'ATENDIDA'
WHEN 'BUSY' THEN 'OCUPADO'
WHEN 'FAILED' THEN 'ABANDONADA' ELSE '-' END AS evento,
case when (evento in('COMPLETECALLER', 'COMPLETEAGENT', 'COMPLETAAGENT','COMPLETACALLER'))then param1 else 0 end as tempo_espera,
case when (evento in('COMPLETEAGENT','COMPLETECALLER', 'COMPLETAAGENT','COMPLETACALLER'))then param2 else 0 end as tempo_ligacao,
case evento when ('ABANDON')then param3 else 0 end as tempo_abandono,
transfer,max(duration) as duracao,
case when (evento = 'ABANDON')THEN 0 else max(billsec) end as conversacao
from(
select a.calldate as data, a.uniqueid, a.src,
case when(b.evento in('COMPLETECALLER', 'COMPLETEAGENT')and d.apelido is not null)then (select max(destino) from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid and direcao = 'fila-ramal') else
(select destino from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid and id = (select max(id) from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid)) end as dst,
a.accountcode, a.duration, a.billsec,b.fila as dac, b.agente,
case when(b.evento in('COMPLETECALLER', 'COMPLETEAGENT'))then 'entrada' else 'saida' end as direcao,
coalesce(a.disposition, '') as disposition, strtoint(b.param1) as param1,
strtoint(b.param2) as param2, strtoint(b.param3) as param3,
case when(exists(select '' from pbx_bilhetes where data_bilhete = a.data_bilhete and accountcode = a.uniqueid))then 1 else 0 end as transfer,
b.evento
from pbx_bilhetes a
inner join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento in('COMPLETEAGENT','COMPLETECALLER', 'COMPLETAAGENT','COMPLETACALLER','ABANDON')
left join pbx_usuarios d on d.matricula = substring(b.agente, 7,4)
where a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
union all
select a.calldate as data, a.uniqueid, a.src,a.dst,
a.accountcode, a.duration, a.billsec, '' as dac, '' as agente,
coalesce(b.direcao, '') as direcao, coalesce(a.disposition, '') as disposition, 0 as param1,
0 as param2, 0 as param3,
case when c.accountcode <> '' then 1 else 0 end as transfer,'' as evento
from pbx_bilhetes a
inner join ast_audio_pbx b on b.uniqueid2 = a.uniqueid
left outer join pbx_bilhetes c on c.data_bilhete = a.data_bilhete and c.accountcode = a.uniqueid
where not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
and a.billsec > 3
and a.lastapp <> 'Transferred Call'
) as d
where (dst <> 's' or dst not like '%a%')
group by uniqueid, data, src, dst, dac, agente, disposition, direcao, param1, param2, param3, evento,transfer
order by data;";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaChamadas", $ex);
}
}
$docApi['ListaChamadaTelefone'] = MetodoApi(
'Retorna informa<EFBFBD><EFBFBD>es de origem/destino da chamada de acordo com o per<EFBFBD>odo e o telefone.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa'],
["telefone-65123456789", "STRING", "REQUIRED", 'Informe um telefone']
]
);
function ListaChamadaTelefone($dataInicial, $dataFinal, $numero)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$tel = soNumero($numero);
if (strlen($tel) < 4 || strlen($tel) > 13) {
throw new Exception("Telefone informado \"$tel\" inv<EFBFBD>lido!");
}
$dbcon = $GLOBALS['dbcon'];
$query = "drop table if exists ast_complemento;
create temporary table ast_complemento as
select min(b.id)as id from pbx_bilhetes a
inner join pbx_bilhetes_complemento b on b.uniqueid2 = a.uniqueid
where not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
and a.lastapp <> 'Transferred Call'
group by uniqueid2;
drop table if exists ast_audio_pbx;
create temporary table ast_audio_pbx as
select a.id,a.direcao,a.uniqueid2 from pbx_bilhetes_complemento a
inner join ast_complemento b on b.id=a.id;
select uniqueid, data, src, dst, dac, agente, direcao,
CASE evento
WHEN 'COMPLETARAMAL' THEN 'ATENDIDA'
WHEN 'COMPLETEAGENTRAMAL' THEN 'ATENDIDA'
WHEN 'COMPLETEAGENT' THEN 'ATENDIDA'
WHEN 'COMPLETAAGENT' THEN 'ATENDIDA'
WHEN 'COMPLETACALLER' THEN 'ATENDIDA'
WHEN 'COMPLETECALLER' THEN 'ATENDIDA'
WHEN 'CHAMANDO' THEN 'CHAMANDO'
WHEN 'BUSYS' THEN 'OCUPADO'
WHEN 'ABANDON' THEN 'ABANDONADA'
WHEN 'NO ANSWER' THEN 'ABANDONADA'
WHEN 'ANSWERED' THEN 'ATENDIDA'
WHEN 'BUSY' THEN 'OCUPADO'
WHEN 'FAILED' THEN 'ABANDONADA' ELSE '-' END AS evento,
case when (evento in('COMPLETECALLER', 'COMPLETEAGENT', 'COMPLETAAGENT','COMPLETACALLER'))then param1 else 0 end as tempo_espera,
case when (evento in('COMPLETEAGENT','COMPLETECALLER', 'COMPLETAAGENT','COMPLETACALLER'))then param2 else 0 end as tempo_ligacao,
case evento when ('ABANDON')then param3 else 0 end as tempo_abandono,
transfer,max(duration) as duracao,
case when (evento = 'ABANDON' OR evento = 'CHAMANDO' OR evento = 'BUSYS')THEN 0 else max(billsec) end as conversacao
from(
select a.calldate as data, a.uniqueid, a.src,
case when(b.evento in('COMPLETECALLER', 'COMPLETEAGENT')and d.apelido is not null)then (select max(destino) from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid and direcao = 'fila-ramal') else
(select destino from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid and id = (select max(id) from pbx_bilhetes_complemento where uniqueid2 = a.uniqueid)) end as dst,
a.accountcode, a.duration, a.billsec,b.fila as dac, b.agente,
case when(b.evento in('COMPLETECALLER', 'COMPLETEAGENT'))then 'entrada' else 'saida' end as direcao,
coalesce(a.disposition, '') as disposition, strtoint(b.param1) as param1,
strtoint(b.param2) as param2, strtoint(b.param3) as param3,
case when(exists(select '' from pbx_bilhetes where data_bilhete = a.data_bilhete and accountcode = a.uniqueid))then 1 else 0 end as transfer,
b.evento
from pbx_bilhetes a
inner join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento in('COMPLETEAGENT','COMPLETECALLER', 'COMPLETAAGENT','COMPLETACALLER','ABANDON','CHAMANDO','BUSYS')
left join pbx_usuarios d on d.matricula = substring(b.agente, 7,4)
where a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
union all
select a.calldate as data, a.uniqueid, a.src,a.dst,
a.accountcode, a.duration, a.billsec, '' as dac, '' as agente,
coalesce(b.direcao, '') as direcao, coalesce(a.disposition, '') as disposition, 0 as param1,
0 as param2, 0 as param3,
case when c.accountcode <> '' then 1 else 0 end as transfer,'' as evento
from pbx_bilhetes a
inner join ast_audio_pbx b on b.uniqueid2 = a.uniqueid
left outer join pbx_bilhetes c on c.data_bilhete = a.data_bilhete and c.accountcode = a.uniqueid
where not exists(select '' from pbx_eventos_dacs where uid2 = a.uniqueid)
and a.data_bilhete >= coalesce('$dataInicial', a.data_bilhete)
and a.data_bilhete <= coalesce('$dataFinal', a.data_bilhete)
and a.lastapp <> 'Transferred Call'
) as d
where (dst <> 's' or dst not like '%a%')
and (src like '%$tel%' or dst like '%$tel%')
group by uniqueid, data, src, dst, dac, agente, disposition, direcao, param1, param2, param3, evento,transfer
order by data;";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaChamadaTelefone", $ex);
}
}
$docApi['ListaChamadasDac'] = MetodoApi(
'Retorna lista das chamadas \"Entrantes/Saintes\" por per<EFBFBD>odo.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa']
]
);
function ListaChamadasDac($dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = "select * from (
select 'E' as tipo, a.data_bilhete as data, a.calldate as data_hora,d.matricula as agente,
(case when b.evento IN('COMPLETECALLER', 'COMPLETEAGENT') then e.destino else (a.dst) end) as ramal,
sonumero(a.src) as fone, a.uniqueid, a.billsec as duracao
from pbx_bilhetes a
inner join pbx_bilhetes_complemento e on e.uniqueid2 = a.uniqueid
and e.id = (select min(g.id) from pbx_bilhetes_complemento g where g.uniqueid2=e.uniqueid2 and g.direcao = 'fila-ramal')
left join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento IN('COMPLETECALLER', 'COMPLETEAGENT')
left join pbx_dacs c on c.nome = b.fila
left join pbx_usuarios d on d.matricula = substring(b.agente,7 ,4)
where a.billsec > 3
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call')
union all
select 'S' as tipo, a.data_bilhete as data, a.calldate as data_hora,d.matricula as agente,a.src as ramal,
sonumero(a.dst) as fone, a.uniqueid, a.billsec as duracao
from pbx_bilhetes a
inner join pbx_bilhetes_complemento e on e.uniqueid2 = a.uniqueid
left join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento IN('COMPLETACALLER', 'COMPLETAAGENT')
left join pbx_usuarios d on d.matricula = substring(b.agente,7 ,4)
where a.billsec > 3
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call')
) chamadas
where chamadas.data >= '$dataInicial'
and chamadas.data <= '$dataFinal'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaChamadasDac", $ex);
}
}
$docApi['ListaChamadasFila'] = MetodoApi(
'Retorna lista das chamadas \"Entrantes/Saintes\" por per<EFBFBD>odo.',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa'],
["dac-90", "INTEIRO", "REQUIRED", 'Informe o c<EFBFBD>digo do DAC ou 0 para todos.'],
]
);
function ListaChamadasFila($dac, $dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = "select * from (
select 'E' as tipo, a.data_bilhete as data, a.calldate as data_hora, b.agente,e.destino as ramal,
sonumero(a.src) as fone,a.uniqueid, c.id as id_fila, c.nome as nome_fila, a.billsec as duracao
from pbx_bilhetes a
inner join pbx_bilhetes_complemento e on e.uniqueid2 = a.uniqueid and direcao = 'fila-ramal'
inner join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento IN('COMPLETECALLER', 'COMPLETEAGENT')
inner join pbx_dacs c on c.nome = b.fila and c.id = case when('$dac' = 0)then c.id else '$dac' end
where a.billsec > 3
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call')
union all
select 'S' as tipo, a.data_bilhete as data, a.calldate as data_hora, b.agente,a.src as ramal,
sonumero(a.dst) as fone, a.uniqueid, c.id as id_fila, c.nome as nome_fila, a.billsec as duracao
from pbx_bilhetes a
inner join pbx_bilhetes_complemento e on e.uniqueid2 = a.uniqueid
inner join pbx_eventos_dacs b on b.uid2 = a.uniqueid and b.evento IN('COMPLETACALLER', 'COMPLETAAGENT')
inner join pbx_dacs c on c.nome = b.fila and c.id = case when('$dac' = 0)then c.id else '$dac' end
where a.billsec > 3
and a.id_bilhetes = (select max (l.id_bilhetes) from pbx_bilhetes l where l.uniqueid = a.uniqueid and l.lastapp <> 'Transferred Call')
) chamadas
where chamadas.data >= '$dataInicial'
and chamadas.data <= '$dataFinal'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaChamadasFila", $ex);
}
}
$docApi['InfoChamada'] = MetodoApi(
'Retorna as informa<EFBFBD><EFBFBD>es sobre uma chamada em espec<EFBFBD>fico.',
[
["uniqueid-1536691853.274148", "STRING", "REQUIRED", 'Uniqueid da chamada que deseja visualizar as informa<EFBFBD><EFBFBD>es..'],
["dac-90", "INTEIRO", "REQUIRED", 'Id da fila que deseja a consulta.']
]
);
function InfoChamada($dac, $uniqueid)
{
try {
$dbcon = $GLOBALS['dbcon'];
$sql = "SELECT * FROM (
SELECT DISTINCT 'E' AS tipo, a.data_bilhete AS DATA, a.calldate::TIME AS data_hora,CASE WHEN (d.nome IS NULL) THEN 'Agente Sem Login' ELSE d.nome end AS nome_agente,
e.destino AS ramal,sonumero(a.src) AS fone,a.uniqueid, c.nome AS nome_fila,(a.duration - a.billsec) AS tempo_espera_atend,a.billsec AS duracao_atendimento,
CASE a.disposition WHEN 'ANSWERED' THEN 'ATENDIDA' WHEN 'NO ANSWER' THEN 'NAO ATENDIDA' WHEN 'BUSY' THEN 'OCUPADA' ELSE 'FALHA NA CHAMADA' END AS status_chamada
FROM pbx_bilhetes a
INNER JOIN pbx_bilhetes_complemento e ON e.uniqueid2 = a.uniqueid AND direcao = 'fila-ramal'
INNER JOIN pbx_eventos_dacs b ON b.uid2 = a.uniqueid
INNER JOIN pbx_dacs c ON c.nome = b.fila AND c.id = CASE WHEN('$dac' = 0)THEN c.id ELSE '$dac' end
LEFT JOIN pbx_usuarios d ON d.matricula = substring(b.agente,5,4)
WHERE a.billsec > 3
AND a.id_bilhetes = (select max (l.id_bilhetes) FROM pbx_bilhetes l WHERE l.uniqueid = a.uniqueid AND l.lastapp <> 'Transferred Call')
UNION ALL
SELECT DISTINCT 'S' AS tipo, a.data_bilhete AS DATA, a.calldate::TIME AS data_hora,
CASE WHEN (d.nome IS NULL) THEN 'Agente Sem Login' ELSE d.nome end AS nome_agente ,a.src AS ramal,
sonumero(a.dst) AS fone, a.uniqueid, c.nome AS nome_fila, (a.duration - a.billsec) AS tempo_espera_atend, a.billsec AS duracao,
CASE a.disposition WHEN 'ANSWERED' THEN 'ATENDIDA' WHEN 'NO ANSWER' THEN 'NAO ATENDIDA' WHEN 'BUSY' THEN 'OCUPADA' ELSE 'FALHA NA CHAMADA' END AS status_chamada
FROM pbx_bilhetes a
INNER JOIN pbx_bilhetes_complemento e ON e.uniqueid2 = a.uniqueid
INNER JOIN pbx_eventos_dacs b ON b.uid2 = a.uniqueid
INNER JOIN pbx_dacs c ON c.nome = b.fila AND c.id = CASE WHEN('$dac' = 0)THEN c.id ELSE '$dac' end
LEFT JOIN pbx_usuarios d ON d.matricula = substring(b.agente,5,4)
WHERE a.billsec > 3
AND a.id_bilhetes = (SELECT max (l.id_bilhetes) FROM pbx_bilhetes l WHERE l.uniqueid = a.uniqueid AND l.lastapp <> 'Transferred Call')
)chamadas
WHERE chamadas.uniqueid = '$uniqueid'";
$result = pg_query($dbcon, $sql);
if (!$result) {
"Erro ao consultar dados!";
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("InfoChamada", $ex);
}
}
$docApi['ProducaoAgente'] = MetodoApi(
'Retorna informa<EFBFBD><EFBFBD>es sobre \"Agentes/Dac\" por per<EFBFBD>odo!',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no Formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa.'],
["dac-7", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero da "Fila(DAC)" usada para atendimento.']
]
);
function ProducaoAgente($dac, $dataInicial, $dataFinal)
{
try {
$dbcon = $GLOBALS['dbcon'];
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
if (!VerificaDac($dbcon, $dac))
throw new Exception("Informe um \"ID\" v<EFBFBD>lido para o dac!");
$query = "DROP TABLE IF EXISTS agente_operacao;
DROP TABLE IF EXISTS agente_pausa;
CREATE TEMPORARY TABLE agente_operacao (id_dac int, fila varchar(50) not null, apelido varchar(30), matricula varchar(4) not null, data date not null,
login timestamp, logoff timestamp, tempoLogin int, chamadas_atendidas int, num_pausa int, tempo_espera int, tempo_entrada int, chamadas_realizadas int,
tempo_saida int, tempo_pausa int, num_pausa_prod int, tempo_pausa_prod int, CONSTRAINT \"pkAgtOpera\" PRIMARY KEY( fila, matricula, data ));
insert into agente_operacao
select c.id as id_dac, c.nome as fila, b.apelido, a.matricula, cast(a.login as date) as data, min(login) as login, max(logoff) as logoff, sum(EXTRACT(epoch from ((logoff) - (login)))) as tempoLogin,
0 as chamadas_atendidas, 0 as num_pausa, 0 as tempo_espera, 0 as tempo_entrada, 0 as chamadas_realizadas, 0 as tempo_saida, 0 as tempo_pausa, 0 as num_pausa_prod, 0 as tempo_pausa_prod
from pbx_eventos_agentes a, pbx_usuarios b, pbx_dacs c
where b.matricula = a.matricula
and c.id = a.id_dac
and a.id_dac = coalesce('$dac', a.id_dac)
and cast(a.login as date) >= '$dataInicial'
and cast(a.login as date) <= '$dataFinal'
and b.matricula = coalesce(null, b.matricula)
group by 1, 2, 3, 4, 5;
CREATE TEMPORARY TABLE agente_pausa AS
select a.id_dac, b.apelido, cast(a.entrada_pausa as date) as data,
sum(case when(a.pausa_produtiva = 0)then 1 else 0 end) as num_pausa,
sum(case when(a.pausa_produtiva = 1)then 1 else 0 end) as num_pausa_prod,
sum(EXTRACT(epoch from ( case when(a.pausa_produtiva = 0)then saida_pausa - entrada_pausa else '00:00:00' end ))) as tempo_pausa,
sum(EXTRACT(epoch from ( case when(a.pausa_produtiva = 1)then saida_pausa - entrada_pausa else '00:00:00' end ))) as tempo_pausa_prod
from pbx_eventos_agentes a, pbx_usuarios b
where b.matricula = a.matricula
and a.id_dac = coalesce('$dac', a.id_dac)
and cast(a.entrada_pausa as date) >= '$dataInicial'
and cast(a.entrada_pausa as date) <= '$dataFinal'
and b.matricula = coalesce(null, b.matricula)
group by a.id_dac, b.apelido, cast(a.entrada_pausa as date);
update agente_operacao
set num_pausa = b.num_pausa,
tempo_pausa = b.tempo_pausa,
num_pausa_prod = b.num_pausa_prod,
tempo_pausa_prod = b.tempo_pausa_prod
from agente_pausa as b
where agente_operacao.apelido = b.apelido
and agente_operacao.data = b.data
and agente_operacao.id_dac = b.id_dac;
update agente_operacao
set chamadas_atendidas = a.chamadas_atendidas,
tempo_espera = a.tempo_espera,
tempo_entrada = a.tempo_entrada,
chamadas_realizadas = a.chamadas_realizadas,
tempo_saida = a.tempo_saida
from (select
substring(dac.agente, 7,4) as matricula, bil.data_bilhete as data, dac.fila,
sum(case when(dac.evento in('COMPLETECALLER', 'COMPLETEAGENT', 'TRANSFER'))then 1 else 0 end) as chamadas_atendidas,
sum(case when((dac.evento = 'CONNECT') and (coalesce(dac.param1, '0')::integer > 3) )then dac.param1::integer else 0 end) as tempo_espera,
sum(case when(dac.evento in('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG'))then 1 else 0 end) as chamadas_realizadas,
sum(case when(dac.evento in('COMPLETECALLER', 'COMPLETEAGENT', 'TRANSFER'))then case when(dac.evento = 'TRANSFER')then( case when(coalesce(param4,'') <> '')then coalesce(param4,'0')::integer else 0 end )else( case when(coalesce(param2,'') <> '')then coalesce(param2,'0')::integer else 0 end )end else 0 end) as tempo_entrada,
sum(case when(dac.evento in('COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG') )then case when(dac.evento = 'TRANSFERORIG')then( case when(coalesce(param4,'') <> '')then coalesce(param4,'0')::integer else 0 end )else( case when(coalesce(param2,'') <> '')then coalesce(param2,'0')::integer else 0 end )end else 0 end) as tempo_saida
from pbx_bilhetes bil, pbx_eventos_dacs dac, agente_operacao
where dac.uid2 = bil.uniqueid
and agente_operacao.fila = dac.fila
and agente_operacao.matricula = substring(dac.agente, 7,4)
and agente_operacao.data = bil.data_bilhete
and bil.data_bilhete >= '$dataInicial'
and bil.data_bilhete <= '$dataFinal'
and bil.lastapp <> 'Transferred Call'
group by 1,2,3
) a where agente_operacao.data = a.data
and agente_operacao.matricula = a.matricula
and agente_operacao.matricula = a.matricula
and agente_operacao.fila = a.fila;
select id_dac as id_fila, fila as nome_fila, apelido as username_agente, matricula as matricula_agente, data as data_operacao, login as hora_login, logoff as hora_logoff,
tempologin as tempo_logado, chamadas_atendidas, num_pausa as numero_pausas, tempo_entrada as duracao_entrada, chamadas_realizadas, tempo_saida as duracao_saidas,
tempo_pausa as duracao_pausas, num_pausa_prod as numero_pausas_produtivas, tempo_pausa_prod as duracao_pausas_produtivas
from agente_operacao order by data, apelido";
$result = pg_query($dbcon, $query);
//echo $query; exit;
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ProducaoAgente", $ex);
}
}
$docApi['GetOperadora'] = MetodoApi(
'Retorna informa<EFBFBD><EFBFBD>es sobre \"Agentes/Dac\" por per<EFBFBD>odo!',
[
["destino-6536168282", "STRING", "REQUIRED", 'N<EFBFBD>mero do telefone de destino com DDD.']
]
);
function GetOperadora($detino)
{
try {
$detino = soNumero($detino);
$dbcon = $GLOBALS['dbcon'];
$oper = trim(GetSpid($detino));
if ($oper === false) {
throw new Exception("Erro ao consultar a portabilidade!");
}
$operNome = 'NI';
$operNum = 0;
if ($oper) {
$dbcon = $GLOBALS['dbcon'];
$query = "select oper_nome, oper_numero from pbx_operadoras where oper_spid = '$oper'";
$result = pg_query($dbcon, $query);
if ($result) {
$row = pg_fetch_array($result);
$operNum = $row['oper_numero'];
$operNome = $row['oper_nome'];
}
}
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["destino"] = $detino;
$ret["operadora"] = $oper ? $oper : 0;
$ret["numero"] = $operNum;
$ret["nome"] = $operNome;
$ret["message"] = $oper ? "Opera<EFBFBD><EFBFBD>o realizada com sucesso!" : "N<EFBFBD>mero n<EFBFBD>o localizado na portabilidade";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("GetOperadora", $ex);
}
}
$docApi['GetDadosLogin'] = MetodoApi(
'Retorna as informa<EFBFBD><EFBFBD>es do agente logado pela matricula.',
[
["matricula-1001", "STRING", "REQUIRED", 'Retorna informa<EFBFBD><EFBFBD>es sobre o agente on-line.']
]
);
function GetDadosLogin($matricula)
{
try {
$matricula = soNumero($matricula);
$dbcon = $GLOBALS['dbcon'];
$query = "select nome as login, matricula, ramal, origem_destino as telefone, uniqueid2 as identificador, protocolo, status, dac as fila, case tipo_ligacao when('E')then 'ENTRANTE' when ('S')then 'SAINTE' else '' end as tipo_ligacao from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
if (!pg_num_rows($result)) {
throw new Exception("O agente n<EFBFBD>o esta logado!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("GetOperadora", $ex);
}
}
$docApi['AutenticaUsuario'] = MetodoApi(
'Autentica um usu<EFBFBD>rio na Requisi<EFBFBD><EFBFBD>o!',
[
["login-admin", "STRING", "REQUIRED", 'Login do usu<EFBFBD>rio'],
["senha-0000", "STRING", "REQUIRED", 'Senha do usu<EFBFBD>rio']
]
);
function AutenticaUsuario($login, $senha)
{
try {
$dbcon = $GLOBALS['dbcon'];
$login = md5(trim(substr(strtolower($login), 0, 20)));
$senhaAut = md5(trim(substr($senha, 0, 14)));
//$senha = '0987';
$query = "select count(*) from pbx_usuarios where check_vl = '$login' and senha = '$senhaAut' and coalesce(status, true) = true and coalesce(delete_,0) = 0 ";
$log[] = $query;
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(@pg_last_error());
}
if ($senha == '1234') {
throw new Exception("N<EFBFBD>o <EFBFBD> permitida a autentica<EFBFBD><EFBFBD>o do usu<EFBFBD>rio com a senha padr<EFBFBD>o!");
}
$ret = array();
$row = @pg_fetch_array($result);
if ($row[0]) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = "Usu<EFBFBD>rio autenticado com sucesso!";
GetParametrosLicensa();
$_SESSION[SS_AUT] = 1;
$_SESSION[SS_USER_AUT] = $login;
$_SESSION["SSlogin"] = $login;
} else {
$_SESSION[SS_USER_AUT] = "";
$_SESSION[SS_AUT] = 0;
$ret["status"] = "ERRO";
$ret["result"] = "false";
$ret["message"] = "Usu<EFBFBD>rio ou senha inv<EFBFBD>lidos!";
$_SESSION["SSlogin"] = $login;
}
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("AutenticaUsuario", $ex);
}
}
$docApi['ListaAgentes'] = MetodoApi('Retorna uma lista com os Agentes Dispon<EFBFBD>veis!');
function ListaAgentes()
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select distinct *
from(
select distinct a.apelido, a.nome, a.matricula, a.email, a.penalidade, 0 as idDacPadrao, '' as nomeDacPadrao
from pbx_usuarios a, pbx_campanha_usuarios b
where b.matricula = a.matricula
union all
select distinct a.apelido, a.nome, a.matricula, a.email, a.penalidade, 0 as idDacPadrao, '' as nomeDacPadrao
from pbx_usuarios a, pbx_fila_grupos b, pbx_grupo_usuario c
where b.gp_id = c.gp_id
and a.id = c.user_id
) as a order by 1 ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaAgentes", $ex);
}
}
//funcao responsavel por realizar consulta ao BD e apresentar os dados em formato XML ao solicitante.
$docApi['TarifaPeriodo'] = MetodoApi(
'Tarifa<EFBFBD><EFBFBD>o dos Ramais por periodo! Idenficadores de Registro: [ # - Tarifa Zero ] [ ** - Franquia ] [ * - Franquia Parcial]',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no Formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa.']
]
);
function TarifaPeriodo($dataInicial, $dataFinal)
{
try {
//informa a data inicial para pesquisa das informacoes
$date = soNumero($dataInicial);
if (strlen($date) > 8) {
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
}
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date)) {
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
}
//informa a data final para pesquisa das informacoes
$date = soNumero($dataFinal);
if (strlen($date) > 8) {
throw new Exception("Data final \"$date\" inv<EFBFBD><EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
}
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date)) {
throw new Exception("Data final \"$date\" inv<EFBFBD><EFBFBD>lida!");
}
//query de consulta ao banco de dados.
$dbcon = $GLOBALS['dbcon'];
$query = "select a.trr_id, a.oper_id_dest, a.oper_numero_dest, a.uniqueid, a.trr_link, a.trr_data, a.trr_origem, a.trr_destino, a.trr_inicio, a.trr_fim, a.trr_duracao, a.trr_preco,
a.trr_vc, a.trr_preco_tipo, a.trr_tipo_opera, a.trr_sentido_chamada, a.trr_tarifa_zero, a.trr_conta_senha, a.trr_conta, a.trr_vc_cad, a.trr_vc_ext,
a.trr_preco_total, substring(b.oper_nome, 1, 30) as oper_nome, substring(d.cc_descricao, 1,30) as cc_descricao, coalesce(e.id, 0) as id_empresa, substring(coalesce(e.nome, 'NI'),1,30) as nome_empresa, coalesce(f.id,0) as id_depto, substring(coalesce(f.nome_depto, 'NI'), 1,30) as nome_depto,
case when(substring(a.trr_destino,1,4) = '0800')then 'Gratuito' else g.ttp_descricao end as ttp_descricao,
(a.trr_duracao / 60)::int as duracao_mininuto, (a.trr_duracao % 60) as duracao_segundo, a.trr_franquia, h.contr_tipo_franquia, a.trr_duracao as duracao,
a.trr_tipo_chamada, a.trr_duracao_transf
from pbx_tarif_registra a
inner join pbx_operadoras b on b.oper_id = a.oper_id_dest
inner join pbx_tarif_contrato h on h.contr_id = a.contr_id
left join pbx_pbx_centro_custo_ramais c on c.ramal = a.trr_origem
left join pbx_centro_custo d on d.cc_id = c.cc_id
left join pbx_empresa e on e.id = d.empresa
left join pbx_departamentos f on f.id = d.departamento
left join pbx_tarifa_tipo_preco g on g.ttp_id = a.trr_vc
where length(trr_destino) >= 8
and a.trr_data >= '$dataInicial'
and a.trr_data <= '$dataFinal'
order by a.trr_data, a.trr_inicio ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Errao ao acessar a base de dados!");
}
$chamadas = array();
$transferidas = array();
$consultas = array();
while ($dados = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$tipo = $dados['trr_tipo_chamada'];
$link = $dados['trr_link'];
$uid = $dados['uniqueid'];
$chamadas[$uid] = $dados;
}
//Alimentando as variaveis que serao apresentadas na tela.
$result = array();
foreach ($chamadas as $key => $row) {
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$uid = $row["uniqueid"];
$empresa = $row["nome_empresa"]; // $row["id_empresa"] . '-' . $row["nome_empresa"];
$depto = $row["nome_depto"]; //$row["id_depto"] . '-' . $row["nome_depto"];
$oper = $row["oper_nome"]; //$row["oper_id_dest"] . '-' . $row["oper_nome"];
$tipo = $row["ttp_descricao"];
$origem = $row["trr_origem"];
$conta = $row["trr_conta_senha"] ? $row["trr_conta"] : "-";
$dest = ($tarifaZero ? '#' : ($franquia ? ($franquiaParcial ? '*' : '**') : '')) . $row["trr_destino"];
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$link = $row["trr_link"];
//formata o campo datetime
$data = FormataDBDataHora($row["trr_inicio"]);
$duration = (int) $row["trr_duracao"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = (0);
} else {
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
}
//formata duracao
$duration = SecondToStrTime($duration);
$valor = FormataValor($valor);
$dados = array();
$dados['empresa'] = $empresa;
$dados['departamento'] = $depto;
$dados['operadora'] = $oper;
$dados['tipo'] = $tipo == 'T' ? 'TRANSFERENCIA' : ($tipo == 'C' ? 'CONSULTA' : 'ORIGINADA');
$dados['origem'] = $origem;
$dados['conta'] = $conta;
$dados['destino'] = $dest;
$dados['data'] = $data;
$dados['duracao'] = $duration;
$dados['valor'] = $valor;
$dados['link_transf'] = $link;
$result[] = $dados;
}
//apresenta os dados em formato XML.
return ArrToXml($result);
} catch (Exception $ex) {
return GetErro("TarifaPeriodo", $ex);
}
}
$docApi['TarifaRamal'] = MetodoApi(
'Tarifa<EFBFBD><EFBFBD>o dos Ramais por periodo! Idenficadores de Registro: [ # - Tarifa Zero ] [ ** - Franquia ] [ * - Franquia Parcial]',
[
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no Formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa.']
]
);
function TarifaRamal($dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = " select a.trr_id, a.oper_id_dest, a.oper_numero_dest, a.uniqueid, a.trr_link, a.trr_data, a.trr_origem, a.trr_destino, a.trr_inicio, a.trr_fim, a.trr_duracao, a.trr_preco,
a.trr_vc, a.trr_preco_tipo, a.trr_tipo_opera, a.trr_sentido_chamada, a.trr_tarifa_zero, a.trr_conta_senha, a.trr_conta, a.trr_vc_cad, a.trr_vc_ext,
a.trr_preco_total, substring(b.oper_nome, 1, 30) as oper_nome, substring(d.cc_descricao, 1,30) as cc_descricao, coalesce(e.id, 0) as id_empresa, substring(coalesce(e.nome, 'NI'),1,30) as nome_empresa, coalesce(f.id,0) as id_depto, substring(coalesce(f.nome_depto, 'NI'), 1,30) as nome_depto,
case when(substring(a.trr_destino,1,4) = '0800')then 'Gratuito' else g.ttp_descricao end as ttp_descricao,
(a.trr_duracao / 60)::int as duracao_mininuto, (a.trr_duracao % 60) as duracao_segundo, a.trr_franquia, h.contr_tipo_franquia, a.trr_duracao as duracao,
a.trr_tipo_chamada, a.trr_duracao_transf
from pbx_tarif_registra a
inner join pbx_operadoras b on b.oper_id = a.oper_id_dest
inner join pbx_tarif_contrato h on h.contr_id = a.contr_id
left join pbx_pbx_centro_custo_ramais c on c.ramal = a.trr_origem
left join pbx_centro_custo d on d.cc_id = c.cc_id
left join pbx_empresa e on e.id = d.empresa
left join pbx_departamentos f on f.id = d.departamento
left join pbx_tarifa_tipo_preco g on g.ttp_id = a.trr_vc
where length(trr_destino) >= 8
and a.trr_data >= '$dataInicial'
and a.trr_data <= '$dataFinal'
order by a.trr_data, a.trr_inicio ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Errao ao acessar a base de dados!");
}
$chamadas = array();
$transferidas = array();
$consultas = array();
while ($dados = pg_fetch_array($result, null, PGSQL_ASSOC)) {
$tipo = $dados['trr_tipo_chamada'];
$link = $dados['trr_link'];
$uid = $dados['uniqueid'];
$chamadas[$uid] = $dados;
}
$result = array();
foreach ($chamadas as $key => $row) {
$tipoFranquia = $row["contr_tipo_franquia"];
$tarifaZero = $row["trr_tarifa_zero"] > 0;
$franquia = ($row["trr_franquia"] > 0) && ($tipoFranquia > 0);
$franquiaParcial = $franquia && ($row["trr_franquia"] != $row["trr_duracao"]);
$uid = $row["uniqueid"];
$empresa = $row["nome_empresa"]; // $row["id_empresa"] . '-' . $row["nome_empresa"];
$depto = $row["nome_depto"]; //$row["id_depto"] . '-' . $row["nome_depto"];
$oper = $row["oper_nome"]; //$row["oper_id_dest"] . '-' . $row["oper_nome"];
$tipo = $row["ttp_descricao"];
$origem = $row["trr_origem"];
$conta = $row["trr_conta_senha"] ? $row["trr_conta"] : "-";
$dest = ($tarifaZero ? '#' : ($franquia ? ($franquiaParcial ? '*' : '**') : '')) . $row["trr_destino"];
$tipoTarifa = $row["trr_preco_tipo"];
$precoMinuto = $row["trr_preco"];
$fator = $row["trr_vc_cad"];
$cadencia = $row["trr_vc_ext"];
$link = $row["trr_link"];
$data = FormataDBDataHora($row["trr_inicio"]);
$duration = (int) $row["trr_duracao"];
$dura = $franquiaParcial ? $row["trr_franquia"] : (int) $row["trr_duracao"];
if (($tarifaZero || $franquia) && (!$franquiaParcial)) {
$valor = (0);
} else {
//trr_preco_tipo, trr_duracao, trr_preco, trr_vc_cad, trr_vc_ext
//$valor = $fatorPreco == 1 ? $row["trr_preco"] : (round((($dura / $fatorPreco) * $row["trr_preco"]), 2));
$valor = TarifaChamada($tipoTarifa, $dura, $precoMinuto, $fator, $cadencia);
}
//formata dura<EFBFBD><EFBFBD>o
$duration = SecondToStrTime($duration);
$valor = FormataValor($valor);
$dados = array();
$dados['empresa'] = $empresa;
$dados['departamento'] = $depto;
$dados['operadora'] = $oper;
$dados['tipo'] = $tipo == 'T' ? 'TRANSFERENCIA' : ($tipo == 'C' ? 'CONSULTA' : 'ORIGINADA');
$dados['origem'] = $origem;
$dados['conta'] = $conta;
$dados['destino'] = $dest;
$dados['data'] = $data;
$dados['duracao'] = $duration;
$dados['valor'] = $valor;
$dados['link_transf'] = $link;
$result[] = $dados;
}
$str = ArrToXml($result, false);
$nomeFile = "TarifaRamal_" . date("dmYHis") . ".xls";
EnviaExcel($nomeFile, $str->asXML());
} catch (Exception $ex) {
return GetErro("TarifaRamal", $ex);
}
}
$docApi['ListaDacsAgente'] = MetodoApi(
'Retorna uma lista com os DACS dispon<EFBFBD>veis para o Agente Autenticado!',
[
["agente-nomeAgente", "STRING", "REQUIRED", 'Agente autenticado no Sistema.']
]
);
function ListaDacsAgente($agente)
{
if (strtoupper($agente) == 'ADMIN')
return ListaDacs();
try {
$dbcon = $GLOBALS['dbcon'];
$query = " select 'Receptivo' as tipo, d.id, d.nome,
case when(exists(select '' from pbx_usuarios where id = a.id and dac_padrao = d.id))then 'true' else 'false' end as padrao
from pbx_usuarios a, pbx_grupo_usuario b, pbx_fila_grupos c, pbx_dacs d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.id = c.id
and lower(a.apelido) = lower('$agente')
and d.status = 'A'
union
select 'Ativo' as tipo, cmp_id as id, cmp_descricao as nome, 'false' as padrao from pbx_campanha a where 1=1 and cmp_status <> '0'
and exists(select '' from pbx_campanha_usuarios b, pbx_grupo_usuario c, pbx_usuarios d
where b.cmp_id = a.cmp_id
and b.matricula = d.matricula
and c.user_id = d.id
and c.user_id = (select id from pbx_usuarios where lower(apelido) = lower('$agente'))
)
order by 1, 2 ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaDacsAgente", $ex);
}
}
$docApi['ListaDacsMatricula'] = MetodoApi(
'Retorna uma lista com os DACS dispon<EFBFBD>veis para o Agente Autenticado!',
[
["matricula-1000", "STRING", "REQUIRED", 'Matr<EFBFBD>cula de um agente.']
]
);
function ListaDacsMatricula($matricula)
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select 'Receptivo' as tipo, d.id, d.nome, 'false' as padrao
from pbx_usuarios a, pbx_grupo_usuario b, pbx_fila_grupos c, pbx_dacs d
where b.user_id = a.id
and c.gp_id = b.gp_id
and d.id = c.id
and a.matricula = '$matricula'
and d.status = 'A'
order by 1, 2 ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("ListaDacsMatricula", $ex);
}
}
$docApi['TransferePesquisa'] = MetodoApi(
'Transfere uma chamada para uma pesquisa cadastrada no sistema!',
[
["matricula-1000", "STRING", "REQUIRED", 'Matr<EFBFBD>cula de um agente.'],
["pesquisaId-2", "INTEGER", "REQUIRED", 'Informe o id da pesquisa.'],
]
);
function TransferePesquisa($matricula, $pesquisaId)
{
$dbcon = $GLOBALS['dbcon'];
$numeroTransf = "psq-" . $pesquisaId . "-ini";
try {
$sql = "";
$query = "select canal,status,dac from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel consultar o banco de dados");
}
$row = @pg_fetch_array($result, null, PGSQL_ASSOC);
if (!pg_num_rows($result)) {
throw new Exception("Agente n<EFBFBD>o conectado");
}
if ($row['status'] != "OCUPADO") {
throw new Exception("N<EFBFBD>o existe liga<EFBFBD><EFBFBD>o em curso");
}
//vari<EFBFBD>veis utilizadas pela fun<EFBFBD><EFBFBD>o GetUrl
$_SESSION[AGT_CHANNEL_TRANSF] = $row['canal'];
$_SESSION[AGT_NUM_DISC] = $numeroTransf;
//valida<EFBFBD><EFBFBD>o da pesquisa, verifica se a pesquisa pertence ao dac.
$sql = sprintf("select ''
from pbx_pesquisa_liberacao_dacs a, pbx_pesquisa_liberacao b,pbx_dacs c
where b.pl_id = a.pl_id
and c.id = a.id_dac
and c.nome = '%s'
and a.pl_id = %s
and ( (now()::date >= b.pl_data_inicio) or (b.pl_data_inicio is null))
and ( (now()::date <= b.pl_data_fim) or (b.pl_data_fim is null))
and b.pl_ativa = 1", $row['dac'], $pesquisaId);
$result = pg_query($dbcon, $sql);
if (!$result) {
throw new Exception("Erro ao consultar o banco de dados");
}
if (!pg_num_rows($result)) {
throw new Exception("Pesquisa n<EFBFBD>o pertence ao dac");
}
$result = GetUrl(AST_TRANSF_PESQUISA);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel Transferir para a pesquisa");
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = "true";
$ret["message"] = "Transfer<EFBFBD>ncia para a Pesquisa Conclu<EFBFBD>da com Sucesso!";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("TransferePesquisa", $ex);
}
}
$docApi['RelPesquisa'] = MetodoApi(
'Retorna dados das Pesquisas de satisfa<EFBFBD><EFBFBD>o por per<EFBFBD>odo.',
[
["dac-Atendimento", "STRING", "REQUIRED", 'Informe o Nome do DAC.'],
["pesquisa-Pesquisa1", "INTEGER", false, 'Informe o Nome da Pesquisa!'],
["dataInicial-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no Formato: ddmmaaaa.'],
["dataFinal-" . date('dmY'), "DATETIME", "REQUIRED", 'Informe um valor no formato: ddmmaaa.']
]
);
function RelPesquisa($dac, $pesquisa, $dataInicial, $dataFinal)
{
try {
$date = soNumero($dataInicial);
if (strlen($date) > 8)
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataInicial = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data inicial \"$date\" inv<EFBFBD>lida!");
$date = soNumero($dataFinal);
if (strlen($date) > 8)
throw new Exception("Data final \"$date\" inv<EFBFBD>lida! Informe a data no formato \"ddmmaaaa\"!");
$dataFinal = sprintf("%s/%s/%s", substr($date, 4, 4), substr($date, 2, 2), substr($date, 0, 2));
$date = sprintf("%s/%s/%s", substr($date, 0, 2), substr($date, 2, 2), substr($date, 4, 4));
if (!is_date($date))
throw new Exception("Data final \"$date\" inv<EFBFBD>lida!");
$dbcon = $GLOBALS['dbcon'];
$query = "select f.nome as dac,
a.pl_descricao as nome_pesquisa,
b.pq_questao as questao ,
c.po_tecla,
c.po_opcao as opcao ,
count(d.po_id) as num_resp
from pbx_pesquisa_liberacao a
inner join pbx_pesquisa_questoes b on a.pp_id = b.pp_id
inner join pbx_pesquisa_opcoes c on a.pp_id = c.pp_id and b.pq_id = c.pq_id
inner join pbx_pesquisa_liberacao_dacs e on a.pl_id = e.pl_id
inner join pbx_dacs f on e.id_dac = f.id
left outer join pbx_pesquisa_movimento d on d.po_id = c.po_id
and a.pl_id = d.pl_id and d.pq_id = c.pq_id and d.id_dac = f.id
and d.pm_data >= '$dataInicial'
and d.pm_data <= '$dataFinal'
where f.nome = '$dac'\n";
if ($pesquisa)
$query .= "and a.pl_descricao = '$pesquisa'\n";
$query .= "group by f.nome ,a.pl_descricao, b.pq_questao,c.po_tecla, c.po_opcao
order by 2,3,4";
//echo $query;
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("Erro ao consultar dados!");
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("RelPesquisa", $ex);
}
}
$docApi['ValidaRamal'] = MetodoApi(
'Verifica se o ramal est<EFBFBD> cadastrado na base de dados.',
[
["ramal-1003", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero do ramal para atendimento no dac.']
]
);
function ValidaRamal($ramal)
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select count(*) from pbx_ramais where nome = '$ramal'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$row = @pg_fetch_row($result);
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $row[0] ? "true" : "false";
$ret["message"] = "Ramal v<EFBFBD>lido";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("ValidaRamal", $ex);
}
}
$docApi['IniciarGravacao'] = MetodoApi(
'Inicia a grava<EFBFBD><EFBFBD>o da chamada corrente ao comando do agente.',
[
["nomeArquivo-audio01", "STRING", false, 'Um nome <EFBFBD>nico para o arquivo. Se n<EFBFBD>o informado ser<EFBFBD> gerado pelo sistema.'],
["tipoArquivo-gsm", "STRING", false, 'O formato desejado para o <EFBFBD>udio. O valor padr<EFBFBD>o <EFBFBD> wav49. Tipos suportados:[gsm,wav,wav49]']
]
);
function IniciarGravacao($nomeArquivo = "", $tipoArquivo = "wav49")
{
$dbcon = $GLOBALS['dbcon'];
$matricula = @GetMatriculaAgente();
//Tenta iniciar uma nova transacao no banco de dados
$result = pg_query($dbcon, 'begin');
try {
if (!$matricula) {
throw new Exception("Agente n<EFBFBD>o logado em uma campanha!");
}
//Se nao houve sucesso no inicio da transacao gera uma excessao
if (!$result) {
$inTransaction = false;
throw new Exception(pg_last_error());
}
$inTransaction = true;
$query = "select canal, ramal, nome, dac, uniqueid from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_AUDIO_TIPO] = $tipoArquivo;
$uniqueId = $row["uniqueid"];
$dac = $_SESSION[AGT_DAC_CONECT];
$_SESSION[AGT_ID_GRAVACAO] = $uniqueId;
$_SESSION[AGT_AUDIO_FILE] = empty($nomeArquivo) ? sprintf('_%s.%s', $uniqueId, GetExtensaoAudio($tipoArquivo)) : $nomeArquivo;
// Associa audio a arquivo gerado pelo unique id
$query = "insert into pbx_campanha_audio(cmp_id, uniqueid, aud_nome, matricula, aud_data)values(%s, %s, %s, %s, cast(now() as date))";
$query = sprintf($query, QuotedStr($dac), QuotedStr($uniqueId), QuotedStr($_SESSION[AGT_AUDIO_FILE]), QuotedStr($matricula));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$query = "update pbx_supervisor_agentes set status_gravacao = 'V' where matricula = %s";
$query = sprintf($query, QuotedStr($matricula));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$result = GetUrl(AST_INICIA_GRAVACAO);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar a grava<EFBFBD><EFBFBD>o!");
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
throw new Exception(pg_last_error());
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "In<EFBFBD>cio da grava<EFBFBD><EFBFBD>o efetuado com sucesso";
return ResultToXml($ret);
} catch (Exception $ex) {
if ($inTransaction)
pg_query($dbcon, 'rollback');
return GetErro("IniciarGravacao", $ex);
}
}
$docApi['FinalizarGravacao'] = MetodoApi('Finaliza a grava<EFBFBD><EFBFBD>o da chamada.');
function FinalizarGravacao()
{
$dbcon = $GLOBALS['dbcon'];
$matricula = @GetMatriculaAgente();
//Tenta iniciar uma nova transacao no banco de dados
$result = pg_query($dbcon, 'begin');
try {
if (!$matricula) {
throw new Exception("Agente n<EFBFBD>o logado em uma campanha!");
}
//Se nao houve sucesso no inicio da transacao gera uma excessao
if (!$result) {
$inTransaction = false;
throw new Exception(pg_last_error());
}
$inTransaction = true;
$uniqueId = $_SESSION[AGT_ID_GRAVACAO];
// Associa audio a arquivo gerado pelo unique id
$query = "update pbx_campanha_audio set data_fim = now() where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$query = "update pbx_supervisor_agentes set status_gravacao = 'F' where matricula = %s ";
$query = sprintf($query, QuotedStr($matricula));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$result = GetUrl(AST_FINALISA_GRAVACAO);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel finalizar a grava<EFBFBD><EFBFBD>o!");
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
throw new Exception(pg_last_error());
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "Grava<EFBFBD><EFBFBD>o finalizada";
return ResultToXml($ret);
} catch (Exception $ex) {
if ($inTransaction)
pg_query($dbcon, 'rollback');
return GetErro("FinalizarGravacao", $ex);
}
}
$docApi['IniciaMute'] = MetodoApi('Inicializa o mute durante uma chamada.');
function IniciaMute()
{
try {
$matricula = $matricula = GetMatriculaAgente();
$dbcon = $GLOBALS['dbcon'];
$query = "select canal, ramal, nome, dac, canal_agente, uniqueid, sala_2 from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
if (pg_num_rows($result) == 0) {
throw new Exception("N<EFBFBD>o h<EFBFBD> nenhuma liga<EFBFBD><EFBFBD>o em curso!");
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$_SESSION["salaMute"] = $row["sala_2"];
$ret["sessao"] = $_SESSION['sessao_mute'];
if (!$_SESSION['sessao_mute']) {
$result = GetUrl(AST_MUTE_CLIENTE);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o mute! CLIENTE");
}
sleep(1);
$result = GetUrl(AST_MUTE_ATENDENTE);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o mute! ATENDENTE");
}
}
$_SESSION['sessao_mute'] = 1;
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "Mute iniciado";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("IniciaMute", $ex);
}
}
$docApi['FinalizaMute'] = MetodoApi('Finaliza o mute durante uma chamada.');
function FinalizaMute()
{
try {
if ($_SESSION['sessao_mute']) {
$result = GetUrl(AST_REM_MUTE);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel finalizar o mute!");
}
}
$_SESSION['sessao_mute'] = 0;
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "Mute finalizada";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("FinalizaMute", $ex);
}
}
$docApi['IniciaConferencia'] = MetodoApi('Inicia uma confer<EFBFBD>ncia a tr<EFBFBD>s.');
function IniciaConferencia()
{
try {
$dbcon = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$query = "select canal, canal_transfer, ramal, nome, dac, uniqueid from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(@pg_last_error());
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
$result = GetUrl(AST_TRCONSULTA_CONFERENCIA);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar a confer<EFBFBD>ncia!: CLIENTE");
}
$_SESSION['sessao_conferencia'] = 1;
//$_SESSION['sessao_mute'] = 1;
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "Confer<EFBFBD>ncia Iniciada!";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("IniciaConferencia", $ex);
}
}
$docApi['IniciaTransferenciaConsulta'] = MetodoApi(
'Inicia uma transferencia com consulta.',
[
["numeroTransferencia-6533654489", "STRING", "REQUIRED", "N<EFBFBD>mero para o qual ser<EFBFBD> realizada a transfer<EFBFBD>ncia"]
]
);
function IniciaTransferenciaConsulta($numeroTransferencia)
{
try {
$matricula = GetMatriculaAgente();
$dbcon = $GLOBALS['dbcon'];
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
if (pg_num_rows($result) == 0) {
throw new Exception("N<EFBFBD>o h<EFBFBD> nenhuma liga<EFBFBD><EFBFBD>o em curso!");
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$emtransf = !empty($row["canal_transfer"]);
/*
* Ainda n<EFBFBD>o iniciou a transferencia
* Se canal_transfer estiver vazio
*/
if (!$emtransf) {
$_SESSION[AGT_NUM_DISC] = $numeroTransferencia;
IniciaPendulo();
sleep(1);
$result = GetUrl(AST_TRCONSULTA_ESPERA);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o transfer<EFBFBD>ncia! ESPERA");
}
$_SESSION['sessao_transferencia'] = 1;
$messageAgente = "Transfer<EFBFBD>ncia Iniciada";
$query = "update pbx_supervisor_agentes set canal_transfer = 'Agent/$matricula' where matricula = '$matricula'";
pg_query($dbcon, $query);
} else {
$result = GetUrl(AST_TRCONSULTA_TRANSFERE_ABORTA);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o transfer<EFBFBD>ncia! DEVOLVE");
}
$_SESSION['sessao_mute'] = 0;
$_SESSION['sessao_transferencia'] = 0;
$messageAgente = "Transfer<EFBFBD>ncia interropida";
$query = "update pbx_supervisor_agentes set canal_transfer = '' where matricula = '$matricula'";
pg_query($dbcon, $query);
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = $messageAgente;
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("IniciaTransferenciaConsulta", $ex);
}
}
$docApi['FinalizaTransferenciaConsulta'] = MetodoApi('Finaliza uma transferencia com consulta.');
function FinalizaTransferenciaConsulta()
{
try {
$matricula = GetMatriculaAgente();
$dbcon = $GLOBALS['dbcon'];
$query = "select canal, canal_transfer, ramal, nome, dac, uniqueid from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
if (pg_num_rows($result) == 0) {
throw new Exception("N<EFBFBD>o h<EFBFBD> nenhuma liga<EFBFBD><EFBFBD>o em curso!");
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
$emtransf = !empty($row["canal_transfer"]);
if (!$emtransf)
throw new Exception("Transfer<EFBFBD>ncia Iniciada!");
return DesligarChamada();
} catch (Exception $ex) {
return GetErro("FinalizaTransferenciaConsulta", $ex);
}
}
$docApi['IniciaPendulo'] = MetodoApi(
'Inicializa o p<EFBFBD>ndulo durante uma chamada.'
);
function IniciaPendulo()
{
try {
$matricula = GetMatriculaAgente();
$dbcon = $GLOBALS['dbcon'];
$query = "select canal, ramal, nome, dac, canal_agente, uniqueid, sala_2 from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
if (pg_num_rows($result) == 0) {
throw new Exception("N<EFBFBD>o h<EFBFBD> nenhuma liga<EFBFBD><EFBFBD>o em curso!");
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$_SESSION["salaMute"] = $row["sala_2"];
$ret["sessao"] = $_SESSION['sessao_mute'];
$result = GetUrl(AST_PENDULO_ADD_CANAIS);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o p<EFBFBD>ndulo! ADD CANAL");
}
$_SESSION['sessao_pendulo'] = 1;
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "p<EFBFBD>ndulo iniciado";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("IniciaPendulo", $ex);
}
}
$docApi['FinalizaPendulo'] = MetodoApi(
'Finaliza o p<EFBFBD>ndulo durante uma chamada.'
);
function FinalizaPendulo()
{
try {
if ($_SESSION['sessao_pendulo']) {
$result = GetUrl(AST_PENDULO_REM_CANAIS);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel finalizar o p<EFBFBD>ndulo!");
}
}
$_SESSION['sessao_pendulo'] = 0;
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "P<EFBFBD>ndulo finalizada";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("FinalizaPendulo", $ex);
}
}
$docApi['DesligarChamada'] = MetodoApi(
'Desliga chamada corrente.'
);
function DesligarChamada()
{
$dbcon = $GLOBALS['dbcon'];
try {
if (!isset($_SESSION[AGT_MATRICULA]))
throw new Exception("Agente Desconectado!");
$matricula = GetMatriculaAgente();
$query = "select canal, canal_transfer, canal_agente, ramal, nome, dac, uniqueid, status from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query); //
if (!$result) {
throw new Exception(@pg_last_error());
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$_SESSION[AGT_CHANNEL_TRANSF] = $row["canal"];
$_SESSION[AGT_CHANNEL_TRCONSULTA] = $row["canal_transfer"];
$emTransf = !empty($row["canal_transfer"]);
$_SESSION[SS_AGT_CHANNEL_AGENTE] = $row["canal_agente"];
$_SESSION[SS_INICIA_TRANSFERENCIA] = $emTransf;
$status = $row["status"];
if ($emTransf && !$_SESSION['sessao_conferencia']) {
$result = GetUrl(AST_TRCONSULTA_TRANSFERE);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel transferir a chamada! TRANSFERE");
}
$_SESSION[SS_INICIA_TRANSFERENCIA] = 0;
$_SESSION['sessao_mute'] = 0;
$_SESSION['sessao_pendulo'] = 0;
$_SESSION['sessao_transferencia'] = 0;
$messageAgente = "Chamada transferida com sucesso!";
$query = "update pbx_supervisor_agentes set canal_transfer = '' where matricula = '$matricula'";
pg_query($dbcon, $query);
} else {
if (!isset($_SESSION[AGT_MATRICULA]))
throw new Exception("Agente Desconectado!");
if ($status == 'PAUSA') {
$query = "update pbx_supervisor_agentes
set canal_transfer = '',
origem_destino = '',
uniqueid = '',
tipo_ligacao = '',
status_gravacao = 'F'
where matricula = '$matricula'";
} else {
$query = "update pbx_supervisor_agentes
set canal_transfer = '',
origem_destino = '',
status = 'LIVRE',
duracao = now(),
uniqueid = '',
tipo_ligacao = '',
status_gravacao = 'F'
where matricula = '$matricula'";
}
$result = pg_query($dbcon, $query);
if (!$_SESSION['sessao_transferencia'] && !$_SESSION['sessao_conferencia'] && !$_SESSION['sessao_mute'] && !$_SESSION['sessao_pendulo']) {
//Desliga o canal do lado agente
@GetUrl(AST_DESLIGAR_LIGACAO);
} else if ($_SESSION['sessao_conferencia']) {
//Desliga o canal do lado agente
@GetUrl(AST_DESLIGAR_LIGACAO);
} else {
//Desliga o canal do lado cliente
@GetUrl(AST_DESLIGA_CANAL_CLIENTE);
}
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel desligar a chamada!");
}
$_SESSION['sessao_transferencia'] = 0;
$_SESSION['sessao_conferencia'] = 0;
$messageAgente = "Chamada encerrada";
$_SESSION['sessao_mute'] = 0;
$_SESSION['sessao_pendulo'] = 0;
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = $messageAgente;
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("DesligarChamada", $ex);
}
}
$docApi['LiberaAgente'] = MetodoApi('Libera o agente do discador.');
function LiberaAgente()
{
$log = &$GLOBALS["log"];
$log[] = sprintf('Metodo: Libera Agente %s Linha: %s ', date('d/m/Y H:i:s'), 944);
$dbcon = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
try {
@GetUrl(AST_REM_PAUSA);
@UpdatePausa($dbcon);
$result = 1;
$identificador = $_SESSION['cont_identificador'];
$numeroFone = $_SESSION['origem_destino'];
$id = QuotedStr($identificador);
$query = "select max(cont_id) as cont_id from pbx_campanha_contato where cont_identificador = $id and cont_status = 1 ";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
// Configura informacoes sobre o audio
$row = @pg_fetch_array($result);
$contId = $row["cont_id"];
$fone = soNumero($numeroFone);
$query = "update pbx_supervisor_agentes set status = 'LIVRE', status_agente = '1',duracao = now(),motivo_pausa = '0' where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
if (!@pg_affected_rows($result)) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel liberar o Agente! Registro n<EFBFBD>o encontrado!");
}
$ret = array();
$ret["status"] = "ok";
$ret["result"] = $result ? "true" : "false";
$ret["message"] = "Agente Liberado";
return ResultToXml($ret);
} catch (Exception $ex) {
$log[] = sprintf('Metodo Fim: Libera Agente %s Status: Erro Msg: ', date('d/m/Y H:i:s'), $ex->getMessage());
return GetErro("LiberaAgente", $ex);
}
}
function DecodeParam($cmd)
{
$info = base64_decode($cmd);
$obj = unserialize($info);
return $obj;
}
$docApi['GetMotivosPausa'] = MetodoApi('Retorna lista com motivos de pausa.');
function GetMotivosPausa()
{
try {
$dbcon = $GLOBALS['dbcon'];
//se o agente estiver conectado n<EFBFBD>o carrega login
//$incluiLogin = $_SESSION[AGT_CONECT] ? " where motivo <> 'login' " : "";
$query = "select id, motivo from pbx_motivos_pausas order by motivo";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("GetMotivosPausa", $ex);
}
}
$docApi['InformacoesAtendimento'] = MetodoApi("Retorna informa<EFBFBD><EFBFBD>es sobre atendimento. $obsConectaAgente");
function InformacoesAtendimento()
{
global $log, $obsConectaAgente;
$dbcon = $GLOBALS['dbcon'];
try {
if (!isset($_SESSION[SS_NOME_DAC]) || !isset($_SESSION[AGT_MATRICULA]))
throw new Exception("Agente Desconectado!");
$nomeDac = $_SESSION[SS_NOME_DAC];
$matricula = $_SESSION[AGT_MATRICULA];
$infoChamada = array(
"ramal" => '-', "matricula" => '-', "nome" => '-', "tempo_login" => '00:00:00', "modo_atendimento" => '-',
"origem_destino" => '-', "status_agente" => 'LOGOFF', "duracao" => '00:00:00', "fila" => '-', "abandonadas" => '0',
"atendidas_pa" => '0', "espera" => '0', "tme" => '00:00:00', "tma" => '00:00:00', "qt_fila" => '0', "cont_identificador" => '0',
"tipo_ligacao" => '-', "status_gravacao" => '', "motivo_pausa" => '', "uniqueid" => '', "disponivel_atendimento" => "1", "protocolo" => '-'
);
$query = "select ramal, matricula, nome, (LOCALTIMESTAMP(0) - tempo_login) as tempo_login, modo_atendimento, origem_destino, status as status_agente, (LOCALTIMESTAMP(0) - duracao) as duracao,
cont_identificador, tipo_ligacao, dac as fila, status_gravacao, motivo_pausa, uniqueid, disponivel_atendimento, protocolo
from pbx_supervisor_agentes
where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception(pg_last_error());
if (pg_num_rows($result) > 0) {
$row = @pg_fetch_array($result);
$_SESSION['cont_identificador'] = $row['cont_identificador'];
if (!empty($row['origem_destino'])) {
$_SESSION['origem_destino'] = $row['origem_destino'];
} else {
//$_SESSION['sessao_mute'] = 0;
$_SESSION[SS_INICIA_TRANSFERENCIA] = 0;
$_SESSION['sessao_mute'] = 0;
$_SESSION['sessao_pendulo'] = 0;
$_SESSION['sessao_transferencia'] = 0;
$_SESSION['sessao_conferencia'] = 0;
}
foreach ($row as $key => $value) {
if (array_key_exists($key, $infoChamada)) {
$infoChamada[$key] = $value;
}
}
} else {
$infoChamada["status_agente"] = AGENTE_LOGOFF;
}
/*
* Atualiza tabela de pbx_eventos_agentes para manter integridade nos relatorios
* e a tabela pbx_supervisor_agentes para n<EFBFBD>o ser deslogado pelo script que
* mantem a secao do agente
*/
if (trim($infoChamada["status_agente"]) == "PAUSA") {
UpdateLogoff($dbcon);
UpdatePausa($dbcon);
} else if (trim($infoChamada["status_agente"]) != "LOGOFF") {
UpdateLogoff($dbcon);
}
if (trim($infoChamada["status_agente"]) != "LOGOFF") {
/*
* Informa<EFBFBD><EFBFBD>es da fila
*/
$query = GetQueryInfoFila($nomeDac, $matricula);
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception(pg_last_error());
if (pg_num_rows($result) > 0) {
$row = @pg_fetch_array($result);
foreach ($row as $key => $value) {
if (array_key_exists($key, $infoChamada)) {
$infoChamada[$key] = $value;
}
}
}
}
$ret = array();
$ret[] = $infoChamada;
return ArrToXml($ret);
} catch (Exception $ex) {
$log[] = $query;
$log[] = $ex->getMessage();
return GetErro("InformacoesAtendimento", $ex);
}
}
$docApi['InformacoesAgentesGeral'] = MetodoApi("Retorna informa<EFBFBD><EFBFBD>es de todos os agentes logados nas filas");
function InformacoesAgentesGeral()
{
$query = "select a.ramal as ramal_monitor,
a.matricula,
a.nome,
(LOCALTIMESTAMP(0) - a.tempo_login) as tempo_logado,
a.modo_atendimento,
a.origem_destino as fone,
case when((a.status = 'PAUSA') and (coalesce(a.motivo_pausa, '') <> ''))then a.status || '-' || upper(a.motivo_pausa)
else a.status end as status,
(LOCALTIMESTAMP(0) - a.duracao) as duracao,
(SELECT count(*)
FROM ast_bilhetes x, ast_eventos_dacs y
where y.uid2 = x.uniqueid
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG')
and x.lastapp <> 'Transferred Call' )as originadas_pa,
(SELECT count(*)
FROM ast_bilhetes x, ast_eventos_dacs y,pbx_bilhetes_complemento z
where y.uid2 = x.uniqueid
and x.uniqueid = z.uniqueid2
and z.direcao = 'fila-ramal'
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETECALLER', 'COMPLETEAGENT' ,'COMPLETECALLERRAMAL', 'TRANSFER')
and x.lastapp <> 'Transferred Call') AS atendidas_pa,
(SELECT sum(CASE WHEN ((y.evento = 'TRANSFER') or (y.evento = 'TRANSFERORIG')) THEN case when(y.param4 = '')then 0
else y.param4::int end
ELSE case when(y.param2 = '')then 0 else y.param2::int end END)
FROM ast_bilhetes x, ast_eventos_dacs y
where y.uid2 = x.uniqueid
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETECALLER', 'COMPLETEAGENT','COMPLETECALLERRAMAL', 'TRANSFER',
'COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG')
and x.lastapp <> 'Transferred Call' ) AS tempo_atendimento, a.dac,
((EXTRACT(EPOCH FROM (now() - a.duracao)) / 60)) as status_time
FROM pbx_supervisor_agentes a
WHERE a.dac = case when(upper('TODOS') = 'TODOS')then a.dac else '' end";
try {
$dbcon = $GLOBALS['dbcon'];
$result = pg_query($dbcon, $query);
if (pg_num_rows($result) == 0) {
throw new Exception("Nao Existem Agentes Logados!");
} elseif (!$result) {
throw new Exception(pg_last_error());
}
} catch (Exception $ex) {
return GetErro("InformacoesAgentesGeral", $ex);
}
return BdToXml($result);
}
$docApi['InformacoesSupervisor'] = MetodoApi(
"Retorna informa<EFBFBD><EFBFBD>es sobre a Fila(DAC) Informada.",
[
["dac-atendimento", "STRING", "REQUIRED", "Identifica<EFBFBD><EFBFBD>o da Fila a ser monitorada."]
]
);
function InformacoesSupervisor($dac)
{
$query = "select a.ramal,
a.matricula,
a.nome,
(LOCALTIMESTAMP(0) - a.tempo_login) as tempo_login,
a.modo_atendimento,
a.origem_destino,
case when((a.status = 'PAUSA') and (coalesce(a.motivo_pausa, '') <> ''))then a.status || '-' || upper(a.motivo_pausa) else a.status end as status,
(LOCALTIMESTAMP(0) - a.duracao) as duracao,
( SELECT count(*)
FROM ast_bilhetes x, ast_eventos_dacs y
where y.uid2 = x.uniqueid
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG')
and x.lastapp <> 'Transferred Call' )as chamadas_originadas,
( SELECT count(*)
FROM ast_bilhetes x, ast_eventos_dacs y
where y.uid2 = x.uniqueid
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETECALLER', 'COMPLETEAGENT' , 'TRANSFER')
and x.lastapp <> 'Transferred Call' ) AS chamadas_atendidas,
( SELECT sum( CASE WHEN ((y.evento = 'TRANSFER') or (y.evento = 'TRANSFERORIG')) THEN case when(y.param4 = '')then 0 else y.param4::int end
ELSE case when(y.param2 = '')then 0 else y.param2::int end END
)
FROM ast_bilhetes x, ast_eventos_dacs y
where y.uid2 = x.uniqueid
and x.data_bilhete in(a.tempo_login::date, now()::date)
and y.fila = a.dac
and substring(y.agente, 7, 4) = a.matricula
and y.evento in('COMPLETECALLER', 'COMPLETEAGENT' , 'TRANSFER', 'COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG')
and x.lastapp <> 'Transferred Call' ) AS tempo_atendimento,
a.monitorar as statusmonitorar,
a.intercalar as statusintercalar,
a.chamada_classificado as status_classificacao,
a.disponivel_atendimento,
a.dac,
a.tipo_ligacao
FROM pbx_supervisor_agentes a
WHERE a.dac = %s order by a.dac, a.nome";
$query = sprintf($query, (strtoupper($dac) == 'TDS' ? 'a.dac' : QuotedStr($dac)));
try {
$dbcon = $GLOBALS['dbcon'];
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception(pg_last_error());
//return BdToXml($result);
while ($row = pg_fetch_array($result)) {
$matricula = $row['matricula'];
/*
* Variaveis disponibilizam informa<EFBFBD><EFBFBD>es sobre monitoria/intercala<EFBFBD><EFBFBD>o.
* As variaveis de sessao abaixo s<EFBFBD>o utilizadas pelas funcoes Monitora/Intercalar Agente.
*/
$idSessao = "SSmonitorar_" . $matricula;
$_SESSION[$idSessao] = $row['statusmonitorar'];
$idSessao = "SSinter_" . $matricula;
$_SESSION[$idSessao] = $row['statusintercalar'];
}
pg_result_seek($result, 0);
return BdToXml($result);
} catch (Exception $ex) {
$log[] = $query;
$log[] = $ex['message'];
return GetErro("InformacoesSupervisor", $ex);
}
}
$docApi['InformacoesDacs'] = MetodoApi(
"Retorna informa<EFBFBD><EFBFBD>es sobre a produtividade da(s) Fila(s)(DAC) Informada(s).",
[
["dac-atendimento", "STRING", "REQUIRED", "Identifica<EFBFBD><EFBFBD>o da(s) Fila(s) a ser(em) monitorada(s)."]
]
);
function InformacoesDacs($dac)
{
if ($dac) {
$params = explode(",", $dac);
foreach ($params as $key => $value) {
$dacsAcesso .= !$dacsAcesso ? "'$value'" : ",'$value'";
}
}
$query = "select distinct coalesce(sel, 0) as sel, e.dac, coalesce(originadas_pa,0) as originadas, coalesce(a.atendidas, 0) as atendidas,
coalesce(a.abandonadas::int, 0) as abandonadas,sp.origem_destino,coalesce(e.espera::int, 0) as espera,
(coalesce(e.tempo_espera::int, 0) * INTERVAL '1 SECOND') as tempo_espera, coalesce(e.tempo_espera::int, 0) as tempo_espera_int,
( round(coalesce(a.inb,0),0)::text || '%') as tempo_nivel_servico,'D' as tipo, transbordando, transbordada,
(select count(*) from pbx_nao_classificado where fila = a.dac and data_bilhete = a.data) as nao_classificado, id_dac,
(select count(*) from pbx_supervisor_agentes where dac = e.dac) as num_agente, 1 as ord
from pbx_supervisor_dacs e
left join (
SELECT 0 as sel, DAC, ID_DAC,
DATA,
ABANDONADAS
,ATENDIDAS_PA AS ATENDIDAS
,ORIGINADAS_PA
,ESPERA
,round( CASE WHEN(ESPERA = 0)THEN 0 ELSE (TEMPO_ESPERA / ESPERA) END ) * INTERVAL '1 SECOND' AS TME
,round( CASE WHEN(ATENDIDAS_PA = 0)THEN 0 ELSE (TEMPO_ATENDIMENTO / (ATENDIDAS_PA + ORIGINADAS_PA))END) * INTERVAL '1 SECOND' AS TMA
,round(CASE WHEN(ABANDONADAS = 0)THEN 0 ELSE (TEMPO_ABANDONO / ABANDONADAS) END) * INTERVAL '1 SECOND' AS TMAB
,(CASE WHEN(OFERECIDAS = 0)THEN 0 ELSE ATENDIDAS_30::FLOAT / OFERECIDAS::FLOAT END * 100)::numeric(5,2) as INB
,(CASE WHEN(OFERECIDAS::FLOAT = 0)THEN 0 ELSE (ABANDONADAS::FLOAT / OFERECIDAS::FLOAT) END * 100)::numeric(5,2) as IAB
,TEMPO_ESPERA
,TEMPO_ATENDIMENTO
,TEMPO_ABANDONO
,TRANSBORDANDO
,TRANSBORDADA
FROM (
SELECT DATA,
DAC, ID_DAC
,SUM (CASE WHEN EVENTO = 'ENTERQUEUE' THEN 1 ELSE 0 END) AS OFERECIDAS
,SUM (CASE WHEN EVENTO = 'ENTERQUEUE' THEN 1 ELSE 0 END) AS ATENDIDAS_URA
,SUM (CASE WHEN EVENTO = 'ABANDON' THEN 1 ELSE 0 END) AS ABANDONADAS
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER','TRANSFER') THEN 1 ELSE 0 END) AS ATENDIDAS_PA
,SUM (CASE WHEN EVENTO IN ('COMPLETAAGENT','COMPLETACALLER','TRANSFERORIG') THEN 1 ELSE 0 END) AS ORIGINADAS_PA
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER','TRANSFER') AND strtoint(param1) <= '30' THEN 1 ELSE 0 END) AS ATENDIDAS_30
,SUM (CASE WHEN EVENTO IN ('TRANSFER') THEN 1 ELSE 0 END) AS TRANSFERIDAS
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND strtoint(param1) > '3' THEN 1 ELSE 0 END) AS ESPERA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND strtoint(param1) > '1' THEN strtoint(param1) ELSE 0 END) AS TEMPO_ESPERA
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER') AND strtoint((case when(param2 = '')then '0' else param2 end)) > '1' THEN strtoint((case when(param2 = '')then '0' else param2 end)) ELSE 0 END) AS TEMPO_ATENDIMENTO
,SUM (CASE WHEN EVENTO IN ('ABANDON') THEN strtoint(param3) ELSE 0 END) AS TEMPO_ABANDONO
,SUM (CASE WHEN EVENTO IN('', 'TRANSBORDANDO') THEN 1 ELSE 0 END) AS TRANSBORDANDO
,SUM (transbordada) AS TRANSBORDADA
FROM (
SELECT D.NOME AS DAC, d.id as ID_DAC,
a.calldate::date AS DATA, a.calldate,b.fila,b.evento,b.param1,b.param2,b.param3,b.param4,
case when((evento = 'TRANSBORDADO') OR ((evento = 'ENTERQUEUE') and exists(select '' from ast_eventos_dacs where uid2 = b.uid2 and fila <> b.fila and evento = 'EXITWITHTIMEOUT' and b.id > id)))then 1 else 0 end as transbordada
FROM ast_eventos_dacs b
INNER JOIN ast_bilhetes a on a.uniqueid = b.uid2 and a.lastapp <> 'Transferred Call'
INNER JOIN pbx_dacs d on d.nome = b.fila and d.status = 'A'
WHERE b.evento in ('ABANDON','COMPLETEAGENT','COMPLETECALLER','CONNECT','ENTERQUEUE','TRANSFER', 'COMPLETAAGENT','COMPLETACALLER', 'TRANSFERORIG', 'EXITWITHTIMEOUT', 'TRANSBORDANDO', 'TRANSBORDADO')
AND 1 = CASE WHEN(b.evento = 'ABANDON')then (case when(not exists(select '' from ast_eventos_dacs where uid2 = b.uid2 and evento = 'TRANSBORDANDO' and fila = b.fila)) then 1 else 0 end) else 1 end
AND a.data_bilhete = now()::date
) AS DADOS
GROUP BY DATA, DAC, ID_DAC
) AS DADOS ORDER BY 1
) a on e.dac = a.dac
left join pbx_supervisor_agentes sp on e.dac = sp.dac\n";
if ($dac) {
$query .= " where e.dac in($dacsAcesso)\n";
}
$query .= " order by 15,2";
try {
$dbcon = $GLOBALS['dbcon'];
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
return BdToXml($result);
} catch (Exception $ex) {
$log[] = $query;
$log[] = $ex['message'];
return GetErro("InformacoesDacs", $ex);
}
}
/*
$metodos["InformacoesAtendimentoRT"] = "Retorna informa<EFBFBD><EFBFBD>es sobre atendimento atrav<EFBFBD>s de httpstream. $obsConectaAgente";
$metodosParam["InformacoesAtendimentoRT"] = array();
$metodosRetorno["InformacoesAtendimentoRT"] = "text/xml";
*/
function InformacoesAtendimentoRT()
{
$num = 0;
// @ob_start();
echo (str_repeat('.', 256));
_flush();
while (true) {
echo "<script type=\"text/javascript\">
window.parent.document.getElementById('info').innerHTML = $num;
</script>";
_flush();
sleep(1);
$num++;
//if($num == 59)break;
}
$dbcon = $GLOBALS['dbcon'];
$nomeDac = $_SESSION[SS_NOME_DAC];
$matricula = $_SESSION[AGT_MATRICULA];
$infoChamada = array(
"ramal" => '-', "matricula" => '-', "nome" => '-', "tempo_login" => '00:00:00', "modo_atendimento" => '-',
"origem_destino" => '-', "status" => 'LOGOFF', "duracao" => '00:00:00'
);
$infoFila = array(
"fila" => '-', "abandonadas" => '0', "atendidas_pa" => '0', "espera" => '0', "tme" => '00:00:00',
"tma" => '00:00:00', "qt_fila" => '0'
);
$infoFilaOld = array(
"fila" => '-', "abandonadas" => '0', "atendidas_pa" => '0', "espera" => '0', "tme" => '00:00:00',
"tma" => '00:00:00', "qt_fila" => '0'
);
/*
* Informa<EFBFBD><EFBFBD>es da chamada corrente
*/
$queryAgente = "select ramal, matricula, nome, (LOCALTIMESTAMP(0) - tempo_login) as tempo_login, modo_atendimento, origem_destino, status, (LOCALTIMESTAMP(0) - duracao) as duracao
from pbx_supervisor_agentes
where matricula = '$matricula' ";
$queryFila = GetQueryInfoFila($nomeDac, $matricula);
try {
//Indica o tempo entre as requisi<EFBFBD><EFBFBD>es para verifica o status do agente no banco de dados
define("TEMPO_DORME", 10);
define("MAX_ERROS", 10);
//Variavel armazena o status do agente na sessao atual
if (!$_SESSION[AGT_CONECT])
throw new Exception('O agente n<EFBFBD>o esta logado!');
//Tolerancia de tentavias de acesso ao banco de dados
$numErros = 0;
//Id do bloco de informacoes retornado
$idBloco = 1;
//Buffer necess<EFBFBD>rio para o browser comecar a receber atualiza<EFBFBD><EFBFBD>es
echo (str_repeat(' ', 256));
_flush();
//Contera blocos de informa<EFBFBD><EFBFBD>es sobre filas e agentes
/* $encode = $GLOBALS['server']->getEncoding();
$info = "\n<?xml version=\"1.0\" encoding=\"$encode\" ?>\n";
$info .= "<root>\n";
$info .= "<status>ok</status>\n";
*
*/
$info = "<message>Inicializando monitoramento de agente! Aguarde...</message>\n";
DisplayInfo($info); //simplexml_load_string($info)->asXml();
$info = "";
//Flag que indica se ha dados a enviar ao processo chamador
$display = 0;
//Variavel define o status atual do agente
$statusAgente = $_SESSION[SS_STATUS_AGENTE];
$start = 0;
//Indica que houve mudan<EFBFBD>a na fila
$statusFila = 0;
//Display das informa<EFBFBD><EFBFBD>es para o chamador
while (true) {
$info = "";
$display = 0;
$result = pg_query($dbcon, $queryAgente);
$ret = array();
if (!$result) {
$numErros++;
} else {
//Se o agente foi desconectado, gera uma excess<EFBFBD>o informando o processo chamador
if (!pg_num_rows($result))
throw new Exception('O agente foi desconectado!');
// Recupera informa<EFBFBD><EFBFBD>es do banco de dados sobre o agente logado
$row = @pg_fetch_array($result);
GetValoresInfo($row, $infoChamada);
if ((!$start) || ($statusAgente != $infoChamada["status"])) {
// $ret[] = $infoChamada;
$statusAgente = $infoChamada["status_agente"];
$info = "<agente id=\"$idBloco\">\n";
$info .= ArrToStrXml($infoChamada);
$info .= "</agente>\n";
DisplayInfo($info);
$display++;
}
if ($display) {
$idBloco++;
$display = 0;
}
//Recupera informa<EFBFBD><EFBFBD>es sobre a fila de atendimento
$result = pg_query($dbcon, $queryFila);
if (!$result) {
$numErros++;
} else {
$row = @pg_fetch_array($result);
if (!empty($row["fila"])) {
GetValoresInfo($row, $infoFila);
if (!$start)
GetValoresInfo($row, $infoFilaOld);
$statusFila = GetStatusFila($infoFila, $infoFilaOld);
if (!$start || $statusFila) {
$ret = array();
// $ret[] = $infoFila;
$info = "<dac id=\"$idBloco\">\n";
$info .= $info .= ArrToStrXml($infoFila);
$info .= "</dac>\n";
$display++;
DisplayInfo($info);
GetValoresInfo($row, $infoFilaOld);
}
}
}
if ($display) {
$idBloco++;
$display = 0;
}
}
if ($numErros > MAX_ERROS)
throw new Exception('A aplica<EFBFBD><EFBFBD>o foi encerrada porque atingiu o limite m<EFBFBD>ximo de erros ao tentar acessar o banco de dados!');
$start++;
sleep(TEMPO_DORME);
}
} catch (Exception $ex) {
echo GetErroSimples("InformacoesAtendimentoRT", $ex);
}
}
$docApi['DisponivelFila'] = MetodoApi(
"Bloqueia o recebimento de chamadas pela Fila(Dac), mas permite que o agente fa<EFBFBD>a liga<EFBFBD>oes. Utilize o parametro disponivel_atendimento retornado em InformacoesAtendimento para controlar o status. $obsConectaAgente",
[
["dac-atendimento", "STRING", "REQUIRED", "Identifica<EFBFBD><EFBFBD>o da(s) Fila(s) a ser(em) monitorada(s)."]
]
);
function DisponivelFila()
{
$erroBd = 0;
$dispo = 0;
try {
$dbcon = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$result = pg_query($dbcon, 'begin');
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar a opera<EFBFBD><EFBFBD>o!");
}
$query = "select dac, status, disponivel_atendimento from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result || !pg_num_rows($result))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o status do \"Agente Logado\"!");
$row = pg_fetch_array($result);
$dispo = $row["disponivel_atendimento"];
$status = $row["status"] == 'PAUSA';
$dac = $row["dac"];
if ($dispo) {
if (!GetUrl(AST_ADD_PAUSA))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel colocar o \"Agente como Indispon<EFBFBD>vel\"!");
$newDispo = 0;
} else if (!$dispo && !$status) {
if (!GetUrl(AST_REM_PAUSA))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel remover a \"Indisponibilidade do Agente\"!");
$newDispo = 1;
} else {
$newDispo = $dispo ? 0 : 1;
}
$query = "update pbx_supervisor_agentes set disponivel_atendimento = '$newDispo' where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
$erroBd = 1;
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel alterar o status do \"Agente Logado\"!");
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
$erroBd = 1;
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel finalizar a opera<EFBFBD><EFBFBD>o!");
}
$ret["status"] = "ok";
$ret["result"] = "true";
$ret["message"] = "Opera<EFBFBD><EFBFBD>o Realizada com Sucesso!";
return ResultToXml($ret);
} catch (Exception $ex) {
/* Se ocorrer erro apenas no banco tenta voltar o agente ao status anterior */
if ($erroBd) {
if ($dispo)
@GetUrl(AST_REM_PAUSA);
else
@GetUrl(AST_ADD_PAUSA);
}
return GetErro("DisponivelFila", $ex);
}
}
$docApi['MonitorCampanha'] = MetodoApi(
"Monitora o progresso da Campanha.",
[
["idCampanha-1", "STRING", "REQUIRED", "Identificador da Campanha. Pode ser passado o Nome(Identificador textual) ou C<EFBFBD>digo(Identificador N<EFBFBD>merico)."]
]
);
function MonitorCampanha($idCampanha)
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = " select a.cmp_id as id_campanha, a.cmp_descricao as desc_campanha, a.cmp_status as status_campanha,
b.conf_fone as fone, b.conf_status as status, round(extract(epoch from age(now(), b.conf_data))) * interval '1 second' as tempo
from pbx_campanha a
left outer join pbx_campanha_contato_fone b on b.cmp_id = a.cmp_id
where (a.cmp_id::text = '$idCampanha' or a.cmp_descricao = '$idCampanha')
and b.conf_status_lista = '1'
and upper(b.conf_status) = upper('discando')
and round(extract(epoch from age(now(),conf_data))) <= '30' ";
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel obter informa<EFBFBD><EFBFBD>es da \"Campanha\"!");
return BdToXml($result);
} catch (Exception $ex) {
return GetErro("MonitorCampanha", $ex);
}
}
$docApi['InvalidaNumeroCampanha'] = MetodoApi(
"Monitora o progresso da Campanha.",
[
["idCampanha-1", "STRING", "REQUIRED", "Identificador da Campanha. Pode ser passado o Nome(Identificador textual) ou C<EFBFBD>digo(Identificador N<EFBFBD>merico)."],
["idLista-1", "STRING", "REQUIRED", "Identificador da Lista. Pode ser passado o Nome(Identificador textual) ou C<EFBFBD>digo(Identificador N<EFBFBD>merico)."],
["idCliente-1", "STRING", "REQUIRED", "Identificador da cliente. Conforme enviado na lista."],
["telefone-6536844908", "STRING", "REQUIRED", "Identificador da Campanha. Pode ser passado o Nome(Identificador textual) ou C<EFBFBD>digo(Identificador N<EFBFBD>merico)"],
]
);
function InvalidaNumeroCampanha($idCampanha, $idLista, $idCliente, $telefone)
{
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select b.cmp_id, b.list_id, c.cont_id
from pbx_campanha a, pbx_campanha_lista b, pbx_campanha_contato c
where b.cmp_id = a.cmp_id
and c.cmp_id = b.cmp_id and c.list_id = b.list_id
and (a.cmp_id::text = '$idCampanha' or a.cmp_descricao = '$idCampanha')
and (b.list_id::text = '$idLista' or b.list_nome = '$idLista')
and c.cont_identificador = '$idCliente' ";
$result = pg_query($dbcon, $query);
if (!$result || !pg_num_rows($result))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel obter informa<EFBFBD><EFBFBD>es da \"Lista\"!");
$dados = pg_fetch_array($result);
$idCampanha = $dados['cmp_id'];
$idLista = $dados['list_id'];
$idCliente = $dados['cont_id'];
$query = "update pbx_campanha_contato_fone set conf_status = 'INVALIDO'
where cmp_id = '$idCampanha'
and list_id = '$idLista'
and cont_id = '$idCliente'
and conf_fone = '$telefone' ";
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception("Erro ao invalidar \"Telefone\"!");
if (!pg_affected_rows($result))
throw new Exception("\"Telefone\" n<EFBFBD>o encontrado!");
$ret["status"] = "ok";
$ret["result"] = "true";
$ret["message"] = "Opera<EFBFBD><EFBFBD>o Realizada com Sucesso!";
return ResultToXml($ret);
} catch (Exception $ex) {
return GetErro("InvalidaNumeroCampanha", $ex);
}
}
function GetErroSimples($method, $ex)
{
$xml = "<erro>\n";
$xml .= "<status>erro</status>\n";
$xml .= "<SIPID>%s</SIPID>\n";
$xml .= "<method>%s</method>\n";
$xml .= "<code>%s</code>\n";
$xml .= "<message>%s</message>\n";
$xml .= "<line>%s</line>\n";
$xml .= "<file>%s</file>\n";
$xml .= "</erro>\n";
$xml = sprintf($xml, session_id(), $method, $ex->getCode(), $ex->getMessage(), $ex->getLine(), $ex->getFile());
return $xml;
}
function DisplayInfo($info)
{
echo $info; //simplexml_load_string($info)->asXml();
_flush();
}
function _flush()
{
echo (str_repeat(' ', 256));
// check that buffer is actually set before flushing
if (ob_get_length()) {
@ob_flush();
@flush();
}
}
function GetStatusFila($infoFila, $infoFilaOld)
{
$count = count($infoFila);
for ($i = 0; $i < $count; $i++) {
if ($infoFila[$i] != $infoFilaOld[$i])
return true;
}
return false;
}
function GetValoresInfo($row, &$infoArray)
{
foreach ($row as $key => $value) {
if (array_key_exists($key, $infoArray)) {
$infoArray[$key] = $value;
}
}
}
$docApi['ConectaAgente'] = MetodoApi(
"Conecta um agente a um DAC.",
[
["dac-3", "STRING", "REQUIRED", "Dac em que o agente vai logar."],
["nomeDac-discador", "STRING", false, "Nome do Dac em que o agente vai logar."],
["matriculaAgente-1001", "INTEIRO", "REQUIRED", "Matr<EFBFBD>cula do Agente."],
["apelidoAgente-admin", "STRING", false, "Login do Agente"],
["ramal-6008", "STRING", "REQUIRED", "Ramal em que o agente esta logado"],
["tipoAtende-**50", "STRING", "REQUIRED", "Tipo de Atendimento, possui 2(dois) valores v<EFBFBD>lidos. **50 Manual e **60 Autom<EFBFBD>tico"],
]
);
function ConectaAgente($dac, $nomeDac = '', $matriculaAgente = '0', $apelidoAgente = '', $ramal = '0', $tipoAtende = '')
{
global $log;
$db = $GLOBALS['dbcon'];
$_SESSION[AGT_DAC_CONECT] = $dac;
$_SESSION[SS_NOME_DAC] = empty($nomeDac) ? GetDacDesc(null, $dac) : $nomeDac;
$nomeDac = $_SESSION[SS_NOME_DAC];
$_SESSION[AGT_MATRICULA] = $matriculaAgente;
$_SESSION[AGT_RAMAL_CONF] = $ramal;
$_SESSION[AGT_TP_ATEND] = $tipoAtende;
$_SESSION[AGT_LOGIN] = empty($apelidoAgente) ? GetLoginMatricula($matriculaAgente) : $apelidoAgente;
$apelidoAgente = $_SESSION[AGT_LOGIN];
$_SESSION[RAMAL_MONITOR_SUPERVISOR] = "";
$_SESSION[SS_DESTINO_INTERCALAR] = "";
$_SESSION[CANAL_MONITOR_SUPERVISOR] = "";
$_SESSION[AGT_NUM_DISC] = "";
$_SESSION[AGT_CHANNEL_TRANSF] = "";
$_SESSION["SSagentePenalidade"] = 0;
$_SESSION[SS_STATUS_AGENTE] = AGENTE_LOGOFF;
$_SESSION[SS_TIPO_FILA] = "";
$matricula = $matriculaAgente;
$_SESSION['sessao_mute'] = 0;
$inTransaction = 0;
$ultMsg = '';
//Pega o dispositivo pelo ramal
$_SESSION[API_CANAL_DISCAL] = @GetRamalSip($db, $ramal);
$dacCheck = '';
$agtCheck = '';
$result = false;
$_SESSION[SS_AGT_CONTEXTO_RAMAL] = GetContextoRamal($db, $ramal);
if (VerficaAgenteLogado($db)) {
$ramalCon = GetRamalAgenteLogado($db);
$ultMsg = "N<EFBFBD>o <EFBFBD> poss<EFBFBD>vel conectar ao servidor, o Agente j<EFBFBD> est<EFBFBD> Conectado no Ramal: $ramalCon!";
$log[] = $ultMsg;
} else if (VerificaRamalLogado($db, $dacCheck, $agtCheck)) {
$ramal = GetRamalAgente();
$ultMsg = "N<EFBFBD>o <EFBFBD> poss<EFBFBD>vel conectar ao servidor, Ramal: \"$ramal\" j<EFBFBD> conectado! Dac: \"$dacCheck\" Agente: \"$agtCheck\"";
$log[] = $ultMsg;
} else if (VerificaMaxAgenteLogado($db)) {
$ultMsg = "N<EFBFBD>o <EFBFBD> poss<EFBFBD>vel conectar o Agente! O n<EFBFBD>mero m<EFBFBD>ximo de \"PAs\" simultaneos j<EFBFBD> foi atingido!";
$log[] = $ultMsg;
} else {
//loga o agente no asterisk
$result = GetUrl(AST_LOGIN_AGENTE);
if (!$result) {
$ultMsg = "Erro ao conectar agente na central";
$log[] = $ultMsg;
} else {
/*
* verifica se o login foi executado com sucesso
*/
$result = AgentePresente($db, $matricula);
if (!$result) {
$ultMsg = "Erro ao conectar o agente na central, o registro de agente n<EFBFBD>o esta dispon<EFBFBD>vel em \"Supervisor Agentes\"!";
$log[] = $ultMsg;
} else {
/*
* Armazenha o tipo de fila dac ou campanha
*/
$result = GetTipoFila($db, $dac);
$_SESSION[SS_TIPO_FILA] = $result;
if (!$result) {
$ultMsg = "N<EFBFBD>o foi poss<EFBFBD>vel identificar a fila de atendimento!";
$log[] = $ultMsg;
} else {
/*
* Registra login no banco de dados.
*/
$result = pg_query($db, "begin");
if (!$result) {
$ultMsg = "N<EFBFBD>o foi poss<EFBFBD>vel iniciar uma transa<EFBFBD><EFBFBD>o para registro de login no banco de dados!";
$log[] = $ultMsg;
} else {
$inTransaction = 1;
/*
* Insere o registro de login em pbx_supervisor agentes.
*/
$result = RegistraLogin($db, $tipoAtende, $matricula, $ramal, $nomeDac, $apelidoAgente, $dac);
if (!$result) {
$ultMsg = "N<EFBFBD>o foi possivel registrar o login em \"Supervisor Agentes\"!";
$log[] = $ultMsg;
} else {
/*
* Consulta no banco de dados o id da pausa de login
*/
$result = GetMotivoLogin($db);
$motivoLogin = $result;
if (!$result) {
$ultMsg = "N<EFBFBD>o foi possivel recuperar o motivo de pausa login!";
$log[] = $ultMsg;
} else {
/*
* Registra a pausa de login no banco de dados.
*/
$relEvt = 0;
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, id_motivo_pausa, entrada_pausa, flag, relaciona_eventos)
values('$matricula', '$ramal', $dac, $motivoLogin, now(), 0, $relEvt)";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
}
}
}
}
}
}
}
$ret = array();
if ($result) {
pg_query($db, "commit");
$_SESSION[AGT_CONECT] = 1;
$_SESSION[SS_STATUS_AGENTE] = AGENTE_EM_PAUSA;
$ret["status"] = "OK";
$ret["agente_status"] = AGENTE_EM_PAUSA;
$ret["tipo_fila"] = $_SESSION[SS_TIPO_FILA];
$ret["message"] = "Agente conectado com sucesso!";
$log[] = "Agente logado";
} else {
if ($inTransaction)
pg_query($db, "rollback");
$_SESSION[AGT_CONECT] = 0;
$_SESSION[SS_STATUS_AGENTE] = AGENTE_LOGOFF;
$ret["status"] = "erro";
$ret["agente_status"] = AGENTE_LOGOFF;
$ret["tipo_fila"] = $_SESSION[SS_TIPO_FILA];
$ret["message"] = $ultMsg;
}
return ResultToXml($ret);
}
function RegistraLogin($db, $tipoAtende, $matricula, $ramal, $dacDesc, $login, $dac)
{
global $log;
$ultMsg = sprintf("Metodo: RegistraLogin() Data: %s Status: ok", date('d/m/Y H:i:s'));
$log[] = $ultMsg;
$tipo = ($tipoAtende == '**50') ? 'Manual' : 'Autom<EFBFBD>tico';
/*
* Registra o login do usuario.
*/
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, \"login\", logoff, flag)
values('$matricula', '$ramal', $dac, now(), now(), 0)";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = "N<EFBFBD>o foi possivel inserir o registro em \"Eventos Agentes\"";
$log[] = $ultMsg;
$log[] = $query;
} else {
/*
* atualiza dados do supervisor
*/
$query = "update pbx_supervisor_agentes
set ramal = '$ramal',
nome = '$login',
dac = '$dacDesc',
modo_atendimento = '$tipo',
duracao = now(),
status_agente = '1',
relaciona_evento = '0'
where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = "N<EFBFBD>o foi possivel atualizar informa<EFBFBD><EFBFBD>es em \"Supervisor Agentes\"";
$log[] = $ultMsg;
$log[] = $query;
}
}
return $result;
}
$docApi['DesconectaAgente'] = MetodoApi("Desconecta o agente.$obsConectaAgente");
function DesconectaAgente()
{
global $log;
$ultMsg = sprintf("Metodo: DesconectaAgente() Data: %s Status: ok", date('d/m/Y H:i:s'));
$log[] = $ultMsg;
$db = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$ramal = GetRamalAgente();
$login = GetLoginAgente();
$dac = GetIdDac();
$ultMsg = '';
//se tpatend manual remove agente da fila
if ($_SESSION[AGT_TP_ATEND] == AGT_MODU_MANUAL) {
@GetUrl(AST_REM_FILA);
}
$result = @GetUrl(AST_LOGOFF_AGENTE);
if (!$result) {
$ultMsg = "N<EFBFBD>o foi poss<EFBFBD>vel efetura logoff no asterisk.";
$log[] = $ultMsg;
} else {
//Desenvolvendo
$result = pg_query($db, "begin");
if (!$result) {
$ultMsg = "N<EFBFBD>o iniciar transa<EFBFBD><EFBFBD>o no banco de dados!";
$log[] = $ultMsg;
} else {
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if (!$result) {
$ultMsg = "N<EFBFBD>o foi poss<EFBFBD>vel deletar o agente em \"Supervisor Agentes\"!";
$log[] = $ultMsg;
$log[] = $query;
} else {
if ($result) {
$query = "update pbx_eventos_agentes set logoff = now(), flag = 2
where matricula = '$matricula' and id_dac = $dac and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
$result = pg_query($db, $query);
}
if (!$result) {
$ultMsg = "N<EFBFBD>o foi Atualizar \"Eventos Agentes\"!";
$log[] = $ultMsg;
$log[] = $query;
}
}
}
}
$ret = array();
if ($result) {
$ultMsg = "Logoff efetuado com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
$ret["status"] = "OK";
$ret["message"] = $ultMsg;
GravaLogItgr();
SetSessionDesconect();
} else {
pg_query($db, "rollback");
$ret["status"] = "OK";
$ret["message"] = $ultMsg;
}
return ResultToXml($ret);
}
$docApi['EntradaPausa'] = MetodoApi(
"Coloca o agente em pausa. $obsConectaAgente",
[
["codMotivo-3", "STRING", 'INTEIRO', 'Indica o motivo da pausa']
]
);
function EntradaPausa($codMotivo)
{
$log = &$GLOBALS["log"];
$ultMsg = sprintf("Metodo: EntradaPausa() Data: %s Status: ok", date('d/m/Y H:i:s'));
$log[] = $ultMsg;
$db = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$dac = GetIdDac();
$ramal = GetRamalAgente();
$msgErro = '';
$result = !VerificaMaxAgentePausa($dac);
if (!$result) {
$ultMsg = 'N<EFBFBD>mero M<EFBFBD>ximo de Agente/Pausa Excedido, Aguarde!';
$log[] = $ultMsg;
} else {
$result = GetUrl(AST_ADD_PAUSA);
if (!$result) {
$ultMsg = 'N<EFBFBD>o foi poss<EFBFBD>vel adicionar o agente em pausa na central!';
$log[] = $ultMsg;
} else {
$result = pg_query($db, "begin");
if (!$result) {
$ultMsg = 'N<EFBFBD>o foi poss<EFBFBD>vel iniciar uma transa<EFBFBD><EFBFBD>o com o banco de dados!';
$log[] = $ultMsg;
} else {
//pega descricao do motivo de pausa
$query = "select motivo from pbx_motivos_pausas where id = '$codMotivo'";
$result = pg_query($db, $query);
$log[] = $query;
if (!pg_num_rows($result)) {
$ultMsg = 'N<EFBFBD>o foi poss<EFBFBD>vel carregar informa<EFBFBD><EFBFBD>es sobre o \"Motivo da Pausa\"!';
$log[] = $ultMsg;
} else {
$rowMotivo = @pg_fetch_row($result);
$descMotivo = $rowMotivo[0];
//atualiza dados do supervisor
$query = "update pbx_supervisor_agentes set status = 'PAUSA', duracao = now(), id_eventos_agente = '0', motivo_pausa = '$descMotivo' where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
$log[] = $query;
if (!$result) {
$ultMsg = 'N<EFBFBD>o foi poss<EFBFBD>vel atualizar o status de pausa em \"Supervisor Agentes\""!';
$log[] = $ultMsg;
} else {
$relEvt = 0;
$query = "insert into pbx_eventos_agentes(matricula, ramal, id_dac, id_motivo_pausa, entrada_pausa, flag, relaciona_eventos, saida_pausa, pausa_produtiva)
values('$matricula', '$ramal', $dac, $codMotivo, now(), 0, $relEvt, now(), (select produtiva from pbx_motivos_pausas where id = '$codMotivo'))";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
$log[] = $query;
if (!$result) {
$ultMsg = 'N<EFBFBD>o foi poss<EFBFBD>vel atualizar o status de pausa em \"Supervisor Agentes\""!';
$log[] = $ultMsg;
}
}
}
}
}
}
$ret = array();
if ($result) {
$ultMsg = "Agente colocado em \"Pausa\" com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
$_SESSION[AGT_EM_PAUSA] = 1;
$_SESSION[AGT_PAUSA_MOTIVO] = $codMotivo;
$ret["status"] = "OK";
$ret["agente_status"] = AGENTE_EM_PAUSA;
$ret["message"] = $ultMsg;
} else {
pg_query($db, "rollback");
$ret["status"] = "erro";
$ret["agente_status"] = AGENTE_LIVRE;
$ret["message"] = $ultMsg;
}
return ResultToXml($ret);
}
$docApi['SaidaPausa'] = MetodoApi(
"Retira o agente da pausa.$obsConectaAgente"
);
function SaidaPausa()
{
$log = &$GLOBALS["log"];
$ultMsg = sprintf("Metodo: SaidaPausa() Data: %s Status: ok", date('d/m/Y H:i:s'));
$log[] = $ultMsg;
$db = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$ramal = GetRamalAgente();
$login = GetLoginAgente();
$dac = GetIdDac();
/*
* Remove o agente da pausa no asterisk.
*/
$result = GetUrl(AST_REM_PAUSA);
if (!$result) {
$ultMsg = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel remover o agente da pausa na Central!");
$log[] = $ultMsg;
} else {
$result = pg_query($db, "begin");
if (!$result) {
$ultMsg = sprintf("N<EFBFBD> foi poss<EFBFBD>vel iniciar uma transa<EFBFBD><EFBFBD>o com o banco de dados!");
$log[] = $ultMsg;
} else {
$query = "update pbx_eventos_agentes set saida_pausa = now(), flag = 2
where matricula = '$matricula' and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = sprintf("N<EFBFBD> foi poss<EFBFBD>vel atualizar o registro de pausa em \"Eventos Agentes\"!");
$log[] = $ultMsg;
} else {
$query = "update pbx_supervisor_agentes set status = 'LIVRE', duracao = now(), motivo_pausa = '0', status_agente = '0' where matricula = '$matricula'";
$result = pg_query($db, $query);
$result = $result && @pg_affected_rows($result);
if (!$result) {
$ultMsg = sprintf("N<EFBFBD> foi poss<EFBFBD>vel atualizar o registro de pausa em \"Supervisor Agentes\"!");
$log[] = $ultMsg;
}
}
}
} //remove pausa
$ret = array();
if ($result) {
$ultMsg = "Agente removido de \"Pausa\" com sucesso!";
$log[] = $ultMsg;
pg_query($db, "commit");
$_SESSION[AGT_EM_PAUSA] = 0;
$_SESSION[AGT_PAUSA_MOTIVO] = 0;
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["agente_status"] = AGENTE_LIVRE;
$ret["message"] = $ultMsg;
} else {
pg_query($db, "rollback");
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["agente_status"] = AGENTE_EM_PAUSA;
$ret["message"] = $ultMsg;
}
return ResultToXml($ret);
}
$docApi['Discar'] = MetodoApi(
"Disca para o n<EFBFBD>mero informado. $obsConectaAgente",
[
["numeroDiscar-36844900", "INTEIRO", 'REQUIRED', 'N<EFBFBD>mero de telefone']
]
);
function Discar($numeroDiscar)
{
$log = &$GLOBALS["log"];
$log[] = sprintf('Metodo Inicio: Discar %s Status: ok ', date('d/m/Y H:i:s'));
$log[] = sprintf('Numero -> : %s Linha: %s ', $numeroDiscar, 1893);
$log[] = sprintf('Metodo Fim: Discar %s Status: ok ', date('d/m/Y H:i:s'));
$db = $GLOBALS['dbcon'];
$matricula = GetMatriculaAgente();
$result = 0;
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
$msgSis = "";
$query = "select status,motivo_pausa from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query); //
if ($result)
$row = @pg_fetch_array($result);
if (!$result) {
$msgSis = "N<EFBFBD>o foi poss<EFBFBD>vel acessar banco de dados. Erro: " . @pg_last_error();
} else if (strtoupper($row["status"]) == "PAUSA" && strtoupper($row["motivo_pausa"]) != "ACW") {
$msgSis = "N<EFBFBD>o foi poss<EFBFBD>vel discar. Erro: Agente em pausa";
$result = false;
}
if (($result) && (GetUrl(AST_DISCAR))) {
if (strtoupper($row["motivo_pausa"]) == "ACW") {
$query = "update pbx_supervisor_agentes set canal_agente = 'Agent/$matricula', origem_destino = '$numeroDiscar' where matricula = '$matricula'";
} else {
$query = "update pbx_supervisor_agentes set status = 'OCUPADO', canal_agente = 'Agent/$matricula', origem_destino = '$numeroDiscar', duracao = now() where matricula = '$matricula'";
}
$result = pg_query($db, $query);
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = "N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado!";
$result = false;
}
$ret = array();
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['DiscarDireto'] = MetodoApi(
"Disca para o n<EFBFBD>mero informado, <EFBFBD> necess<EFBFBD>io passar o Ramal de Origem",
[
["numeroDiscar-36844900", "INTEIRO", 'REQUIRED', 'N<EFBFBD>mero de telefone/ramal a discar.'],
["ramal-1001", "INTEIRO", 'REQUIRED', 'N<EFBFBD>mero do Ramal de Origem.']
]
);
function DiscarDireto($numeroDiscar, $ramal)
{
$db = $GLOBALS['dbcon'];
$result = 1;
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
$_SESSION[AGT_RAMAL_CONF] = $ramal;
$_SESSION[API_CANAL_DISCAL] = GetDispositivoRamal($db, $ramal);
// echo "DiscarDireto"; exit;
$msgSis = "";
if ($_SESSION[API_CANAL_DISCAL] == -1) {
$msgSis = "Ramal Inv<EFBFBD>lido!";
$result = false;
}
if (($result) && (GetUrl(AST_DISCAR_DIRETO))) {
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado! N<EFBFBD>mero: %s Ramal: %s Canal: %s", $numeroDiscar, $ramal, $_SESSION[API_CANAL_DISCAL]);
$result = false;
}
$ret = array();
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['MonitoraChamadas'] = MetodoApi(
"Apresenta as chamadas em curso na central atualizadas em tempo real."
);
function MonitoraChamadas($numeroDiscar, $ramal)
{
$chamadas = GetMonitorAst13();
$ret = array();
if ($chamadas) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret['chamadas'] = json_encode($chamadas);
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = "Nenhuma chamada em curso.";
}
return ResultToXml($ret);
}
$docApi['ChamadaRamal'] = MetodoApi(
"Disca para o n<EFBFBD>mero informado, <EFBFBD> necess<EFBFBD>rio passar o Ramal de Origem",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de telefone/ramal a discar.'],
["ramal-1001", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero do Ramal de Origem ou N<EFBFBD>mero Fixo/Celular.']
],
'text/json'
);
function ChamadaRamal($numeroDiscar, $ramal)
{
$db = $GLOBALS['dbcon'];
$msg = '';
$pathLog = '/var/log/asterisk/ChamadaRamal.log';
$tipoRetorno = $_REQUEST['tipoRetorno'];
GravaLog(sprintf("Data: %s NumeroDiscar: %s Ramal: %s \n", date("y-m-d H:i:s"), $numeroDiscar, $ramal), $pathLog);
$envExterno = strlen($ramal) >= 8;
try {
if ($envExterno) {
$channel = trim($ramal);
if (!$ramal = GetRamalApi()) {
GeraExcept("Ramal API n<EFBFBD>o cadastrado!");
}
} else {
$channel = GetDispositivoRamal($db, $ramal);
}
if ($channel == -1) {
GeraExcept("Ramal Inv<EFBFBD>lido!");
}
// GravaLog(sprintf("Data: %s Channel: %s NumeroDiscar: %s Ramal: %s Externo: %s \n", date("y-m-d H:i:s"), $channel, $numeroDiscar, $ramal, ($envExterno ? 'S' : 'N')), $pathLog);
/*
* Realiza a chamada e retorna o resultado.
*/
$uniqueid = ChamadaRamalAmi($channel, $numeroDiscar, $ramal, $envExterno);
GravaLog(sprintf("Data: %s Channel: %s NumeroDiscar: %s Ramal: %s Externo: %s Uid: %s \n", date("y-m-d H:i:s"), $channel, $numeroDiscar, $ramal, ($envExterno ? 'S' : 'N'), $uniqueid), $pathLog);
/*
* Verifica se a chamada foi completada.
*/
while ($status = VerificaChamadaRamal(($envExterno ? $numeroDiscar : $channel))) {
if ($status === 1) {
$msg = 'A chamada n<EFBFBD>o pode ser atendida!';
pg_query(sprintf("insert into pbx_chamada_ramal(chdr_channel, chdr_numero, chrd_direcao_chamada, chdr_status, chdr_fim, uniqueid)values('%s','%s','%s','%s', now(),'%s')", $channel, $numeroDiscar, 'S', 'OCUPADA', $uniqueid));
GravaLog(sprintf("Data: %s Msg: %s \n", date("y-m-d H:i:s"), 'Chamada nao Atendida!'), $pathLog);
break;
} else if ($status == 2) {
/*
* Chamada em andamento;
*/
usleep(200000);
} else if ($status == 3) {
$msg = 'Chamada realizada com sucesso!';
pg_query(sprintf("insert into pbx_chamada_ramal(chdr_channel, chdr_numero, chrd_direcao_chamada, chdr_status, uniqueid)values('%s','%s','%s','%s', '%s')", $channel, $numeroDiscar, 'S', 'ATENDIDA', $uniqueid));
GravaLog(sprintf("Data: %s Msg: %s \n", date("y-m-d H:i:s"), 'Chamada Atendida!'), $pathLog);
break;
}
}
GravaLog(sprintf("Data: %s Msg: %s \n\n", date("y-m-d H:i:s"), 'Final Api!'), $pathLog);
$ret = array();
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["id_chamada"] = $uniqueid;
$ret["message"] = RemoveAcentos($msg);
} catch (Exception $ex) {
$ret["status"] = "erro";
$ret["result"] = "erro";
$ret["id_chamada"] = '0';
$ret["message"] = RemoveAcentos($ex->getMessage());
GravaLog(sprintf("Data: %s Erro: %s \n\n", date("y-m-d H:i:s"), $ret["message"], $pathLog));
}
return $tipoRetorno != 'XML' ? ResultToJSON($ret) : ResultToXml($ret);
}
$docApi['Alarme'] = MetodoApi(
"Disca para o n<EFBFBD>mero informado, <EFBFBD> necess<EFBFBD>io passar o Ramal de Origem",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de telefone/ramal a discar.'],
["ramal-1001", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de um ramal com permiss<EFBFBD>o para discagem, n<EFBFBD>o precisa estar registrado.']
]
);
function Alarme($numeroDiscar, $ramal)
{
$db = $GLOBALS['dbcon'];
$result = 1;
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
$_SESSION[AGT_RAMAL_CONF] = $ramal;
$_SESSION[API_CANAL_DISCAL] = GetDispositivoRamal($db, $ramal);
$msgSis = "";
if ($_SESSION[API_CANAL_DISCAL] == -1) {
$msgSis = "Ramal Inv<EFBFBD>lido!";
$result = false;
}
if (($result) && (GetUrl(AST_ALARME))) {
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado! N<EFBFBD>mero: %s Ramal: %s Canal: %s", $numeroDiscar, $ramal, $_SESSION[API_CANAL_DISCAL]);
$result = false;
}
$ret = array();
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['AlarmeFila'] = MetodoApi(
"Disca para um conjunto de ramais est<EFBFBD>ticos na fila",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero da fila.'],
["ramal-1001", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de um ramal com permiss<EFBFBD>o para discagem, n<EFBFBD>o precisa estar registrado.']
]
);
function AlarmeFila($numeroFila, $ramal)
{
$db = $GLOBALS['dbcon'];
$result = 1;
$_SESSION[AGT_RAMAL_CONF] = $ramal;
$_SESSION[API_CANAL_DISCAL] = GetDispositivoRamal($db, $ramal);
$msgSis = "";
if ($_SESSION[API_CANAL_DISCAL] == -1) {
$msgSis = "Ramal Inv<EFBFBD>lido!";
$result = false;
}
$resultFila = pg_query($db, "select id,nome from pbx_dacs where numero = '{$numeroFila}'");
$arFila = pg_fetch_array($resultFila, null, PGSQL_ASSOC);
$sql = "SELECT b.nome from pbx_queues_membros a, pbx_ramais b where a.dispositivo = b.dispositivo and a.id_fila = '{$arFila['id']}'";
$resultado = pg_query($db, $sql);
if (($result)) {
while ($numeroDiscar = pg_fetch_array($resultado, null, PGSQL_ASSOC)) {
$_SESSION[AGT_NUM_DISC] = $numeroDiscar['nome'];
GetUrl(AST_ALARME);
}
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado! "
. "N<EFBFBD>mero: %s Ramal: %s Canal: %s", $numeroDiscar['nome'], $ramal, $_SESSION[API_CANAL_DISCAL]);
$result = false;
}
$ret = array();
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['Callback'] = MetodoApi(
"Retorna para o n<EFBFBD>mero informado, <EFBFBD> necess<EFBFBD>rio passar o Ramal de Origem",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de telefone/ramal a discar.'],
["ramal-1001", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero do Ramal de Origem.'],
["destino-5000", "STRING", "REQUIRED", 'Destino para qual a liga<EFBFBD><EFBFBD>o vai ser enviada.']
]
);
function Callback($numeroDiscar, $ramal, $destino)
{
$db = $GLOBALS['dbcon'];
$result = 1;
$numeroDiscar = RemoveDddPadrao($numeroDiscar);
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
$_SESSION[AGT_RAMAL_CONF] = $ramal;
$_SESSION[API_CANAL_DISCAL] = $destino;
$msgSis = "";
if ($_SESSION[API_CANAL_DISCAL] == -1) {
$msgSis = "Ramal Inv<EFBFBD>lido!";
$result = false;
}
if (($result) && (GetUrl(AST_CALLBACK))) {
$msgSis = "Discagem realizada com sucesso!";
} else if (empty($msgSis)) {
$msgSis = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado! N<EFBFBD>mero: %s Ramal: %s Canal: %s", $numeroDiscar, $ramal, $_SESSION[API_CANAL_DISCAL]);
$result = false;
}
$ret = array();
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['LigueGratis'] = MetodoApi(
"Retorna para o n<EFBFBD>mero informado.",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de telefone com DDD.']
]
);
function LigueGratis($numeroDiscar)
{
try {
$log[] = 'LigueGratis';
/*
* Torna o numero discar disponivel;
*/
SetNumeroLigueGratis(RemoveDddPadrao($numeroDiscar));
if (!GetRamalLigueGratis()) {
GeraExcept("Dispositivo Inv<EFBFBD>lido!");
}
if (!GetAnuncioLigueGratis()) {
GeraExcept("Ligue gr<EFBFBD>tis inativo!");
}
if (!GetUrl(AST_LIGUE_GRATIS)) {
GeraExcept("O Ligue Gr<EFBFBD>tis n<EFBFBD>o conseguiu retornar! N<EFBFBD>mero: %s Dispositivo: %s Recurso: %s", GetNumeroLigueGratis(), GetRamalLigueGratis(), GetAnuncioLigueGratis());
}
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = 'Retorno Ligue Gratis realizado!';
// return ResultToXml(array("status" => 'ok', "resutl" => 'true', "message" => 'Retorno Ligue Gratis realizado!'));
} catch (Exception $exc) {
$log[] = $exc->getMessage();
//return ResultToXml(array("status" => 'ok', "resutl" => 'false', "message" => $exc->getMessage()));
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $exc->getMessage();
}
return ResultToXml($ret);
}
$docApi['Transferir'] = MetodoApi(
"Transfere a liga<EFBFBD><EFBFBD>o corrente para o n<EFBFBD>mero informado. $obsConectaAgente",
[
["numeroDiscar-36844900", "INTEIRO", "REQUIRED", 'N<EFBFBD>mero de telefone.']
]
);
function Transferir($numeroDiscar)
{
$db = $GLOBALS['dbcon'];
$msgSis = "N<EFBFBD>o foi poss<EFBFBD>vel transferir para o n<EFBFBD>mero informado!";
$matricula = GetMatriculaAgente();
$result = 0;
$_SESSION[AGT_NUM_DISC] = $numeroDiscar;
//atualiza dados do supervisor
$query = "select canal from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
if ($result)
$row = @pg_fetch_row($result);
if ($row[0])
$_SESSION[AGT_CHANNEL_TRANSF] = $row[0];
//if($result)
GetUrl(AST_SET_VAR);
$result = GetUrl(AST_TRANSFERIR);
if ($result) {
$query = "update pbx_supervisor_agentes
set status = 'LIVRE',
origem_destino = '',
duracao = now(),
canal = ''
where matricula = '$matricula'";
if ($result)
$result = pg_query($db, $query);
if ($result)
$msgSis = "Transfer<EFBFBD>ncia realizada com sucesso!";
}
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['Rediscar'] = MetodoApi(
"Indica que um contato dever<EFBFBD> ser incluido novamente na campanha para rediscagem!. $obsConectaAgente",
[
["identificador-id_cliente", "STRING", "REQUIRED", 'Identificador do Cliente no Sistema de Cobran<EFBFBD>a!']
]
);
function Rediscar($identificador)
{
$log = &$GLOBALS["log"];
$db = $GLOBALS['dbcon'];
$msgSis = "N<EFBFBD>o foi poss<EFBFBD>vel realizar a opera<EFBFBD><EFBFBD>o!";
$dac = GetIdDac();
$listId = 0;
$id = $identificador;
$result = 0;
//Recupera o id da lista ativar para campanha corrente
$query = "select max(list_id) as list_id from pbx_campanha_lista where cmp_id = '$dac' and list_status = 1 ";
$result = pg_query($db, $query);
$log[] = "$query \n Exec: " . ($result ? "ok" : "erro");
if ($result) {
$row = @pg_fetch_row($result);
$listId = $row[0];
//update pbx_campanha_contato set cont_discado = '0', cont_peso = '-10' where cont_id = '502274';
$query = "update pbx_campanha_contato set cont_discado = '0', cont_peso = '-10' where cmp_id = '$dac' and list_id = '$listId' and cont_identificador = '$id'";
//$query = "update pbx_campanha_contato set cont_rediscar = 9 where cmp_id = '$dac' and list_id = '$listId' and cont_identificador = '$id'";
$result = pg_query($db, $query);
$log[] = "$query \n Exec: " . ($result ? "ok" : "erro");
if ($result) {
$msgSis = "Opera<EFBFBD><EFBFBD>o realizada dom sucesso!";
}
}
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
$log[] = $msgSis;
return ResultToXml($ret);
}
$docApi['IntercalarAgente'] = MetodoApi(
"Permite interagir com agente durante o atendimento.",
[
["fila-atendimento", "STRING", "REQUIRED", 'Nome da fila em que o agente esta logado.'],
["matriculaAgente-1000", "STRING", "REQUIRED", 'Matricula do agente logado.'],
["ramalAgente-1001", "STRING", "REQUIRED", 'Ramal do agente logado.'],
["ramalIntercalar-1005", "STRING", "REQUIRED", 'Ramal usado para interagir durante o atendimento.']
]
);
function IntercalarAgente($fila, $matriculaAgente, $ramalAgente, $ramalIntercalar)
{
$dbcon = $GLOBALS['dbcon'];
$_SESSION[SS_DESTINO_INTERCALAR] = $ramalAgente;
$_SESSION[RAMAL_MONITOR_SUPERVISOR] = $ramalIntercalar;
$_SESSION[CANAL_MONITOR_SUPERVISOR] = GetRamalSip($dbcon, $ramalIntercalar);
$matricula = $matriculaAgente;
$dac = $fila;
$idSessao = "SSinter_" . $matricula;
$monitorar = $_SESSION[$idSessao];
$query = "update pbx_supervisor_agentes
set intercalar = '{Status}'
where matricula = '$matricula'";
if (!$monitorar) {
if (GetUrl(AST_INTERCALAR, $dac, $matricula)) {
$query = str_replace("{Status}", "1", $query);
$result = pg_query($dbcon, $query);
if ($result)
$result = pg_affected_rows($result);
if ($result)
$_SESSION[$idSessao] = 1;
if ($result) {
$msgSis = '"Intercala<EFBFBD><EFBFBD>o Iniciada"';
} else {
$msgSis = 'Erro ao acessar base de dados ao "Iniciar a Intercala<EFBFBD><EFBFBD>o"';
}
} else {
$msgSis = 'A central reportou erro ao "Iniciar a Intercala<EFBFBD><EFBFBD>o"!';
}
} else {
$result = false;
$msgSis = 'Intercala<EFBFBD><EFBFBD>o em Andamento!';
}
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "true";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "OK";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
$log[] = $msgSis;
return ResultToXml($ret);
}
$docApi['GetAudio'] = MetodoApi(
"Permite recuperar o <EFBFBD>udio de um atendimento.",
[
["uniqueid-123456666.555", "STRING", "REQUIRED", 'Identificador da chamada retornada por InformacoesAtendimento. Obs.: Retorna o arquivo ou mensagem em xml!'],
["tipo-wav", "STRING", false, 'O formato desejado para o <EFBFBD>udio. O valor padr<EFBFBD>o <EFBFBD> wav. Tipos suportados: [wav, mp3]']
],
'json/stream'
);
function GetAudio($uniqueid, $tipo)
{
$tipoRetorno = $_REQUEST['tipoRetorno'];
try {
$dbcon = $GLOBALS['dbcon'];
$query = "select userfield as file, (select prm_path_audio from pbx_parametros limit 1) as path_audio "
. "from pbx_bilhetes a where uniqueid = '$uniqueid' and trim(coalesce(userfield, '')) <> '' and lastapp <> 'Transferred Call'";
$result = pg_query($dbcon, $query);
if (!$result)
throw new Exception('Erro ao consultar informa<EFBFBD><EFBFBD>es no servidor!');
$dados = pg_fetch_array($result);
$file = $dados["file"];
$filepath = VerificaCharFinal($dados["path_audio"]) . $dados["file"];
if (!file_get_contents($filepath))
throw new Exception('Arquivo n<EFBFBD>o encontrado!');
DownloadAudio($file, $filepath, $tipo);
} catch (Exception $ex) {
$ret["status"] = "erro";
$ret["result"] = "erro";
$ret["message"] = RemoveAcentos($ex->getMessage());
return $tipoRetorno != 'XML' ? ResultToJSON($ret) : ResultToXml($ret);
}
}
$docApi['MonitorRamais'] = MetodoApi(
"Lista os ramais o seus respctivos status.",
[
["filtro-2", "INTEGER", "REQUIRED", 'Filtro por Status 0-Inativos 1-Ativos 2-Ambos']
]
);
function MonitorRamais($filtro = 2)
{
try {
define("RAMAL_OFF", 0);
define("RAMAL_ON", 1);
define("RAMAL_TODOS", 2);
$dbcon = $GLOBALS['dbcon'];
$NomeRamais = array();
$NomeRamais = GetRamaisNome();
list($sckHost, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$socket = ConectaAmi($sckHost, $sckPort, $sckUser, $sckPass);
if (!$socket)
throw new Exception("N<EFBFBD>o possivel conectar ao Manager!");
$actionid = rand(000000000, 9999999999);
fwrite($socket, "action: sippeers\r\n");
fwrite($socket, "ActionID: " . $actionid . "\r\n\r\n");
$start = 0;
$ramais = array();
while (!feof($socket)) {
$buffer = fgets($socket);
list($param, $value) = explode(':', $buffer);
$param = trim($param);
$value = trim($value);
/*
* Paramaetros usados na an<EFBFBD>lise.
*/
$paramsValid = array('ObjectName', 'IPaddress', 'Status');
/*
* Indica o come<EFBFBD>o de um bloco retornado.
*/
if (!$start)
$start = ($param == "Event") && ($value == "PeerEntry");
/*
* Le o bloco ate encotrar o final.
*/
if ($start && (array_search($param, $paramsValid) !== false)) {
$ramal[$param] = AnalisaParams($param, $value, $ramal);
}
if ($param == "RealtimeDevice") {
$ip = soNumero($ramal['IPaddress']);
if ((($filtro == RAMAL_TODOS) || ((int) $filtro == (int) $ramal['Status'])) && ($ip !== "127001")) {
$ramal['Name'] = isset($NomeRamais[$ramal["ObjectName"]]) ? $NomeRamais[$ramal["ObjectName"]] : $ramal["ObjectName"];
if ($ramal['Status'] == RAMAL_OFF) {
$ramal['IPaddress'] = 'N<EFBFBD>O REGISTRADO';
}
//$ramais[$ramal["ObjectName"]] = $ramal;
$ramais[] = $ramal;
}
$start = false;
}
/*
* Garante que o socket n<EFBFBD>o vai procurar para sempre
*/
if (trim($value) == "PeerlistComplete") {
break;
}
if ($buffer === false) {
break;
}
}
return ArrToXml($ramais);
} catch (Exception $ex) {
$log[] = $query;
$log[] = $ex->getMessage();
return GetErro("InformacoesAtendimento", $ex);
}
}
$docApi['MonitoraRamal'] = MetodoApi(
"Lista os ramais o seus respctivos status.",
[
["ramal-2512", "INTEGER", "REQUIRED", 'Ramal a ser monitorado.']
],
'xml/stream'
);
function MonitoraRamal($ramal)
{
try {
/*
* Verifica se o ramal esta conectao a uma fila se afirmativo
* retorna as informa<EFBFBD><EFBFBD>es a partir da fila.
*/
$dbcon = $GLOBALS['dbcon'];
$ramais = InfoRamalFila($dbcon, $ramal);
if ($ramais !== false) {
return ResultToXml($ramais);
}
/*
* Retrona informa<EFBFBD><EFBFBD>es do ramal a partir do manager.
*/
list($sckHost, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$socket = ConectaAmi($sckHost, $sckPort, $sckUser, $sckPass);
if (!$socket)
throw new Exception("N<EFBFBD>o possivel conectar ao Manager!");
$ramais = InfoRamalAmi($socket, $ramal);
return ResultToXml($ramais);
} catch (Exception $ex) {
$log[] = $query;
$log[] = $ex->getMessage();
return GetErro("MonitoraRamal", $ex);
}
}
function InfoRamalFila($dbcon, $ramal)
{
$query = "select tipo_ligacao as direcao, status, substring((now() - duracao)::text, 1, 8) as duracao, sonumero(origem_destino) as numero from pbx_supervisor_agentes where ramal = '$ramal'";
$result = pg_query($dbcon, $query);
if (!$result || !pg_num_rows($result)) {
return false;
}
$ramais = pg_fetch_array($result, null, PGSQL_ASSOC);
return $ramais;
}
$docApi['EnviaSMS'] = MetodoApi(
"Envia SMS.",
[
["TroncoSainte-b0c5", "TEXTO", "REQUIRED", 'Tronco de sa<EFBFBD>da.'],
["NumeroDestino-65999893984", "INTEGER", "REQUIRED", 'N<EFBFBD>mero do destino.'],
["Texto-Envia teste de sms", "TEXTO", "REQUIRED", 'Mensagem a ser enviada.'],
["login-login", "TEXTO", "REQUIRED", 'Login.'],
["senha-1234", "TEXTO", "REQUIRED", 'Senha.']
],
'xml/stream'
);
function EnviaSMS($troncoSainte, $numeroDestino, $texto)
{
$db = $GLOBALS['dbcon'];
$result = 1;
$_SESSION[AGT_NUM_DISC] = $numeroDestino;
$_SESSION[API_CANAL_DISCAL] = $troncoSainte;
$_SESSION["SStexto"] = utf8_decode($texto);
$GLOBALS["SSrand"] = "";
$msgSis = "";
$ret = array();
if (GetUrl(AST_SMS_SEND)) {
$sms = $GLOBALS["SSrand"];
$query = "select sms_sip_id, sms_tronco_envio, sms_destino, sms_mensagem, "
. "sms_status, sms_cod_erro, sms_nome_erro, "
. "sms_id_envio, sms_data_envio::date as sms_data_envio, sms_data_envio::time as sms_hora_envio "
. "from pbx_sms_send "
. "where sms_sip_id = '$sms'";
$result = pg_query($db, $query);
if (pg_num_rows($result)) {
$dados = pg_fetch_array($result);
$ret['sms_sip_id'] = $dados['sms_sip_id'];
$ret['sms_tronco_envio'] = $dados['sms_tronco_envio'];
$ret['sms_destino'] = $dados['sms_destino'];
$ret['sms_mensagem'] = $dados['sms_mensagem'];
$ret['sms_status'] = $dados['sms_status'];
$ret['sms_cod_erro'] = $dados['sms_cod_erro'];
$ret['sms_nome_erro'] = $dados['sms_nome_erro'];
$ret['sms_id_envio'] = $dados['sms_id_envio'];
$ret['sms_data_envio'] = $dados['sms_data_envio'];
$ret['sms_hora_envio'] = $dados['sms_hora_envio'];
$msgSis = "Fun<EFBFBD><EFBFBD>o executada com sucesso!";
} else {
$result = false;
$msgSis = "Fun<EFBFBD><EFBFBD>o executada com sucesso!";
}
} else {
$msgSis = sprintf("N<EFBFBD>o foi poss<EFBFBD>vel executar a fun<EFBFBD><EFBFBD>o!");
$result = false;
}
if ($result) {
$ret["status"] = "OK";
$ret["result"] = "OK";
$ret["message"] = $msgSis;
} else {
$ret["status"] = "false";
$ret["result"] = "false";
$ret["message"] = $msgSis;
}
return ResultToXml($ret);
}
$docApi['GerenciaAgenda'] = MetodoApi(
"Permite o gerenciamento da agenda do SimplesIP.",
[
["telefone-36168280", "INTEGER", "REQUIRED", 'Telefone/Ramal do contato'],
["acao-BUSCAR", "STRING", "REQUIRED", 'Acao a ser desempenhada pela API. As opera<EFBFBD><EFBFBD>es padr<EFBFBD>o s<EFBFBD>o: BUSCAR, INSERIR, EDITAR, EXCLUIR'],
["identificacao-user", "STRING", "REQUIRED", 'Nome/Empresa do contato.'],
["DDD-65", "STRING", "REQUIRED", 'DDD da localiza<EFBFBD><EFBFBD>o do contato.'],
["teloriginal-36168280", "STRING", false, 'Telefone original do contato. Somente utilizado na a<EFBFBD><EFBFBD>o EDITAR.'],
["departamento-simplesip", "STRING", false, 'Indica qual departamento o usu<EFBFBD>rio ser<EFBFBD> inserido. Somente utilizado na a<EFBFBD><EFBFBD>o INSERIR.']
],
'text/xml || text/json'
);
function GerenciaAgenda($telefone, $acao, $identificacao, $ddd, $telOrig = '', $departamento = '')
{ // Adicionar o Tipo de retorno JSON ou XML
$ddd = GetDddPadrao();
$telefone = isset($telefone) ? $telefone : '';
$identificacao = isset($identificacao) ? RemoveAcentos($identificacao) : '';
$departamento = isset($departamento) ? $departamento : '';
$action = strtoupper($acao);
$dbcon = $GLOBALS['dbcon'];
$tipoRetorno = $_REQUEST['tipoRetorno'];
try {
if ($action == 'BUSCAR') {
$complemento = sprintf("and (a.nome::text ilike '%s' or a.callerid::text ilike '%s')", PreparaLike($telefone), PreparaLike($identificacao));
$query = "SELECT a.id, coalesce(c.dpto_nome, 'PADR<EFBFBD>O') as dpto_nome,
a.nome, a.callerid, a.tipo_table
FROM pbx_ramais_mesa a
left join rma_depto_ramais b ON b.nome = a.nome
left join rma_departamentos c ON c.dpto_id = b.dpto_id
where 1=1 $complemento
ORDER BY a.nome ASC";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("ERRO! - Nenhum registro encontrado!");
}
return $tipoRetorno == 'XML' || empty($tipoRetorno) ? BdToXml($result) : ArrToJSON($result);
}
$numMaxLinhas = 0;
$numLinhasArquivo = 1;
$codigoOper = 0;
$start = 0;
while (!feof($arq)) {
$linha = trim(fgets($arq));
if (!$linha)
continue;
$params = explode(";", $linha);
/*
* VERIFICA SE JA POSSUI ALGUM RAMAL CADASTRADO
*/
if (!$start++) {
list(, $nomeCampanha, $nomeLista, $dac, $label, $ramal, $qtLiga, $aguardaChamada) = $params;
if ($codigoOper !== 1) {
throw new Exception("C<EFBFBD>digo de opera<EFBFBD><EFBFBD>o inv<EFBFBD>lido! Linha: $numLinhasArquivo.");
}
/*
* VERIFICA SE REGISTROS FORAM INSERIDOS
*/
$busca = "SELECT rma_telefone,rma_nome FROM pbx_ramais_agenda "
. "WHERE rma_telefone='$telefone' AND rma_nome='$identificacao' AND ddd='$ddd'";
$result = pg_query($dbcon, $busca);
if (pg_num_rows($result) >= 1) {
$dept = "SELECT dpto_id, dpto_nome FROM rma_departamentos WHERE dpto_nome = '$departamento'";
$result = pg_query($dbcon, $dept);
$retorno = pg_fetch_array($result, null, PGSQL_ASSOC);
if ($retorno) {
/*
* RELACIONA REGISTRO COM O DEPARTAMENTO
*/
$insert = sprintf("INSERT INTO rma_depto_ramais (nome,dpto_id) VALUES ('%s','%s')", $telefone, $retorno['dpto_id']);
$query = pg_query($dbcon, $insert);
}
} else {
throw new Exception("Erro ao inserir Telefone!");
}
}
$ret["message"] = "Cadastro realizado com sucesso!";
return $tipoRetorno == 'XML' || empty($tipoRetorno) ? ResultToXml($ret) : ResultJSON($ret);
}
if ($action == 'EDITAR') {
$query = "SELECT rma_telefone FROM pbx_ramais_agenda WHERE rma_telefone = '$telefone'";
$result = pg_query($dbcon, $query);
if (pg_num_rows($result) >= 1) {
throw new Exception("Telefone j<EFBFBD> esta cadastrado!");
} else {
$query = "SELECT rma_telefone FROM pbx_ramais_agenda WHERE rma_telefone = '$telOrig'";
$result = pg_query($dbcon, $query);
if (!pg_num_rows($result)) {
throw new Exception('Nenhum registro encontrado!');
}
$result = pg_query($dbcon, 'begin');
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar a opera<EFBFBD><EFBFBD>o!");
}
if (empty($identificacao)) {
$query = "UPDATE pbx_ramais_agenda SET rma_telefone = '$telefone' WHERE rma_telefone = '$telOrig'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel editar o \"Ramal\" Selecionado");
}
} else {
$query = "update pbx_ramais_agenda set (rma_telefone, rma_nome) = ('$telefone','$identificacao') where rma_telefone = '$telOrig'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel editar o \"Ramal\" Selecionado");
}
}
$query = "UPDATE rma_depto_ramais SET nome = '$telefone' WHERE nome = '$telOrig'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel editar o \"Ramal\" Selecionado");
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel finalizar a opera<EFBFBD><EFBFBD>o!");
}
}
$ret['message'] = '"Ramal" editado com sucesso!';
return $tipoRetorno == 'XML' || empty($tipoRetorno) ? ResultToXml($ret) : ResultToJSON($ret);
}
if ($action == 'EXCLUIR') {
$query = "SELECT rma_telefone FROM pbx_ramais_agenda WHERE rma_telefone='$telefone' ";
$result = pg_query($dbcon, $query);
if (!pg_num_rows($result)) {
throw new Exception('Ramal Inv<EFBFBD>lido, n<EFBFBD>o foi poss<EFBFBD>vel excluir o registro!');
}
$result = pg_query($dbcon, 'begin');
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel iniciar a opera<EFBFBD><EFBFBD>o!');
}
$deleta = "DELETE FROM pbx_ramais_agenda WHERE rma_telefone='$telefone'";
$result = pg_query($dbcon, $deleta);
if (!$result) {
pg_query($dbcon, 'rollback');
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel excluir o "Ramal" selecionado!');
}
$deleta = "DELETE FROM rma_depto_ramais WHERE nome='$telefone'";
$result = pg_query($dbcon, $deleta);
if (!$result) {
pg_query($dbcon, 'rollback');
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel remover as depend<EFBFBD>ncias do "Ramal" selecionado!');
}
$result = pg_query($dbcon, 'commit');
if (!$result) {
pg_query($dbcon, 'rollback');
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel finalizar a opera<EFBFBD><EFBFBD>o!');
}
$ret['message'] = 'O "Ramal" foi excluido com sucesso!';
return $tipoRetorno == 'XML' || empty($tipoRetorno) ? ResultToXml($ret) : ResultJSON($ret);
}
} catch (Exception $ex) {
$ex->getMessage();
return GetErro('GerenciaAgenda', $ex, 0, $tipoRetorno);
}
}
$docApi['EnviarDadosCampanha'] = MetodoApi(
"Recebe arquivo com informa<EFBFBD><EFBFBD>es de Campanha para discagem autom<EFBFBD>tica.",
[
["org_id", "STRING", "REQUIRED", "Identifica<EFBFBD><EFBFBD>o (ID) da organiza<EFBFBD><EFBFBD>o."],
["arquivoCampanha-file", "FILE", "REQUIRED", "Arquivo de Campanha. Cont<EFBFBD>m informa<EFBFBD><EFBFBD>es da campanha e lista para discagem. " . GetLinkFile("", "pdf16.png", "layouteBaseDiscador.pdf", "Layout do Arquivo de Campanha!")]
]
);
function EnviarDadosCampanha()
{
try {
global $dbcon;
$inTran = 0;
$labelParams = array();
$org_id = $_POST['org_id'];
if (empty($org_id)) {
throw new Exception('Informe a identifica<EFBFBD><EFBFBD>o da organiza<EFBFBD><EFBFBD>o "org_id"!');
}
if (!isset($_FILES['arquivoCampanha']['name']) || empty($_FILES['arquivoCampanha']['name'])) {
throw new Exception('Para esta opera<EFBFBD><EFBFBD>o <EFBFBD> necess<EFBFBD>rio informar um "Arquivo de Campanha!"');
}
$tmpFileName = $_FILES['arquivoCampanha']['tmp_name'];
$arq = fopen($tmpFileName, 'rt');
if ($arq === false) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel ler o "Arquivo de Campanha!"');
}
$numMaxLinhas = 0;
$numLinhasArquivo = 1;
$codigoOper = 0;
$start = 0;
while (!feof($arq)) {
$linha = trim(fgets($arq));
if (!$linha) {
continue;
}
$params = explode(";", $linha);
/*
* Verifica o c<EFBFBD>digo da opera<EFBFBD><EFBFBD>o.
*/
if (!is_numeric($params[0])) {
throw new Exception("C<EFBFBD>digo de opera<EFBFBD><EFBFBD>o inv<EFBFBD>lido! Linha: $numLinhasArquivo.");
}
$codigoOper = (int) $params[0];
/*
* Verifica a campanha
*/
if (!$start++) {
list(, $nomeCampanha, $nomeLista, $dac, $label, $ramal, $qtLiga, $aguardaChamada) = $params;
if ($codigoOper !== 1) {
throw new Exception("C<EFBFBD>digo de opera<EFBFBD><EFBFBD>o inv<EFBFBD>lido! Linha: $numLinhasArquivo.");
}
/*
* Entrada para o discador ligth.
*/
$ramal = -1;
if ($label) {
$labelParams = explode('|', $label);
}
if (!$nomeCampanha) {
throw new Exception('Informe um "Nome para Campanha"!');
}
if (!$nomeLista) {
throw new Exception('Informe um "Nome para Lista"!');
}
if (!$dac) {
throw new Exception('Informe o "C<EFBFBD>digo do Dac"!');
}
if (!$ramal) {
throw new Exception('Informe um "Ramal para Campanha"');
}
if (!$qtLiga) {
$qtLiga = 1;
}
if (!$aguardaChamada) {
$aguardaChamada = 1;
}
if (!VerificaDac($dbcon, $dac)) {
throw new Exception("N<EFBFBD>mero do Dac <EFBFBD> inv<EFBFBD>lido!");
}
if (VerificaCampanhaLista($dbcon, $nomeLista)) {
throw new Exception("Lista j<EFBFBD> inserida!");
}
$user = GetLoginApi();
$existeCampanha = VerificaCampanha($dbcon, $nomeCampanha);
if (CampanhaAtiva($dbcon, $existeCampanha)) {
throw new Exception("Para inserir uma nova \"Lista\" a \"Campanha\" n<EFBFBD>o pode estar \"Ativa\"!");
}
$filePathDest = sprintf("lista_%s_%s_%s.csv", $nomeCampanha, $nomeLista, date('YmdHis'));
if ($existeCampanha == false) {
$idProc = sprintf("Inserido: %s Data: %s|", $user, date('Y-m-d H:i:s'));
$query = "INSERT INTO pbx_campanha(cmp_descricao, cmp_ramal, id_dac, cmp_aguarda_agente, cmp_numero_ligacoes_agente, ident_proc, cmp_status, org_id)
VALUES(%s,%s,%s,%s,%s,%s, '2', $org_id);";
$query = sprintf($query, QuotedStr($nomeCampanha), QuotedStr($ramal), QuotedStr($dac), QuotedStr($aguardaChamada), QuotedStr($qtLiga), QuotedStr($idProc));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar a "Campanha"!');
}
$existeCampanha = VerificaCampanha($dbcon, $nomeCampanha);
if ($existeCampanha == false) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar a "Campanha"!');
}
} else {
PendenciasDiscador($dbcon, $existeCampanha);
DesativaLista($dbcon, $existeCampanha);
$idProc = sprintf("Ult. Alt: %s Data: %s|", $user, date('Y-m-d H:i:s'));
$query = "UPDATE pbx_campanha
SET cmp_ramal = %s,
id_dac = %s,
cmp_aguarda_agente = %s,
cmp_numero_ligacoes_agente = %s,
ident_proc = coalesce(ident_proc) || %s,
cmp_status = '2'
WHERE cmp_id = %s ;";
$query = sprintf($query, QuotedStr($ramal), QuotedStr($dac), QuotedStr($aguardaChamada), QuotedStr($qtLiga), QuotedStr($idProc), QuotedStr($existeCampanha));
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel alterar a "Campanha"!');
}
}
$query = "INSERT INTO pbx_campanha_lista(cmp_id, list_nome, list_file, org_id) VALUES(%s,%s,%s,%s);";
$query = sprintf($query, QuotedStr($existeCampanha), QuotedStr($nomeLista), QuotedStr($filePathDest), $org_id);
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar a "Lista"!');
}
$listId = VerificaCampanhaLista($dbcon, $nomeLista);
/*
* Se passado grava o label se nao atribuiu default;
*/
if (!count($labelParams)) {
$labelParams = array('-', '-', '-', '-', '-');
}
$dispParam = array('null', 'null', 'null', 'null', 'null');
foreach ($labelParams as $key => $value) {
$dispParam[$key] = QuotedStr(substr($value, 0, 20));
}
$query = "INSERT INTO pbx_campanha_contato_display(cmp_id, list_id, disp_param1, disp_param2, disp_param3, disp_param4, disp_param5, org_id)
VALUES(%s, %s, %s, %s, %s, %s, %s, %s);";
$query = sprintf($query, QuotedStr($existeCampanha), QuotedStr($listId), $dispParam[0], $dispParam[1], $dispParam[2], $dispParam[3], $dispParam[4], $org_id);
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar os "Labels"!');
}
}
if ($codigoOper == 2) {
try {
$paramsCliente = array('null', 'null', 'null', 'null', 'null');
list(, $codCliente, $paramsClienteLista, $fones) = $params;
if ($paramsClienteLista) {
$paramsClienteLista = str_replace('#', '', $paramsClienteLista);
$paramsClienteLista = explode("|", $paramsClienteLista);
foreach ($paramsClienteLista as $key => $value) {
$paramsCliente[$key] = QuotedStr(substr($value, 0, 60));
}
}
$codCliente = substr($codCliente, 0, 200);
$query = "INSERT INTO pbx_campanha_contato(cmp_id, list_id, cont_identificador, cont_param1, cont_param2, cont_param3, cont_param4, cont_param5, cont_status, org_id)
VALUES(%s,%s,%s,%s,%s,%s,%s,%s,'0',%s);";
$query = sprintf($query, QuotedStr($existeCampanha), QuotedStr($listId), QuotedStr($codCliente), $paramsCliente[0], $paramsCliente[1], $paramsCliente[2], $paramsCliente[3], $paramsCliente[4], $org_id);
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar o "Contato"! Linha: ' . $numLinhasArquivo);
}
$idContato = GetContatoFone($dbcon, $existeCampanha, $listId, $codCliente);
if (!$idContato) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel criar o "Contato"! Linha: ' . $numLinhasArquivo);
}
$listaFones = explode("|", $fones);
if (!count($listaFones)) {
throw new Exception('"Lista de Telefones" inv<EFBFBD>lida! Linha: ' . $numLinhasArquivo);
}
foreach ($listaFones as $telefone) {
if (!$telefone) {
continue;
}
if (!is_numeric($telefone)) {
throw new Exception('Telefone inv<EFBFBD>lido, use apenas n<EFBFBD>meros! Linha: ' . $numLinhasArquivo);
}
if (!VerificaFoneContato($idContato, $telefone)) {
$query = "INSERT INTO pbx_campanha_contato_fone(cmp_id, list_id, cont_id, conf_fone, org_id) VALUES(%s, %s, %s, %s, %s);";
$query = sprintf($query, QuotedStr($existeCampanha), QuotedStr($listId), QuotedStr($idContato), QuotedStr($telefone), $org_id);
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception('N<EFBFBD>o foi poss<EFBFBD>vel gravar o "Telefone: ' . $telefone . ' "! Linha: ' . $numLinhasArquivo);
}
}
}
} catch (Exception $ex) {
WriteLog(sprintf("[%s] Linha: %s Msg: %s", date('Y-m-d H:i:s'), $numLinhasArquivo, $ex->getMessage()), '/var/log/asterisk/envia_dados_campanha.log');
WriteLog(sprintf("[%s] Linha: %s BD: %s", date('Y-m-d H:i:s'), $numLinhasArquivo, pg_last_error()), '/var/log/asterisk/envia_dados_campanha.log');
WriteLog(sprintf("[%s] Linha: %s Cmd: %s", date('Y-m-d H:i:s'), $numLinhasArquivo, $query), '/var/log/asterisk/envia_dados_campanha.log');
}
}
/*
* Garante que n<EFBFBD>o tenha lista com mais de MAX_LINHAS_FILE_CAMPANHA linhas.
*/
if (($codigoOper == 2) && (++$numMaxLinhas >= MAX_LINHAS_FILE_CAMPANHA)) {
break;
}
if (++$numLinhasArquivo >= (MAX_LINHAS_FILE_CAMPANHA + 10)) {
break;
}
}
$nomeArq = strtolower($tmpFileName);
$nomeArq = ($nomeArq);
$pathFile = 'arquivoCampanha/' . $filePathDest;
$tmpFileName = $_FILES['arquivoCampanha']['tmp_name'];
@move_uploaded_file($tmpFileName, $pathFile);
/*
* Apaga registros de contato sem telefone.
*/
$query = "DELETE FROM pbx_campanha_contato a WHERE not exists(select '' from pbx_campanha_contato_fone where cont_id = a.cont_id)";
pg_query($dbcon, $query);
$ret["status"] = "ok";
$ret["result"] = "true";
$ret["id_campanha"] = $existeCampanha;
$ret["nome_campanha"] = $nomeCampanha;
$ret["id_lista"] = $listId;
$ret["nome_lista"] = $nomeLista;
$ret["message"] = "Arquivo processado com sucesso";
} catch (Exception $ex) {
WriteLog(sprintf("Linha: %s Final: %s \n", $numLinhasArquivo, $ex->getMessage()), '/var/log/asterisk/envia_dados_campanha.log');
/*
* Mantem integridade das tabelas
*/
$query = "DELETE FROM pbx_campanha_contato a WHERE not exists(SELECT '' FROM pbx_campanha_contato_fone WHERE cont_id = a.cont_id);\n";
$query .= "DELETE FROM pbx_campanha_contato_display a WHERE not exists(SELECT '' FROM pbx_campanha_contato WHERE list_id = a.list_id);\n";
$query .= "DELETE FROM pbx_campanha_lista a WHERE not exists(SELECT '' FROM pbx_campanha_contato WHERE list_id = a.list_id);\n";
$query .= "DELETE FROM pbx_campanha a WHERE not exists(SELECT '' FROM pbx_campanha_lista WHERE cmp_id = a.cmp_id);\n";
pg_query($dbcon, $query);
//echo GetErro("EnviarDadosCampanha", "$ex");
$ret["status"] = "erro";
$ret["result"] = "false";
$ret["message"] = $ex->getMessage();
}
return ResultToXml($ret);
}
$docApi['InfoChamadaAlgar'] = MetodoApi(
"Apresenta informa<EFBFBD><EFBFBD>es de uma chamda atrav<EFBFBD>s do protocolo Algar",
[
["ProtocoloAlgar-7645272", "STRING", "REQUIRED", "Protocolo de chamada Algar Telecom"]
],
'text/json'
);
function InfoChamadaAlgar($protocoloAlgar)
{
$dbcon = $GLOBALS['dbcon'];
try {
$sql = "SELECT d.vdr_nome AS \"Nome_Vendedor\", a.emp_nome_fantasia AS \"Fantasia\",a.emp_cnpj as cnpj,c.chm_fila, c.chm_src AS \"Origem\", c.chm_dst AS \"Destino\",
b.uid, b.prt_proto_parceiro AS \"Protocolo_Algar\", c.chm_data_bilhete AS \"Data\",
c.chm_calldate::time AS \"Hora\",(c.chm_billsec * INTERVAL '1SECOND') AS \"Tempo_Conversacao\", a.emp_diretorio_ftp as diretorio_audio, b.prt_proto_parceiro, a.emp_id
FROM vds_protcolos b
INNER JOIN vds_empresas a ON a.emp_id = b.emp_id
INNER JOIN vds_chamadas c ON b.emp_id = c.emp_id AND c.uid = b.uid
INNER JOIN vds_vendedores d ON d.vdr_matricula = c.chm_matricula AND d.emp_id = c.emp_id
WHERE b.prt_proto_parceiro = '{$protocoloAlgar}' ";
$result = pg_query($dbcon, $sql);
$numRows = pg_num_rows($result);
if (!$numRows) {
GeraExcept("O protocolo informado: {$protocoloAlgar} nao foi encontrado na base de dados!");
}
while ($infoChamada = pg_fetch_assoc($result)) {
$fileSize = 0;
$dataAudio = date('Y/m/d', strtotime($infoChamada['Data']));
$file = sprintf("%s_%s.WAV", $infoChamada['prt_proto_parceiro'], $infoChamada['uid']);
$filepath = sprintf('/hdaux/ftp/algar/audios/%s/%s/%s', $infoChamada['diretorio_audio'], $dataAudio, $file);
$fileExist = CnvrtFileExists($filepath);
if ($fileExist) {
$fileSize = CnvrtFileSize($filepath);
}
$query = "select clas_descricao, clas_descricao_item as clas from vds_classificacoes where uid = '{$infoChamada['uid']}' and emp_id = '{$infoChamada['emp_id']}'";
$resClass = pg_query($dbcon, $query);
$resClass = pg_fetch_all($resClass);
$infoArq[] = array(
"id_audio" => sprintf("%s_%s", $infoChamada['prt_proto_parceiro'], $infoChamada['uid']),
"nome_vendedor" => mb_convert_encoding($infoChamada['Nome_Vendedor'], 'UTF-8'),
"nome_empresa" => trim($infoChamada['Fantasia']),
"CNPJ" => $infoChamada['cnpj'],
"fila" => $infoChamada['chm_fila'],
"origem" => $infoChamada['Origem'],
"destino" => $infoChamada['Destino'],
"uniqueid" => $infoChamada['uid'],
"protocolo_algar" => $infoChamada['Protocolo_Algar'],
// "classificacao" => (!$resClass ? [] : $resClass),
"classifica_descricao" => '',
"classifica_descricao_item" => '',
"data" => $infoChamada['Data'],
"hora" => $infoChamada['Hora'],
"tempo_conversacao" => $infoChamada['Tempo_Conversacao'],
"arquivo_nome" => $file,
"arquivo_disponivel" => ($fileExist ? 'sim' : 'nao'),
"arquivo_tamanho" => $fileSize
);
}
$ret['status'] = "Sucesso";
$ret['result'] = "true";
$ret['num_rows'] = $numRows;
$ret['rows'] = $infoArq;
return ResultJSON($ret);
} catch (Exception $ex) {
$ret['status'] = "Erro";
$ret['result'] = "false";
$ret['num_rows'] = 0;
$ret['rows'] = array();
$ret['mensagem'] = $ex->getMessage();
return ResultJSON($ret);
}
}
$docApi['RecebeAudioAlgar'] = MetodoApi(
"Passe o identificador recebido pela API InfoChamadaAlgar ou o Protocolo Algar para receber todos os <EFBFBD>udios em um arquivo zip.",
[
["idAudio-7645272", "STRING", "REQUIRED", "Identificador do <EFBFBD>udio no sistema."]
],
'json/stream'
);
function RecebeAudioAlgar($idAudio)
{
$dbcon = $GLOBALS['dbcon'];
$isProto = false;
try {
if (ValidaProtocoloAlgar($idAudio, true)) {
$isProto = true;
} else {
list($idAudio, $uid) = explode("_", $idAudio);
}
$sql = "SELECT a.emp_id, a.emp_nome_fantasia AS empresa,b.uid, b.prt_proto_parceiro AS protocolo_algar,
c.chm_calldate::date AS data,c.chm_calldate::time AS hora, c.chm_userfield AS audio_chamada, a.emp_diretorio_ftp AS diretorio_audio, a.emp_vpn
FROM vds_protcolos b
INNER JOIN vds_empresas a ON a.emp_id = b.emp_id
INNER JOIN vds_chamadas c ON b.emp_id = c.emp_id AND c.uid = b.uid
WHERE b.prt_proto_parceiro = '{$idAudio}' ";
if (!$isProto) {
$sql .= "and b.uid = '{$uid}' ";
}
$result = pg_query($dbcon, $sql);
if (!$result) {
GeraExcept("Erro ao consultar dados!");
}
$numRows = pg_num_rows($result);
if (!$numRows) {
GeraExcept("Registro nao encontrado na base de dados!");
}
while ($audio = pg_fetch_array($result, null, PGSQL_ASSOC)) {
/*
* informacoes do audio coletados do banco
*/
$dataAudio = date('Y/m/d', strtotime($audio['data']));
$file = sprintf("%s_%s.WAV", $audio['protocolo_algar'], $audio['uid']);
$filepath = sprintf('/hdaux/ftp/algar/audios/%s/%s/%s', $audio['diretorio_audio'], $dataAudio, $file);
if (!CnvrtFileExists($filepath)) {
GeraExcept('Arquivo nao encontrado!');
}
$files[$file] = $filepath;
}
/*
* Retorno com o audio convertido.
*/
DownloadAudioAlgar($files);
} catch (Exception $ex) {
$ret['status'] = "Erro";
$ret['result'] = "false";
$ret['mensagem'] = $ex->getMessage();
return ResultToJSON($ret);
}
}
$docApi['ListaNaoPerturbe'] = MetodoApi(
"Retorna com os n<EFBFBD>meros a serem incluidos no N<EFBFBD>o Perturbe Anatel.",
[
["info-1", "INTEIRO", "REQUIRED", "Informe 1 para obterinforma<EFBFBD><EFBFBD>es do arquivo e 0 para download."],
["id-1", "INTEIRO", "REQUIRED", "Quando \"info = 1\" passe o c<EFBFBD>digo do cliente(emp_id), quando \"info = 0\" passe o id do arquivo(np_id)."]
],
'json/stream'
);
function ListaNaoPerturbe($info, $id)
{
$dbcon = $GLOBALS['dbcon'];
try {
if ($info) {
$query = "select case when(np_id_cli < np_id_atu)then np_id_atu else 0 end as np_id,
(select np_path from pbx_nao_perturbe_controle where np_id = atualiza.np_id_atu) as np_path,
(select np_md5 from pbx_nao_perturbe_controle where np_id = atualiza.np_id_atu) as np_md5
from (
select coalesce(max(a.np_id), 0) as np_id_cli, (select max(np_id) from pbx_nao_perturbe_controle) as np_id_atu
from pbx_nao_perturbe_cliente a, pbx_nao_perturbe_controle b
where b.np_id = a.np_id
and a.emp_id = '{$id}'
) as atualiza";
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel consultar a base n<EFBFBD>o perturbe!");
}
$dados = pg_fetch_array($result, null, PGSQL_ASSOC);
$ret['status'] = "Sucesso";
$ret['result'] = "true";
$ret['np_id'] = $dados["np_id"];
$ret['np_md5'] = $dados["np_md5"];
$ret['np_name'] = basename($dados["np_path"]);
return ResultJSON($ret);
} else {
DownloadNaoPerturbe($id);
}
} catch (Exception $ex) {
$ret['status'] = "Erro";
$ret['result'] = "false";
$ret['mensagem'] = $ex->getMessage();
return ResultToJSON($ret);
}
}
$docApi['RegNaoPerturbe'] = MetodoApi(
"Retorna com os n<EFBFBD>meros a serem incluidos no N<EFBFBD>o Perturbe Anatel.",
[
["idCliente-1", "INTEIRO", "REQUIRED", "Id do cliente atualizado."],
["npId-1", "INTEIRO", "REQUIRED", "Id da lista atualizada."]
],
'text/plain'
);
function RegNaoPerturbe($idCliente, $npId)
{
$dbcon = $GLOBALS['dbcon'];
try {
$query = sprintf("insert into pbx_nao_perturbe_cliente(np_id, emp_id)values(%s, %s);", QuotedStr($npId), QuotedStr($idCliente));
$result = pg_query($dbcon, $query);
if (!$result) {
GeraExcept("N<EFBFBD>o foi poss<EFBFBD>vel registrar a lista n<EFBFBD>o perturbe para o cliente informado!");
}
return "OK";
} catch (Exception $ex) {
return "ER|" . $ex->getMessage();
}
}
/* FUNCOES AUXILIARES PARA O WEBSERVICES */
function GravaArquivo($file, $dados, $mode = 'a', $replaceText = '')
{
/*
* Prepara strings para replace.
* Para substituir strings no comando deve-se
* passar os valores separados por ";" ex.: $replaceText = "value search;values replace"
*/
$replace = $replaceText !== '';
if ($replace) {
list($search, $repl) = explode(";", $replaceText);
}
/*
* Cria o arquivo passado, retorna -1 em caso de falha.
*/
if (!$handle = fopen($file, $mode)) {
return -1;
}
$numRegAtu = 0;
foreach ($dados as $cmd) {
if ($replace) {
$cmd = str_replace($search, $repl, $cmd);
}
/*
* Grava os comandos no arquivo de texto.
*/
fwrite($handle, $cmd . "\n");
$numRegAtu++;
}
/*
* Fecha o arquivo e retorna o numero de linhas inseridas.
*/
fclose($handle);
return $numRegAtu;
}
function GetLinkFile($label, $img, $file, $title)
{
return sprintf('<a href="download/%s" target="_new"><img src="imgIntegra/%s" title="%s" >%s</a>', $file, $img, $title, $label);
}
function AnalisaParams($param, $value, $ramal)
{
if ($param == "ObjectName") {
return $value;
}
if ($param == "IPaddress") {
if (strstr($value, "-none-"))
return 'N<EFBFBD>O REGISTRADO';
else
return "$value";
}
if ($param == "Status") {
if (stripos($value, "OK") !== false) {
return RAMAL_ON;
} else {
return RAMAL_OFF;
}
}
return "";
}
function VerificaFoneContato($idContato, $telefone)
{
$query = sprintf("select '' from pbx_campanha_contato_fone where cont_id = %s and conf_fone = %s", QuotedStr($idContato), QuotedStr($telefone));
$result = pg_query($query);
return pg_num_rows($result);
}
function GetRamaisNome()
{
$ret = array();
$db = $GLOBALS['dbcon'];
$query = "select nome, callerid from pbx_sip_ramais where coalesce(callerid,'') <> ''";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel acesso o banco de dados!");
if (pg_num_rows($result)) {
while ($dados = pg_fetch_array($result))
$ret[$dados['nome']] = $dados['callerid'];
}
return $ret;
}
function BdToXml($result)
{
$sessionId = session_id();
$numReg = pg_num_rows($result);
$encode = $GLOBALS['encoding'];
$xml = "<?xml version=\"1.0\" encoding=\"$encode\" ?>\n";
$xml .= "<root>\n";
$xml .= "<status>ok</status>\n";
$xml .= "<SIPID>$sessionId</SIPID>\n";
$xml .= "<rows_count>$numReg</rows_count>\n";
$xml .= "<rows>\n";
$numReg = 0;
while ($dados = pg_fetch_array($result)) {
$xml .= "<row>";
for ($i = 0; pg_num_fields($result) > $i; $i++) {
$xml .= sprintf('<%s>%s</%s>%s', pg_field_name($result, $i), $dados[$i], pg_field_name($result, $i), '');
}
$xml .= "</row>\n";
$numReg++;
}
$xml .= "</rows>";
$xml .= "</root>";
$xml = simplexml_load_string($xml);
return $xml;
}
function ArrToXml($result, $addHeader = true)
{
$sessionId = session_id();
$numReg = count($result);
$xml = "";
$encode = $GLOBALS['encoding'];
$xml = "<?xml version=\"1.0\" encoding=\"$encode\" ?>\n";
$xml .= "<root>\n";
if ($addHeader) {
$xml .= "<status>ok</status>\n";
$xml .= "<SIPID>$sessionId</SIPID>\n";
$xml .= "<rows_count>$numReg</rows_count>\n";
}
$xml .= "<rows>\n";
for ($i = 0; $i < $numReg; $i++) {
$dados = array();
$dados = $result[$i];
$xml .= "<row>\n";
foreach ($dados as $key => $value) {
$xml .= sprintf('<%s>%s</%s>%s', $key, $value, $key, "\n");
}
$xml .= "</row>\n";
}
$xml .= "</rows>";
$xml .= "</root>";
$xml = trim($xml);
$xml = simplexml_load_string($xml);
return $xml;
}
function ArrToStrXml($result)
{
$dados = array();
$dados = $result;
$xml = "<row>\n";
foreach ($dados as $key => $value) {
$xml .= sprintf('<%s>%s</%s>%s', $key, $value, $key, '\n');
}
$xml .= "</row>\n";
return $xml;
}
function ResultToXml($result)
{
header('Content-Type: application/xml; charset=ISO-8859-1');
$xml = new SimpleXMLElement('<root/>');
foreach ($result as $key => $value) {
$xml->addChild($key, htmlspecialchars($value));
}
$sessionId = session_id();
$xml->addChild('SIPID', $sessionId);
return $xml->asXML();
}
function ResultJSON($result)
{
foreach ($result as $key => $value) {
$arr[$key] = $value;
}
return json_encode($arr);
}
function ArrToJSON($result)
{
while ($arr = pg_fetch_array($result, NULL, PGSQL_ASSOC)) {
$json[] = json_encode($arr);
}
$arrFilter = array_filter($json);
$arrAdjust = array_values($arrFilter);
$arrAdjust = json_encode($arrAdjust);
return stripcslashes($arrAdjust);
}
function ResultToJSON($result)
{
foreach ($result as $key => $value) {
$arr[$key] = RemoveAcentos($value);
}
return json_encode($arr);
}
function GetIdDacPadrao($dbcon, $idUser)
{
$query = "select d.id, d.nome
from pbx_dac_usuario u, pbx_dacs d
where d.id = u.id_dac
and padrao = true
and u.id_usuario = $idUser";
$result = pg_query($dbcon, $query);
$ret = 0;
if (pg_num_rows($result) > 0) {
$row = pg_fetch_row($result);
$ret = $row[0];
}
return $ret;
}
function GetDacDesc($id)
{
$dbcon = $GLOBALS['dbcon'];
$query = "select d.nome from pbx_dacs d where id = $id";
$result = pg_query($dbcon, $query);
$row = pg_fetch_row($result);
$ret = $row[0];
return $ret;
}
function GetLoginMatricula($matricula)
{
$dbcon = $GLOBALS['dbcon'];
$query = "select apelido from pbx_usuarios where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
$row = pg_fetch_row($result);
$ret = $row[0];
return $ret;
}
function GetErro($method, $ex, $mostraErro = 0, $tipoRetorno = 'XML')
{
global $ativaDebug;
$msgComple = $ativaDebug ? $_SESSION["SSsetURl"] : '';
$encode = $GLOBALS['encoding'];
$erroSys = $mostraErro ? GetLasterror() : '';
$tipoRetorno = isset($tipoRetorno) ? $tipoRetorno : '';
if (empty($tipoRetorno) || $tipoRetorno == 'XML') {
header('Content-Type: application/xml; charset=ISO-8859-1');
$xml = sprintf("<?xml version=\"1.0\" encoding=\"$encode\"?>
<root>
<status>erro</status>
<result>erro</result>
<SIPID>%s</SIPID>
<method>%s</method>
<code>%s</code>
<message>%s</message>
<msgerro>%s</msgerro>
<line>%s</line>
<file>%s</file>
<comple>%s</comple>
</root>", session_id(), $method, '0', RemoveAcentos($ex->getMessage()), $erroSys, $ex->getLine(), "funcoes", RemoveAcentos($msgComple)); //$ex->getFile()
$xml = simplexml_load_string($xml);
return $xml->asXML();
} else {
header('Content-Type: application/json; charset=ISO-8859-1');
$json = array(
"status" => "erro",
"result" => "erro",
"SIPID" => session_id(),
"method" => $method,
"code" => "0",
"message" => RemoveAcentos($ex->getMessage()),
"line" => $ex->getLine(),
"file" => "funcoes",
"comple" => RemoveAcentos($msgComple)
);
$result = json_encode($json);
return $result;
}
}
function GetParamUrl($paramUrl)
{
/*
* Este array contem as definicoes de parametros para cada metodo declarado na api
*/
$metodosParam = $GLOBALS["docApi"];
$values = array();
$key = $paramUrl["method"];
//echo "nome metodo -> " . $key . "<br />";
foreach ($metodosParam[$key] as $params) {
foreach ($params as $req) {
/*
* Recupera o nome do parametro
*/
$arr = explode("-", $req[0]);
$param = $arr[0];
/*
* Adiciona o valor correspondente dos parametros obtidos pela url
*/
//echo "nome param -> " . $arr[0] . " valor ->> " . $paramUrl[$arr[0]] . " <br />";
$values[] = $paramUrl[$arr[0]];
}
}
return $values;
}
function Display($paramUrl)
{
$params = GetParamUrl($paramUrl);
if ($paramUrl['tipoRetorno'] != 'XML') {
header('Content-Type: application/json; charset=ISO-8859-1');
echo call_user_func_array($paramUrl["method"], $params);
} else {
header('Content-Type: application/xml; charset=ISO-8859-1');
echo call_user_func_array($paramUrl["method"], $params)->asXML();
}
}
function ArrToStr($ar)
{
$ret = "";
foreach ($ar as $value)
$ret .= empty($ret) ? $values : '|' . $values;
return $ret;
}
function GetMetodos()
{
global $docApi;
asort($docApi);
$htmltable = '<br/><br/>
<table width="%s" id="tableStyle" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td>
<table>
<tr>
<td>
<span id="TipoRetorno">%s</span>
</td>
<td>
<h2> &nbsp; %s</h2>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>
<div style="margin-left: 40px;"><span style="color: #888">Sobre: <i>%s</i></span></div>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>
<span style="margin-left: 40px; font-size: 14px; color: #888">Retornos: </span>
<span id="TipoResponse">%s</span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td><hr class="separate"/></td>
</tr>
<tr>
<td>
<table cellpadding="10" align="center">
<tr>
<td>
<span><b>QUERY PARAMS/BODY</b></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table cellpadding="10">
%s
</table>
</td>
</tr>
<tr>
<td><hr class="separate"/></td>
</tr>
<tr>
<td>
<table cellpadding="20">
<tr>
<td colspan="6">
<b>Exemplo:</b>
<span id="url"><a href="%s" target="_blank">%s</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>';
$listaApi = "";
/*
* Lista os m<EFBFBD>todos contidos no array e sua descri<EFBFBD><EFBFBD>o.
*/
foreach ($docApi as $key => $value) {
/*
* Extrai os parametros referentes ao metodo corrente no array $metodos
*/
$display = !isset($docApi['metodosDisplay']) || $docApi['metodosDisplay'] == true ? true : false;
if ($display) {
$parametros = "";
$url = "$key";
foreach ($value['metodosParam'] as $param) {
$prm = explode('-', $param[0]);
$parametros .= '<tr><td>';
$parametros .= strtoupper($param[2]) == 'REQUIRED' ? '<span id="isRequire">REQUIRED</span>&nbsp;' : '<span id="isNoRequire">OPCIONAL</span>&nbsp;';
$parametros .= sprintf('<span id="TipoParam">%s</span> <td><b>%s</b></td>', strtoupper($param[1]), $prm[0]);
$parametros .= sprintf('</td><td><span style="color: #888">%s</span></td></tr>', $param[3]);
$parametros .= '<tr><td colspan="8"><hr class="new"></td></tr>';
$url .= "&{$prm[0]}={$prm[1]}";
}
if (!$parametros) {
$parametros = "<tr align='center'><td><i><p style='font-size: 12px'>ESTE M<EFBFBD>TODO N<EFBFBD>O POSSUI NENHUM PARAMETRO DE ENTRADA!</p></i><td></tr>";
}
$idSession = session_id();
$server = array_key_exists('SERVER_ADDR', $_SERVER) ? $_SERVER['SERVER_ADDR'] : $_SERVER['SERVER_NAME'];
$incId = $key != "AutenticaUsuario" ? "&SIPID=$idSession" : "";
$url = sprintf('http://%s/integracao?method=%s%s&tipoRetorno=%s', $server, $url, $incId, GetTipoRetorno($docApi['metodosRetorno']));
$docApi[$key]['metodosURL'] = $url;
$listaApi .= sprintf($htmltable, '100%', $value['metodosTipo'], $key, $value['metodos'], $value['metodosRetorno'], $parametros, $url, $url);
}
}
$arq = file_get_contents("integracao.tpl", false);
$arq = str_replace("{LINHAS}", $listaApi, $arq);
$arq = str_replace("{LOGO}", LOGO_API_SITE, $arq);
echo str_replace("{VERSAO}", VERSAO_API, $arq);
}
function GetTipoRetorno($tipo)
{
if (stripos($tipo, 'json/stream') !== false) {
return 'JSON/STREAM';
} else if (stripos($tipo, 'xml/stream') !== false) {
return 'XML/STREAM';
} else if (stripos($tipo, 'text/plain') !== false) {
return 'TEXT/PLAIN';
} else if (stripos($tipo, 'json|xml') !== false || stripos($tipo, 'xml|json') !== false) {
return 'XML & JSON';
} else if (stripos($tipo, 'json') !== false) {
return 'JSON';
}
return 'XML';
}
function VerificaCharFinal($str, $ch = "/")
{
return substr($str, -1) == $ch ? $str : $str . $ch;
}
function DownloadFileApi($fullPath, $delete = false)
{
ob_clean();
if ($fd = fopen($fullPath, "rb")) {
while (!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose($fd);
if ($delete) {
unlink($fullPath);
}
exit;
}
function QuebraUrl($url)
{
$tamUrl = strlen($url);
if ($tamUrl <= MAX_QUEBRA)
return $url;
$cont = 0;
$seg = 0;
$str = "";
$char = "";
while ($cont < $tamUrl) {
$char = substr($url, $cont, 1);
$str .= $char;
if (($seg == MAX_QUEBRA) && (substr($url, $cont + 1, 1) == "&")) {
$str .= "<br />";
$seg = 0;
}
$cont++;
if ($seg < MAX_QUEBRA)
$seg++;
}
return $str;
}
function UserAut()
{
global $log;
if (!isset($_SESSION[SS_AUT]) || !$_SESSION[SS_AUT]) {
$param = $GLOBALS["paramUrl"]; //login=loginUser&senha
$log[] = sprintf("Login: %s Senha: %s", $param["login"], $param["senha"]);
if ((!isset($param["login"])) || (!isset($param["senha"]))) {
$_SESSION[SS_AUT] = 0;
$_SESSION[SS_USER_AUT] = "";
return false;
} else if (Autentica($param["login"], $param["senha"])) {
$_SESSION[SS_AUT] = 1;
$_SESSION[SS_USER_AUT] = $param["login"];
return true;
} else {
return false;
}
}
$log[] = sprintf("SS_AUT: ", $_SESSION[SS_AUT]);
return $_SESSION[SS_AUT];
}
function GetChannel()
{
return $_SESSION[API_CANAL_DISCAL];
}
function GetDacAtende()
{
return $_SESSION[SS_NOME_DAC];
}
function GetDestinoIntercalar()
{
return $_SESSION[SS_DESTINO_INTERCALAR];
}
function GetNumDiscTransf()
{
return $_SESSION[AGT_NUM_DISC];
}
function GetModoAtende()
{
return $_SESSION[AGT_TP_ATEND];
}
function GetRamalAgente()
{
return $_SESSION[AGT_RAMAL_CONF];
}
function GetMatriculaAgente()
{
return isset($_SESSION[AGT_MATRICULA]) ? $_SESSION[AGT_MATRICULA] : false;
}
function GetChannelTransf()
{
return $_SESSION[AGT_CHANNEL_TRANSF];
}
function GetChannelTrConsulta()
{
return $_SESSION[AGT_CHANNEL_TRCONSULTA];
}
function GetLoginAgente()
{
return $_SESSION[AGT_LOGIN];
}
function GetLoginApi()
{
return $_SESSION[SS_USER_AUT];
}
function GetIdDac()
{
return $_SESSION[AGT_DAC_CONECT];
}
function GetAudioTipo()
{
return $_SESSION[AGT_AUDIO_TIPO];
}
function GetAudioFile()
{
return $_SESSION[AGT_AUDIO_FILE];
}
function GetMuteSala()
{
return $_SESSION["salaMute"];
}
function GetChannelAgente()
{
return $_SESSION[SS_AGT_CHANNEL_AGENTE];
}
function __GetContextoRamal()
{
return !$_SESSION[SS_AGT_CONTEXTO_RAMAL] ? 'padrao' : $_SESSION[SS_AGT_CONTEXTO_RAMAL];
}
function GetCannelMute($matricula)
{
$dbcon = $GLOBALS['dbcon'];
$query = "select canal_agente from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$row = pg_fetch_row($result);
if ($row[0]) {
return $row[0];
} else {
return "";
}
}
function SetMuteSala($matricula)
{
define("MAX_TENTAVIAS", 10);
$tentativas = 0;
$dbcon = $GLOBALS['dbcon'];
while ($tentativas < MAX_TENTAVIAS) {
$query = "select sala_2 from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($dbcon, $query);
if (!$result) {
throw new Exception(pg_last_error());
}
$row = pg_fetch_row($result);
if ($row[0]) {
$_SESSION["salaMute"] = $row[0];
return true;
} else {
$_SESSION["salaMute"] = '0000';
}
$tentativas++;
usleep(500000);
}
return false;
}
function GetUrlAterisk($acao, $socket)
{
$param = "";
$matricula = GetMatriculaAgente();
$channel = GetChannel();
$channelTransf = GetChannelTransf();
$channelMute = GetCannelMute($matricula);
$modoAtende = GetModoAtende();
$ramal = GetRamalAgente();
$numDisc = GetNumDiscTransf();
$dac = GetDacAtende();
$rand = rand(0, 99999999999); //.rand(0, 99999999999);
$penalidade = $_SESSION["SSagentePenalidade"];
$ramalIntercalar = GetRamalMonitorar(RAMAL_MONITOR_SUPERVISOR);
$canalIntercalar = GetRamalMonitorar(CANAL_MONITOR_SUPERVISOR);
$rmalDestinoIntercalar = GetDestinoIntercalar();
$fileAudioTipo = GetAudioTipo();
$fileAudio = GetAudioFile();
$canalAgente = "Agent/" . GetMatriculaAgente();
$salaConferencia = GetMuteSala();
$channelTransfConsulta = GetChannelTrConsulta();
$contextoRamal = __GetContextoRamal();
$channelAgente = GetChannelAgente();
$texto = $_SESSION["SStexto"];
switch ($acao) {
case AST_LOGIN_AGENTE:
$param = LoginAgenteAmi($socket, $channel, $modoAtende, $ramal, $dac, $matricula, $penalidade);
break;
case AST_LOGOFF_AGENTE:
$param = LogoffAgenteAmi($socket, $matricula);
break;
case AST_ADD_FILA:
$param = AddFilaAmi($socket, $dac, $matricula);
break;
case AST_REM_FILA:
$param = RemFilaAmi($socket, $dac, $matricula);
break;
case AST_ADD_PAUSA:
$param = AddPausaAmi($socket, $matricula, $ramal);
break;
case AST_REM_PAUSA:
$param = RemPausaAmi($socket, $matricula, $ramal);
break;
case AST_DISCAR:
$param = DiscarCallAmi($socket, $channel, $matricula, $numDisc, $ramal, $contextoRamal);
break;
case AST_DISCAR_DIRETO:
$param = DiscarDiretoAmi($socket, $channel, $numDisc, $ramal);
break;
case AST_TRANSFERIR:
$param = TransferirAmi($socket, $channelTransf, $numDisc);
break;
case AST_INCLUI_AGENTE:
$param = IncluiAgenteAmi($socket);
break;
case AST_TESTE_URL:
$param = TesteUrlAmi($socket);
break;
case MONITOR_AGENTS:
$param = MonitorAgentsAmi($socket);
break;
case AST_INTERCALAR:
$param = IntercalarAmi($socket, $canalIntercalar, $ramalIntercalar, $rmalDestinoIntercalar);
break;
case AST_MONITORAR:
$param = MonitorarAmi($socket, $canalIntercalar, $ramalIntercalar, $rmalDestinoIntercalar);
break;
case AST_INICIA_GRAVACAO:
$param = IniciaGravacaoAmi($socket, $channelTransf, $fileAudio, $fileAudioTipo);
break;
case AST_FINALISA_GRAVACAO:
$param = FinalizaGravacaoAmi($socket, $channelTransf);
break;
case AST_INICIA_PAUSA_GRAVACAO:
$param = IniciaPausaGravacaoAmi($socket, $channelTransf);
break;
case AST_FINALISA_PAUSA_GRAVACAO:
$param = FinalizaPausaGravacaoAmi($socket, $channelTransf);
break;
case AST_DESLIGAR_LIGACAO:
$param = DesligarAmi($socket, $channelAgente);
break;
case AST_DESLIGA_CANAL_CLIENTE:
$param = DesligaClienteAmi($socket, $channelTransf);
break;
case AST_PENDULO_ADD_CANAIS:
$param = PenduloAddCanaisAmi($socket, $ramal, $matricula, $channelTransf);
break;
//Remove musica em espera
case AST_PENDULO_REM_CANAIS:
$param = PenduloRemCanaisAmi($socket, $ramal, $matricula, $channelTransf);
break;
case AST_TRCONSULTA_ESPERA:
$param = TrConsultaEsperaAmi($socket, $ramal, $matricula, $numDisc);
break;
//Transferie a liga<EFBFBD><EFBFBD>o
case AST_TRCONSULTA_TRANSFERE:
$param = TrConsultaTransfereAmi($socket, $channelTransfConsulta, $matricula);
break;
//Retorna da consulta sem transferir
case AST_TRCONSULTA_TRANSFERE_ABORTA:
$param = TrConsultaTransfereAbortaAmi($socket, $channelTransfConsulta, $matricula);
break;
//Inicia uma conferencia
case AST_TRCONSULTA_CONFERENCIA:
$param = TrConsultaConferenciaAmi($socket, $channelTransfConsulta, $matricula);
break;
//Inicia o MUTE na parte cliente
case AST_MUTE_CLIENTE:
$param = TrMuteClienteAmi($socket, $channelTransf, $matricula);
break;
//Inicia o MUTE na parte atendente
case AST_MUTE_ATENDENTE:
$param = TrMuteAtendenteAmi($socket, $ramal, $matricula);
break;
//Remove o Mute
case AST_REM_MUTE:
$param = TrRemMuteAmi($socket, $channelTransf, $matricula);
break;
case AST_ALARME:
$param = AlarmeAmi($socket, $channel, $numDisc, $ramal);
break;
case AST_CALLBACK:
$param = CallbackAmi($socket, $channel, $numDisc, $ramal);
break;
case AST_LIGUE_GRATIS:
$param = LigueGratisAmi($socket);
break;
case AST_SMS_SEND:
$param = EnviaSmsAmi($socket, $channel, $numDisc, $texto);
break;
}
return $param;
}
function GetUrl($acao)
{
$log = &$GLOBALS["log"];
list($sckHost, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$socket = ConectaAmi($sckHost, $sckPort, $sckUser, $sckPass);
/*
* Chama funcoes de socket de acordo com a acao
*/
$get = @GetUrlAterisk($acao, $socket);
$log[] = $get;
/*
* fechar o socket
*/
DesconectaAmi($socket);
/*
* Retorna true se nao houver a palavra erro no retorno da execu<EFBFBD><EFBFBD>o
*/
return !stripos($get, "Error");
}
function GetRamalSip($dbcon, $ramalAgente)
{
$query = "select dispositivo from pbx_ramais where nome = '$ramalAgente'";
$result = pg_query($dbcon, $query);
$row = @pg_fetch_row($result);
$ret = $row[0];
return $ret;
}
function GetMotivoLogin($db)
{
$query = "select id from pbx_motivos_pausas where upper(motivo) = 'LOGIN'";
$result = pg_query($db, $query);
$row = @pg_fetch_array($result);
$_SESSION["motivoLogin"] = $row[0];
return $row[0];
}
function GetMotivoAusente($db)
{
$query = "select id from pbx_motivos_pausas where upper(motivo) = 'AUSENTE'";
$result = pg_query($db, $query);
$row = @pg_fetch_array($result);
$_SESSION["motivoLogin"] = $row[0];
return $row[0];
}
function GetQueryInfoFila($nomeDac, $matricula)
{
$uniqueid = $_SESSION[SS_TIPO_FILA] == 'Ativo' ? 'a.accountcode' : 'a.uniqueid';
return "SELECT fila
,ABANDONADAS
,ATENDIDAS_PA
,ESPERA
,round( CASE WHEN(ESPERA = 0)THEN 0 ELSE (TEMPO_ESPERA / ESPERA) END ) * INTERVAL '1 SECOND' AS TME
,round( CASE WHEN(ATENDIDAS_PA = 0)THEN 0 ELSE (TEMPO_ATENDIMENTO / ATENDIDAS_PA)END) * INTERVAL '1 SECOND' AS TMA,
coalesce((select max(espera) as espera from pbx_supervisor_dacs where dac = DADOS.fila), '0') as qt_fila
FROM
(
SELECT fila
,SUM (CASE WHEN EVENTO = 'ABANDON' THEN 1 ELSE 0 END) AS ABANDONADAS
,SUM (CASE WHEN EVENTO IN ('CONNECT') THEN 1 ELSE 0 END) AS ATENDIDAS_PA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND to_number(param1,'999999999') > '3' THEN 1 ELSE 0 END) AS ESPERA
,SUM (CASE WHEN EVENTO IN ('CONNECT') AND to_number(param1,'999999999') > '1' THEN to_number(param1,'999999999') ELSE 0 END) AS TEMPO_ESPERA
,SUM (CASE WHEN EVENTO IN ('COMPLETEAGENT','COMPLETECALLER') AND to_number(param2,'999999999') > '1' THEN to_number(param2,'999999999') ELSE 0 END) AS TEMPO_ATENDIMENTO
FROM
( SELECT a.calldate,b.fila,b.evento,b.param1,b.param2
FROM ast_bilhetes a
INNER JOIN ast_eventos_dacs b on b.uid2 = $uniqueid
WHERE b.evento in ('ABANDON','COMPLETEAGENT','COMPLETECALLER','CONNECT','ENTERQUEUE')
AND a.calldate IS NOT NULL
AND a.lastapp <> 'Transferred Call'
AND a.data_bilhete = now()::date
AND substring(b.agente, 7,4) = '$matricula'
AND b.fila = '$nomeDac'
) AS DADOS
GROUP BY FILA
) AS DADOS
";
}
function UpdatePausa($db)
{
$matricula = GetMatriculaAgente();
$dac = GetIdDac();
$query = "update pbx_eventos_agentes set saida_pausa = now(), flag = 1 where matricula = '$matricula' and id_dac = $dac
and entrada_pausa = (select max(entrada_pausa) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
}
function UpdateLogoff($db)
{
$dac = GetIdDac();
$matricula = GetMatriculaAgente();
$query = "update pbx_supervisor_agentes set logado = now() where matricula = '$matricula'";
$result = pg_query($db, $query);
$query = "update pbx_eventos_agentes set logoff = now(), flag = 1 where matricula = '$matricula' and id_dac = $dac
and login = (select max(login) from pbx_eventos_agentes where matricula = '$matricula' and id_dac = $dac)";
pg_query($db, $query);
}
function SetSessionDesconect()
{
$_SESSION = array();
session_destroy();
}
function Autentica($login, $senha)
{
global $log;
$dbcon = $GLOBALS['dbcon'];
$login = md5(trim(substr(strtolower($login), 0, 20)));
$senhaAut = md5(trim(substr($senha, 0, 14)));
//$senha = '0987';
$query = "select count(*) as num from pbx_usuarios where check_vl = '$login' and senha = '$senhaAut' and coalesce(delete_,0) = 0 "; //and coalesce(status, true) = true
$result = pg_query($dbcon, $query);
$log[] = $query;
$row = pg_fetch_row($result);
if ($row[0] && ($senha == '1234')) {
trigger_error("N<EFBFBD>o <EFBFBD> permitida a autentica<EFBFBD><EFBFBD>o do usu<EFBFBD>rio com a senha padr<EFBFBD>o!");
return false;
}
return $row[0];
}
function ValidaMetodos($paramUrl)
{
global $docApi;
$ret = "erro";
$metodos = $docApi;
$metodosParam = $docApi[$paramUrl["method"]]["metodosParam"];
$metodosRetorno = $docApi[$paramUrl["method"]]["metodosRetorno"];
if (array_key_exists($paramUrl["method"], $metodos)) {
$key = $paramUrl["method"];
foreach ($metodosParam[$key] as $params) {
/*
* Recupera o nome do parametro
*/
$arr = (explode("-", $params[0]));
$param = $arr[0];
$tipoParam = trim(strtoupper($params[1]));
/*
* verifica se o parametro <EFBFBD> requerido
*/
$txt = $params[2];
$req = stripos($txt, "requerido");
/*
* verifica se o parametro foi informado
*/
if ($req && ($tipoParam == 'FILE')) {
if (!isset($_FILES[$param])) {
$ret = sprintf('Parametro FILE "%s" deve ser informado obrigat<EFBFBD>riamente!', $param);
return $ret;
}
} else if ($req && !isset($paramUrl[$param])) {
//O valor n<EFBFBD>o foi informado ou esta vasio
$ret = sprintf('Parametro "%s" deve ser informado obrigat<EFBFBD>riamente!', $param);
return $ret;
} else if (isset($paramUrl[$param])) {
if ((strtoupper($params[1]) == 'INTEIRO') && (!is_numeric($paramUrl[$param]))) {
$ret = sprintf('O valor "%s" informado para o parametro "%s" <EFBFBD> inv<EFBFBD>lido. Infome somente n<EFBFBD>meros', $paramUrl[$param], $param);
return $ret;
}
}
}
$ret = "OK";
} else {
$ret = sprintf('M<EFBFBD>todo "%s" n<EFBFBD>o esta dispon<EFBFBD>vel!', $paramUrl["method"]);
}
return $ret;
}
function GetExtensaoAudio($tipoArquivo)
{
$monitorFormat = strtoupper($tipoArquivo);
if ($monitorFormat == 'WAV')
return 'wav';
else if ($monitorFormat == 'GSM')
return 'gsm';
else if ($monitorFormat == 'WAV49')
return 'WAV';
}
function GetTipoFila($db, $dac)
{
try {
//$senha = '0987';
$query = "select count(*) as num from pbx_campanha where cmp_id = '$dac' ";
$result = pg_query($db, $query);
if (!$result)
throw new Exception('');
$row = @pg_fetch_row($result);
return $row[0] ? "Ativo" : "Receptivo";
} catch (Exception $e) {
return "";
}
}
function GetUrlAgente()
{
global $ativaDebug;
return $ativaDebug ? htmlentities($_SESSION["SSsetURl"]) : '';
}
function GetDispositivoRamal($dbcon, $ramal)
{
$query = "select case when( upper(tipo_ramal) = 'KHOMP')then upper(tipo_ramal) || '/r' || nome else dispositivo end as dispositivo from pbx_ramais where nome = '$ramal'";
$result = pg_query($dbcon, $query);
$row = pg_fetch_row($result);
return !$row[0] ? -1 : $row[0];
}
function GravaLogItgr()
{
global $gravaLog;
global $log;
$mensagem = $log;
if ($gravaLog && count($mensagem)) {
$path = "/var/log/asterisk/";
$data = date('Y-m-d');
$login = !GetLoginAgente() ? 'inativo' : GetLoginAgente();
$loginAut = !$_SESSION[SS_USER_AUT] ? 'anonimo' : $_SESSION[SS_USER_AUT];
/*
* Arquivo para gravar o log
*/
//$file = sprintf('%s%s_%s_%s.log', $pathFull, $bar, $login, $data);
$file = sprintf('%sapi.log', $path);
// $file = sprintf('log/_%s_%s.log', $login, $data);
$arq = fopen($file, 'a');
if ($arq) {
foreach ($mensagem as $linha) {
fwrite($arq, sprintf("Data: %s User: %s Agente: %s Log: %s\n", $data, $login, $loginAut, $linha));
}
fwrite($arq, "\n");
fclose($arq);
$log = array();
}
}
}
function CriaAgendamento($agdId, $agente, $fone, $cmpId, $contId, $cmpDesc, $data, $tipo, &$callfile)
{
$AGD_ID = $agdId;
$AGENTE = $agente;
$FONE = $fone;
$CMP_ID = $cmpId;
$CONT_ID = $contId;
$CAMPANHA = $cmpDesc;
$AGENDAMENTO = $data;
$AGD_TIPO = $tipo;
$file = array();
//$file[] = "cat <<-EOF1\n";
$file[] = "Channel: Local/$FONE@ext-agendamento\n";
$file[] = "Callerid: $FONE\n";
$file[] = "MaxRetries: 2\n"; //; Numero de Tentativas de discagem
$file[] = "RetryTime: 10\n"; //Intervalo entre as tentativas de discagem
$file[] = "WaitTime: 100\n"; //; Tempo de Ring
$file[] = "Context: app-agendamento\n";
$file[] = "Extension: $FONE\n";
$file[] = "Priority: 1\n";
$file[] = "Set: PERMISSAO=OK\n";
$file[] = "Set: AGD_ID=$AGD_ID\n";
$file[] = "Set: ID_CLI=$CONT_ID\n";
$file[] = "Set: TIPOLIGACAO=AGENDAMENTO\n";
$file[] = "Set: AGENTE=$AGENTE\n";
$file[] = "Set: CAMPANHA=$CAMPANHA\n";
$file[] = "Set: CMP_ID=$CMP_ID\n";
$file[] = "Set: AGD_TIPO=$AGD_TIPO\n";
$file[] = "Archive: Yes\n";
$data = str_replace(":", "-", str_replace(" ", "-", $AGENDAMENTO));
$RAND = rand(000000000, 9999999999);
$dirDestino = "/var/spool/asterisk/outgoing/";
$dirArquivo = "/var/log/asterisk/";
$fileName = sprintf("%s-%s-%s-%s.call", $data, $FONE, $AGENTE, $RAND);
$callfile = $fileName;
$arq = fopen($dirArquivo . $fileName, 'w');
if ($arq) {
foreach ($file as $values) {
fwrite($arq, $values);
}
fclose($file);
//return touchAgt($dirArquivo.$fileName, $AGENDAMENTO) && rename($dirArquivo.$fileName, $dirDestino.$fileName);
return CmdAgt($dirArquivo . $fileName, $AGENDAMENTO) && rename($dirArquivo . $fileName, $dirDestino . $fileName);
} else {
fclose($file);
return false;
}
}
function CmdAgt($file, $data)
{
$data = str_replace("-", "", $data);
$data = str_replace(":", "", $data);
$data = str_replace(" ", "", $data);
$data = substr($data, 0, strlen($data) - 2) . ".00";
$cmd = "touch -t $data $file";
$exec = exec($cmd);
if (!$exec) {
$cmd = "chmod 777 $file";
$exec = exec($cmd);
return empty($exec);
}
return false;
}
function AgentePresente($db, $matricula)
{
$i = 0;
while ($i++ < 10) {
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' and upper(status) = 'PAUSA' ";
$result = pg_query($db, $query);
$row = @pg_fetch_row($result);
$result = $row[0] ? true : false;
if ($result)
return true;
usleep(500000);
}
return false;
}
function GetRamalAgenteLogado($db)
{
$matricula = GetMatriculaAgente();
$query = "select ramal from pbx_supervisor_agentes where matricula = '$matricula' ";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function VerificaDac($db, $idDac)
{
$query = "select count(*) from pbx_dacs where id = '$idDac' ";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
return $row[0];
}
function VerificaCampanha($db, $nomeCampanha)
{
$query = "select cmp_id from pbx_campanha where cmp_descricao = '$nomeCampanha'";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar a \"Campanha\"!");
if (!pg_num_rows($result))
return false;
$row = pg_fetch_row($result);
return $row[0];
}
function CampanhaAtiva($db, $existeCampanha)
{
if (!$existeCampanha)
return false;
$query = "select count(*) from pbx_campanha where cmp_id = '$existeCampanha' and cmp_status = '1' ";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o \"Status da Campanha\"!");
$row = pg_fetch_row($result);
return ($row[0] > 0);
}
function VerificaCampanhaLista($db, $nomeLista)
{
$query = "select list_id from pbx_campanha_lista where list_nome = '$nomeLista'";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar a \"Lista\"!");
if (!pg_num_rows($result))
return 0;
$row = pg_fetch_row($result);
return $row[0];
}
function GetContatoFone($db, $existeCampanha, $listId, $codCliente)
{
$query = "select cont_id from pbx_campanha_contato where cmp_id = '$existeCampanha' and list_id = '$listId' and cont_identificador = '$codCliente'";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o \"Contato\"!");
if (!pg_num_rows($result))
return 0;
$row = pg_fetch_row($result);
return $row[0];
}
$docApi['StatusCampanha'] = MetodoApi(
'Altera o status de uma Campanha.',
[
["idCampanha-1", "STRING", "REQUIRED", 'Identificador da Campanha. Pode ser passado o Nome(Identificador textual) ou C<EFBFBD>digo(Identificador N<EFBFBD>merico)'],
["status-1", "INTEGER", "REQUIRED", 'Opera<EFBFBD><EFBFBD>o a ser Realizada. 1-\"Exclui\", exclui a campanha. N<EFBFBD>o pode ser desfeito. 1-\"Ativa\", inicia o discador para a lista ativa. 3 - \"Suspende\", para a discagem temporariamente. 4 - \"Cancela\", cancela a lista atual. N<EFBFBD>o pode ser reativada.']
]
);
function StatusCampanha($idCampanha, $status)
{
$inTran = 0;
$statusValidos = array(0, 1, 3, 4);
try {
if (array_search($status, $statusValidos) === false)
throw new Exception('Status informado <EFBFBD> inv<EFBFBD>lido!');
$ativar = $status == 1;
$db = $GLOBALS['dbcon'];
$result = pg_query($db, 'begin');
if (!$result)
throw new Exception('Nao foi poss<EFBFBD>vel \"Iniciar a Opera<EFBFBD><EFBFBD>o\"!');
$inTran = 1;
/*
* Seleciona informa<EFBFBD><EFBFBD>es sobre a campanha informada.
*/
$query = " select cmp_id, cmp_descricao, cmp_aguarda_agente, cmp_numero_ligacoes_agente, coalesce(cmp_pid, 0) as cmp_pid from pbx_campanha where (cmp_id::text = '$idCampanha' or cmp_descricao = '$idCampanha')";
$result = pg_query($db, $query);
if (!$result || !pg_num_rows($result))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel obter informa<EFBFBD><EFBFBD>es sobre a \"Campanha\"!");
$dados = pg_fetch_array($result, PGSQL_ASSOC);
$idCampanha = $dados["cmp_id"];
$nomeCampanha = $dados["cmp_descricao"];
$qtdeLigacoes = $dados["cmp_numero_ligacoes_agente"];
$agenteAguarda = $dados["cmp_aguarda_agente"];
$pidOld = $dados["cmp_pid"];
$pid = 0;
/*
* Atualiza o Status da capanha.
*/
$query = "update pbx_campanha set cmp_status = '%s' where cmp_id = '%s' ";
$query = sprintf($query, $fieldsForm['cmp_status'], $idCampanha);
$result = pg_query($db, $query);
if (!$result)
throw new Exception('A opera<EFBFBD><EFBFBD>o n<EFBFBD>o pode ser realizada!');
if ($ativar) {
$query = "select count(*) as lista from pbx_campanha_lista where cmp_id = '$idCampanha' and list_status = '1'";
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o \"Status da Lista\"!");
$row = @pg_fetch_row($result);
if (!$row[0])
Exception('N<EFBFBD>o Existe uma lista ativa para essa Campanha!');
$comando = sprintf("/var/lib/asterisk/scripts/discador.sh %s %s saida-campanha-%s %s >> /tmp/%s.log 2>&1 &", $nomeCampanha, $idCampanha, $nomeCampanha, $qtdeLigacoes, $nomeCampanha);
$result = ExecutaComando($comando, $db);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel ativar o servi<EFBFBD>o de \"Discagem\"!");
$query = "select cmp_pid from pbx_campanha where cmp_id = '$id$idCampanha'";
while ($i++ < 10) {
$result = pg_query($db, $query);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o servi<EFBFBD>o de \"Discagem\"!");
$row = pg_fetch_row($result);
if ($row[0] != $pidOld) {
$pid = $row[0];
break;
}
sleep(1);
}
if (!$pid)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel iniciar o servi<EFBFBD>o de \"Discagem\"!");
$msg = "Servi<EFBFBD>o Iniciado com Sucesso!";
} else {
if (!$pid)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel verificar o servi<EFBFBD>o de \"Discagem\"!");
$comando = sprintf("kill -9 %s", $pid);
$result = ExecutaComando($comando, $db);
if (!$result)
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel parar o servi<EFBFBD>o de \"Discagem\"!");
$msg = "Servi<EFBFBD>o Interrompido com Sucesso!";
}
$result = pg_query($db, 'commit');
if (!$result)
throw new Exception('Nao foi poss<EFBFBD>vel \"Finalizar a Opera<EFBFBD><EFBFBD>o\"!');
$ret["status"] = "ok";
$ret["result"] = "true";
$ret["id_campanha"] = $idCampanha;
$ret["nome_campanha"] = $nomeCampanha;
$ret["message"] = $msg;
return ResultToXml($ret);
} catch (Exception $ex) {
pg_query($db, 'rollback');
return GetErro("StatusCampanha", $ex);
}
}
function ExecutaComando($comando, $db)
{
$query = "SELECT usuario_servidor, senha_servidor, porta_servidor FROM pbx_conf_padrao";
$result = pg_query($db, $query);
$dados = pg_fetch_array($result);
$usuario_servidor = $dados['usuario_servidor'];
$senha_servidor = $dados['senha_servidor'];
$porta_servidor = $dados['porta_servidor'];
//endereco do servidor onde ser<EFBFBD> executado o comando
$ssh = new Net_SSH2('127.0.0.1', $porta_servidor);
if (!$ssh->login($usuario_servidor, $senha_servidor))
throw new Exception("N<EFBFBD>o foi poss<EFBFBD>vel conectar ao \"Servidor da Central\"!");
//return $ssh->exec($comando);
return $ssh->exec(sprintf("sudo %s", $comando));
}
function VerificaRamalLogado($db, &$dac, &$agente)
{
$ramal = GetRamalAgente();
$query = "select dac, nome, count(*) from pbx_supervisor_agentes where ramal = '$ramal' group by dac, nome";
$result = pg_query($db, $query);
$row = pg_fetch_array($result);
if (pg_num_rows($result)) {
$dac = $row["dac"];
$agente = $row["nome"];
return true;
}
return false;
}
function VerficaAgenteLogado($db)
{
$matricula = GetMatriculaAgente();
$query = "select count(*) from pbx_supervisor_agentes where matricula = '$matricula' ";
$result = pg_query($db, $query);
$row = pg_fetch_row($result);
$ret = $row[0];
if ($ret) {
$query = "select extract(epoch from (now() - logado))::int , trim(ramal) from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$dados = pg_fetch_row($result);
if (empty($dados[1]) || ($dados[0] >= 60)) {
$query = "delete from pbx_supervisor_agentes where matricula = '$matricula'";
$result = pg_query($db, $query);
$ret = false;
}
}
return $ret;
}
function VerificaMaxAgenteLogado($db, $org_id)
{
return false;
$numAgt = GetModeloPa();
/*
* Numero de PAs setado como zero permite ilimitada conex<EFBFBD>es.
*/
if ($numAgt === 0)
return false;
/*
* Verifico a quantidade de PAs logado.
*/
$query = "select (count(*) + 1) as num_total_pa from pbx_supervisor_agentes where org_id=$org_id";
$result = pg_query($db, $query);
if ($result) {
$row = pg_fetch_row($result);
return ($row[0] > $numAgt);
}
return true;
}
function VerificaChamadaRamal($channel)
{
$arStatusChannel = array();
$actionid = rand(000000000, 9999999999);
$pathLog = '/tmp/ChamadaRamal.log';
$socket = __ConectaManager();
if (!$socket) {
GeraExcept('N<EFBFBD>o foi poss<EFBFBD>vel conectar a central!');
}
fwrite($socket, "action: command\r\n");
fwrite($socket, "command: core show channels concise\r\n"); //Ramal local sip/1001
fwrite($socket, "ActionID: $actionid\r\n\r\n");
//GravaLog($buffer . "--------------------Inicio--------------------\n", $pathLog);
$i = 0;
while (!feof($socket)) {
$buffer = trim(fgets($socket));
//GravaLog($buffer . "\n", $pathLog);
list($param, $value) = explode(":", $buffer);
if (!$start) {
$start = (strtoupper($param) == 'ACTIONID') && ($actionid == (int) $value);
}
if ($start) {
if (!$startInfo) {
$startInfo = (trim($param) == 'ActionID') && (($actionid == (int) $value));
}
if ($startInfo) {
/*
* Le o bloco de informa<EFBFBD><EFBFBD>es.
*/
if (stripos($buffer, $channel) !== false) {
$arStatus = explode("!", $buffer);
$arStatusChannel[$channel] = $arStatus[11];
$startInfo = false;
}
}
}
/*
* Encerra a leitura.
*/
if (stripos($buffer, 'END COMMAND') !== false) {
break;
}
}
//GravaLog($buffer . "\n--------------------fim--------------------\n", $pathLog);
fclose($socket);
if (!count($arStatusChannel)) {
return 1;
}
if (stripos($arStatusChannel[$channel], 'none') !== false) {
return 2;
}
if (stripos($arStatusChannel[$channel], 'none') === false) {
return 3;
}
}
function ChamadaRamalAmi($channel, $numDisc, $ramal, $envExtrn = false)
{
$actionid = rand(000000000, 9999999999);
$pathLog = '/tmp/ChamadaRamal.log';
$startMessage = 0;
$startChanel = 0;
/*
* Conecata ao manager;
*/
$socket = __ConectaManager('on');
if (!$socket) {
GeraExcept('N<EFBFBD>o foi poss<EFBFBD>vel conectar a central!');
}
/*
* $envExtrn indica que a chamada sera redirecionada para um n<EFBFBD>mero fixo
* ou um celular em vez de um ramal.
*/
$rand = rand(000000000, 9999999999);
fwrite($socket, "Action: Originate\r\n");
fwrite($socket, $envExtrn ? "Channel: Local/$channel@padrao/n\r\n" : "Channel: $channel\r\n");
fwrite($socket, "Context: padrao\r\n");
fwrite($socket, "Exten: $numDisc\r\n"); //numero a discar
fwrite($socket, "Priority: 1\r\n");
fwrite($socket, "Callerid: $ramal\r\n"); //Ramal local 1001
fwrite($socket, "Timeout: 60000\r\n");
fwrite($socket, "Variable: RAMAL=$ramal\r\n");
fwrite($socket, "ActionID: $rand\r\n\r\n");
//GravaLog($buffer . "--------------------Inicio--------------------\n", $pathLog);
$uid = '0';
$i = 0;
while (!feof($socket)) {
$buffer = trim(fgets($socket));
//GravaLog($buffer . "\n", $pathLog);
list($param, $value) = explode(":", $buffer);
if (!$start) {
$start = (strtoupper($param) == 'ACTIONID') && ($rand == (int) $value);
}
if ($start) {
if (!$startMessage) {
$startMessage = ((trim($param) == 'ActionID') && ($rand == (int) $value));
}
if ($startMessage) {
/*
* Le o bloco de informa<EFBFBD><EFBFBD>es.
*/
if (trim($param) == 'Message') {
if (trim($value) !== 'Originate successfully queued') {
GeraExcept('N<EFBFBD>o foi poss<EFBFBD>vel discar para o n<EFBFBD>mero informado!');
}
$startMessage = false;
}
}
if (!$startChanel) {
$startChanel = ((trim($param) == 'Event') && ((trim($value) == 'Newchannel')));
}
if ($startChanel) {
/*
* Le o bloco de informa<EFBFBD><EFBFBD>es.
*/
$arChannel[$param] = trim($value);
if (trim($param) == 'Uniqueid') {
if (stripos($arChannel['Channel'], $channel) !== false) {
$uid = trim($value);
break;
}
$startChanel = false;
}
}
}
if (++$i > 10000) {
return '0';
}
}
fclose($socket);
return $uid;
}
function __ConectaManager($events = 'off')
{
list($host, $sckPort, $sckUser, $sckPass) = GetSckConnect();
$sckHost = $servidor ? $servidor : $host;
$timeout = 5;
$socket = fsockopen($sckHost, $sckPort, $errno, $errstr, $timeout);
if ($socket) {
$actionid = rand(000000000, 9999999999);
fwrite($socket, "action: login\r\n");
fwrite($socket, "username: $sckUser\r\n");
fwrite($socket, "secret: $sckPass\r\n");
fwrite($socket, "events: $events\r\n");
fwrite($socket, "ActionID: " . $actionid . "\r\n\r\n");
$i = 0;
$ret = false;
while (!feof($socket)) {
$buffer = fgets($socket);
if (stristr($buffer, "Authentication accepted")) {
return $socket;
}
if (stristr($buffer, "Authentication failed")) {
return false;
}
if ($buffer === false) {
return false;
}
}
return false;
}
return false;
}
function GetRamalApi()
{
$query = "select nome from pbx_ramais_mesa where callerid = 'RAMAL_API'";
$result = pg_query($query);
$row = pg_fetch_row($result);
return $row[0] ? $row[0] : false;
}
function GetMonitorAst13()
{
$socket = ConectaAmi();
$params = array('action' => 'command', 'command' => 'core show channels concise');
$result = GetAmi($socket, $params);
$chamadas = GetMonitorConcise($result);
$arChamadas = array();
/*
* CLASSIFICA O TIPO DE CHAMADA
*/
foreach ($chamadas as $key => $chnl) {
$arChamadas[$key] = $chnl;
if ($chnl[1] != "ext-transferencia") {
foreach ($chamadas as $chave => $chn) {
if ($chn[12] == $chnl[12] && $chn[0] != $chnl[0] && $chn[5] == "AppDial") {
$arChamadas[$key][9] = $chn[7];
unset($arChamadas[$chave]);
}
}
} else if ($chnl[1] == "ext-transferencia") {
if ($chnl[2] == $chnl[7]) {
unset($arChamadas[$key]);
}
}
}
/*
* LIMPA OS DADOS QUE EST<EFBFBD> FORA DE CONTEXTO COM AS CHAMADAS CORRENTES
*/
foreach ($arChamadas as $chv => $chamada) {
if ($chamada[5] == "AppDial" && empty($chamada[9]) && $chamada[3] > 1) {
unset($arChamadas[$chv]);
}
if ($chamada[5] == "Dial" && empty($chamada[9]) && $chamada[3] < 18) {
unset($arChamadas[$chv]);
}
if ($chamada[1] == "ext-transferencia") {
unset($arChamadas[$chv]);
}
}
/*
* LIMPA OS DADOS QUE N<EFBFBD>O EST<EFBFBD>O SENDO UTILIZADOS
*/
foreach ($arChamadas as $sc => $cham) {
foreach ($arChamadas as $ky => $chm) {
if ($chm[0] != $cham[0] && $cham[12] == $chm[12] && $chm[5] == "AppDial") {
unset($arChamadas[$ky]);
}
if ($chm[0] != $cham[0] && $cham[7] == $chm[7] && $chm[5] == "AppDial") {
unset($arChamadas[$ky]);
}
if ($chm[0] != $cham[0] && $cham[7] == $chm[7] && $chm[5] == "Dial") {
unset($arChamadas[$sc]);
}
$chamadaChn = explode(';', $chm[0]);
$chamadaChn2 = explode(';', $cham[0]);
if ($chamadaChn[0] == $chamadaChn2[0] && $cham[5] == "AppQueue") {
unset($arChamadas[$sc]);
}
}
}
/*
* MONTA O ARRAY DE ACORDO COM A GRID NO MONITOR
*/
$chamadasMonitor = array();
foreach ($arChamadas as $map => $app) {
$chamadasMonitor[$map]['uniqueid'] = $arChamadas[$map][13];
$chamadasMonitor[$map]['channel'] = $arChamadas[$map][0];
$chamadasMonitor[$map]['status'] = $arChamadas[$map][4];
$chamadasMonitor[$map]['origem'] = $arChamadas[$map][7];
$chamadasMonitor[$map]['destino'] = $arChamadas[$map][9];
$chamadasMonitor[$map]['duracao'] = $arChamadas[$map][11];
}
return $chamadasMonitor;
}
function GetMonitorConcise($result)
{
/*
* Limpando array do AMI.
*/
$count = count($result) - 1;
unset($result[$count]);
for ($a = 0; $a < 3; $a++) {
unset($result[$a]);
}
foreach ($result as $key => $chm) {
$result[$key] = explode('!', $chm);
}
return $result;
}
function MetodoApi($descricao, $dados = array(), $tipoRetorno = 'xml|json')
{
$docApi = [
'metodos' => $descricao,
'metodosParam' => $dados,
'metodosRetorno' => strtoupper(GetTipoRetorno($tipoRetorno)),
'metodosTipo' => 'GET'
];
return $docApi;
}