From 001d1c099ad5fee93e903961c6cff002d37d3a15 Mon Sep 17 00:00:00 2001 From: Rodrigo Bertoldo de Sousa Martins Date: Sun, 29 Mar 2026 10:57:11 -0300 Subject: [PATCH] =?UTF-8?q?datacom:=20faz=20verifica=C3=A7=C3=A3o=20de=20e?= =?UTF-8?q?xistencia=20da=20ONU=20ao=20adicionar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Rodrigo Bertoldo de Sousa Martins --- src/bot/handler.js | 363 ++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 322 insertions(+), 41 deletions(-) diff --git a/src/bot/handler.js b/src/bot/handler.js index df93b5e..39667f4 100644 --- a/src/bot/handler.js +++ b/src/bot/handler.js @@ -1433,6 +1433,12 @@ Digite /help para ver todos os comandos disponíveis! } else if (data.startsWith('remove_onu_')) { console.log(`🔍 Chamando handleRemoveOnuCallback`); await this.handleRemoveOnuCallback(callbackQuery, data); + } else if (data.startsWith('remove_readd_vlan_')) { + console.log(`🔍 Chamando handleRemoveAndReAddCallback (vlan)`); + await this.handleRemoveAndReAddCallback(callbackQuery, data); + } else if (data.startsWith('remove_readd_')) { + console.log(`🔍 Chamando handleRemoveAndReAddCallback`); + await this.handleRemoveAndReAddCallback(callbackQuery, data); } else if (data.startsWith('add_onu_vlan_')) { console.log(`🔍 Chamando handleAddOnuVlanCallback`); await this.handleAddOnuVlanCallback(callbackQuery, data); @@ -2592,6 +2598,170 @@ Digite /help para ver todos os comandos disponíveis! } } + /** + * Handle callback para iniciar processo de adição de ONU + */ + /** + * Handler: remove ONU já cadastrada e tenta readicioná-la automaticamente. + * Formatos de callback_data: + * remove_readd____ + * remove_readd_vlan_____ + */ + async handleRemoveAndReAddCallback(callbackQuery, data) { + const chatId = callbackQuery.message.chat.id; + const hasVlan = data.startsWith('remove_readd_vlan_'); + const parts = data.split('_'); + + let oltId, slot, onuId, vlanId, serialNumber; + + if (hasVlan) { + // remove_readd_vlan_olt_pedro_afonso_slot_onuId_vlanId_serial + // remove_readd_vlan_olt_dito_slot_onuId_vlanId_serial + // parts[0]=remove [1]=readd [2]=vlan [3]=olt [4]=dito|pedro [5]=afonso|slot ... + if (parts[4] === 'pedro' && parts[5] === 'afonso') { + oltId = parts[3] + '_' + parts[4] + '_' + parts[5]; + slot = parts[6].replace(/-/g, '/'); + onuId = parts[7]; + vlanId = parts[8]; + serialNumber = parts.slice(9).join('_'); + } else { + oltId = parts[3] + '_' + parts[4]; + slot = parts[5].replace(/-/g, '/'); + onuId = parts[6]; + vlanId = parts[7]; + serialNumber = parts.slice(8).join('_'); + } + } else { + // remove_readd_olt_pedro_afonso_slot_onuId_serial + // remove_readd_olt_dito_slot_onuId_serial + // parts[0]=remove [1]=readd [2]=olt [3]=dito|pedro [4]=afonso|slot ... + if (parts[3] === 'pedro' && parts[4] === 'afonso') { + oltId = parts[2] + '_' + parts[3] + '_' + parts[4]; + slot = parts[5].replace(/-/g, '/'); + onuId = parts[6]; + serialNumber = parts.slice(7).join('_'); + } else { + oltId = parts[2] + '_' + parts[3]; + slot = parts[4].replace(/-/g, '/'); + onuId = parts[5]; + serialNumber = parts.slice(6).join('_'); + } + } + + console.log(`🗑️➕ remove_readd - oltId: ${oltId}, slot: ${slot}, onuId: ${onuId}, vlanId: ${vlanId || 'auto'}, serial: ${serialNumber}`); + + await this.bot.answerCallbackQuery(callbackQuery.id); + + await this.bot.editMessageText( + `🗑️ **Removendo ONU cadastrada...**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `📍 **Slot:** ${slot}, ONU ${onuId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `⏳ Aguarde...`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + + try { + const removeResult = await this.ssh.removeOnu(oltId, slot, onuId); + + if (!removeResult.success) { + await this.bot.editMessageText( + `❌ **Erro ao remover ONU**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `❌ **Erro:** ${removeResult.message}\n\n` + + `🔄 Verifique o status da ONU e tente novamente.`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + return; + } + + // ONU removida — aguardar brevemente e tentar redescobrir + await this.bot.editMessageText( + `✅ **ONU removida!** Aguardando redescoberta...\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `⏳ Verificando discovered-onus...`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + + // Aguardar 4 segundos para a ONU voltar à lista de discovered + await new Promise(resolve => setTimeout(resolve, 4000)); + + const addResult = await this.ssh.addOnuBySerial(oltId, serialNumber, vlanId || undefined); + + if (addResult.success && addResult.readyForAddition) { + const effectiveVlan = vlanId || addResult.vlanId; + const keyboard = { + inline_keyboard: [ + [ + { text: '✅ CONFIRMAR ADIÇÃO', callback_data: `confirm_add_${oltId}_${addResult.slot.replace(/\//g, '-')}_${addResult.onuId}_${effectiveVlan}_${serialNumber}` } + ], + [ + { text: '❌ Cancelar', callback_data: 'cancel_action' } + ] + ] + }; + + await this.bot.editMessageText( + `✅ **ONU pronta para adição!**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `📍 **Slot descoberto:** ${addResult.slot}\n` + + `🔢 **ONU ID a usar:** ${addResult.onuId}\n` + + `🏷️ **VLAN ID:** ${effectiveVlan}${vlanId ? ' (customizada)' : ''}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `📋 **ONU IDs em uso no slot:** ${addResult.usedIds.join(', ')}\n\n` + + `✅ **Confirme que deseja adicionar esta ONU:**`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown', + reply_markup: keyboard + } + ); + } else { + // ONU não apareceu em discovered-onus ainda + await this.bot.editMessageText( + `✅ **ONU removida com sucesso!**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `⚠️ A ONU ainda não apareceu como disponível para adição.\n\n` + + `💡 Aguarde alguns instantes e tente:\n` + + `\`adicionar onu ${serialNumber}\``, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + } + } catch (error) { + console.error('Erro em handleRemoveAndReAddCallback:', error); + await this.bot.editMessageText( + `❌ **Erro interno**\n\n` + + `Não foi possível concluir a operação.\n` + + `Erro: ${error.message}`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + } + } + /** * Handle callback para iniciar processo de adição de ONU */ @@ -2667,28 +2837,82 @@ Digite /help para ver todos os comandos disponíveis! } ); } else { - let errorMessage = `❌ **Não foi possível adicionar a ONU**\n\n` + - `📱 **Serial:** ${serialNumber}\n` + - `🏢 **OLT:** ${oltId.replace('olt_', '').toUpperCase()}\n\n`; - - if (result.message) { - errorMessage += `❌ **Erro:** ${result.message}\n\n`; - } - + // ONU não encontrada em discovered-onus — verificar se já está cadastrada no running-config if (result.message && result.message.includes('discovered-onus')) { - errorMessage += `💡 **Dica:** Verifique se a ONU está ligada e descoberta pela OLT.\n` + - `Use o comando: \`show interface gpon discovered-onus\``; - } else if (result.message && result.message.includes('todos os ONU IDs')) { - errorMessage += `💡 **Dica:** O slot está lotado. Considere usar outro slot ou remover ONUs inutilizadas.`; - } else { - errorMessage += `💡 Verifique a conectividade com a OLT ou se a ONU está descoberta.`; - } + await this.bot.editMessageText( + `🔍 **ONU não disponível para adição**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').toUpperCase()}\n\n` + + `⏳ Verificando se a ONU já está cadastrada...`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); - await this.bot.editMessageText(errorMessage, { - chat_id: chatId, - message_id: callbackQuery.message.message_id, - parse_mode: 'Markdown' - }); + const findResult = await this.ssh.findOnuBySerial(oltId, serialNumber); + + if (findResult.success && findResult.onuInfo && findResult.onuInfo.found) { + const { slot, onuId } = findResult.onuInfo; + const keyboard = { + inline_keyboard: [ + [ + { text: '🗑️ Remover e adicionar novamente', callback_data: `remove_readd_${oltId}_${slot.replace(/\//g, '-')}_${onuId}_${serialNumber}` } + ], + [ + { text: '❌ Cancelar', callback_data: 'cancel_action' } + ] + ] + }; + await this.bot.editMessageText( + `⚠️ **ONU já cadastrada na OLT**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `📍 **Localização atual:** Slot ${slot}, ONU ${onuId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').toUpperCase()}\n\n` + + `A ONU já está cadastrada e não aparece como disponível para adição.\n\n` + + `Deseja **remover** o cadastro atual e adicioná-la novamente?`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown', + reply_markup: keyboard + } + ); + } else { + await this.bot.editMessageText( + `❌ **ONU não disponível**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').toUpperCase()}\n\n` + + `A ONU não foi encontrada em discovered-onus nem no running-config.\n\n` + + `💡 **Dica:** Verifique se a ONU está ligada e conectada à OLT.\n` + + `Use o comando: \`show interface gpon discovered-onus\``, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + } + } else { + let errorMessage = `❌ **Não foi possível adicionar a ONU**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').toUpperCase()}\n\n`; + + if (result.message) errorMessage += `❌ **Erro:** ${result.message}\n\n`; + + if (result.message && result.message.includes('todos os ONU IDs')) { + errorMessage += `💡 **Dica:** O slot está lotado. Considere usar outro slot ou remover ONUs inutilizadas.`; + } else { + errorMessage += `💡 Verifique a conectividade com a OLT ou se a ONU está descoberta.`; + } + + await this.bot.editMessageText(errorMessage, { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + }); + } } } catch (error) { console.error('Erro ao analisar ONU para adição:', error); @@ -2787,29 +3011,86 @@ Digite /help para ver todos os comandos disponíveis! } ); } else { - let errorMessage = `❌ **Não foi possível adicionar a ONU**\n\n` + - `📱 **Serial:** ${serialNumber}\n` + - `🏷️ **VLAN:** ${vlanId}\n` + - `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n`; - - if (result.message) { - errorMessage += `❌ **Erro:** ${result.message}\n\n`; - } - + // ONU não encontrada em discovered-onus — verificar se já está cadastrada no running-config if (result.message && result.message.includes('discovered-onus')) { - errorMessage += `💡 **Dica:** Verifique se a ONU está ligada e descoberta pela OLT.\n` + - `Use o comando: \`show interface gpon discovered-onus\``; - } else if (result.message && result.message.includes('todos os ONU IDs')) { - errorMessage += `💡 **Dica:** O slot está lotado. Considere usar outro slot ou remover ONUs inutilizadas.`; - } else { - errorMessage += `💡 Verifique a conectividade com a OLT ou se a ONU está descoberta.`; - } + await this.bot.editMessageText( + `🔍 **ONU não disponível para adição**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏷️ **VLAN:** ${vlanId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `⏳ Verificando se a ONU já está cadastrada...`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); - await this.bot.editMessageText(errorMessage, { - chat_id: chatId, - message_id: callbackQuery.message.message_id, - parse_mode: 'Markdown' - }); + const findResult = await this.ssh.findOnuBySerial(oltId, serialNumber); + + if (findResult.success && findResult.onuInfo && findResult.onuInfo.found) { + const { slot, onuId } = findResult.onuInfo; + const keyboard = { + inline_keyboard: [ + [ + { text: '🗑️ Remover e adicionar novamente', callback_data: `remove_readd_vlan_${oltId}_${slot.replace(/\//g, '-')}_${onuId}_${vlanId}_${serialNumber}` } + ], + [ + { text: '❌ Cancelar', callback_data: 'cancel_action' } + ] + ] + }; + await this.bot.editMessageText( + `⚠️ **ONU já cadastrada na OLT**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `📍 **Localização atual:** Slot ${slot}, ONU ${onuId}\n` + + `🏷️ **VLAN a usar:** ${vlanId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `A ONU já está cadastrada e não aparece como disponível para adição.\n\n` + + `Deseja **remover** o cadastro atual e adicioná-la novamente com VLAN ${vlanId}?`, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown', + reply_markup: keyboard + } + ); + } else { + await this.bot.editMessageText( + `❌ **ONU não disponível**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏷️ **VLAN:** ${vlanId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n` + + `A ONU não foi encontrada em discovered-onus nem no running-config.\n\n` + + `💡 **Dica:** Verifique se a ONU está ligada e conectada à OLT.\n` + + `Use o comando: \`show interface gpon discovered-onus\``, + { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + } + ); + } + } else { + let errorMessage = `❌ **Não foi possível adicionar a ONU**\n\n` + + `📱 **Serial:** ${serialNumber}\n` + + `🏷️ **VLAN:** ${vlanId}\n` + + `🏢 **OLT:** ${oltId.replace('olt_', '').replace(/_/g, '\\_').toUpperCase()}\n\n`; + + if (result.message) errorMessage += `❌ **Erro:** ${result.message}\n\n`; + + if (result.message && result.message.includes('todos os ONU IDs')) { + errorMessage += `💡 **Dica:** O slot está lotado. Considere usar outro slot ou remover ONUs inutilizadas.`; + } else { + errorMessage += `💡 Verifique a conectividade com a OLT ou se a ONU está descoberta.`; + } + + await this.bot.editMessageText(errorMessage, { + chat_id: chatId, + message_id: callbackQuery.message.message_id, + parse_mode: 'Markdown' + }); + } } } catch (error) { console.error('Erro ao analisar ONU para adição com VLAN customizada:', error);