diff --git a/app/Http/Controllers/Admin/ChatBotController.php b/app/Http/Controllers/Admin/ChatBotController.php index e1ece97..f1733a1 100644 --- a/app/Http/Controllers/Admin/ChatBotController.php +++ b/app/Http/Controllers/Admin/ChatBotController.php @@ -266,4 +266,101 @@ class ChatBotController extends Controller return response()->json($response); } + + public function testRequest(Request $request) + { + $jsonData = $request->getContent(); + $step = json_decode($jsonData, true); + $queryParams = array(); + + $tempvars = $step['options']['webhook']['temporaryVars']; + $url = $this->formatarTexto($step['options']['webhook']['url'], $tempvars); + $method = strtoupper($step['options']['webhook']['method']); + $queryParams = isset($step['options']['webhook']['queryParams']) ? $step['options']['webhook']['queryParams'] : []; + $authorization = isset($step['options']['webhook']['authorization']) ? $step['options']['webhook']['authorization'] : null; + $headers = isset($step['options']['webhook']['headers']) ? $step['options']['webhook']['headers'] : []; + $body = isset($step['options']['webhook']['body']) ? $this->formatarTexto($step['options']['webhook']['body'], $tempvars) : null; + + // Constrói a URL com os parâmetros de consulta (query params) + if (!empty($queryParams)) { + $queryArray = []; + foreach ($queryParams as $param) { + $queryArray[$this->formatarTexto($param['key'], $tempvars)] = $this->formatarTexto($param['value'], $tempvars); + } + $url .= '?' . http_build_query($queryArray); + } + + // Inicializa o cURL + $ch = curl_init(); + + // Configura a URL e o método + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + + // Configura os headers + $curlHeaders = []; + if (!empty($authorization)) { + $curlHeaders[] = "Authorization: $authorization"; + } + + foreach ($headers as $header) { + $curlHeaders[] = $this->formatarTexto($header['key'], $tempvars) . ": ". $this->formatarTexto($header['value'], $tempvars); + } + + // Configura o corpo da requisição se for PUT + if (($method === 'PUT' || $method === 'POST') && !empty($body)) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); + } + + if (!empty($curlHeaders)) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders); + } + + // Configura para retornar a resposta como string + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); + // Executa a requisição + $response = curl_exec($ch); + + if (curl_errno($ch)) { + $error_msg = curl_error($ch); + $httpCode = 400; + + $data = $error_msg; + + $jsonReponse = json_encode(array("statusCode" => $httpCode, "data" => $data)); + return response()->json($jsonReponse, 200); + } else { + $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + $data = json_decode($response); + + $jsonReponse = json_encode(array("statusCode" => $httpCode, "data" => $data)); + return response()->json($jsonReponse, 200); + } + } + + public function formatarTexto(string $string, array $vars) { + $variaveis = []; + + foreach ($vars as $item) { + $variaveis[$item['key']] = $item['value']; + } + + if (!preg_match('/{{.*?}}/', $string)) { + return $string; + } else { + + preg_match_all('/{{(.*?)}}/', $string, $matches); + + foreach ($matches[1] as $key => $match) { + if (isset($variaveis[$match])) { + $string = str_replace($matches[0][$key], $variaveis[$match], $string); + } + } + + return $string; + } + } + } diff --git a/public/js/views/chatBot/requestChatBot.js b/public/js/views/chatBot/requestChatBot.js index 1a79166..79a14fa 100644 --- a/public/js/views/chatBot/requestChatBot.js +++ b/public/js/views/chatBot/requestChatBot.js @@ -1,81 +1,44 @@ +const currentURL = window.location.href; // Get the current URL +const baseURL = currentURL.split('/').slice(0, -1).join('/'); // Extract base URL +const completeURL = baseURL + '/request'; async function makeRequest(cell) { $('#request-container').empty(); - // Extrai as opções do step - const tempVars = cell.attr('properties/temporaryVars'); - const oldUrl = formataTempVars(cell.attr('properties/text'), tempVars); - const url = new URL(oldUrl); - const method = cell.attr('properties/method').toUpperCase(); - const queryParams = cell.attr('properties/queryParams') || []; - const authorization = cell.attr('properties/authorization') || null; - const headers = cell.attr('properties/headers') || []; - const body = cell.attr('properties/body') || null; - - // Constrói a URL com os parâmetros de consulta (query params) - if (queryParams.length > 0) { - queryParams.forEach(param => { - url.searchParams.append( - formataTempVars(param.key, tempVars), - formataTempVars(param.value, tempVars) - ); - }); - } - - // Configura os headers - const fetchHeaders = new Headers(); - if (authorization) { - fetchHeaders.append('Authorization', formataTempVars(authorization, tempVars)); - } - - headers.forEach(header => { - fetchHeaders.append( - formataTempVars(header.key, tempVars), - formataTempVars(header.value, tempVars) - ); + + var data = getBlockById(jsonBlocks, cell.id); + var jsonData = JSON.stringify(data); + + $.ajax({ + url: completeURL, + type: "POST", + headers: { + 'Content-Type': 'application/json', + 'X-CSRF-TOKEN': csrfToken + }, + data: jsonData, + success: function (response) { + response = JSON.parse(response); + const httpCode = response.statusCode; + const data = response.data; + const json = { "statusCode": httpCode, "data": data }; + const requestResponse = `
${JSON.stringify(json, null, 2)}
`; + $('#request-container').append(requestResponse); + + const jsonvars = getJsonPaths(json); + const datalist = document.getElementById('itemList'); + + jsonvars.forEach(item => { + const option = document.createElement('option'); + option.value = item; + datalist.appendChild(option); + }); + + return { httpCode, data }; + }, + error: function (res) { + alert('Nao foi possivel retirar de pausa.') + } }); - - if (method === 'PUT' && body) { - fetchHeaders.append('Content-Type', 'application/json'); - } - - // Configura as opções da requisição - const fetchOptions = { - method: method, - headers: fetchHeaders, - redirect: 'follow' - }; - - // Adiciona o corpo da requisição se for PUT - if (method === 'PUT' && body) { - fetchOptions.body = JSON.stringify(body); - } - - try { - // Executa a requisição - const response = await fetch(url.toString(), fetchOptions); - const httpCode = response.status; - const data = await response.json(); - const json = {"statusCode" : httpCode, "data" : data}; - const requestReponse = `
${JSON.stringify(json, null, 2)}
`; - $('#request-container').append(requestReponse); - - const jsonvars = getJsonPaths(json); - const datalist = document.getElementById('itemList') - - jsonvars.forEach(item => { - const option = document.createElement('option'); - option.value = item; - datalist.appendChild(option); - }); - - return { httpCode, data }; - } catch (error) { - const json = {"statusCode" : null, "data" : null}; - console.error('Error:', error); - const requestReponse = `
${JSON.stringify(json, null, 2)}
`; - $('#request-container').append(requestReponse); - return { httpCode: null, data: null, error }; - } } function formataTempVars(string, vars) { @@ -143,4 +106,26 @@ function getJsonPaths(obj, path = '') { } return paths; -} \ No newline at end of file +} + +function getBlockById(jsonData, blockId) { + // Parse the JSON string if needed + if (typeof jsonData === 'string') { + jsonData = JSON.parse(jsonData); + } + + // Loop through each element in the "blocks" array + for (const element of jsonData) { + if (element.hasOwnProperty('blocks')) { + for (const block of element.blocks) { + if (block.id === blockId) { + return block; + } + } + } + } + + // Block not found + return null; + } + \ No newline at end of file diff --git a/resources/views/admin/cadastros/editChatBots.blade.php b/resources/views/admin/cadastros/editChatBots.blade.php index bdd21f9..d3e5dbd 100644 --- a/resources/views/admin/cadastros/editChatBots.blade.php +++ b/resources/views/admin/cadastros/editChatBots.blade.php @@ -452,6 +452,7 @@