UNPKG

@corlabs-holding/n8n-nodes-bankerize

Version:

N8n community nodes para integração completa com API Bankerize - 4 nodes especializados: FGTS, E-Consignado, Gerenciamento de Propostas e Administração

1,135 lines (1,134 loc) 60.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BankerizeFgts = void 0; const n8n_workflow_1 = require("n8n-workflow"); const BankerizeHelpers_1 = require("./BankerizeHelpers"); class BankerizeFgts { constructor() { this.description = { displayName: 'Bankerize - FGTS', name: 'bankerizeFgts', icon: 'file:icon.svg', group: ['transform'], version: 1, subtitle: '={{$parameter.operation}}', description: 'Gerenciar operações FGTS da API Bankerize: simular propostas (incluindo por parcelas), criar propostas e consultar status. Use para realizar operações de antecipação do Saque-Aniversário FGTS.', defaults: { name: 'Bankerize - FGTS', }, inputs: ["main" /* NodeConnectionType.Main */], outputs: ["main" /* NodeConnectionType.Main */], usableAsTool: true, // IMPORTANTE: Para funcionar como tool credentials: [ { name: 'bankerizeCredentialsApi', required: true, }, ], properties: [ { displayName: 'Operation', name: 'operation', type: 'options', noDataExpression: true, options: [ { name: 'Simulate', value: 'simulate', description: 'Simular proposta FGTS', action: 'Simular proposta FGTS', }, { name: 'Simulate by Installments', value: 'simulateByInstallments', description: 'Simular proposta FGTS manipulando parcelas específicas', action: 'Simular FGTS por parcelas', }, { name: 'Create Proposal', value: 'createProposal', description: 'Criar proposta FGTS', action: 'Criar proposta FGTS', }, { name: 'Get Proposal', value: 'getProposal', description: 'Consultar proposta FGTS', action: 'Consultar proposta FGTS', }, ], default: 'simulate', }, // FGTS Simulate fields { displayName: 'CPF', name: 'cpf', type: 'string', displayOptions: { show: { operation: ['simulate'], }, }, default: '', required: true, description: 'CPF do cliente (apenas números)', }, { displayName: 'Banco', name: 'bank', type: 'options', displayOptions: { show: { operation: ['simulate'], }, }, options: [ { name: 'BMP', value: 'bmp', }, ], default: 'bmp', required: true, description: 'Banco parceiro para a operação', }, { displayName: 'Valor Desejado', name: 'desiredValue', type: 'string', displayOptions: { show: { operation: ['simulate'], }, }, default: '', description: 'Valor líquido desejado (deixe vazio ou "null" para valor máximo)', }, { displayName: 'Filtrar por ID da Tabela', name: 'tableIds', type: 'string', displayOptions: { show: { operation: ['simulate'], }, }, default: '', description: 'Filtra a resposta para mostrar apenas as tabelas com os IDs especificados. Use vírgulas para múltiplos IDs (ex: cb9a1a44-b25b-4cdb-9da1-ae21a0a61507). Deixe vazio para retornar todas as tabelas disponíveis.', placeholder: 'cb9a1a44-b25b-4cdb-9da1-ae21a0a61507', }, { displayName: 'Traduzir Resposta', name: 'translateResponse', type: 'boolean', displayOptions: { show: { operation: ['simulate'], }, }, default: false, description: 'Whether to translate response fields to Portuguese (ex: error -> erro, table -> tabela)', }, // FGTS Simulate by Installments fields { displayName: 'CPF', name: 'installmentCpf', type: 'string', displayOptions: { show: { operation: ['simulateByInstallments'], }, }, default: '', required: true, description: 'CPF do cliente (apenas números)', }, { displayName: 'Banco', name: 'installmentBank', type: 'options', displayOptions: { show: { operation: ['simulateByInstallments'], }, }, options: [ { name: 'BMP', value: 'bmp', }, ], default: 'bmp', required: true, description: 'Banco parceiro para a operação', }, { displayName: 'Table ID', name: 'tableId', type: 'string', displayOptions: { show: { operation: ['simulateByInstallments'], }, }, default: '', required: true, description: 'ID da tabela obtido na simulação inicial (ex: 51acd201-0dc8-475e-9f43-e74c423cb6a0)', placeholder: '51acd201-0dc8-475e-9f43-e74c423cb6a0', }, { displayName: 'Parcelas', name: 'installments', type: 'json', displayOptions: { show: { operation: ['simulateByInstallments'], }, }, default: `[ { "date": "2024-10-01", "released_value": 1000, "available_value": 1500 }, { "date": "2024-11-01", "released_value": 800, "available_value": 1200 } ]`, required: true, description: 'Array JSON com as parcelas a manipular. Cada parcela deve ter: date (YYYY-MM-DD), released_value (valor liberado) e available_value (valor disponível)', typeOptions: { rows: 10, }, }, // FGTS Create Proposal fields { displayName: 'Simulation ID', name: 'simulationId', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'ID da simulação escolhida', }, // Dados Pessoais { displayName: 'Dados Pessoais', name: 'personalDataNotice', type: 'notice', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Preencha os dados pessoais do cliente', }, { displayName: 'Nome Completo', name: 'customerName', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Nome completo do cliente', }, { displayName: 'CPF', name: 'customerCpf', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'CPF do cliente (apenas números)', }, { displayName: 'Data De Nascimento', name: 'birthDate', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, placeholder: 'YYYY-MM-DD', description: 'Data de nascimento no formato YYYY-MM-DD (ex: 1990-12-25)', }, { displayName: 'Gênero', name: 'gender', type: 'options', displayOptions: { show: { operation: ['createProposal'], }, }, options: [ { name: 'Masculino', value: 'M', }, { name: 'Feminino', value: 'F', }, ], default: 'M', required: true, description: 'Gênero do cliente', }, { displayName: 'Estado Civil', name: 'civilStatus', type: 'options', displayOptions: { show: { operation: ['createProposal'], }, }, options: [ { name: 'Solteiro(a)', value: '1' }, { name: 'Casado(a)', value: '2' }, { name: 'Divorciado(a)', value: '3' }, { name: 'Separado(a)', value: '4' }, { name: 'Viúvo(a)', value: '5' }, { name: 'Outros', value: '6' }, ], default: '1', required: true, description: 'Estado civil do cliente', }, { displayName: 'Escolaridade', name: 'scholarity', type: 'options', displayOptions: { show: { operation: ['createProposal'], }, }, options: [ { name: 'Maternal Incompleto', value: '1' }, { name: 'Maternal Completo', value: '2' }, { name: 'Ensino Fundamental Incompleto', value: '3' }, { name: 'Ensino Fundamental Completo', value: '4' }, { name: 'Ensino Médio Incompleto', value: '5' }, { name: 'Ensino Médio Completo', value: '6' }, { name: 'Ensino Superior Incompleto', value: '7' }, { name: 'Ensino Superior Completo', value: '8' }, ], default: '6', required: true, description: 'Escolaridade do cliente', }, { displayName: 'Número Do RG', name: 'rgNumber', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Número do RG do cliente', }, { displayName: 'Órgão Emissor Do RG', name: 'rgOrgan', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: 'SSP', required: true, description: 'Órgão emissor do RG (ex: SSP)', }, { displayName: 'UF Do RG', name: 'rgUf', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'UF onde o RG foi emitido (ex: SP)', }, // Contatos { displayName: 'Contatos', name: 'contactsNotice', type: 'notice', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Informações de contato do cliente', }, { displayName: 'Email', name: 'email', type: 'string', placeholder: 'name@email.com', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Email do cliente', }, { displayName: 'Celular', name: 'celphone', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Celular do cliente (ex: 11987654321)', }, // Endereço { displayName: 'Endereço', name: 'addressNotice', type: 'notice', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Endereço residencial do cliente', }, { displayName: 'CEP', name: 'zipcode', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'CEP (apenas números)', }, { displayName: 'Rua', name: 'street', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Nome da rua/logradouro', }, { displayName: 'Número', name: 'addressNumber', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Número do endereço', }, { displayName: 'Complemento', name: 'complement', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Complemento (apartamento, casa, etc.)', }, { displayName: 'Bairro', name: 'district', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, }, { displayName: 'Cidade', name: 'city', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, }, { displayName: 'UF', name: 'uf', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Estado (UF) - ex: SP, RJ, MG', }, // Dados Bancários { displayName: 'Dados Bancários', name: 'bankNotice', type: 'notice', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Conta bancária onde será creditado o valor', }, { displayName: 'Código Do Banco', name: 'bankId', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Código do banco (ex: 237 para Bradesco, 1 para Banco do Brasil)', }, { displayName: 'Tipo De Conta', name: 'accountType', type: 'options', displayOptions: { show: { operation: ['createProposal'], }, }, options: [ { name: 'Conta Corrente', value: 'CCT' }, { name: 'Conta Poupança', value: 'CPP' }, { name: 'Conta Pagamento', value: 'CPG' }, ], default: 'CCT', required: true, description: 'Tipo da conta bancária', }, { displayName: 'Agência', name: 'agency', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Número da agência (sem dígito)', }, { displayName: 'Dígito Da Agência', name: 'agencyDigit', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Dígito verificador da agência', }, { displayName: 'Número Da Conta', name: 'accountNumber', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Número da conta (sem dígito)', }, { displayName: 'Dígito Da Conta', name: 'accountDigit', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Dígito verificador da conta', }, { displayName: 'Valor Split', name: 'splitValue', type: 'number', displayOptions: { show: { operation: ['createProposal'], }, }, default: 100, required: true, description: 'Valor da comissão/split', }, // Assinantes { displayName: 'Assinantes', name: 'subscribersNotice', type: 'notice', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', description: 'Dados dos assinantes do empréstimo', }, { displayName: 'CPF Do Assinante', name: 'subscriberCpf', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'CPF do assinante (apenas números)', }, { displayName: 'Nome Do Assinante', name: 'subscriberName', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, description: 'Nome completo do assinante', }, { displayName: 'Email Do Assinante', name: 'subscriberEmail', type: 'string', displayOptions: { show: { operation: ['createProposal'], }, }, default: '', required: true, placeholder: 'assinante@email.com', }, // FGTS Get Proposal fields { displayName: 'Proposal Code', name: 'proposalCode', type: 'string', displayOptions: { show: { operation: ['getProposal'], }, }, default: '', required: true, description: 'Código da proposta para consulta', }, ], }; } async execute() { var _a, _b, _c, _d; const items = this.getInputData(); const returnData = []; for (let i = 0; i < items.length; i++) { try { const operation = this.getNodeParameter('operation', i); const credentials = await this.getCredentials('bankerizeCredentialsApi'); const responseData = await handleFgtsOperations.call(this, operation, i, credentials); if (responseData === undefined || responseData === null) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Operação não retornou dados: ${operation}`); } // Se a resposta for um array (de 'simulate'), divida-a em vários itens n8n. // Caso contrário (para 'create' ou 'get'), trate-a como um único item. if (Array.isArray(responseData)) { if (responseData.length === 0) { // Lidar com o caso em que o filtro não retorna resultados const message = { message: "Nenhuma tabela encontrada com os IDs fornecidos." }; returnData.push({ json: message, pairedItem: { item: i } }); } else { // Crie um novo item n8n para cada objeto no array const executionData = responseData.map(item => ({ json: item, pairedItem: { item: i } })); returnData.push(...executionData); } } else { // É um único objeto returnData.push({ json: responseData, pairedItem: { item: i } }); } } catch (error) { if (this.continueOnFail()) { // Se houver resposta de erro da API, preservar a estrutura exata if (error.response) { const errorData = { status: error.response.status, statusText: error.response.statusText || 'Error', data: ((_a = error.response.data) === null || _a === void 0 ? void 0 : _a.data) || [], message: ((_b = error.response.data) === null || _b === void 0 ? void 0 : _b.message) || error.message || 'Unknown error' }; returnData.push({ json: errorData, pairedItem: { item: i }, }); continue; } // Para outros tipos de erro returnData.push({ json: { error: error.message || 'Unknown error', details: error }, pairedItem: { item: i }, }); continue; } // Para AI Agent (usado como tool), preservar a mensagem de erro igual ao modo manual if (error.response) { const errorData = { status: error.response.status, statusText: error.response.statusText || 'Error', data: ((_c = error.response.data) === null || _c === void 0 ? void 0 : _c.data) || [], message: ((_d = error.response.data) === null || _d === void 0 ? void 0 : _d.message) || error.message || 'Unknown error' }; returnData.push({ json: errorData, pairedItem: { item: i }, }); continue; } // Se não for para continuar em caso de falha, usar o helper (0, BankerizeHelpers_1.handleBankerizeError)(error, this.getNode()); } } return [returnData]; } } exports.BankerizeFgts = BankerizeFgts; // Função para obter URLs baseadas no ambiente function getUrls(credentials) { const environment = credentials.environment; if (environment === 'develop') { return { authUrl: 'https://develop.auth.bankerize.com.br/realms/bankerize/protocol/openid-connect/token', apiUrl: 'https://develop.api.bankerize.com.br/v1', }; } else { return { authUrl: 'https://auth.bankerize.com.br/realms/bankerize/protocol/openid-connect/token', apiUrl: 'https://api.bankerize.com.br/v1', }; } } // Função para obter token de acesso async function getAccessToken(credentials) { const { authUrl } = getUrls(credentials); const formData = `grant_type=client_credentials&client_id=${encodeURIComponent(credentials.clientId)}&client_secret=${encodeURIComponent(credentials.clientSecret)}`; try { const response = await this.helpers.httpRequest({ method: 'POST', url: authUrl, headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', }, body: formData, }); if (!response.access_token) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Resposta de autenticação inválida - Token não encontrado na resposta da API'); } return response.access_token; } catch (error) { (0, BankerizeHelpers_1.handleBankerizeError)(error, this.getNode()); } } // Operações FGTS async function handleFgtsOperations(operation, itemIndex, credentials) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; const { apiUrl } = getUrls(credentials); const accessToken = await getAccessToken.call(this, credentials); const headers = { 'Authorization': `Bearer ${accessToken}`, 'Accept': 'application/json', 'Content-Type': 'application/json', }; switch (operation) { case 'simulate': { const cpf = this.getNodeParameter('cpf', itemIndex); const bank = this.getNodeParameter('bank', itemIndex); const desiredValue = this.getNodeParameter('desiredValue', itemIndex); const tableIds = this.getNodeParameter('tableIds', itemIndex); const translateResponse = this.getNodeParameter('translateResponse', itemIndex); // Validações de entrada if (!cpf || cpf.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF é obrigatório para simulação'); } const cleanCpf = cpf.replace(/\D/g, ''); if (cleanCpf.length !== 11) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF deve conter exatamente 11 dígitos'); } if (!bank || bank.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Banco é obrigatório para simulação'); } // Processar desired_value let processedDesiredValue = null; if (desiredValue && desiredValue.trim() !== '' && desiredValue.toLowerCase() !== 'null') { const numValue = parseFloat(desiredValue); if (isNaN(numValue) || numValue <= 0 || numValue > 999999) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Valor desejado deve ser um número entre R$ 1,00 e R$ 999.999,00 ou deixe em branco para valor máximo'); } processedDesiredValue = numValue; } const body = { cpf: cleanCpf, bank, desired_value: processedDesiredValue, }; let apiResponse; try { apiResponse = await this.helpers.httpRequest({ method: 'POST', url: `${apiUrl}/proposals/fgts/simulate`, headers, body, json: true, }); } catch (httpError) { // Captura erro HTTP e preserva a mensagem da API if ((_b = (_a = httpError.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.message) { // Retorna o erro como sucesso com estrutura de erro return [{ error: true, status: httpError.response.status || 502, statusText: httpError.response.statusText || 'Bad Gateway', data: ((_c = httpError.response.data) === null || _c === void 0 ? void 0 : _c.data) || [], message: httpError.response.data.message }]; } throw httpError; } // Verificação especial para debug - retorna informações se filtro específico for usado if (tableIds === 'DEBUG_VERSION_1.2.0') { return [{ debug: true, version: '1.2.0', timestamp: new Date().toISOString(), message: 'Esta é a versão 1.2.0 com filtro corrigido e tradução', original_tables_count: Array.isArray(apiResponse) ? ((_e = (_d = apiResponse[0]) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.length) || 0 : ((_f = apiResponse === null || apiResponse === void 0 ? void 0 : apiResponse.data) === null || _f === void 0 ? void 0 : _f.length) || 0, translate_response_param: translateResponse }]; } // Debug específico para tradução if (tableIds === 'TEST_TRANSLATION') { const testData = { error: false, table: { id: 'test-id', name: 'Test Table' }, tc_percentage: 10, simulation: { rules: { allow_simulate_by_installments: true }, payload: { net_value: 1000, gross_value: 1200 } } }; if (translateResponse) { return [translateToPortuguese(testData)]; } else { return [testData]; } } // Teste do filtro com múltiplas tabelas if (tableIds === 'TEST_FILTER') { const mockApiResponse = { data: [ { error: false, table: { id: 'cb9a1a44-b25b-4cdb-9da1-ae21a0a61507', name: 'Hogwarts Plus' }, tc_percentage: 35, simulation: { rules: { allow_simulate_by_installments: false }, payload: { net_value: 57.25, gross_value: 103.01 } } }, { error: false, table: { id: '1b791376-8c87-44fb-8651-44438f96825f', name: 'Banco Premium' }, tc_percentage: 30, simulation: { rules: { allow_simulate_by_installments: true }, payload: { net_value: 65.50, gross_value: 120.00 } } }, { error: false, table: { id: '9f2d3e45-a1b2-4c5d-8e9f-0123456789ab', name: 'Fintech Gold' }, tc_percentage: 25, simulation: { rules: { allow_simulate_by_installments: true }, payload: { net_value: 78.75, gross_value: 140.25 } } } ], message: 'Simulação realizada com sucesso!' }; return { test_info: 'Teste do filtro - use tableIds: cb9a1a44-b25b-4cdb-9da1-ae21a0a61507 para filtrar apenas a primeira tabela', original_response: mockApiResponse, total_tables: mockApiResponse.data.length, available_table_ids: mockApiResponse.data.map(item => item.table.id) }; } // Extrai o array de dados principal da resposta let allTables = []; // Trata diferentes estruturas de resposta possíveis if (Array.isArray(apiResponse)) { // Se a resposta é um array, pega o primeiro elemento const firstElement = apiResponse[0]; if (firstElement && firstElement.data && Array.isArray(firstElement.data)) { allTables = firstElement.data; } } else if (apiResponse && apiResponse.data && Array.isArray(apiResponse.data)) { // Se a resposta é um objeto com propriedade data allTables = apiResponse.data; } // Aplica filtragem se tableIds foi fornecido if (tableIds && tableIds.trim()) { // Parse dos IDs removendo espaços e entradas vazias const tableIdList = tableIds .split(',') .map(id => id.trim()) .filter(id => id.length > 0); if (tableIdList.length > 0) { // Filtra as tabelas que têm ID correspondente const filteredTables = allTables.filter((item) => { // Verifica se o item tem a estrutura esperada if (!item || typeof item !== 'object' || !item.table || !item.table.id) { return false; } // Verifica se o ID da tabela está na lista de IDs desejados return tableIdList.includes(item.table.id); }); // Preserva a estrutura original da resposta da API const filteredResponse = { data: translateResponse ? filteredTables.map(item => translateToPortuguese(item)) : filteredTables, message: apiResponse.message || 'Simulação realizada com sucesso!' }; return filteredResponse; } } // Se não houver filtro ou a lista de IDs estiver vazia, retorna todas as tabelas // Preserva a estrutura original da resposta da API const fullResponse = { data: translateResponse ? allTables.map(item => translateToPortuguese(item)) : allTables, message: apiResponse.message || 'Simulação realizada com sucesso!' }; return fullResponse; } case 'simulateByInstallments': { const cpf = this.getNodeParameter('installmentCpf', itemIndex); const bank = this.getNodeParameter('installmentBank', itemIndex); const tableId = this.getNodeParameter('tableId', itemIndex); const installmentsParam = this.getNodeParameter('installments', itemIndex); // Validações de entrada if (!cpf || cpf.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF é obrigatório para simulação por parcelas'); } const cleanCpf = cpf.replace(/\D/g, ''); if (cleanCpf.length !== 11) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF deve conter exatamente 11 dígitos'); } if (!bank || bank.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Banco é obrigatório para simulação por parcelas'); } if (!tableId || tableId.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Table ID é obrigatório - obtenha este ID na simulação inicial'); } if (!installmentsParam || installmentsParam.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Array de parcelas é obrigatório'); } // Parse e validação do JSON de parcelas let installments; try { installments = JSON.parse(installmentsParam); } catch (parseError) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Array de parcelas deve ser um JSON válido'); } if (!Array.isArray(installments) || installments.length === 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Array de parcelas deve conter pelo menos uma parcela'); } // Validar cada parcela for (let i = 0; i < installments.length; i++) { const installment = installments[i]; if (!installment.date) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Parcela ${i + 1}: campo 'date' é obrigatório`); } // Validar formato da data const dateRegex = /^\d{4}-\d{2}-\d{2}$/; if (!dateRegex.test(installment.date)) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Parcela ${i + 1}: data deve estar no formato YYYY-MM-DD (ex: 2024-10-01)`); } if (typeof installment.released_value !== 'number' || installment.released_value <= 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Parcela ${i + 1}: 'released_value' deve ser um número maior que zero`); } if (typeof installment.available_value !== 'number' || installment.available_value <= 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Parcela ${i + 1}: 'available_value' deve ser um número maior que zero`); } if (installment.released_value > installment.available_value) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Parcela ${i + 1}: 'released_value' não pode ser maior que 'available_value'`); } } const body = { cpf: cleanCpf, bank: bank, table_id: tableId.trim(), installments: installments, }; try { return await this.helpers.httpRequest({ method: 'POST', url: `${apiUrl}/proposals/fgts/installment-simulation`, headers, body, json: true, }); } catch (httpError) { // Captura erro HTTP e preserva a mensagem da API if ((_h = (_g = httpError.response) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.message) { // Retorna o erro como sucesso com estrutura de erro return { error: true, status: httpError.response.status || 502, statusText: httpError.response.statusText || 'Bad Gateway', data: ((_j = httpError.response.data) === null || _j === void 0 ? void 0 : _j.data) || [], message: httpError.response.data.message }; } throw httpError; } } case 'createProposal': { const simulationId = this.getNodeParameter('simulationId', itemIndex); const splitValue = this.getNodeParameter('splitValue', itemIndex); // Dados pessoais const customerName = this.getNodeParameter('customerName', itemIndex); const customerCpf = this.getNodeParameter('customerCpf', itemIndex); const birthDate = this.getNodeParameter('birthDate', itemIndex); const gender = this.getNodeParameter('gender', itemIndex); const civilStatus = this.getNodeParameter('civilStatus', itemIndex); const scholarity = this.getNodeParameter('scholarity', itemIndex); const rgNumber = this.getNodeParameter('rgNumber', itemIndex); const rgOrgan = this.getNodeParameter('rgOrgan', itemIndex); const rgUf = this.getNodeParameter('rgUf', itemIndex); // Contatos const email = this.getNodeParameter('email', itemIndex); const celphone = this.getNodeParameter('celphone', itemIndex); // Endereço const zipcode = this.getNodeParameter('zipcode', itemIndex); const street = this.getNodeParameter('street', itemIndex); const addressNumber = this.getNodeParameter('addressNumber', itemIndex); const complement = this.getNodeParameter('complement', itemIndex); const district = this.getNodeParameter('district', itemIndex); const city = this.getNodeParameter('city', itemIndex); const uf = this.getNodeParameter('uf', itemIndex); // Dados bancários const bankId = this.getNodeParameter('bankId', itemIndex); const accountType = this.getNodeParameter('accountType', itemIndex); const agency = this.getNodeParameter('agency', itemIndex); const agencyDigit = this.getNodeParameter('agencyDigit', itemIndex); const accountNumber = this.getNodeParameter('accountNumber', itemIndex); const accountDigit = this.getNodeParameter('accountDigit', itemIndex); // Assinante const subscriberCpf = this.getNodeParameter('subscriberCpf', itemIndex); const subscriberName = this.getNodeParameter('subscriberName', itemIndex); const subscriberEmail = this.getNodeParameter('subscriberEmail', itemIndex); // Validações de entrada obrigatórias if (!simulationId || simulationId.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'ID da simulação é obrigatório para criar proposta'); } if (!splitValue || splitValue <= 0) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Valor do split deve ser maior que zero'); } // Validações dados pessoais if (!customerName || customerName.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Nome do cliente é obrigatório'); } if (!customerCpf || customerCpf.trim() === '') { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF do cliente é obrigatório'); } const cleanCustomerCpf = customerCpf.replace(/\D/g, ''); if (cleanCustomerCpf.length !== 11) { throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'CPF do cliente deve conter exatamente 11 dígitos'); }