Browse Source

Att: atualização função de testar requisição http chatbot

chatbot
Felipe Fontana 4 months ago
parent
commit
5a11dd6688
  1. 97
      app/Http/Controllers/Admin/ChatBotController.php
  2. 135
      public/js/views/chatBot/requestChatBot.js
  3. 1
      resources/views/admin/cadastros/editChatBots.blade.php
  4. 1
      routes/web.php

97
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;
}
}
}

135
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 = `<code><pre id="pre-code-area" style="border: 1px solid #7A7A7A; overflow-y: hidden">${JSON.stringify(json, null, 2)}</pre></code>`;
$('#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 = ` <code ><pre id="pre-code-area" style="border: 1px solid #7A7A7A; overflow-y: hidden">${JSON.stringify(json, null, 2)}</pre></code>`;
$('#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 = ` <code ><pre id="pre-code-area" style="border: 1px solid #7A7A7A; overflow-y: hidden">${JSON.stringify(json, null, 2)}</pre></code>`;
$('#request-container').append(requestReponse);
return { httpCode: null, data: null, error };
}
}
function formataTempVars(string, vars) {
@ -143,4 +106,26 @@ function getJsonPaths(obj, path = '') {
}
return paths;
}
}
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;
}

1
resources/views/admin/cadastros/editChatBots.blade.php

@ -452,6 +452,7 @@
<script src="{{ asset('js/views/chatBot/requestChatBot.js') }}"></script>
<script>
const csrfToken = '{{ csrf_token() }}';
const { dia, util, format, shapes, highlighters, elementTools, ui } = joint;
const types_id = {

1
routes/web.php

@ -68,6 +68,7 @@ Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/bots/{bot}/steps', [ChatBotController::class, 'steps'])->name('bots.steps');
Route::put('/bots/{bot}/steps/update', [ChatBotController::class, 'updateSteps'])->name('bots.updateSteps');
Route::get('/bots/{id}/options/{code_id}', [ChatBotController::class, 'options'])->name('bots.options');
Route::post('/bots/{id}/request', [ChatBotController::class, 'testRequest'])->name('bots.test_request');
Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard');
Route::get('/dashboard/getRelatorioDados', [DashboardController::class, 'getRelatorioDados'])->name('dashboard.relatorios');

Loading…
Cancel
Save