topsapp: estruturar suporte
Signed-off-by: Rodrigo B. de Sousa Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
723ad8c268
commit
8dc6c594c9
7 files changed
+1687
-104
No files matched your search
+152
-28
@@ -1,5 +1,6 @@
|
||||
const axios = require('axios');
|
||||
const https = require('https');
|
||||
const logger = require('../utils/logger');
|
||||
|
||||
class TopSappAPI {
|
||||
constructor() {
|
||||
@@ -23,10 +24,8 @@ class TopSappAPI {
|
||||
httpsAgent: new https.Agent({
|
||||
rejectUnauthorized: false
|
||||
}),
|
||||
timeout: 30000,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
}
|
||||
timeout: 30000
|
||||
// Não definir Content-Type, deixar o FormData fazer isso automaticamente
|
||||
};
|
||||
|
||||
console.log('🔗 TopSappAPI inicializado');
|
||||
@@ -53,31 +52,45 @@ class TopSappAPI {
|
||||
async login(instance, credentials) {
|
||||
try {
|
||||
console.log(`🔐 Fazendo login na instância: ${instance.name}`);
|
||||
console.log(`📍 URL: ${instance.baseURL}/Login`);
|
||||
console.log(`👤 Usuario: ${credentials.usuario}`);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('usuario', credentials.usuario);
|
||||
formData.append('senha', credentials.senha);
|
||||
formData.append('identificador', credentials.identificador || 'BotTelegram');
|
||||
formData.append('idUsuario', credentials.idUsuario || '1');
|
||||
|
||||
const response = await axios.post(
|
||||
`${instance.baseURL}/Login`,
|
||||
formData,
|
||||
this.axiosConfig
|
||||
{
|
||||
...this.axiosConfig,
|
||||
timeout: 10000
|
||||
}
|
||||
);
|
||||
|
||||
if (response.data && response.data.status === 'success') {
|
||||
console.log(`📊 Status da resposta: ${response.status}`);
|
||||
console.log(`📋 Dados da resposta:`, response.data);
|
||||
|
||||
if (response.data && response.data.resultado === true) {
|
||||
const sessionId = response.data.sessao;
|
||||
const idUsuario = response.data.id_usuario;
|
||||
|
||||
this.sessions.set(instance.baseURL, {
|
||||
sessionId,
|
||||
idUsuario,
|
||||
timestamp: Date.now(),
|
||||
instance
|
||||
});
|
||||
|
||||
console.log(`✅ Login realizado com sucesso na instância: ${instance.name}`);
|
||||
return { success: true, sessionId, instance };
|
||||
console.log(`🎫 Sessão: ${sessionId}`);
|
||||
console.log(`👤 ID do usuário: ${idUsuario}`);
|
||||
return { success: true, sessionId, idUsuario, instance };
|
||||
} else {
|
||||
throw new Error(response.data?.message || 'Login falhou');
|
||||
const errorMsg = response.data?.msg || 'Login falhou';
|
||||
console.log(`❌ Erro no login: ${errorMsg}`);
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -127,15 +140,19 @@ class TopSappAPI {
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('sessao', session.sessionId);
|
||||
formData.append('identificador', credentials.identificador || 'BotTelegram');
|
||||
|
||||
// Adicionar parâmetros extras
|
||||
Object.keys(data).forEach(key => {
|
||||
if (data[key] !== undefined && data[key] !== null) {
|
||||
formData.append(key, data[key]);
|
||||
// Converter idCliente para inteiro se necessário
|
||||
const value = key === 'idCliente' ? parseInt(data[key], 10) : data[key];
|
||||
formData.append(key, value.toString());
|
||||
}
|
||||
});
|
||||
|
||||
console.log(`📡 Fazendo requisição para: ${instance.baseURL}/${endpoint}`);
|
||||
console.log(`📊 Parâmetros:`, data);
|
||||
|
||||
const response = await axios.post(
|
||||
`${instance.baseURL}/${endpoint}`,
|
||||
@@ -143,14 +160,19 @@ class TopSappAPI {
|
||||
this.axiosConfig
|
||||
);
|
||||
|
||||
if (response.data && response.data.status === 'success') {
|
||||
console.log(`📊 Status da resposta: ${response.status}`);
|
||||
console.log(`📋 Dados da resposta:`, response.data);
|
||||
|
||||
if (response.data && response.data.resultado === true) {
|
||||
return {
|
||||
success: true,
|
||||
data: response.data,
|
||||
instance: instance.name
|
||||
};
|
||||
} else {
|
||||
throw new Error(response.data?.message || 'Requisição falhou');
|
||||
const errorMsg = response.data?.msg || 'Requisição falhou';
|
||||
console.log(`❌ Erro na API: ${errorMsg}`);
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -170,19 +192,26 @@ class TopSappAPI {
|
||||
const instance = this.getInstanceByLocation(location);
|
||||
|
||||
try {
|
||||
// Obter sessão válida para pegar o idUsuario
|
||||
const session = await this.getValidSession(instance, credentials);
|
||||
|
||||
// Tentar buscar por diferentes critérios
|
||||
const searchParams = {};
|
||||
const searchParams = {
|
||||
idUsuario: session.idUsuario || 1 // Usar ID do usuário da sessão
|
||||
};
|
||||
|
||||
// Se é número, pode ser CPF ou ID
|
||||
if (/^\d+$/.test(query)) {
|
||||
if (query.length === 11) {
|
||||
searchParams.cpf = query;
|
||||
if (query.length === 11 || query.length === 14) {
|
||||
// CPF (11 dígitos) ou CNPJ (14 dígitos)
|
||||
searchParams.cpfCnpj = query;
|
||||
} else {
|
||||
// ID do cliente
|
||||
searchParams.idCliente = query;
|
||||
}
|
||||
} else {
|
||||
// Buscar por nome
|
||||
searchParams.nome = query;
|
||||
// CPF formatado ou nome - usar o endpoint de busca geral
|
||||
searchParams.cpfCnpj = query.replace(/[^\d]/g, ''); // Remove formatação
|
||||
}
|
||||
|
||||
const result = await this.makeRequest('ObterClientes', searchParams, instance, credentials);
|
||||
@@ -190,7 +219,7 @@ class TopSappAPI {
|
||||
if (result.success) {
|
||||
return {
|
||||
success: true,
|
||||
clientes: result.data.clientes || [],
|
||||
clientes: result.data.dados || [], // Usar 'dados' em vez de 'clientes'
|
||||
instance: result.instance
|
||||
};
|
||||
}
|
||||
@@ -221,7 +250,85 @@ class TopSappAPI {
|
||||
async obterServicosCliente(idCliente, location = '', credentials) {
|
||||
const instance = this.getInstanceByLocation(location);
|
||||
|
||||
return await this.makeRequest('ObterClientesServicos', { idCliente }, instance, credentials);
|
||||
// Obter o idUsuario da sessão atual
|
||||
const session = await this.getValidSession(instance, credentials);
|
||||
|
||||
console.log(`🔍 Obtendo serviços para cliente: ${idCliente} (tipo: ${typeof idCliente})`);
|
||||
|
||||
const clienteIdInt = parseInt(idCliente, 10);
|
||||
|
||||
// Tentar diferentes abordagens para obter serviços do cliente
|
||||
let response = null;
|
||||
let tentativas = [
|
||||
// Tentativa 1: Endpoint padrão com idCliente
|
||||
{ endpoint: 'ObterClientesServicos', data: { idCliente: clienteIdInt, idUsuario: session.idUsuario || 1 } },
|
||||
// Tentativa 2: Endpoint alternativo (se existir)
|
||||
{ endpoint: 'ObterServicosCliente', data: { idCliente: clienteIdInt, idUsuario: session.idUsuario || 1 } },
|
||||
// Tentativa 3: Com parâmetros alternativos
|
||||
{ endpoint: 'ObterClientesServicos', data: { cliente_id: clienteIdInt, idUsuario: session.idUsuario || 1 } }
|
||||
];
|
||||
|
||||
logger.debug('Iniciando tentativas de busca de serviços', {
|
||||
clienteIdInt,
|
||||
sessionId: session.idUsuario,
|
||||
tentativasCount: tentativas.length
|
||||
});
|
||||
|
||||
for (let i = 0; i < tentativas.length; i++) {
|
||||
const tentativa = tentativas[i];
|
||||
try {
|
||||
console.log(`📋 Tentativa ${i + 1} - Endpoint: ${tentativa.endpoint}, Dados:`, tentativa.data);
|
||||
logger.debug(`Tentativa ${i + 1}`, {
|
||||
endpoint: tentativa.endpoint,
|
||||
data: tentativa.data
|
||||
});
|
||||
|
||||
response = await this.makeRequest(tentativa.endpoint, tentativa.data, instance, credentials);
|
||||
logger.apiCall(tentativa.endpoint, tentativa.data, response);
|
||||
|
||||
if (response.success && response.data) {
|
||||
console.log(`✅ Sucesso na tentativa ${i + 1} - Total de itens: ${response.data.dados?.length || response.data.length || 0}`);
|
||||
logger.debug(`Sucesso na tentativa ${i + 1}`, {
|
||||
totalItems: response.data.dados?.length || response.data.length || 0,
|
||||
hasData: !!response.data
|
||||
});
|
||||
|
||||
// Verificar se os dados são relevantes para o cliente
|
||||
const dados = response.data.dados || response.data;
|
||||
if (Array.isArray(dados) && dados.length > 0) {
|
||||
// Verificar quantos itens realmente pertencem ao cliente
|
||||
const servicosDoCliente = dados.filter(item => {
|
||||
const itemClienteId = parseInt(item.idCliente || item.cliente_id || item.id_cliente || 0, 10);
|
||||
return itemClienteId === clienteIdInt;
|
||||
});
|
||||
|
||||
console.log(`🎯 Serviços filtrados para cliente ${clienteIdInt}: ${servicosDoCliente.length} de ${dados.length} total`);
|
||||
logger.debug('Filtragem de serviços', {
|
||||
clienteIdBuscado: clienteIdInt,
|
||||
servicosEncontrados: servicosDoCliente.length,
|
||||
totalServicos: dados.length,
|
||||
primeiroItem: dados[0] ? {
|
||||
id_cliente: dados[0].id_cliente,
|
||||
idCliente: dados[0].idCliente,
|
||||
cliente_id: dados[0].cliente_id
|
||||
} : null
|
||||
});
|
||||
|
||||
// Se encontrou serviços específicos do cliente, usar essa resposta
|
||||
if (servicosDoCliente.length > 0 || i === tentativas.length - 1) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ Falha na tentativa ${i + 1}: ${error.message}`);
|
||||
if (i === tentativas.length - 1) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -230,19 +337,31 @@ class TopSappAPI {
|
||||
async obterFaturas(idCliente, location = '', credentials) {
|
||||
const instance = this.getInstanceByLocation(location);
|
||||
|
||||
// Obter o idUsuario da sessão atual
|
||||
const session = await this.getValidSession(instance, credentials);
|
||||
|
||||
return await this.makeRequest('ObterDocReceber', {
|
||||
idCliente,
|
||||
situacao: 1 // Faturas em aberto
|
||||
idUsuario: session.idUsuario || 1, // Usar ID do usuário da sessão
|
||||
status: 0, // 0 = Faturas abertas
|
||||
situacaoFatura: 0 // 0 = Faturas ativas
|
||||
}, instance, credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obter dados para pagamento da fatura (linha digitável)
|
||||
*/
|
||||
async obterDadosFatura(idFatura, location = '', credentials) {
|
||||
async obterDadosFatura(idFatura, idCliente, location = '', credentials) {
|
||||
const instance = this.getInstanceByLocation(location);
|
||||
|
||||
return await this.makeRequest('ObterDocReceberDadosFatura', { idFatura }, instance, credentials);
|
||||
// Obter o idUsuario da sessão atual
|
||||
const session = await this.getValidSession(instance, credentials);
|
||||
|
||||
return await this.makeRequest('ObterDocReceberDadosFatura', {
|
||||
idFatura,
|
||||
idCliente,
|
||||
idUsuario: session.idUsuario || 1
|
||||
}, instance, credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -257,28 +376,33 @@ class TopSappAPI {
|
||||
/**
|
||||
* Alterar status do serviço (bloquear/liberar)
|
||||
*/
|
||||
async alterarStatusServico(idServico, status, location = '', credentials) {
|
||||
async alterarStatusServico(idServico, idCliente, status, location = '', credentials) {
|
||||
const instance = this.getInstanceByLocation(location);
|
||||
|
||||
// Obter o idUsuario da sessão atual
|
||||
const session = await this.getValidSession(instance, credentials);
|
||||
|
||||
// Status: 1 = Ativo, 2 = Bloqueado, 3 = Desativado
|
||||
return await this.makeRequest('AlterarServicoStatus', {
|
||||
idServico,
|
||||
status
|
||||
idCliente,
|
||||
idUsuario: session.idUsuario || 1,
|
||||
idStatus: status
|
||||
}, instance, credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bloquear serviço do cliente
|
||||
*/
|
||||
async bloquearServico(idServico, location = '', credentials) {
|
||||
return await this.alterarStatusServico(idServico, 2, location, credentials);
|
||||
async bloquearServico(idServico, idCliente, location = '', credentials) {
|
||||
return await this.alterarStatusServico(idServico, idCliente, 2, location, credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liberar serviço do cliente
|
||||
*/
|
||||
async liberarServico(idServico, location = '', credentials) {
|
||||
return await this.alterarStatusServico(idServico, 1, location, credentials);
|
||||
async liberarServico(idServico, idCliente, location = '', credentials) {
|
||||
return await this.alterarStatusServico(idServico, idCliente, 1, location, credentials);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user