Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: pesquisar perguntas melhorado #159

Merged
merged 2 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion api/src/Controllers/PerguntaController.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,9 @@ private function processCollectionRequest(string $method, array $ordenacao): voi

$qtdPorPg = filter_input(INPUT_GET, "quantidade_por_pagina", FILTER_SANITIZE_NUMBER_INT) ?? 10;

echo json_encode($this->gateway->getAll($ordenacao, $pagina, $qtdPorPg, isset($_GET["order"]) ? $_GET["order"] : ''));
$titulo = $_GET['titulo'] ?? '';

echo json_encode($this->gateway->getAll($ordenacao, $pagina, $qtdPorPg, isset($_GET["order"]) ? $_GET["order"] : '', $titulo));
break;
case "POST":
$usuarioLogado = $this->authController->verifyAccessToken($this->config, $this->token);
Expand Down
17 changes: 14 additions & 3 deletions api/src/Gateways/PerguntaGateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,15 @@ public function __construct(Database $database)
$this->conn = $database->getConnection();
}

public function getAll(array $ordenacao, $pagina = 1, $qtdPorPg = 10, $order = "asc"): array
public function getAll(array $ordenacao, $pagina = 1, $qtdPorPg = 10, $order = "asc", $titulo = ''): array
{
$sql = "SELECT COUNT(*) AS qtd_pg FROM pergunta";
$stmt = $this->conn->query($sql);
$tituloParam = '%' . $titulo . '%';

$sql = "SELECT COUNT(*) AS qtd_pg FROM pergunta WHERE pergunta LIKE :titulo";
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(':titulo', $tituloParam, PDO::PARAM_STR);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);
$qtd_pg = ceil($result["qtd_pg"] / $qtdPorPg);

Expand All @@ -36,6 +41,7 @@ public function getAll(array $ordenacao, $pagina = 1, $qtdPorPg = 10, $order = "
LEFT JOIN usuario u ON p.criado_por = u.id
LEFT JOIN pergunta_editada_por pe ON p.id = pe.pergunta_id
LEFT JOIN usuario ue ON pe.usuario_id = ue.id
WHERE p.pergunta LIKE :titulo
ORDER BY p.id $order LIMIT :limit OFFSET :offset
";

Expand All @@ -53,6 +59,7 @@ public function getAll(array $ordenacao, $pagina = 1, $qtdPorPg = 10, $order = "
LEFT JOIN usuario u ON p.criado_por = u.id
LEFT JOIN pergunta_editada_por pe ON p.id = pe.pergunta_id
LEFT JOIN usuario ue ON pe.usuario_id = ue.id
WHERE p.pergunta LIKE :titulo
ORDER BY
CASE
WHEN prioridade = 'Alta' THEN 1
Expand All @@ -75,11 +82,15 @@ public function getAll(array $ordenacao, $pagina = 1, $qtdPorPg = 10, $order = "
LEFT JOIN usuario u ON p.criado_por = u.id
LEFT JOIN pergunta_editada_por pe ON p.id = pe.pergunta_id
LEFT JOIN usuario ue ON pe.usuario_id = ue.id
WHERE p.pergunta LIKE :titulo
ORDER BY curtidas DESC
LIMIT :limit OFFSET :offset";
}



$stmt = $this->conn->prepare($sql);
$stmt->bindParam(':titulo', $tituloParam, PDO::PARAM_STR);
$stmt->bindParam(":limit", $qtdPorPg, PDO::PARAM_INT);
$stmt->bindParam(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
Expand Down
112 changes: 92 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import './scripts/autocomplete/autoComplete.js';
import { decrementarCurtidas } from './scripts/perguntas/decrementarCurtidas.js';
import { incrementarCurtidas } from './scripts/perguntas/incrementarCurtidas.js';
import { listarPerguntas } from './scripts/perguntas/listarPerguntas.js';
Expand Down Expand Up @@ -25,13 +26,16 @@ pgNumerosPerguntas.innerHTML = `

let paginas = 1;
let qtdPgs = 0;
let loading = false;
const renderPerguntas = async ({
maisAlta = true,
pagina = 1,
qtdPorPg = 20,
order = 'asc',
titulo = '',
} = {}) => {
try {
loading = true;
spinnerContainer.classList.add('mostrar');
questionsContainer.innerHTML = '';
pgNumerosPerguntas.innerHTML = '';
Expand All @@ -41,6 +45,7 @@ const renderPerguntas = async ({
pagina,
qtdPorPg,
order,
titulo,
});

paginas = perguntas.pagina;
Expand Down Expand Up @@ -86,26 +91,6 @@ const renderPerguntas = async ({
)
.join('');

// pega todas as divs containers que tem a tag faq-container para filtrar
const form = document.querySelector('form');
const containers = document.querySelectorAll('.faq-container');
form.addEventListener('keyup', (event) => {
event.preventDefault();
const searchValue = form.querySelector('input').value.toLowerCase();
containers.forEach((container) => {
const questionTitleText = container
.querySelector('.question-title')
.textContent.toLowerCase();
const content = container.querySelector('.content').textContent.toLowerCase();

if (questionTitleText.includes(searchValue) || content.includes(searchValue)) {
container.style.display = 'block';
} else {
container.style.display = 'none';
}
});
});

//deixa o coração vermelho ao clicar e chama a funçao de incrementar
const hearts = document.querySelectorAll('.heart');
let idCurtidasLocalStorage = localStorage.getItem('idCurtidas');
Expand Down Expand Up @@ -159,6 +144,7 @@ const renderPerguntas = async ({
toast('Houve um erro ao carregar as perguntas', true);
console.log(error);
} finally {
loading = false;
spinnerContainer.classList.remove('mostrar');
window.scrollTo({
top: 0,
Expand Down Expand Up @@ -228,3 +214,89 @@ pgUltimoPerguntas.addEventListener('click', async function () {
pagina: qtdPgs,
});
});

const autoCompleteJS = new autoComplete({
data: {
src: async () => {
try {
document.getElementById('autoComplete').disabled = true;
document.getElementById('autoComplete').setAttribute('placeholder', 'Carregando...');

const data = await listarPerguntas({ qtdPorPg: 2000 });

document
.getElementById('autoComplete')
.setAttribute('placeholder', autoCompleteJS.placeHolder);

const { resultado } = data;

const perguntasArray = resultado.map((item) => item.pergunta);

return perguntasArray;
} catch (error) {
return error;
} finally {
document.getElementById('autoComplete').disabled = false;
}
},
cache: true,
},
placeHolder: 'Quando abre o vestibular?',
resultsList: {
element: (list, data) => {
const info = document.createElement('p');
if (data.results.length > 0) {
info.innerHTML = `Mostrando <strong>${data.results.length}</strong> de <strong>${data.matches.length}</strong> resultados`;
} else {
info.innerHTML = `Encontrado <strong>${data.matches.length}</strong> resultados que combinam com <strong>"${data.query}"</strong>`;
}
list.prepend(info);
},
noResults: true,
tabSelect: true,
},
resultItem: {
element: (item, data) => {
item.style = 'display: flex; justify-content: space-between;';
item.innerHTML = `
<span style="text-overflow: ellipsis; white-space: nowrap; overflow: hidden;">
${data.match}
</span>
`;
},
highlight: true,
},
events: {
input: {
focus: () => {
if (autoCompleteJS.input.value.length) autoCompleteJS.start();
},
},
},
});

autoCompleteJS.input.addEventListener('input', async function (event) {
if (loading) return;
if (!event.target.value) {
await renderPerguntas();
}
});

autoCompleteJS.input.addEventListener('results', async function (event) {
if (loading) return;
await renderPerguntas({
titulo: event.detail.query,
});
});

autoCompleteJS.input.addEventListener('selection', async function (event) {
if (loading) return;
const feedback = event.detail;
autoCompleteJS.input.blur();

document.querySelector('#autoComplete');
autoCompleteJS.input.value = feedback.selection.value;
await renderPerguntas({
titulo: feedback.selection.value,
});
});
10 changes: 4 additions & 6 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
<script src="https://kit.fontawesome.com/1aacb3a88a.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<link rel="stylesheet" href="./scripts/autocomplete/css/autoComplete.custom.css">
<script defer type="text/javascript" src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script src="index.js" type="module" defer></script>
<script src="./scripts/global.js" defer></script>
Expand All @@ -32,12 +33,9 @@
<div class="keyword-container">
<div class="keyword-content">
<h1>Filtre sua dúvida</h1>
<form id="formulary">
<div class="input-container">
<i class="fas fa-search"></i>
<input id="search-input" type="text" placeholder="Ex: O que é a Fatec Itapira?" />
</div>
</form>
<div class="autoComplete_wrapper">
<input disabled placeholder="Quando abre o vestibular?" id="autoComplete" type="search" dir="ltr" spellcheck=false autocorrect="off" autocomplete="off" autocapitalize="off" maxlength="2048" tabindex="1">
</div>
</div>
</div>
</section>
Expand Down
Loading