@poli-digital/n8n-nodes-poli
Version:
Nó para interagir com a API da Poli
177 lines • 8.02 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PoliTrigger = void 0;
const n8n_workflow_1 = require("n8n-workflow");
const transport_1 = require("./transport");
class PoliTrigger {
constructor() {
this.description = {
displayName: 'Trigger',
name: 'poliTrigger',
icon: 'file:poli.svg',
group: ['trigger'],
version: 1,
description: 'Trigger para receber webhooks da API da Poli',
defaults: {
name: 'Trigger',
},
subtitle: '={{ $parameter["appName"] }}',
inputs: [],
outputs: ['main'],
credentials: [
{
name: 'poliApi',
required: true,
},
],
webhooks: [
{
name: 'default',
httpMethod: 'POST',
responseMode: 'onReceived',
path: '={{$parameter["webhookPath"]}}',
isStatic: false,
},
],
properties: [
{
displayName: 'App Name',
name: 'appName',
type: 'string',
default: '',
required: true,
description: 'Nome do app que será criado na Poli',
},
{
displayName: 'Eventos',
name: 'events',
type: 'multiOptions',
options: [
{ name: 'Message Received', value: 'message.received' },
{ name: 'Message Status Updated', value: 'message.status' },
{ name: 'Contact Updated', value: 'contact.updated' },
{ name: 'Contact Created', value: 'contact.created' },
],
default: ['message.received'],
required: true,
description: 'Eventos que serão monitorados',
},
{
displayName: 'Webhook Path',
name: 'webhookPath',
type: 'string',
default: 'poli',
required: true,
description: 'Path customizado para a URL do webhook',
},
{
displayName: 'Page',
name: 'page',
type: 'number',
default: 1,
required: false,
description: 'Número da página para listar os aplicativos',
},
],
};
}
async webhook() {
const bodyData = this.getBodyData();
if (!bodyData) {
throw new Error('Nenhum dado recebido no webhook');
}
console.log('📥 Webhook recebido:', JSON.stringify(bodyData, null, 2));
const event = bodyData.event || bodyData.type || 'evento_não_identificado';
const filtered = Object.keys(bodyData)
.filter((key) => !['_debug', 'webhookReceivedAt', 'webhookHeaders', 'baggage', 'x-request-id', 'x-real-ip'].includes(key))
.reduce((acc, key) => {
acc[key] = bodyData[key];
return acc;
}, {});
const structuredOutput = {
event,
timestamp: new Date().toISOString(),
payload: filtered,
};
return {
workflowData: [this.helpers.returnJsonArray([structuredOutput])],
};
}
async activate() {
var _a, _b;
const credentials = await this.getCredentials('poliApi');
const webhookHost = process.env.WEBHOOK_URL || 'http://localhost:5678';
const webhookEndpoint = process.env.N8N_ENDPOINT_WEBHOOK || 'webhook';
const webhookPath = this.getNodeParameter('webhookPath', 0);
const webhookUrl = `${webhookHost}/${webhookEndpoint}/${webhookPath}`;
console.log('🚀 URL de webhook:', webhookUrl);
const accountUuid = credentials.accountUuid;
const events = this.getNodeParameter('events', 0);
const appName = this.getNodeParameter('appName', 0);
const page = this.getNodeParameter('page', 0) || 1;
const perPage = 100;
try {
const appsResponse = await transport_1.apiRequest.call(this, 'GET', `/accounts/${accountUuid}/applications?include=attributes&perPage=${perPage}&page=${page}`);
let applicationId;
const existingApp = (_a = appsResponse.data) === null || _a === void 0 ? void 0 : _a.find((app) => { var _a; return ((_a = app.attributes) === null || _a === void 0 ? void 0 : _a.name) === appName; });
if (existingApp) {
applicationId = existingApp.id;
console.log('🟢 App existente encontrado:', applicationId);
}
else {
const appData = {
visibility: 'PRIVATE',
attributes: {
name: appName,
description: 'App criado pelo n8n para webhooks',
responsible: 'n8n',
email: 'n8n@poli.digital',
phone: '0000000000',
},
};
const appResponse = await transport_1.apiRequest.call(this, 'POST', `/accounts/${accountUuid}/applications?include=attributes`, appData);
applicationId = appResponse.data.id;
console.log('🆕 Novo app criado:', applicationId);
}
const webhooksResponse = await transport_1.apiRequest.call(this, 'GET', `/applications/${applicationId}/webhooks?include=url,subscriptions`);
const webhookExists = (_b = webhooksResponse.data) === null || _b === void 0 ? void 0 : _b.some((webhook) => webhook.url === webhookUrl);
if (!webhookExists) {
const webhookData = {
url: webhookUrl,
subscriptions: events,
};
await transport_1.apiRequest.call(this, 'POST', `/applications/${applicationId}/webhooks?include=url,subscriptions`, webhookData);
console.log('✅ Webhook criado:', webhookUrl);
}
else {
console.log('ℹ️ Webhook já registrado:', webhookUrl);
}
}
catch (error) {
console.error('❌ Erro ao ativar webhook:', error);
throw new n8n_workflow_1.NodeApiError(this.getNode(), error);
}
}
async deactivate() {
var _a;
const credentials = await this.getCredentials('poliApi');
const accountUuid = credentials.accountUuid;
const appName = this.getNodeParameter('appName', 0);
try {
const appsResponse = await transport_1.apiRequest.call(this, 'GET', `/accounts/${accountUuid}/applications?include=attributes`);
const app = (_a = appsResponse.data) === null || _a === void 0 ? void 0 : _a.find((app) => { var _a; return ((_a = app.attributes) === null || _a === void 0 ? void 0 : _a.name) === appName; });
if (app === null || app === void 0 ? void 0 : app.id) {
const webhooksResponse = await transport_1.apiRequest.call(this, 'GET', `/applications/${app.id}/webhooks?include=url,subscriptions`);
for (const webhook of webhooksResponse.data || []) {
await transport_1.apiRequest.call(this, 'DELETE', `/applications/${app.id}/webhooks/${webhook.id}`);
}
console.log('🧹 Webhooks removidos com sucesso');
}
}
catch (error) {
console.error('⚠️ Erro ao desativar webhook:', error);
}
}
}
exports.PoliTrigger = PoliTrigger;
//# sourceMappingURL=PoliTrigger.node.js.map