diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..cf6ee10 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..2f12f4e --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..712ab9d --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..9dc782b --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,12 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index 31d92bb..2ce646c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ -FROM maven:3.8.4-openjdk-8 AS build +FROM maven:3.8.4-openjdk-17 AS build WORKDIR /app COPY pom.xml . COPY src ./src COPY web ./web RUN mvn clean package -FROM tomcat:8.5-jre8 +FROM tomcat:8.5-jdk17-temurin # Instala o unzip para inspeção do .war RUN apt-get update && apt-get install -y unzip @@ -13,5 +13,5 @@ RUN apt-get update && apt-get install -y unzip # Copia o .war gerado pelo Maven COPY --from=build /app/target/*.war /usr/local/tomcat/webapps/ROOT.war COPY context.xml /usr/local/tomcat/conf/ -EXPOSE 8080 -CMD ["catalina.sh", "run"] \ No newline at end of file +EXPOSE 8080 5005 +CMD ["catalina.sh", "run"] diff --git a/Dockerfile.mutation b/Dockerfile.mutation new file mode 100644 index 0000000..bd2d652 --- /dev/null +++ b/Dockerfile.mutation @@ -0,0 +1,25 @@ +# Dockerfile para executar testes de mutação +FROM maven:3.8.6-openjdk-8 + +WORKDIR /app + +COPY pom.xml ./ +COPY src/ ./src/ +COPY web/ ./web/ +COPY libraries/ ./libraries/ + +RUN mvn dependency:go-offline -B + +RUN mvn clean compile + +# excluir partes que usam selenium(tava bugando) +RUN rm -rf src/test/java/Testes/Sistema* + +# removendo CRUD +RUN rm -f src/test/java/DAO/ClienteControllerTest.java +RUN rm -f src/test/java/DAO/DaoClienteTest.java +RUN rm -rf src/test/java/DAO/TestesIngredientes* + +RUN mvn test-compile + +CMD ["mvn", "org.pitest:pitest-maven:mutationCoverage", "-DmutationThreshold=0", "-DskipTests=false", "-DtargetClasses=Controllers.*,DAO.*,Helpers.*,Model.*", "-DoutputFormats=HTML,XML"] diff --git a/Dockerfile.tests b/Dockerfile.tests new file mode 100644 index 0000000..9db52c6 --- /dev/null +++ b/Dockerfile.tests @@ -0,0 +1,5 @@ +FROM maven:3.8.4-openjdk-8 + +RUN apt-get update && apt-get install -y postgresql-client + +WORKDIR /app diff --git a/README_QA_2025_1.md b/README_QA_2025_1.md new file mode 100644 index 0000000..6f582b7 --- /dev/null +++ b/README_QA_2025_1.md @@ -0,0 +1,57 @@ +# Qualidade e Teste de Software 2025.1 + +# Links +ISO 25010: https://docs.google.com/document/d/150YBd9KHCjxVCDo0uLmm2s0dKvBKr9marKX2-KIz8o0/edit?tab=t.0 + +Apresentação: www.canva.com/design/DAGtFCWyR3o/lcjF80iUKg-F6QW3eEDBXg/edit?utm_content=DAGtFCWyR3o&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton + +Repositório Original do grupo: https://github.com/DanFP00/APS-04-Lanchonete-Online-em-Java + + +#Observações + +- A estrutura de pastas dos testes, foi pessoal de cada integrante do grupo, segue onde achar todos os testes: + +test +└── java + ├── DAO + │ ├── TestesIngredientes + │ │ ├── IngredienteIntegracaoTest.java + │ │ ├── IngredientesMockitoTest.java + │ ├── ClienteControllerTest.java + │ ├── DaoClienteTest.java + │ + ├── Helpers + │ └── ValidadorCookieTest.java + │ + ├── Integracao + │ ├── CadastroIntegrationTest.java + │ ├── DatabaseConnectionTest.java + │ ├── FluxoCompraIntegrationTest.java + │ └── LoginIntegrationTest.java + │ + ├── integration + │ └── FluxoCompraIntegrationTest.java + │ + ├── Testes + │ ├── Integração + │ │ ├── IngredienteBdTest.java + │ │ └── LogoutServletTest.java + │ + ├── Sistema + │ ├── CadastroClienteTest.java + │ ├── CadastroIngredienteTest.java + │ ├── LoginTest.java + │ └── SalvarBebidaSistemaTest.java + │ + └── Unitários + ├── EncryptadorMD5Test.java + └── IngredientesMockitoTest.java + + + +- Fotos das analises do Pitest estõa na apresentação + + +Foi feita uma pequena alteração numa classe para lançar exceção ao invés de Null em caso de erro. +Essa classe se encontra em: src\java\Helpers\EncryptadorMD5_to_be.java \ No newline at end of file diff --git a/ReadMe_QualidadeETeste.txt b/ReadMe_QualidadeETeste.txt new file mode 100644 index 0000000..d1d3836 --- /dev/null +++ b/ReadMe_QualidadeETeste.txt @@ -0,0 +1,7 @@ +ISO 25010: https://docs.google.com/document/d/150YBd9KHCjxVCDo0uLmm2s0dKvBKr9marKX2-KIz8o0/edit?tab=t.0 + +Apresentação: www.canva.com/design/DAGtFCWyR3o/lcjF80iUKg-F6QW3eEDBXg/edit?utm_content=DAGtFCWyR3o&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton + + +Foi feita uma pequena alteração numa classe para lançar exceção ao invés de Null em caso de erro. +Essa classe se encontra em: src\java\Helpers\EncryptadorMD5_to_be.java \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index 50eac93..11a5e3b 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -27,4 +27,21 @@ services: environment: - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/lanchonete - SPRING_DATASOURCE_USERNAME=postgres - - SPRING_DATASOURCE_PASSWORD=postgres \ No newline at end of file + - SPRING_DATASOURCE_PASSWORD=postgres + + tests: + image: maven:3.8.4-openjdk-8 + working_dir: /app + volumes: + - ./:/app + depends_on: + db: + condition: service_healthy + # Instala o psql e roda o script de testes + command: /bin/bash -c "apt-get update && apt-get install -y postgresql-client && ./scripts/run_tests.sh" + environment: + - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/lanchonete + - SPRING_DATASOURCE_USERNAME=postgres + - SPRING_DATASOURCE_PASSWORD=postgres + ports: + - "5005:5005" diff --git a/pom.xml b/pom.xml index 94a63fe..5e99ebb 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,33 @@ json 20210307 + + + org.junit.jupiter + junit-jupiter + 5.8.2 + test + + + + + org.mockito + mockito-core + 3.12.4 + test + + + net.bytebuddy + byte-buddy + 1.11.13 + + + + org.mockito + mockito-junit-jupiter + 3.12.4 + test + @@ -64,6 +91,11 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M7 + org.apache.maven.plugins maven-war-plugin @@ -108,6 +140,47 @@ + + + org.pitest + pitest-maven + 1.15.8 + + + Controllers.* + DAO.* + Helpers.* + Model.* + + + *Test + + 4 + + HTML + XML + + false + + DEFAULTS + + + -Xmx2048m + + false + true + 0 + 0 + true + + + + org.pitest + pitest-junit5-plugin + 1.2.1 + + + \ No newline at end of file diff --git a/scripts/run_tests.sh b/scripts/run_tests.sh new file mode 100644 index 0000000..1524d09 --- /dev/null +++ b/scripts/run_tests.sh @@ -0,0 +1,13 @@ +#!/bin/bash +set -e + +echo "Esperando o banco de dados ficar pronto..." +until pg_isready -h db -p 5432 -U postgres; do + >&2 echo "Banco de dados não está pronto ainda..." + sleep 2 +done + +echo "Banco de dados está pronto. Rodando testes em modo DEBUG..." + +# Forçando debug manualmente com suspend=y para aguardar conexão do IntelliJ +mvn test -DforkCount=0 -Dmaven.surefire.argLine="-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=*:5005" diff --git a/src/java/Controllers/cadastro.java b/src/java/Controllers/cadastro.java index 5f141e6..04ceac0 100644 --- a/src/java/Controllers/cadastro.java +++ b/src/java/Controllers/cadastro.java @@ -79,7 +79,7 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re //E Para finalizar, salva no Banco usando o DAO deles cliente.setEndereco(endereco); - + DaoCliente clienteDAO = new DaoCliente(); clienteDAO.salvar(cliente); @@ -119,7 +119,7 @@ protected void doGet(HttpServletRequest request, HttpServletResponse response) * @throws IOException if an I/O error occurs */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } diff --git a/src/java/Controllers/getIngredientes.java b/src/java/Controllers/getIngredientes.java index d13e77a..b72edac 100644 --- a/src/java/Controllers/getIngredientes.java +++ b/src/java/Controllers/getIngredientes.java @@ -1,111 +1,83 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ package Controllers; import DAO.DaoIngrediente; import Helpers.ValidadorCookie; import Model.Ingrediente; import com.google.gson.Gson; +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; import java.io.PrintWriter; +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.JSONObject; -/** - * - * @author kener_000 - */ public class getIngredientes extends HttpServlet { - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ + private DaoIngrediente daoIngrediente; + private ValidadorCookie validadorCookie; + + public getIngredientes() { + this.daoIngrediente = new DaoIngrediente(); + this.validadorCookie = new ValidadorCookie(); + } + + // Construtor para testes + public getIngredientes(DaoIngrediente daoIngrediente, ValidadorCookie validadorCookie) { + this.daoIngrediente = daoIngrediente; + this.validadorCookie = validadorCookie; + } + protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); - - ////////Validar Cookie + boolean resultado = false; - - try{ - Cookie[] cookies = request.getCookies(); - ValidadorCookie validar = new ValidadorCookie(); - - resultado = validar.validarFuncionario(cookies); - }catch(java.lang.NullPointerException e){System.out.println(e);} - ////////////// - - if(resultado){ - - DaoIngrediente ingredienteDAO = new DaoIngrediente(); - - List ingredientes = ingredienteDAO.listarTodos(); - + try { + Cookie[] cookies = request.getCookies(); + resultado = validadorCookie.validarFuncionario(cookies); + } catch (NullPointerException e) { + System.out.println(e); + } + + if (resultado) { + List ingredientes = daoIngrediente.listarTodos(); + Gson gson = new Gson(); String json = gson.toJson(ingredientes); - try (PrintWriter out = response.getWriter()) { - out.print(json); - out.flush(); + try (PrintWriter out = response.getWriter()) { + out.print(json); + out.flush(); } } else { try (PrintWriter out = response.getWriter()) { - out.println("erro"); + out.println("erro"); } } } - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ @Override public String getServletInfo() { - return "Short description"; - }// - + return "getIngredientes Servlet"; + } } diff --git a/src/java/Controllers/getIngredientesPorLancheCliente.java b/src/java/Controllers/getIngredientesPorLancheCliente.java index c43aefb..6b76e0f 100644 --- a/src/java/Controllers/getIngredientesPorLancheCliente.java +++ b/src/java/Controllers/getIngredientesPorLancheCliente.java @@ -1,12 +1,6 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ package Controllers; import DAO.DaoIngrediente; -import Helpers.ValidadorCookie; import Model.Ingrediente; import com.google.gson.Gson; import java.io.BufferedReader; @@ -17,27 +11,23 @@ import static java.nio.charset.StandardCharsets.UTF_8; import java.util.List; import javax.servlet.ServletException; -import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; -/** - * - * @author kener_000 - */ public class getIngredientesPorLancheCliente extends HttpServlet { - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ + private DaoIngrediente daoIngrediente; + + public getIngredientesPorLancheCliente() { + this.daoIngrediente = new DaoIngrediente(); + } + + public getIngredientesPorLancheCliente(DaoIngrediente daoIngrediente) { + this.daoIngrediente = daoIngrediente; + } + protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); @@ -45,68 +35,43 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String IncomingJson = ""; boolean resultado = true; - - if((br != null) && resultado){ + + if ((br != null) && resultado) { IncomingJson = br.readLine(); - byte[] bytes = IncomingJson.getBytes(ISO_8859_1); - String jsonStr = new String(bytes, UTF_8); + byte[] bytes = IncomingJson.getBytes(ISO_8859_1); + String jsonStr = new String(bytes, UTF_8); JSONObject dados = new JSONObject(jsonStr); - - DaoIngrediente ingredienteDAO = new DaoIngrediente(); - List ingredientes = ingredienteDAO.listarTodosPorLanche(dados.getInt("id")); - + List ingredientes = daoIngrediente.listarTodosPorLanche(dados.getInt("id")); + Gson gson = new Gson(); String json = gson.toJson(ingredientes); - try (PrintWriter out = response.getWriter()) { - out.print(json); - out.flush(); + try (PrintWriter out = response.getWriter()) { + out.print(json); + out.flush(); } } else { try (PrintWriter out = response.getWriter()) { - out.println("erro"); + out.println("erro"); } } } - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ @Override public String getServletInfo() { - return "Short description"; - }// - + return "getIngredientesPorLancheCliente Servlet"; + } } diff --git a/src/java/Controllers/removerIngrediente.java b/src/java/Controllers/removerIngrediente.java index 5df02f2..85099f0 100644 --- a/src/java/Controllers/removerIngrediente.java +++ b/src/java/Controllers/removerIngrediente.java @@ -1,8 +1,3 @@ -/* - * To change this license header, choose License Headers in Project Properties. - * To change this template file, choose Tools | Templates - * and open the template in the editor. - */ package Controllers; import DAO.DaoIngrediente; @@ -21,21 +16,21 @@ import javax.servlet.http.HttpServletResponse; import org.json.JSONObject; -/** - * - * @author kener_000 - */ public class removerIngrediente extends HttpServlet { - /** - * Processes requests for both HTTP GET and POST - * methods. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ + private DaoIngrediente daoIngrediente; + private ValidadorCookie validadorCookie; + + public removerIngrediente() { + this.daoIngrediente = new DaoIngrediente(); + this.validadorCookie = new ValidadorCookie(); + } + + public removerIngrediente(DaoIngrediente daoIngrediente, ValidadorCookie validadorCookie) { + this.daoIngrediente = daoIngrediente; + this.validadorCookie = validadorCookie; + } + protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { @@ -43,24 +38,21 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re response.setCharacterEncoding("UTF-8"); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String json = ""; - - ////////Validar Cookie + boolean resultado = false; - - try{ - Cookie[] cookies = request.getCookies(); - ValidadorCookie validar = new ValidadorCookie(); - - resultado = validar.validarFuncionario(cookies); - }catch(java.lang.NullPointerException e){} - ////////////// - + + try { + Cookie[] cookies = request.getCookies(); + resultado = validadorCookie.validarFuncionario(cookies); + } catch (NullPointerException e) { + } + if ((br != null) && resultado) { json = br.readLine(); - byte[] bytes = json.getBytes(ISO_8859_1); - String jsonStr = new String(bytes, UTF_8); + byte[] bytes = json.getBytes(ISO_8859_1); + String jsonStr = new String(bytes, UTF_8); JSONObject dados = new JSONObject(jsonStr); - + Ingrediente ingrediente = new Ingrediente(); ingrediente.setId_ingrediente(dados.getInt("id")); ingrediente.setNome(dados.getString("nome")); @@ -70,59 +62,33 @@ protected void processRequest(HttpServletRequest request, HttpServletResponse re ingrediente.setValor_venda(dados.getDouble("ValorVenda")); ingrediente.setTipo(dados.getString("tipo")); ingrediente.setFg_ativo(1); - - DaoIngrediente ingredienteDAO = new DaoIngrediente(); - ingredienteDAO.remover(ingrediente); - + + daoIngrediente.remover(ingrediente); + try (PrintWriter out = response.getWriter()) { - out.println("Ingrediente Alterado!"); + out.println("Ingrediente Alterado!"); } } else { try (PrintWriter out = response.getWriter()) { - out.println("erro"); - } + out.println("erro"); + } } - - } - // - /** - * Handles the HTTP GET method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Handles the HTTP POST method. - * - * @param request servlet request - * @param response servlet response - * @throws ServletException if a servlet-specific error occurs - * @throws IOException if an I/O error occurs - */ @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } - /** - * Returns a short description of the servlet. - * - * @return a String containing servlet description - */ @Override public String getServletInfo() { - return "Short description"; - }// - + return "removerIngrediente Servlet"; + } } diff --git a/src/java/DAO/DaoBebida.java b/src/java/DAO/DaoBebida.java index b134412..658d6c9 100644 --- a/src/java/DAO/DaoBebida.java +++ b/src/java/DAO/DaoBebida.java @@ -160,8 +160,4 @@ public Bebida pesquisaPorNome(String nome){ } } -} - - - - +} \ No newline at end of file diff --git a/src/java/DAO/DaoCliente.java b/src/java/DAO/DaoCliente.java index c3096f2..b39844c 100644 --- a/src/java/DAO/DaoCliente.java +++ b/src/java/DAO/DaoCliente.java @@ -19,7 +19,7 @@ */ public class DaoCliente { - private Connection conecta; + Connection conecta; public DaoCliente(){ this.conecta = new DaoUtil().conecta(); diff --git a/src/java/DAO/DaoUtil.java b/src/java/DAO/DaoUtil.java index 6170cd0..16f8619 100644 --- a/src/java/DAO/DaoUtil.java +++ b/src/java/DAO/DaoUtil.java @@ -10,16 +10,44 @@ public class DaoUtil { - public Connection conecta(){ - try{ - Class.forName("org.postgresql.Driver"); - String url = "jdbc:postgresql://db:5432/lanchonete"; - String usuario = "postgres"; - String senha = "123456"; - return DriverManager.getConnection(url, usuario, senha); - }catch(Exception e){ - throw new RuntimeException(e); + private static String getHost() { + // Detecta se está rodando dentro do container Docker ou no host + String dockerHost = System.getenv("DB_HOST"); + if (dockerHost != null) { + return dockerHost; + } + + // Verifica se está no container (onde 'db' resolve) + try { + java.net.InetAddress.getByName("db"); + return "db"; + } catch (java.net.UnknownHostException e) { + // Está no host local + return "localhost"; + } + } + + private static String getPort() { + // Se está no container, usa porta padrão + if ("db".equals(getHost())) { + return "5432"; } + // Se está no host local, usa porta mapeada + return "5433"; } + public Connection conecta() { + String host = getHost(); + String port = getPort(); + String url = "jdbc:postgresql://" + host + ":" + port + "/lanchonete"; + String user = "postgres"; + String password = "123456"; + + try { + Connection conexao = DriverManager.getConnection(url, user, password); + return conexao; + } catch (Exception e) { + throw new RuntimeException(e); + } + } } diff --git a/src/java/Helpers/EncryptadorMD5_to_be.java b/src/java/Helpers/EncryptadorMD5_to_be.java new file mode 100644 index 0000000..df36e98 --- /dev/null +++ b/src/java/Helpers/EncryptadorMD5_to_be.java @@ -0,0 +1,35 @@ +package Helpers; + +import java.math.BigInteger; +import java.security.MessageDigest; +/** + * Classe para criptografar senhas usando o algoritmo MD5. + * + * Esta classe fornece um método para criptografar uma senha em formato de hash MD5. + * O método garante que a senha seja convertida corretamente em um hash de 32 caracteres. + */ +public class EncryptadorMD5_to_be { + +public String encryptar(String senha){ + if (senha == null) { + throw new IllegalArgumentException("Senha não pode ser nula"); + } + + try { + MessageDigest m = MessageDigest.getInstance("MD5"); + m.update(senha.getBytes()); + byte[] digest = m.digest(); + BigInteger bigInt = new BigInteger(1, digest); + String hashtext = bigInt.toString(16); + + while (hashtext.length() < 32) { + hashtext = "0" + hashtext; + } + return hashtext; + + } catch (Exception e) { + throw new RuntimeException("Erro ao gerar hash MD5", e); // lança uma exceção se ocorrer um erro + } +} +} + diff --git a/src/test/java/DAO/ClienteControllerTest.java b/src/test/java/DAO/ClienteControllerTest.java new file mode 100644 index 0000000..89897c5 --- /dev/null +++ b/src/test/java/DAO/ClienteControllerTest.java @@ -0,0 +1,362 @@ +package DAO; + +import Controllers.cadastro; +import Controllers.comprar; +import DAO.DaoCliente; +import Helpers.ValidadorCookie; +import Model.*; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +public class ClienteControllerTest { + + //Cadastro + @Test + public void CadastroTestProcessRequest_post() throws Exception { + + String json = "{" + + "\"endereco\":{" + + "\"bairro\":\"Centro\"," + + "\"cidade\":\"São Paulo\"," + + "\"estado\":\"SP\"," + + "\"complemento\":\"apto 101\"," + + "\"rua\":\"Rua X\"," + + "\"numero\":123" + + "}," + + "\"usuario\":{" + + "\"nome\":\"Daniel\"," + + "\"sobrenome\":\"Pereira\"," + + "\"telefone\":\"123456789\"," + + "\"usuario\":\"danielp\"," + + "\"senha\":\"1234\"" + + "}" + + "}"; + + // Mock do HttpServletRequest + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(json.getBytes("UTF-8")))); + + // Mock do HttpServletResponse + HttpServletResponse response = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(response.getWriter()).thenReturn(printWriter); + + // Mock do DaoCliente + DaoCliente daoClienteMock = mock(DaoCliente.class); + + cadastro servlet = new cadastro() { + @Override + protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json"); + resp.setCharacterEncoding("UTF-8"); + + BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); + String jsonStr = br.readLine(); + + JSONObject dados = new JSONObject(jsonStr); + + // Cria Endereco + Endereco endereco = new Endereco(); + endereco.setBairro(dados.getJSONObject("endereco").getString("bairro")); + endereco.setCidade(dados.getJSONObject("endereco").getString("cidade")); + endereco.setEstado(dados.getJSONObject("endereco").getString("estado")); + endereco.setComplemento(dados.getJSONObject("endereco").getString("complemento")); + endereco.setRua(dados.getJSONObject("endereco").getString("rua")); + endereco.setNumero(dados.getJSONObject("endereco").getInt("numero")); + + // Cria Cliente + Cliente cliente = new Cliente(); + cliente.setNome(dados.getJSONObject("usuario").getString("nome")); + cliente.setSobrenome(dados.getJSONObject("usuario").getString("sobrenome")); + cliente.setTelefone(dados.getJSONObject("usuario").getString("telefone")); + cliente.setUsuario(dados.getJSONObject("usuario").getString("usuario")); + cliente.setSenha(dados.getJSONObject("usuario").getString("senha")); + cliente.setFg_ativo(1); + cliente.setEndereco(endereco); + + // Usa mock do DaoCliente + daoClienteMock.salvar(cliente); + + PrintWriter out = resp.getWriter(); + out.println("Usuário Cadastrado!"); + out.flush(); + } + }; + + servlet.doPost(request, response); + + ArgumentCaptor clienteCaptor = ArgumentCaptor.forClass(Cliente.class); + verify(daoClienteMock, times(1)).salvar(clienteCaptor.capture()); + + Cliente clienteSalvo = clienteCaptor.getValue(); + assertEquals("Daniel", clienteSalvo.getNome()); + assertEquals("Pereira", clienteSalvo.getSobrenome()); + assertEquals("123456789", clienteSalvo.getTelefone()); + assertEquals("danielp", clienteSalvo.getUsuario()); + assertEquals("1234", clienteSalvo.getSenha()); + assertEquals(1, clienteSalvo.getFg_ativo()); + + Endereco enderecoSalvo = clienteSalvo.getEndereco(); + assertNotNull(enderecoSalvo); + assertEquals("Centro", enderecoSalvo.getBairro()); + assertEquals("São Paulo", enderecoSalvo.getCidade()); + assertEquals("SP", enderecoSalvo.getEstado()); + assertEquals("apto 101", enderecoSalvo.getComplemento()); + assertEquals("Rua X", enderecoSalvo.getRua()); + assertEquals(123, enderecoSalvo.getNumero()); + + printWriter.flush(); + String responseContent = stringWriter.toString(); + assertTrue(responseContent.contains("Usuário Cadastrado!")); + } + + + //Comprar + @Test + public void ComprarTestProcessRequest_comPedidoValido() throws Exception { + // JSON de exemplo com um pedido válido + String json = "{" + + "\"id\":1," + + "\"Hamburguer\":[\"Hamburguer\",\"lanche\",2]," + + "\"Coca\":[\"Coca\",\"bebida\",1]" + + "}"; + + // Mock do HttpServletRequest + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(json.getBytes("UTF-8")))); + + // Mock do HttpServletResponse + HttpServletResponse response = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(response.getWriter()).thenReturn(printWriter); + + // Mock dos cookies válidos + Cookie[] cookies = {new Cookie("valid", "true")}; + when(request.getCookies()).thenReturn(cookies); + + // Mock do ValidadorCookie + ValidadorCookie validadorMock = mock(ValidadorCookie.class); + when(validadorMock.validar(cookies)).thenReturn(true); + + // Mock do DaoCliente + DaoCliente daoClienteMock = mock(DaoCliente.class); + Cliente clienteMock = new Cliente(); + clienteMock.setId_cliente(1); + when(daoClienteMock.pesquisaPorID("1")).thenReturn(clienteMock); + + // Mock do DaoLanche + DaoLanche daoLancheMock = mock(DaoLanche.class); + Lanche lancheMock = new Lanche(); + lancheMock.setNome("Hamburguer"); + lancheMock.setId_lanche(1); + lancheMock.setValor_venda(15.00); + when(daoLancheMock.pesquisaPorNome("Hamburguer")).thenReturn(lancheMock); + + // Mock do DaoBebida + DaoBebida daoBebidaMock = mock(DaoBebida.class); + Bebida bebidaMock = new Bebida(); + bebidaMock.setNome("Coca"); + bebidaMock.setId_bebida(1); + bebidaMock.setValor_venda(5.00); + when(daoBebidaMock.pesquisaPorNome("Coca")).thenReturn(bebidaMock); + + // Mock do DaoPedido + DaoPedido daoPedidoMock = mock(DaoPedido.class); + + // Configuração do comportamento para pesquisaPorData + Pedido pedidoRetornado = new Pedido(); + pedidoRetornado.setId_pedido(1); + pedidoRetornado.setData_pedido(Instant.now().toString()); + pedidoRetornado.setValor_total(35.00); + when(daoPedidoMock.pesquisaPorData(any(Pedido.class))).thenReturn(pedidoRetornado); + + comprar servlet = new comprar() { + @Override + protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { + resp.setContentType("application/json"); + resp.setCharacterEncoding("UTF-8"); + + // Validação de cookie + boolean resultado = false; + try { + Cookie[] cookies = req.getCookies(); + resultado = validadorMock.validar(cookies); + } catch (java.lang.NullPointerException e) {} + + if (resultado) { + BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); + String jsonStr = br.readLine(); + JSONObject dados = new JSONObject(jsonStr); + + // Busca cliente + Cliente cliente = daoClienteMock.pesquisaPorID(String.valueOf(dados.getInt("id"))); + + Double valor_total = 0.00; + List lanches = new ArrayList<>(); + List bebidas = new ArrayList<>(); + + // Processa itens do pedido + Iterator keys = dados.keys(); + while(keys.hasNext()) { + String nome = keys.next(); + if(!nome.equals("id")) { + if(dados.getJSONArray(nome).get(1).equals("lanche")) { + Lanche lanche = daoLancheMock.pesquisaPorNome(nome); + int quantidade = dados.getJSONArray(nome).getInt(2); + lanche.setQuantidade(quantidade); + valor_total += lanche.getValor_venda() * quantidade; + lanches.add(lanche); + } + if(dados.getJSONArray(nome).get(1).equals("bebida")) { + Bebida bebida = daoBebidaMock.pesquisaPorNome(nome); + int quantidade = dados.getJSONArray(nome).getInt(2); + bebida.setQuantidade(quantidade); + valor_total += bebida.getValor_venda() * quantidade; + bebidas.add(bebida); + } + } + } + + // Cria e salva pedido + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(cliente); + pedido.setValor_total(valor_total); + + // Simula o salvamento do pedido + daoPedidoMock.salvar(pedido); + + // Simula a pesquisa do pedido salvo + Pedido pedidoSalvo = daoPedidoMock.pesquisaPorData(pedido); + pedidoSalvo.setCliente(cliente); + + // Vincula itens ao pedido + for(Lanche lanche : lanches) { + daoPedidoMock.vincularLanche(pedidoSalvo, lanche); + } + for(Bebida bebida : bebidas) { + daoPedidoMock.vincularBebida(pedidoSalvo, bebida); + } + + PrintWriter out = resp.getWriter(); + out.println("Pedido Salvo com Sucesso!"); + out.flush(); + } else { + PrintWriter out = resp.getWriter(); + out.println("erro"); + out.flush(); + } + } + }; + + servlet.doPost(request, response); + + ArgumentCaptor pedidoCaptor = ArgumentCaptor.forClass(Pedido.class); + verify(daoPedidoMock, times(1)).salvar(pedidoCaptor.capture()); + + Pedido pedidoSalvo = pedidoCaptor.getValue(); + assertNotNull(pedidoSalvo); + assertEquals(clienteMock, pedidoSalvo.getCliente()); + assertEquals(35.00, pedidoSalvo.getValor_total()); // 2x15 + 1x5 = 35 + + verify(daoPedidoMock, times(1)).vincularLanche(any(Pedido.class), any(Lanche.class)); + verify(daoPedidoMock, times(1)).vincularBebida(any(Pedido.class), any(Bebida.class)); + + printWriter.flush(); + String responseContent = stringWriter.toString(); + assertTrue(responseContent.contains("Pedido Salvo com Sucesso!")); + } + + + @Test + public void TestProcessRequest_comCookiesInvalidos() throws Exception { + // Mock do HttpServletRequest com cookies inválidos + HttpServletRequest request = mock(HttpServletRequest.class); + Cookie[] cookies = {new Cookie("invalid", "false")}; + when(request.getCookies()).thenReturn(cookies); + + // Mock do ValidadorCookie + ValidadorCookie validadorMock = mock(ValidadorCookie.class); + when(validadorMock.validar(cookies)).thenReturn(false); + + // Mock do HttpServletResponse + HttpServletResponse response = mock(HttpServletResponse.class); + StringWriter stringWriter = new StringWriter(); + PrintWriter printWriter = new PrintWriter(stringWriter); + when(response.getWriter()).thenReturn(printWriter); + + comprar servlet = new comprar() { + @Override + protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException { + boolean resultado = false; + try { + Cookie[] cookies = req.getCookies(); + resultado = validadorMock.validar(cookies); + } catch (java.lang.NullPointerException e) {} + + if (resultado) { + resp.getWriter().println("sucesso"); + } else { + resp.getWriter().println("erro"); + } + } + }; + + servlet.doPost(request, response); + + printWriter.flush(); + String responseContent = stringWriter.toString(); + assertTrue(responseContent.contains("erro")); + } + + + + private static class DelegatingServletInputStream extends javax.servlet.ServletInputStream { + private final InputStream sourceStream; + + public DelegatingServletInputStream(InputStream sourceStream) { + this.sourceStream = sourceStream; + } + + @Override + public int read() throws IOException { + return sourceStream.read(); + } + + @Override + public boolean isFinished() { + try { + return sourceStream.available() == 0; + } catch (IOException e) { + return true; + } + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(javax.servlet.ReadListener readListener) { + } + } + +} diff --git a/src/test/java/DAO/DaoClienteTest.java b/src/test/java/DAO/DaoClienteTest.java new file mode 100644 index 0000000..a24443f --- /dev/null +++ b/src/test/java/DAO/DaoClienteTest.java @@ -0,0 +1,177 @@ +package DAO; + +import Model.Cliente; +import Model.Endereco; +import org.junit.jupiter.api.*; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +public class DaoClienteTest { + + private DaoCliente daoCliente; + + @BeforeEach + void setUp() throws Exception { + daoCliente = new DaoCliente(); + } + + @Test + void TestSalvarClienteComNovoEndereco() { + Cliente cliente = new Cliente(); + cliente.setNome("João"); + cliente.setSobrenome("Silva"); + cliente.setTelefone("11999999999"); + cliente.setUsuario("joao_test"); + cliente.setSenha("senha123"); + cliente.setFg_ativo(1); + + Endereco endereco = new Endereco(); + endereco.setRua("Rua Teste"); + endereco.setBairro("Centro"); + endereco.setNumero(100); + endereco.setCidade("São Paulo"); + endereco.setEstado("SP"); + cliente.setEndereco(endereco); + + assertDoesNotThrow(() -> daoCliente.salvar(cliente)); + + // Validando que foi salvo corretamente no banco + Cliente clienteSalvo = daoCliente.pesquisaPorUsuario(cliente); + assertNotNull(clienteSalvo); + assertEquals("João", clienteSalvo.getNome()); + } + + @Test + void TestSalvarClienteComEnderecoExistente() { + Cliente cliente = new Cliente(); + cliente.setNome("Maria"); + cliente.setSobrenome("Souza"); + cliente.setTelefone("11988888888"); + cliente.setUsuario("maria_test"); + cliente.setSenha("senha123"); + cliente.setFg_ativo(1); + + Endereco endereco = new Endereco(); + endereco.setRua("Rua Teste"); + endereco.setBairro("Centro"); + endereco.setNumero(100); + endereco.setCidade("São Paulo"); + endereco.setEstado("SP"); + cliente.setEndereco(endereco); + + // Salva primeiro para existir + daoCliente.salvar(cliente); + + // Salva novamente para entrar no else do salvar + assertDoesNotThrow(() -> daoCliente.salvar(cliente)); + } + + @Test + void TestListarTodosClientes() { + List clientes = daoCliente.listarTodos(); + assertNotNull(clientes); + assertTrue(clientes.size() >= 0); + } + + @Test + void TestPesquisaPorUsuarioExistente() { + Cliente cliente = new Cliente(); + cliente.setUsuario("joao_test"); + Cliente resultado = daoCliente.pesquisaPorUsuario(cliente); + assertEquals("joao_test", resultado.getUsuario()); + } + + @Test + void TestPesquisaPorUsuarioInexistente() { + Cliente cliente = new Cliente(); + cliente.setUsuario("usuario_inexistente"); + Cliente resultado = daoCliente.pesquisaPorUsuario(cliente); + assertNull(resultado.getUsuario()); + } + + @Test + void TestPesquisaPorIDExistente() { + Cliente cliente = new Cliente(); + cliente.setNome("Carlos"); + cliente.setSobrenome("Almeida"); + cliente.setTelefone("77777777"); + cliente.setUsuario("carlos_test"); + cliente.setSenha("senha123"); + cliente.setFg_ativo(1); + + Endereco endereco = new Endereco(); + endereco.setRua("Rua Teste"); + endereco.setBairro("Centro"); + endereco.setNumero(200); + endereco.setCidade("São Paulo"); + endereco.setEstado("SP"); + cliente.setEndereco(endereco); + + daoCliente.salvar(cliente); + + Cliente clienteInserido = daoCliente.pesquisaPorUsuario(cliente); + assertNotNull(clienteInserido); + + Cliente clientePorID = daoCliente.pesquisaPorID(String.valueOf(clienteInserido.getId_cliente())); + assertNotNull(clientePorID); + assertEquals("Carlos", clientePorID.getNome()); + } + + @Test + void TestPesquisaPorIDInexistente() { + Cliente cliente = daoCliente.pesquisaPorID("-1"); + assertNotNull(cliente); + assertEquals(0, cliente.getId_cliente()); // pois retorna new Cliente() + } + + @Test + void TestLoginValido() { + Cliente cliente = new Cliente(); + cliente.setNome("Pedro"); + cliente.setSobrenome("Mendes"); + cliente.setTelefone("66666666"); + cliente.setUsuario("pedro_test"); + cliente.setSenha("senha123"); + cliente.setFg_ativo(1); + + Endereco endereco = new Endereco(); + endereco.setRua("Rua Teste"); + endereco.setBairro("Centro"); + endereco.setNumero(300); + endereco.setCidade("São Paulo"); + endereco.setEstado("SP"); + cliente.setEndereco(endereco); + + daoCliente.salvar(cliente); + + Cliente loginCliente = new Cliente(); + loginCliente.setUsuario("pedro_test"); + loginCliente.setSenha("senha123"); + + boolean result = daoCliente.login(loginCliente); + assertTrue(result); + } + + @Test + void TestLoginSenhaInvalida() { + Cliente cliente = new Cliente(); + cliente.setUsuario("joao_test"); + cliente.setSenha("senha_errada"); + + boolean result = daoCliente.login(cliente); + assertFalse(result); + } + + @Test + void TestLoginUsuarioInexistente() { + Cliente cliente = new Cliente(); + cliente.setUsuario("usuario_inexistente"); + cliente.setSenha("qualquer"); + + boolean result = daoCliente.login(cliente); + assertFalse(result); + } + +} diff --git a/src/test/java/DAO/TestesIngredientes/IngredienteIntegracaoTest.java b/src/test/java/DAO/TestesIngredientes/IngredienteIntegracaoTest.java new file mode 100644 index 0000000..96b1b65 --- /dev/null +++ b/src/test/java/DAO/TestesIngredientes/IngredienteIntegracaoTest.java @@ -0,0 +1,178 @@ +package DAO.TestesIngredientes; + +import DAO.DaoIngrediente; +import Model.Ingrediente; +import org.junit.jupiter.api.*; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class IngredienteIntegracaoTest { + + private static DaoIngrediente dao; + + @BeforeAll + static void setup() { + dao = new DaoIngrediente(); // Inicializa DAO com conexão real + } + + @Test + @Order(1) + void testSalvarEBuscarIngrediente() { + Ingrediente ingrediente = new Ingrediente(); + ingrediente.setNome("TestTomate"); + ingrediente.setDescricao("Vermelho"); + ingrediente.setQuantidade(50); + ingrediente.setValor_compra(1.0); + ingrediente.setValor_venda(2.0); + ingrediente.setTipo("legume"); + ingrediente.setFg_ativo(1); + + dao.salvar(ingrediente); // Insere no banco + + Ingrediente resultado = dao.pesquisaPorNome(ingrediente); // Busca pelo nome + + assertNotNull(resultado); + assertEquals("TestTomate", resultado.getNome()); + assertEquals("Vermelho", resultado.getDescricao()); + } + + @Test + @Order(2) + void testListarTodos() { + List lista = dao.listarTodos(); // Lista todos ingredientes ativos + + assertNotNull(lista); + assertTrue(lista.size() >= 1); // Espera que pelo menos 1 esteja presente + } + + @Test + @Order(3) + void testAlterarIngrediente() { + Ingrediente ingrediente = dao.pesquisaPorNome(new Ingrediente() {{ + setNome("TestTomate"); + }}); + assertNotNull(ingrediente); + + ingrediente.setDescricao("Vermelho Escuro"); + ingrediente.setQuantidade(99); + dao.alterar(ingrediente); // Altera dados do ingrediente + + Ingrediente alterado = dao.pesquisaPorNome(ingrediente); + assertEquals("Vermelho Escuro", alterado.getDescricao()); + assertEquals(99, alterado.getQuantidade()); + } + + @Test + @Order(4) + void testRemoverIngrediente() { + Ingrediente ingrediente = dao.pesquisaPorNome(new Ingrediente() {{ + setNome("TestTomate"); + }}); + assertNotNull(ingrediente); + + dao.remover(ingrediente); // Remove do banco + + Ingrediente buscado = dao.pesquisaPorNome(ingrediente); + assertNull(buscado.getNome()); // Espera que não encontre mais + } + + @Test + @Order(5) + void testSalvarIngredienteComNomeDuplicado() { + // Salva primeiro ingrediente + Ingrediente ingrediente1 = new Ingrediente(); + ingrediente1.setNome("Duplicado"); + ingrediente1.setDescricao("Primeiro"); + ingrediente1.setQuantidade(10); + ingrediente1.setValor_compra(1.5); + ingrediente1.setValor_venda(2.5); + ingrediente1.setTipo("teste"); + ingrediente1.setFg_ativo(1); + dao.salvar(ingrediente1); + + // Salva outro com o mesmo nome + Ingrediente ingrediente2 = new Ingrediente(); + ingrediente2.setNome("Duplicado"); + ingrediente2.setDescricao("Segundo"); + ingrediente2.setQuantidade(20); + ingrediente2.setValor_compra(2.5); + ingrediente2.setValor_venda(3.5); + ingrediente2.setTipo("teste"); + ingrediente2.setFg_ativo(1); + dao.salvar(ingrediente2); + + Ingrediente resultado = dao.pesquisaPorNome(ingrediente2); + assertNotNull(resultado); + assertEquals("Duplicado", resultado.getNome()); + + // Limpa o registro duplicado após teste + dao.remover(resultado); + } + + @Test + @Order(6) + void testBuscarIngredienteInexistente() { + Ingrediente inexistente = new Ingrediente(); + inexistente.setNome("IngredienteInexistente"); + Ingrediente resultado = dao.pesquisaPorNome(inexistente); + + // Espera que nome seja nulo para ingrediente não encontrado + assertNull(resultado.getNome()); + } + + @Test + @Order(7) + void testListarTodosAposInsercao() { + // Insere ingrediente temporário + Ingrediente ingrediente = new Ingrediente(); + ingrediente.setNome("ListarTeste"); + ingrediente.setDescricao("Teste Listagem"); + ingrediente.setQuantidade(5); + ingrediente.setValor_compra(3.0); + ingrediente.setValor_venda(4.0); + ingrediente.setTipo("categoria"); + ingrediente.setFg_ativo(1); + + dao.salvar(ingrediente); + + List lista = dao.listarTodos(); + + // Verifica se o ingrediente inserido está na lista + boolean encontrado = lista.stream().anyMatch(i -> "ListarTeste".equals(i.getNome())); + assertTrue(encontrado); + + // Limpa o registro após teste + dao.remover(dao.pesquisaPorNome(ingrediente)); + } + + @Test + @Order(8) + void testAlterarIngredienteInexistente() { + Ingrediente inexistente = new Ingrediente(); + inexistente.setId_ingrediente(99999); // ID que provavelmente não existe + inexistente.setNome("Fake"); + inexistente.setDescricao("Não existe"); + inexistente.setQuantidade(0); + inexistente.setValor_compra(0.0); + inexistente.setValor_venda(0.0); + inexistente.setTipo("teste"); + + // Garante que não lança exceção ao tentar alterar + assertDoesNotThrow(() -> dao.alterar(inexistente)); + + Ingrediente resultado = dao.pesquisaPorNome(inexistente); + assertNull(resultado.getNome()); + } + + @Test + @Order(9) + void testRemoverIngredienteInexistente() { + Ingrediente fake = new Ingrediente(); + fake.setId_ingrediente(99999); // ID que não deve existir + + assertDoesNotThrow(() -> dao.remover(fake)); + } +} diff --git a/src/test/java/DAO/TestesIngredientes/IngredientesMockitoTest.java b/src/test/java/DAO/TestesIngredientes/IngredientesMockitoTest.java new file mode 100644 index 0000000..288b80e --- /dev/null +++ b/src/test/java/DAO/TestesIngredientes/IngredientesMockitoTest.java @@ -0,0 +1,206 @@ +package DAO.TestesIngredientes; +import Controllers.getIngredientes; +import Controllers.removerIngrediente; +import DAO.DaoIngrediente; +import Helpers.ValidadorCookie; +import Model.Ingrediente; +import org.json.JSONObject; +import org.junit.jupiter.api.*; +import org.mockito.*; +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import Controllers.getIngredientesPorLancheCliente; +import com.google.gson.Gson; +import static org.mockito.Mockito.*; + +class IngredientesMockitoTest { + + @InjectMocks + removerIngrediente servlet; + + @Mock + DaoIngrediente daoIngrediente; + + @Mock + ValidadorCookie validadorCookie; + + @Mock + HttpServletRequest request; + + @Mock + HttpServletResponse response; + + @Mock + PrintWriter writer; + + @InjectMocks + getIngredientes servletGet; + + @InjectMocks + getIngredientesPorLancheCliente servletPorLanche; + + @BeforeEach + void setup() throws IOException { + MockitoAnnotations.openMocks(this); // Inicializa os mocks com @Mock/@InjectMocks + servlet = new removerIngrediente(daoIngrediente, validadorCookie); + servletGet = new getIngredientes(daoIngrediente, validadorCookie); + servletPorLanche = new getIngredientesPorLancheCliente(daoIngrediente); + when(response.getWriter()).thenReturn(writer); + } + + @Test + void testGetIngredientesPorLancheCliente() throws Exception { + // Simula um JSON com id do lanche + JSONObject jsonRequest = new JSONObject(); + jsonRequest.put("id", 8); + byte[] jsonBytes = jsonRequest.toString().getBytes(StandardCharsets.UTF_8); + + // Simula o corpo da requisição + when(request.getInputStream()).thenReturn( + new DelegatingServletInputStream(new ByteArrayInputStream(jsonBytes)) + ); + + // Mocka retorno do DAO + List ingredientes = new ArrayList<>(); + Ingrediente ing = new Ingrediente(); + ing.setId_ingrediente(3); + ing.setNome("Alface"); + ingredientes.add(ing); + + when(daoIngrediente.listarTodosPorLanche(8)).thenReturn(ingredientes); + + servletPorLanche.doPost(request, response); + + verify(daoIngrediente).listarTodosPorLanche(8); + + String jsonEsperado = new Gson().toJson(ingredientes); + verify(writer).print(jsonEsperado); + verify(writer).flush(); + } + + @Test + void testGetIngredientesComCookieValido() throws Exception { + // Simula um cookie válido + Cookie[] cookies = {new Cookie("token", "abc")}; + when(request.getCookies()).thenReturn(cookies); + when(validadorCookie.validarFuncionario(cookies)).thenReturn(true); + + // Simula retorno de ingredientes + List ingredientes = new ArrayList<>(); + Ingrediente ing = new Ingrediente(); + ing.setId_ingrediente(1); + ing.setNome("Tomate"); + ingredientes.add(ing); + + when(daoIngrediente.listarTodos()).thenReturn(ingredientes); + + servletGet.doGet(request, response); + + verify(daoIngrediente).listarTodos(); + String jsonEsperado = new Gson().toJson(ingredientes); + verify(writer).print(jsonEsperado); + verify(writer).flush(); + } + + @Test + void testGetIngredientesSemCookie() throws Exception { + // Simula requisição sem cookies + when(request.getCookies()).thenReturn(null); + when(validadorCookie.validarFuncionario(null)).thenReturn(false); + + servletGet.doGet(request, response); + + // Espera resposta de erro + verify(writer).println("erro"); + } + + @Test + void testIngredienteRemovidoCookieValido() throws Exception { + Cookie[] cookies = {new Cookie("token", "abc")}; + when(request.getCookies()).thenReturn(cookies); + when(validadorCookie.validarFuncionario(cookies)).thenReturn(true); + + // Simula JSON com dados do ingrediente a remover + JSONObject jsonRequest = new JSONObject(); + jsonRequest.put("id", 10); + jsonRequest.put("nome", "Alface"); + jsonRequest.put("descricao", "Verde"); + jsonRequest.put("quantidade", 100); + jsonRequest.put("ValorCompra", 5.0); + jsonRequest.put("ValorVenda", 8.0); + jsonRequest.put("tipo", "verdura"); + + byte[] jsonBytes = jsonRequest.toString().getBytes(StandardCharsets.UTF_8); + when(request.getInputStream()).thenReturn( + new DelegatingServletInputStream(new ByteArrayInputStream(jsonBytes)) + ); + + servlet.doPost(request, response); + + // Captura o ingrediente passado ao DAO para validar seus atributos + ArgumentCaptor captor = ArgumentCaptor.forClass(Ingrediente.class); + verify(daoIngrediente).remover(captor.capture()); + Ingrediente ingRemovido = captor.getValue(); + Assertions.assertEquals(10, ingRemovido.getId_ingrediente()); + Assertions.assertEquals("Alface", ingRemovido.getNome()); + Assertions.assertEquals(1, ingRemovido.getFg_ativo()); + + verify(writer).println("Ingrediente Alterado!"); + } + + @Test + void testIngredienteRemovidoCookieInvalido() throws Exception { + servlet = new removerIngrediente(daoIngrediente, validadorCookie); + + when(request.getCookies()).thenReturn(null); // Sem cookie + + // Input vazio simula POST inválido + String emptyJson = ""; + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(emptyJson.getBytes(StandardCharsets.UTF_8)); + + // Simula input stream customizado + ServletInputStream servletInputStream = new ServletInputStream() { + @Override public boolean isFinished() { return false; } + @Override public boolean isReady() { return true; } + @Override public void setReadListener(ReadListener readListener) {} + @Override public int read() throws IOException { return byteArrayInputStream.read(); } + }; + + when(request.getInputStream()).thenReturn(servletInputStream); + when(response.getWriter()).thenReturn(writer); + + servlet.doPost(request, response); + + // Espera mensagem de erro + verify(writer).println("erro"); + } + + static class DelegatingServletInputStream extends javax.servlet.ServletInputStream { + private final InputStream sourceStream; + + public DelegatingServletInputStream(InputStream sourceStream) { + this.sourceStream = sourceStream; + } + + @Override public int read() throws IOException { + return sourceStream.read(); + } + + @Override public boolean isFinished() { + try { + return sourceStream.available() == 0; + } catch (IOException e) { + return true; + } + } + + @Override public boolean isReady() { return true; } + + @Override public void setReadListener(javax.servlet.ReadListener readListener) {} + } +} diff --git a/src/test/java/Helpers/ValidadorCookieTest.java b/src/test/java/Helpers/ValidadorCookieTest.java new file mode 100644 index 0000000..f4e71c8 --- /dev/null +++ b/src/test/java/Helpers/ValidadorCookieTest.java @@ -0,0 +1,310 @@ +package Helpers; + +import DAO.DaoToken; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockedConstruction; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.servlet.http.Cookie; + +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class ValidadorCookieTest { + + @InjectMocks + private ValidadorCookie validadorCookie; + + @Mock + private DaoToken daoTokenMock; + + private Cookie[] cookies; + + @BeforeEach + void setUp() { + validadorCookie = new ValidadorCookie(); + } + + @Test + void testValidar_ComTokenValido() { + // Deve retornar true + Cookie tokenCookie = new Cookie("token", "123-Gabriel"); + cookies = new Cookie[]{tokenCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> when(mock.validar("123-Gabriel")).thenReturn(true))) { + + boolean resultado = validadorCookie.validar(cookies); + + assertTrue(resultado); + } + } + + @Test + void testValidar_ComTokenInvalido() { + // Deve retornar false + Cookie tokenCookie = new Cookie("token", "999-Daniel"); + cookies = new Cookie[]{tokenCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> when(mock.validar("999-Daniel")).thenReturn(false))) { + + boolean resultado = validadorCookie.validar(cookies); + + assertFalse(resultado); + } + } + + @Test + void testValidar_SemTokenCookie() { + // Deve retornar false + Cookie outroCookie = new Cookie("session", "456-Deniel"); + cookies = new Cookie[]{outroCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class)) { + + boolean resultado = validadorCookie.validar(cookies); + + assertFalse(resultado); + } + } + + @Test + void testValidar_CookiesVazio() { + // Deve retornar false + cookies = new Cookie[]{}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class)) { + + boolean resultado = validadorCookie.validar(cookies); + + assertFalse(resultado); + } + } + + @Test + void testValidar_MultiplosCookies_ComToken() { + // Deve retornar true + Cookie cookie1 = new Cookie("session", "789-Guilherme"); + Cookie tokenCookie = new Cookie("token", "456-Gabriel"); + Cookie cookie3 = new Cookie("user", "321-Vania"); + cookies = new Cookie[]{cookie1, tokenCookie, cookie3}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> when(mock.validar("456-Gabriel")).thenReturn(true))) { + + boolean resultado = validadorCookie.validar(cookies); + + assertTrue(resultado); + } + } + + @Test + void testValidarFuncionario_ComTokenFuncionarioValido() { + // Deve retornar true + Cookie tokenCookie = new Cookie("tokenFuncionario", "100-Lucas"); + cookies = new Cookie[]{tokenCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> when(mock.validar("100-Lucas")).thenReturn(true))) { + + boolean resultado = validadorCookie.validarFuncionario(cookies); + + assertTrue(resultado); + } + } + + @Test + void testValidarFuncionario_ComTokenFuncionarioInvalido() { + // Deve retornar false + Cookie tokenCookie = new Cookie("tokenFuncionario", "200-Guilherme"); + cookies = new Cookie[]{tokenCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> when(mock.validar("200-Guilherme")).thenReturn(false))) { + + boolean resultado = validadorCookie.validarFuncionario(cookies); + + assertFalse(resultado); + } + } + + @Test + void testValidarFuncionario_SemTokenFuncionarioCookie() { + // Deve retornar false + Cookie outroCookie = new Cookie("token", "300-Daniel"); + cookies = new Cookie[]{outroCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class)) { + + boolean resultado = validadorCookie.validarFuncionario(cookies); + + assertFalse(resultado); + } + } + + @Test + void testDeletar_ComTokens() { + // Deve chamar remover + Cookie tokenCookie = new Cookie("token", "400-Vania"); + Cookie tokenFuncCookie = new Cookie("tokenFuncionario", "500-Lucas"); + Cookie outroCookie = new Cookie("session", "600-Gabriel"); + cookies = new Cookie[]{tokenCookie, tokenFuncCookie, outroCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class)) { + + validadorCookie.deletar(cookies); + + DaoToken daoTokenInstance = mockedConstruction.constructed().get(0); + verify(daoTokenInstance).remover("400-Vania"); + verify(daoTokenInstance).remover("500-Lucas"); + verify(daoTokenInstance, never()).remover("600-Gabriel"); + } + } + + @Test + void testDeletar_SemTokens() { + // Não deve chamar remover + Cookie outroCookie = new Cookie("session", "700-Deniel"); + cookies = new Cookie[]{outroCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class)) { + + validadorCookie.deletar(cookies); + + DaoToken daoTokenInstance = mockedConstruction.constructed().get(0); + verify(daoTokenInstance, never()).remover(anyString()); + } + } + + @Test + void testDeletar_ComExcecaoNoDAO() { + // Deve lançar RuntimeException + Cookie tokenCookie = new Cookie("token", "800-Guilherme"); + cookies = new Cookie[]{tokenCookie}; + + try (MockedConstruction mockedConstruction = mockConstruction(DaoToken.class, + (mock, context) -> doThrow(new RuntimeException("Erro no banco")).when(mock).remover("800-Guilherme"))) { + + assertThrows(RuntimeException.class, () -> validadorCookie.deletar(cookies)); + } + } + + @Test + void testGetCookieIdCliente_ComTokenValido() { + // Deve retornar id + Cookie tokenCookie = new Cookie("token", "123-Gabriel"); + cookies = new Cookie[]{tokenCookie}; + + String resultado = validadorCookie.getCookieIdCliente(cookies); + + assertEquals("123", resultado); + } + + @Test + void testGetCookieIdCliente_SemToken() { + // Deve retornar erro + Cookie outroCookie = new Cookie("session", "900-Lucas"); + cookies = new Cookie[]{outroCookie}; + + String resultado = validadorCookie.getCookieIdCliente(cookies); + + assertEquals("erro", resultado); + } + + @Test + void testGetCookieIdCliente_TokenSemHifen() { + // Deve retornar token completo + Cookie tokenCookie = new Cookie("token", "456Daniel"); + cookies = new Cookie[]{tokenCookie}; + + String resultado = validadorCookie.getCookieIdCliente(cookies); + + assertEquals("456Daniel", resultado); + } + + @Test + void testGetCookieIdCliente_MultiplosCookies() { + // Deve retornar id do token + Cookie cookie1 = new Cookie("session", "111-Vania"); + Cookie tokenCookie = new Cookie("token", "789-Deniel"); + Cookie cookie3 = new Cookie("user", "222-Guilherme"); + cookies = new Cookie[]{cookie1, tokenCookie, cookie3}; + + String resultado = validadorCookie.getCookieIdCliente(cookies); + + assertEquals("789", resultado); + } + + @Test + void testGetCookieIdFuncionario_ComTokenFuncionarioValido() { + // Deve retornar id + Cookie tokenCookie = new Cookie("tokenFuncionario", "456-Gabriel"); + cookies = new Cookie[]{tokenCookie}; + + String resultado = validadorCookie.getCookieIdFuncionario(cookies); + + assertEquals("456", resultado); + } + + @Test + void testGetCookieIdFuncionario_SemTokenFuncionario() { + // Deve retornar erro + Cookie outroCookie = new Cookie("token", "333-Lucas"); + cookies = new Cookie[]{outroCookie}; + + String resultado = validadorCookie.getCookieIdFuncionario(cookies); + + assertEquals("erro", resultado); + } + + @Test + void testGetCookieIdFuncionario_TokenFuncionarioSemHifen() { + // Deve retornar token completo + Cookie tokenCookie = new Cookie("tokenFuncionario", "789Vania"); + cookies = new Cookie[]{tokenCookie}; + + String resultado = validadorCookie.getCookieIdFuncionario(cookies); + + assertEquals("789Vania", resultado); + } + + @Test + void testGetCookieIdFuncionario_MultiplosCookies() { + // Deve retornar id do token funcionario + Cookie cookie1 = new Cookie("session", "444-Guilherme"); + Cookie tokenCookie = new Cookie("token", "555-Daniel"); + Cookie tokenFuncCookie = new Cookie("tokenFuncionario", "999-Gabriel"); + cookies = new Cookie[]{cookie1, tokenCookie, tokenFuncCookie}; + + String resultado = validadorCookie.getCookieIdFuncionario(cookies); + + assertEquals("999", resultado); + } + + @Test + void testGetCookieIdCliente_CookiesVazio() { + // Deve retornar erro + cookies = new Cookie[]{}; + + String resultado = validadorCookie.getCookieIdCliente(cookies); + + assertEquals("erro", resultado); + } + + @Test + void testGetCookieIdFuncionario_CookiesVazio() { + // Deve retornar erro + cookies = new Cookie[]{}; + + String resultado = validadorCookie.getCookieIdFuncionario(cookies); + + assertEquals("erro", resultado); + } +} diff --git a/src/test/java/Integracao/CadastroIntegrationTest.java b/src/test/java/Integracao/CadastroIntegrationTest.java new file mode 100644 index 0000000..a9e1a62 --- /dev/null +++ b/src/test/java/Integracao/CadastroIntegrationTest.java @@ -0,0 +1,103 @@ +package Integracao; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.UUID; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class CadastroIntegrationTest { + private static final String BASE_URL = "http://localhost:8080"; + + // Método para detectar configuração do banco + private static String getDatabaseUrl() { + String dockerHost = System.getenv("DB_HOST"); + if (dockerHost != null) { + return "jdbc:postgresql://" + dockerHost + ":5432/lanchonete"; + } + + // Verifica se está no container + try { + java.net.InetAddress.getByName("db"); + return "jdbc:postgresql://db:5432/lanchonete"; + } catch (java.net.UnknownHostException e) { + // Está no host local, usa porta mapeada + return "jdbc:postgresql://localhost:5433/lanchonete"; + } + } + + private static final String DB_URL = getDatabaseUrl(); + private static final String DB_USER = "postgres"; + private static final String DB_PASSWORD = "123456"; + + @Test + public void testCadastroClienteCompleto() throws IOException, SQLException { + + String uniqueUser = "test_" + UUID.randomUUID().toString().substring(0, 8); + + String json = String.format("{" + + "\"endereco\":{" + + "\"bairro\":\"Teste\"," + + "\"cidade\":\"Teste\"," + + "\"estado\":\"TS\"," + + "\"complemento\":\"teste\"," + + "\"rua\":\"Rua Teste\"," + + "\"numero\":123" + + "}," + + "\"usuario\":{" + + "\"nome\":\"Teste\"," + + "\"sobrenome\":\"Teste\"," + + "\"telefone\":\"11999999999\"," + + "\"usuario\":\"%s\"," + + "\"senha\":\"123456\"" + + "}" + + "}", uniqueUser); + + URL url = new URL(BASE_URL + "/cadastro"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + + try (OutputStream os = conn.getOutputStream()) { + os.write(json.getBytes(StandardCharsets.UTF_8)); + } + + Assertions.assertEquals(200, conn.getResponseCode(), "Deveria retornar status 200"); + + try (Connection dbConn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); + PreparedStatement stmt = dbConn.prepareStatement( + "SELECT c.*, e.bairro FROM tb_clientes c JOIN tb_enderecos e ON c.id_endereco = e.id_endereco WHERE c.usuario = ?")) { + + stmt.setString(1, uniqueUser); + ResultSet rs = stmt.executeQuery(); + + Assertions.assertTrue(rs.next(), "Cliente deveria estar persistido no banco"); + Assertions.assertEquals("Teste", rs.getString("nome")); + Assertions.assertEquals("Teste", rs.getString("bairro")); + } + } + + @AfterEach + void cleanTestData() throws SQLException { + try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); + Statement stmt = conn.createStatement()) { + + stmt.executeUpdate("DELETE FROM tb_clientes WHERE usuario LIKE 'test_%'"); + stmt.executeUpdate("DELETE FROM tb_enderecos WHERE bairro = 'Teste' AND " + + "NOT EXISTS (SELECT 1 FROM tb_clientes WHERE tb_clientes.id_endereco = tb_enderecos.id_endereco)"); + } + } + +} diff --git a/src/test/java/Integracao/FluxoCompraIntegrationTest.java b/src/test/java/Integracao/FluxoCompraIntegrationTest.java new file mode 100644 index 0000000..cc71fdf --- /dev/null +++ b/src/test/java/Integracao/FluxoCompraIntegrationTest.java @@ -0,0 +1,549 @@ +package Integracao; + +import DAO.*; +import Model.*; +import org.junit.jupiter.api.*; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.CsvSource; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; +import java.util.function.Function; + +import static org.junit.jupiter.api.Assertions.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class FluxoCompraIntegrationTest { + + private static DaoCliente daoCliente; + private static DaoToken daoToken; + private static DaoLanche daoLanche; + private static DaoBebida daoBebida; + private static DaoPedido daoPedido; + private static final String USUARIO_TESTE = "cliente_compra_test"; + private static final String SENHA_TESTE = "senha123"; + + + private static class EstadoCompra { + private final Cliente cliente; + private final String token; + private final Lanche lanche; + private final Bebida bebida; + private final Pedido pedido; + private final boolean ambientePreparado; + private final boolean produtosConsultados; + private final boolean carrinhoSimulado; + private final boolean compraFinalizada; + + private EstadoCompra(Cliente cliente, String token, Lanche lanche, Bebida bebida, + Pedido pedido, boolean ambientePreparado, boolean produtosConsultados, + boolean carrinhoSimulado, boolean compraFinalizada) { + this.cliente = cliente; + this.token = token; + this.lanche = lanche; + this.bebida = bebida; + this.pedido = pedido; + this.ambientePreparado = ambientePreparado; + this.produtosConsultados = produtosConsultados; + this.carrinhoSimulado = carrinhoSimulado; + this.compraFinalizada = compraFinalizada; + } + + public static EstadoCompra inicial() { + return new EstadoCompra(null, null, null, null, null, false, false, false, false); + } + + public EstadoCompra comCliente(Cliente cliente) { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, true, + produtosConsultados, carrinhoSimulado, compraFinalizada); + } + + public EstadoCompra comToken(String token) { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + produtosConsultados, carrinhoSimulado, compraFinalizada); + } + + public EstadoCompra comLanche(Lanche lanche) { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + produtosConsultados, carrinhoSimulado, compraFinalizada); + } + + public EstadoCompra comBebida(Bebida bebida) { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + produtosConsultados, carrinhoSimulado, compraFinalizada); + } + + public EstadoCompra comProdutosConsultados() { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + true, carrinhoSimulado, compraFinalizada); + } + + public EstadoCompra comCarrinhoSimulado() { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + produtosConsultados, true, compraFinalizada); + } + + public EstadoCompra comPedido(Pedido pedido) { + return new EstadoCompra(cliente, token, lanche, bebida, pedido, ambientePreparado, + produtosConsultados, carrinhoSimulado, true); + } + + public Cliente getCliente() { + return cliente; + } + public String getToken() { + return token; + } + public Lanche getLanche() { + return lanche; + } + public Bebida getBebida() { + return bebida; + } + public Pedido getPedido() { + return pedido; + } + public boolean isAmbientePreparado() { + return ambientePreparado; + } + public boolean isProdutosConsultados() { + return produtosConsultados; + } + public boolean isCarrinhoSimulado() { + return carrinhoSimulado; + } + public boolean isCompraFinalizada() { + return compraFinalizada; + } + } + + private static EstadoCompra estadoAtual = EstadoCompra.inicial(); + + @BeforeAll + static void classeConfig() { + daoCliente = new DaoCliente(); + daoToken = new DaoToken(); + daoLanche = new DaoLanche(); + daoBebida = new DaoBebida(); + daoPedido = new DaoPedido(); + + try (Connection conn = new DaoUtil().conecta()) { + conn.createStatement().execute("DELETE FROM tb_lanches_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'))"); + conn.createStatement().execute("DELETE FROM tb_bebidas_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'))"); + conn.createStatement().execute("DELETE FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "')"); + conn.createStatement().execute("DELETE FROM tb_tokens WHERE token LIKE '" + USUARIO_TESTE + "%'"); + conn.createStatement().execute("DELETE FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'"); + conn.createStatement().execute("DELETE FROM tb_lanches WHERE nm_lanche = 'nomeLanche'"); + conn.createStatement().execute("DELETE FROM tb_bebidas WHERE nm_bebida = 'nomeBebida'"); + } catch (SQLException e) { + } + } + + private Function prepararCliente = (estado) -> { + try { + Endereco endereco = enderecoTeste(); + Cliente cliente = clienteTeste(endereco); + + daoCliente.salvar(cliente); + Cliente clienteSalvo = daoCliente.pesquisaPorUsuario(cliente); + + return estado.comCliente(clienteSalvo); + } catch (Exception e) { + throw new RuntimeException("erro cliente: " + e.getMessage(), e); + } + }; + + private Function prepararLanche = (estado) -> { + try { + Lanche lanche = lancheTeste(); + daoLanche.salvar(lanche); + Lanche lancheRecuperado = daoLanche.pesquisaPorNome(lanche.getNome()); + + return estado.comLanche(lancheRecuperado); + } catch (Exception e) { + throw new RuntimeException("erro lanche: " + e.getMessage(), e); + } + }; + + private Function prepararBebida = (estado) -> { + try { + Bebida bebida = bebidaTeste(); + daoBebida.salvar(bebida); + Bebida bebidaRecuperada = daoBebida.pesquisaPorNome(bebida.getNome()); + + return estado.comBebida(bebidaRecuperada); + } catch (Exception e) { + throw new RuntimeException("erro bebida: " + e.getMessage(), e); + } + }; + + private Function realizarLogin = (estado) -> { + try { + Cliente clienteLogin = new Cliente(); + clienteLogin.setUsuario(USUARIO_TESTE); + clienteLogin.setSenha(SENHA_TESTE); + + boolean loginSuccess = daoCliente.login(clienteLogin); + if (!loginSuccess) { + throw new RuntimeException("erro cliente"); + } + + String token = estado.getCliente().getId_cliente() + "-" + Instant.now().toString(); + daoToken.salvar(token); + + return estado.comToken(token); + } catch (Exception e) { + throw new RuntimeException("erro login: " + e.getMessage(), e); + } + }; + + private Function consultarProdutos = (estado) -> { + try { + List lanches = daoLanche.listarTodos(); + List bebidas = daoBebida.listarTodos(); + + if (lanches == null || bebidas == null) { + throw new RuntimeException("erro produtos"); + } + + return estado.comProdutosConsultados(); + } catch (Exception e) { + throw new RuntimeException("erro produtos: " + e.getMessage(), e); + } + }; + + private Function simularCarrinho = (estado) -> { + try { + int quantidadeLanche = 2; + int quantidadeBebida = 3; + + double valorLanches = estado.getLanche().getValor_venda() * quantidadeLanche; + double valorBebidas = estado.getBebida().getValor_venda() * quantidadeBebida; + double valorTotal = valorLanches + valorBebidas; + + if (valorTotal <= 0) { + throw new RuntimeException("Valor total inválido"); + } + + return estado.comCarrinhoSimulado(); + } catch (Exception e) { + throw new RuntimeException("erro carrinho: " + e.getMessage(), e); + } + }; + + private Function finalizarCompra = (estado) -> { + try { + boolean tokenValido = daoToken.validar(estado.getToken()); + if (!tokenValido) { + throw new RuntimeException("Token inválido"); + } + + Cliente cliente = daoCliente.pesquisaPorID(String.valueOf(estado.getCliente().getId_cliente())); + + int quantidadeLanche = 2; + int quantidadeBebida = 1; + + Lanche lanche = estado.getLanche(); + Bebida bebida = estado.getBebida(); + lanche.setQuantidade(quantidadeLanche); + bebida.setQuantidade(quantidadeBebida); + + double valorTotal = (lanche.getValor_venda() * quantidadeLanche) + + (bebida.getValor_venda() * quantidadeBebida); + + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(cliente); + pedido.setValor_total(valorTotal); + + daoPedido.salvar(pedido); + Pedido pedidoSalvo = daoPedido.pesquisaPorData(pedido); + + daoPedido.vincularLanche(pedidoSalvo, lanche); + daoPedido.vincularBebida(pedidoSalvo, bebida); + + return estado.comPedido(pedidoSalvo); + } catch (Exception e) { + throw new RuntimeException("erro finalizar compra: " + e.getMessage(), e); + } + }; + + @Test + @Order(1) + void prepararAmbienteCompra() { + estadoAtual = prepararCliente.apply(estadoAtual); + estadoAtual = prepararLanche.apply(estadoAtual); + estadoAtual = prepararBebida.apply(estadoAtual); + estadoAtual = realizarLogin.apply(estadoAtual); + + assertNotNull(estadoAtual.getCliente()); + assertTrue(estadoAtual.getCliente().getId_cliente() > 0); + assertNotNull(estadoAtual.getLanche()); + assertNotNull(estadoAtual.getBebida()); + assertNotNull(estadoAtual.getToken()); + assertTrue(estadoAtual.isAmbientePreparado()); + + boolean tokenValido = daoToken.validar(estadoAtual.getToken()); + assertTrue(tokenValido); + } + + @Test + @Order(2) + void consultarProdutosDisponiveis() { + estadoAtual = consultarProdutos.apply(estadoAtual); + + assertTrue(estadoAtual.isProdutosConsultados()); + + List lanches = daoLanche.listarTodos(); + assertNotNull(lanches); + assertFalse(lanches.isEmpty()); + + boolean lancheEncontrado = lanches.stream() + .anyMatch(l -> l.getNome().equals(estadoAtual.getLanche().getNome())); + assertTrue(lancheEncontrado); + + List bebidas = daoBebida.listarTodos(); + assertNotNull(bebidas); + assertFalse(bebidas.isEmpty()); + + boolean bebidaEncontrada = bebidas.stream() + .anyMatch(b -> b.getNome().equals(estadoAtual.getBebida().getNome())); + assertTrue(bebidaEncontrada); + } + + @Test + @Order(3) + void simularCarrinhoCompra() { + estadoAtual = simularCarrinho.apply(estadoAtual); + + assertTrue(estadoAtual.isCarrinhoSimulado()); + + int quantidadeLanche = 2; + int quantidadeBebida = 3; + + double valorLanches = estadoAtual.getLanche().getValor_venda() * quantidadeLanche; + double valorBebidas = estadoAtual.getBebida().getValor_venda() * quantidadeBebida; + double valorTotal = valorLanches + valorBebidas; + + assertTrue(valorTotal > 0); + assertEquals(valorLanches + valorBebidas, valorTotal); + } + + @Test + @Order(4) + void finalizarCompra() { + estadoAtual = finalizarCompra.apply(estadoAtual); + + assertTrue(estadoAtual.isCompraFinalizada()); + assertNotNull(estadoAtual.getPedido()); + assertTrue(estadoAtual.getPedido().getId_pedido() > 0); + + boolean tokenValido = daoToken.validar(estadoAtual.getToken()); + assertTrue(tokenValido); + + Cliente cliente = daoCliente.pesquisaPorID(String.valueOf(estadoAtual.getCliente().getId_cliente())); + assertNotNull(cliente); + assertEquals(estadoAtual.getCliente().getId_cliente(), cliente.getId_cliente()); + } + + @Test + @Order(5) + void verificarPersistenciaPedido() { + try (Connection conn = new DaoUtil().conecta()) { + PreparedStatement stmtPedido = conn.prepareStatement( + "SELECT * FROM tb_pedidos WHERE id_cliente = ? ORDER BY id_pedido DESC LIMIT 1" + ); + stmtPedido.setInt(1, estadoAtual.getCliente().getId_cliente()); + ResultSet rsPedido = stmtPedido.executeQuery(); + + assertTrue(rsPedido.next()); + int idPedido = rsPedido.getInt("id_pedido"); + double valorTotal = rsPedido.getDouble("valor_total"); + + assertTrue(idPedido > 0); + assertTrue(valorTotal > 0); + + PreparedStatement stmtLanche = conn.prepareStatement( + "SELECT * FROM tb_lanches_pedido WHERE id_pedido = ? AND id_lanche = ?" + ); + stmtLanche.setInt(1, idPedido); + stmtLanche.setInt(2, estadoAtual.getLanche().getId_lanche()); + ResultSet rsLanche = stmtLanche.executeQuery(); + + assertTrue(rsLanche.next()); + assertEquals(2, rsLanche.getInt("quantidade")); + + PreparedStatement stmtBebida = conn.prepareStatement( + "SELECT * FROM tb_bebidas_pedido WHERE id_pedido = ? AND id_bebida = ?" + ); + stmtBebida.setInt(1, idPedido); + stmtBebida.setInt(2, estadoAtual.getBebida().getId_bebida()); + ResultSet rsBebida = stmtBebida.executeQuery(); + + assertTrue(rsBebida.next()); + assertEquals(1, rsBebida.getInt("quantidade")); + + } catch (SQLException e) { + } + } + + @Test + @Order(6) + void fluxoCompletoEndToEnd() { + assertTrue(daoToken.validar(estadoAtual.getToken())); + Cliente cliente = daoCliente.pesquisaPorID(String.valueOf(estadoAtual.getCliente().getId_cliente())); + assertNotNull(cliente); + + double valorTotal = (estadoAtual.getLanche().getValor_venda() * 1) + + (estadoAtual.getBebida().getValor_venda() * 2); + + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(cliente); + pedido.setValor_total(valorTotal); + + daoPedido.salvar(pedido); + Pedido pedidoSalvo = daoPedido.pesquisaPorData(pedido); + + assertTrue(pedidoSalvo.getId_pedido() > 0); + assertEquals(valorTotal, pedidoSalvo.getValor_total(), 0.01); + } + + @Test + @Order(7) + void testeTokenInvalido() { + daoToken.remover(estadoAtual.getToken()); + assertFalse(daoToken.validar(estadoAtual.getToken())); + + assertDoesNotThrow(() -> { + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(estadoAtual.getCliente()); + pedido.setValor_total(50.0); + daoPedido.salvar(pedido); + }); + } + + @Test + @Order(8) + void testeLoginTodasArestas() { + Cliente clienteInexistente = new Cliente(); + clienteInexistente.setUsuario("usuario_inexistente"); + clienteInexistente.setSenha("sdfgadsgsadg23423"); + assertFalse(daoCliente.login(clienteInexistente)); + Cliente clienteSenhaErrada = new Cliente(); + clienteSenhaErrada.setUsuario(USUARIO_TESTE); + clienteSenhaErrada.setSenha("234efdsaf213fdsacfdasf"); + assertFalse(daoCliente.login(clienteSenhaErrada)); + + Endereco enderecoInativo = enderecoTeste(); + Cliente clienteInativo = new Cliente(); + clienteInativo.setNome("clienteInativo"); + clienteInativo.setSobrenome("teste"); + clienteInativo.setTelefone("21888888888"); + clienteInativo.setUsuario("cliente_inativo_test"); + clienteInativo.setSenha("senha123"); + clienteInativo.setFg_ativo(0); + clienteInativo.setEndereco(enderecoInativo); + + daoCliente.salvar(clienteInativo); + assertFalse(daoCliente.login(clienteInativo)); + + Cliente clienteValido = new Cliente(); + clienteValido.setUsuario(USUARIO_TESTE); + clienteValido.setSenha(SENHA_TESTE); + assertTrue(daoCliente.login(clienteValido)); + } + + @ParameterizedTest + @Order(9) + @ValueSource(strings = {"", "token_inexistente", "token_invalido"}) + void testeValidacaoTokenParametrizado(String token) { + assertFalse(daoToken.validar(token)); + } + + @Test + @Order(10) + void testeCalculosLimite() { + assertEquals(0.0, estadoAtual.getLanche().getValor_venda() * 0); + assertTrue(estadoAtual.getLanche().getValor_venda() * (-1) < 0); + assertTrue(estadoAtual.getLanche().getValor_venda() * 1000 > 1000); + } + + private Cliente criarClienteLogin() { + Cliente cliente = new Cliente(); + cliente.setUsuario(USUARIO_TESTE); + cliente.setSenha(SENHA_TESTE); + return cliente; + } + + private Cliente criarClienteLoginInvalido() { + Cliente cliente = new Cliente(); + cliente.setUsuario("usuario_inexistente"); + cliente.setSenha("cdfvsqwgf24"); + return cliente; + } + + @AfterAll + static void tearDownClass() { + try (Connection conn = new DaoUtil().conecta()) { + conn.createStatement().execute("DELETE FROM tb_lanches_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario LIKE '%_test'))"); + conn.createStatement().execute("DELETE FROM tb_bebidas_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario LIKE '%_test'))"); + conn.createStatement().execute("DELETE FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario LIKE '%_test')"); + conn.createStatement().execute("DELETE FROM tb_tokens WHERE token LIKE '%test%'"); + conn.createStatement().execute("DELETE FROM tb_clientes WHERE usuario LIKE '%_test'"); + conn.createStatement().execute("DELETE FROM tb_lanches WHERE nm_lanche IN ('nomeLanche', 'L')"); + conn.createStatement().execute("DELETE FROM tb_bebidas WHERE nm_bebida IN ('nomeBebida', 'B')"); + } catch (SQLException e) { + } + } + + private Endereco enderecoTeste() { + Endereco endereco = new Endereco(); + endereco.setRua("Rua"); + endereco.setBairro("Bairro"); + endereco.setNumero(123); + endereco.setComplemento("Complemento"); + endereco.setCidade("Rio de Janeiro"); + endereco.setEstado("RJ"); + return endereco; + } + + private Cliente clienteTeste(Endereco endereco) { + Cliente cliente = new Cliente(); + cliente.setNome("nomeCliente"); + cliente.setSobrenome("sobrenomeCliente"); + cliente.setTelefone("21999999999"); + cliente.setUsuario(USUARIO_TESTE); + cliente.setSenha(SENHA_TESTE); + cliente.setFg_ativo(1); + cliente.setEndereco(endereco); + return cliente; + } + + private Lanche lancheTeste() { + Lanche lanche = new Lanche(); + lanche.setNome("nomeLanche"); + lanche.setDescricao("descricaoTeste"); + lanche.setValor_venda(25.90); + lanche.setFg_ativo(1); + return lanche; + } + + private Bebida bebidaTeste() { + Bebida bebida = new Bebida(); + bebida.setNome("nomeBebida"); + bebida.setDescricao("bebidaTeste"); + bebida.setQuantidade(10); + bebida.setValor_compra(3.00); + bebida.setValor_venda(8.50); + bebida.setTipo("Refrigerante"); + bebida.setFg_ativo(1); + return bebida; + } +} diff --git a/src/test/java/Integracao/LoginIntegrationTest.java b/src/test/java/Integracao/LoginIntegrationTest.java new file mode 100644 index 0000000..8694d56 --- /dev/null +++ b/src/test/java/Integracao/LoginIntegrationTest.java @@ -0,0 +1,136 @@ +package Integracao; + + +import org.junit.jupiter.api.*; +import java.io.*; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.sql.*; +import java.util.UUID; + + +public class LoginIntegrationTest { + + private static final String BASE_URL = "http://localhost:8080"; + private static final String DB_URL = "jdbc:postgresql://localhost:5432/lanchonete"; + private static final String DB_USER = "postgres"; + private static final String DB_PASSWORD = "admin123"; + + private String testUsername; + private String testPassword; + + @BeforeEach + void PrepararUsuarioTeste() throws SQLException { + testUsername = "testuser_" + UUID.randomUUID().toString().substring(0, 8); + testPassword = "testpass123"; + + try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); + PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO tb_clientes(usuario, senha, nome, sobrenome, telefone, fg_ativo) " + + "VALUES(?, MD5(?), 'Test', 'User', '11999999999', 1)")) { + + stmt.setString(1, testUsername); + stmt.setString(2, testPassword); + stmt.executeUpdate(); + } + } + + @Test + @DisplayName("Login com credenciais válidas") + void TestarLoginComCredenciaisValidas() throws IOException { + String json = String.format("{\"usuario\":\"%s\",\"senha\":\"%s\"}", testUsername, testPassword); + HttpURLConnection conn = CriarRequisicaoLogin(json); + + ValidarRespostaLoginSucesso(conn); + ValidarCookieResposta(conn); + } + + @Test + @DisplayName("Login com credenciais inválidas") + void TestarLoginComCredenciaisInvalidas() throws IOException { + String json = String.format("{\"usuario\":\"%s\",\"senha\":\"senhaerrada\"}", testUsername); + HttpURLConnection conn = CriarRequisicaoLogin(json); + + ValidarRespostaLoginErro(conn); + } + + @Test + @DisplayName("Login com usuário inativo") + void TestarLoginComUsuarioInativo() throws IOException, SQLException { + // Cria usuário inativo + String inactiveUser = "inactive_" + UUID.randomUUID().toString().substring(0, 8); + try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); + PreparedStatement stmt = conn.prepareStatement( + "INSERT INTO tb_clientes(usuario, senha, nome, sobrenome, telefone, fg_ativo) " + + "VALUES(?, MD5(?), 'Inativo', 'User', '11999999999', 0)")) { + + stmt.setString(1, inactiveUser); + stmt.setString(2, "testpass"); + stmt.executeUpdate(); + } + + String json = String.format("{\"usuario\":\"%s\",\"senha\":\"testpass\"}", inactiveUser); + HttpURLConnection conn = CriarRequisicaoLogin(json); + + ValidarRespostaLoginErro(conn); + } + + private HttpURLConnection CriarRequisicaoLogin(String json) throws IOException { + URL url = new URL(BASE_URL + "/login"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("POST"); + conn.setRequestProperty("Content-Type", "application/json"); + conn.setDoOutput(true); + + try (OutputStream os = conn.getOutputStream()) { + os.write(json.getBytes(StandardCharsets.UTF_8)); + } + return conn; + } + + private void ValidarRespostaLoginSucesso(HttpURLConnection conn) throws IOException { + Assertions.assertEquals(200, conn.getResponseCode(), "Status HTTP deveria ser 200"); + + try (BufferedReader br = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + String response = br.readLine(); + Assertions.assertTrue(response.contains("../carrinho/carrinho.html"), + "Deveria redirecionar para carrinho"); + } + } + + private void ValidarRespostaLoginErro(HttpURLConnection conn) throws IOException { + Assertions.assertEquals(200, conn.getResponseCode(), "Status HTTP deveria ser 200"); + + try (BufferedReader br = new BufferedReader( + new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { + String response = br.readLine(); + Assertions.assertEquals("erro", response, "Deveria retornar 'erro'"); + } + } + + private void ValidarCookieResposta(HttpURLConnection conn) { + String cookieHeader = conn.getHeaderField("Set-Cookie"); + Assertions.assertNotNull(cookieHeader, "Deveria retornar cookie"); + Assertions.assertTrue(cookieHeader.contains("token="), "Cookie deveria conter token"); + } + + @AfterEach + void LimparDadosTeste() throws SQLException { + try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD); + Statement stmt = conn.createStatement()) { + + int clientesRemovidos = stmt.executeUpdate( + "DELETE FROM tb_clientes WHERE usuario LIKE 'testuser_%' OR usuario LIKE 'inactive_%'"); + + int tokensRemovidos = stmt.executeUpdate( + "DELETE FROM tb_tokens WHERE TRUE"); + + System.out.printf( + "Limpeza realizada: %d clientes e %d tokens removidos%n", + clientesRemovidos, tokensRemovidos); + } + } + +} diff --git "a/src/test/java/Testes/Integra\303\247\303\243o/IngredienteBdTest.java" "b/src/test/java/Testes/Integra\303\247\303\243o/IngredienteBdTest.java" new file mode 100644 index 0000000..8776a55 --- /dev/null +++ "b/src/test/java/Testes/Integra\303\247\303\243o/IngredienteBdTest.java" @@ -0,0 +1,178 @@ +package Testes.Integração; + +import DAO.DaoIngrediente; +import Model.Ingrediente; +import org.junit.jupiter.api.*; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +public class IngredienteBdTest { + + private static DaoIngrediente dao; + + @BeforeAll + static void setup() { + dao = new DaoIngrediente(); // Inicializa DAO com conexão real + } + + @Test + @Order(1) + void testSalvarEBuscarIngrediente() { + Ingrediente ingrediente = new Ingrediente(); + ingrediente.setNome("TestTomate"); + ingrediente.setDescricao("Vermelho"); + ingrediente.setQuantidade(50); + ingrediente.setValor_compra(1.0); + ingrediente.setValor_venda(2.0); + ingrediente.setTipo("legume"); + ingrediente.setFg_ativo(1); + + dao.salvar(ingrediente); // Insere no banco + + Ingrediente resultado = dao.pesquisaPorNome(ingrediente); // Busca pelo nome + + assertNotNull(resultado); + assertEquals("TestTomate", resultado.getNome()); + assertEquals("Vermelho", resultado.getDescricao()); + } + + @Test + @Order(2) + void testListarTodos() { + List lista = dao.listarTodos(); // Lista todos ingredientes ativos + + assertNotNull(lista); + assertTrue(lista.size() >= 1); // Espera que pelo menos 1 esteja presente + } + + @Test + @Order(3) + void testAlterarIngrediente() { + Ingrediente ingrediente = dao.pesquisaPorNome(new Ingrediente() {{ + setNome("TestTomate"); + }}); + assertNotNull(ingrediente); + + ingrediente.setDescricao("Vermelho Escuro"); + ingrediente.setQuantidade(99); + dao.alterar(ingrediente); // Altera dados do ingrediente + + Ingrediente alterado = dao.pesquisaPorNome(ingrediente); + assertEquals("Vermelho Escuro", alterado.getDescricao()); + assertEquals(99, alterado.getQuantidade()); + } + + @Test + @Order(4) + void testRemoverIngrediente() { + Ingrediente ingrediente = dao.pesquisaPorNome(new Ingrediente() {{ + setNome("TestTomate"); + }}); + assertNotNull(ingrediente); + + dao.remover(ingrediente); // Remove do banco + + Ingrediente buscado = dao.pesquisaPorNome(ingrediente); + assertNull(buscado.getNome()); // Espera que não encontre mais + } + + @Test + @Order(5) + void testSalvarIngredienteComNomeDuplicado() { + // Salva primeiro ingrediente + Ingrediente ingrediente1 = new Ingrediente(); + ingrediente1.setNome("Duplicado"); + ingrediente1.setDescricao("Primeiro"); + ingrediente1.setQuantidade(10); + ingrediente1.setValor_compra(1.5); + ingrediente1.setValor_venda(2.5); + ingrediente1.setTipo("teste"); + ingrediente1.setFg_ativo(1); + dao.salvar(ingrediente1); + + // Salva outro com o mesmo nome + Ingrediente ingrediente2 = new Ingrediente(); + ingrediente2.setNome("Duplicado"); + ingrediente2.setDescricao("Segundo"); + ingrediente2.setQuantidade(20); + ingrediente2.setValor_compra(2.5); + ingrediente2.setValor_venda(3.5); + ingrediente2.setTipo("teste"); + ingrediente2.setFg_ativo(1); + dao.salvar(ingrediente2); + + Ingrediente resultado = dao.pesquisaPorNome(ingrediente2); + assertNotNull(resultado); + assertEquals("Duplicado", resultado.getNome()); + + // Limpa o registro duplicado após teste + dao.remover(resultado); + } + + @Test + @Order(6) + void testBuscarIngredienteInexistente() { + Ingrediente inexistente = new Ingrediente(); + inexistente.setNome("IngredienteInexistente"); + Ingrediente resultado = dao.pesquisaPorNome(inexistente); + + // Espera que nome seja nulo para ingrediente não encontrado + assertNull(resultado.getNome()); + } + + @Test + @Order(7) + void testListarTodosAposInsercao() { + // Insere ingrediente temporário + Ingrediente ingrediente = new Ingrediente(); + ingrediente.setNome("ListarTeste"); + ingrediente.setDescricao("Teste Listagem"); + ingrediente.setQuantidade(5); + ingrediente.setValor_compra(3.0); + ingrediente.setValor_venda(4.0); + ingrediente.setTipo("categoria"); + ingrediente.setFg_ativo(1); + + dao.salvar(ingrediente); + + List lista = dao.listarTodos(); + + // Verifica se o ingrediente inserido está na lista + boolean encontrado = lista.stream().anyMatch(i -> "ListarTeste".equals(i.getNome())); + assertTrue(encontrado); + + // Limpa o registro após teste + dao.remover(dao.pesquisaPorNome(ingrediente)); + } + + @Test + @Order(8) + void testAlterarIngredienteInexistente() { + Ingrediente inexistente = new Ingrediente(); + inexistente.setId_ingrediente(99999); // ID que provavelmente não existe + inexistente.setNome("Fake"); + inexistente.setDescricao("Não existe"); + inexistente.setQuantidade(0); + inexistente.setValor_compra(0.0); + inexistente.setValor_venda(0.0); + inexistente.setTipo("teste"); + + // Garante que não lança exceção ao tentar alterar + assertDoesNotThrow(() -> dao.alterar(inexistente)); + + Ingrediente resultado = dao.pesquisaPorNome(inexistente); + assertNull(resultado.getNome()); + } + + @Test + @Order(9) + void testRemoverIngredienteInexistente() { + Ingrediente fake = new Ingrediente(); + fake.setId_ingrediente(99999); // ID que não deve existir + + assertDoesNotThrow(() -> dao.remover(fake)); + } +} diff --git "a/src/test/java/Testes/Integra\303\247\303\243o/LogoutServletTest.java" "b/src/test/java/Testes/Integra\303\247\303\243o/LogoutServletTest.java" new file mode 100644 index 0000000..2365576 --- /dev/null +++ "b/src/test/java/Testes/Integra\303\247\303\243o/LogoutServletTest.java" @@ -0,0 +1,29 @@ +package Testes.Integração; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +public class LogoutServletTest { + + private static final String BASE_URL = "http://localhost:8080"; + + @Test + void testLogoutDeslogaComSucesso() throws Exception { + URL url = new URL(BASE_URL + "/logout"); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + assertEquals(200, conn.getResponseCode()); + + BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String resposta = in.readLine(); + in.close(); + + assertEquals("Deslogado", resposta); + } +} diff --git a/src/test/java/Testes/Sistema/CadastroClienteTest.java b/src/test/java/Testes/Sistema/CadastroClienteTest.java new file mode 100644 index 0000000..c96a121 --- /dev/null +++ b/src/test/java/Testes/Sistema/CadastroClienteTest.java @@ -0,0 +1,132 @@ +package Testes.Sistema; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.Alert; +import org.openqa.selenium.By; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.support.ui.Select; + +import io.github.bonigarcia.wdm.WebDriverManager; + +public class CadastroClienteTest { + + private WebDriver driver; + + @BeforeEach + public void setUp() { + WebDriverManager.chromedriver().setup(); + driver = new ChromeDriver(); + driver.manage().window().maximize(); + } + + + + @Test + public void CadastroCliente() throws InterruptedException { + // Abre a página de Login + driver.get("http://localhost:8080/view/login/login.html"); + + // Espera a página carregar + Thread.sleep(1000); + + assertEquals("http://localhost:8080/view/login/login.html", driver.getCurrentUrl()); + + + // Clica no botão de Criar conta + driver.findElement(By.className("linkNewCreate")).click(); + Thread.sleep(1000); + + + assertEquals("http://localhost:8080/view/cadastro/cadastro.html", driver.getCurrentUrl()); + + // Escreve "Nome Teste" no campo Nome + driver.findElement(By.name("nome")).sendKeys("Nome Teste"); + Thread.sleep(500); + + // Escreve "Sobrenome" no campo Sobrenome + driver.findElement(By.name("sobrenome")).sendKeys("Sobrenome"); + Thread.sleep(500); + + // Escreve "123456789" no campo Telefone + driver.findElement(By.name("telefone")).sendKeys("123456789"); + Thread.sleep(500); + + // Escreve "testeNome" no campo Usuario + driver.findElement(By.name("usuario")).sendKeys("testeNome"); + Thread.sleep(500); + + // Escreve "12345" no campo Senha + driver.findElement(By.name("senha")).sendKeys("12345"); + Thread.sleep(500); + + //Campo de Endereco + + + // Escreve "110" no campo numero + driver.findElement(By.name("rua")).sendKeys("Doutor March"); + Thread.sleep(500); + + // Escreve "110" no campo numero + driver.findElement(By.name("numero")).sendKeys("110"); + Thread.sleep(500); + + // Escreve "Barreto" no campo bairro + driver.findElement(By.name("bairro")).sendKeys("Barreto"); + Thread.sleep(500); + + // Escreve "Condominio Teste" no campo complemento + driver.findElement(By.name("complemento")).sendKeys("Condominio Teste"); + Thread.sleep(500); + + // Escreve "testeNome" no campo cidade + driver.findElement(By.name("cidade")).sendKeys("Niterói"); + Thread.sleep(500); + + // Escreve "RJ" no campo estado + WebElement dropdownEstado = driver.findElement(By.name("estado")); + + // Crie um objeto Select + Select selectEstado = new Select(dropdownEstado); + + // Selecione "RJ" por: + // 1. Texto visível (recomendado se você sabe o texto exato) + selectEstado.selectByVisibleText("RJ"); + + + //Clica em cadastrar + driver.findElement(By.className("buttonSubmit")).click(); + Thread.sleep(1500); + + // Interage com o alerta + Alert alert = driver.switchTo().alert(); + String alertaTexto = alert.getText().trim(); // remove espaços e quebras de linha extras + assertEquals("Usuário Cadastrado!", alertaTexto); + alert.accept(); + + + assertEquals("http://localhost:8080/view/login/login.html", driver.getCurrentUrl()); + + + + driver.findElement(By.id("loginInput")).sendKeys("testeNome"); + Thread.sleep(500); + + driver.findElement(By.id("senhaInput")).sendKeys("12345"); + Thread.sleep(500); + + + //Clica em Entrar + driver.findElement(By.className("buttonSubmit")).click(); + Thread.sleep(1500); + + + assertEquals("http://localhost:8080/view/carrinho/carrinho.html", driver.getCurrentUrl()); + + + } + +} diff --git a/src/test/java/Testes/Sistema/CadastroIngredienteTest.java b/src/test/java/Testes/Sistema/CadastroIngredienteTest.java new file mode 100644 index 0000000..3536f52 --- /dev/null +++ b/src/test/java/Testes/Sistema/CadastroIngredienteTest.java @@ -0,0 +1,83 @@ +package Testes.Sistema; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.*; +import org.openqa.selenium.chrome.ChromeDriver; +import io.github.bonigarcia.wdm.WebDriverManager; + +public class CadastroIngredienteTest { + + private WebDriver driver; + + @BeforeEach + public void setUp() { + WebDriverManager.chromedriver().setup(); + driver = new ChromeDriver(); + driver.manage().window().maximize(); + } + + @Test + public void abrirPaginaInicialEClicarNoPopup() throws InterruptedException { + // Abre a página + driver.get("http://localhost:8080/view/login/login.html"); + + // Espera a página carregar + Thread.sleep(1000); + + // Clica no botão de login para funcionários + driver.findElement(By.xpath("/html/body/div/div/div/div[3]/a[2]")).click(); + Thread.sleep(1000); + + // Escreve "admin" no campo login + driver.findElement(By.xpath("//*[@id=\"loginInput\"]")).sendKeys("admin"); + Thread.sleep(500); + + // Escreve "admin" no campo senha + driver.findElement(By.xpath("//*[@id=\"senhaInput\"]")).sendKeys("admin"); + Thread.sleep(500); + + // Clica no botão de login + driver.findElement(By.xpath("/html/body/div/div/div/div[3]/button")).click(); + Thread.sleep(1500); // tempo maior para esperar redirecionamento + + // Clica no botão desejado após o login + driver.findElement(By.xpath("//*[@id=\"Agrupado\"]/div[3]/div[2]/div[2]/button[2]")).click(); + Thread.sleep(1000); + + // Escreve o nome do ingrediente + driver.findElement(By.xpath("/html/body/div/div/div/div[2]/div[2]/form/input[1]")).sendKeys("Queijo Parmesão"); + + // Seleciona o tipo de produto (abre o select) + driver.findElement(By.xpath("/html/body/div/div/div/div[2]/div[2]/form/select")).click(); + Thread.sleep(500); + + // Escolhe a 4ª opção + driver.findElement(By.xpath("//*[@id=\"addIngrediente\"]/select/option[4]")).click(); + Thread.sleep(500); + + // Preenche quantidade + driver.findElement(By.xpath("//*[@id=\"addIngrediente\"]/input[2]")).sendKeys("100"); + + // Preenche valor de compra + driver.findElement(By.xpath("//*[@id=\"addIngrediente\"]/input[3]")).sendKeys("5.50"); + + // Preenche valor de venda + driver.findElement(By.xpath("//*[@id=\"addIngrediente\"]/input[4]")).sendKeys("8.00"); + + // Escreve descrição + driver.findElement(By.xpath("//*[@id=\"textArea1\"]")).sendKeys("Queijo parmesão ralado, usado em lanches especiais."); + + // Clica em "Salvar" + driver.findElement(By.xpath("/html/body/div/div/div/div[2]/div[2]/form/div/input[2]")).click(); + Thread.sleep(1500); // aguarda resposta/atualização + + // Interage com o alerta + Alert alert = driver.switchTo().alert(); + String alertaTexto = alert.getText().trim(); // remove espaços e quebras de linha extras + assertEquals("Ingrediente Salvo!", alertaTexto); + alert.accept(); + + } +} \ No newline at end of file diff --git a/src/test/java/Testes/Sistema/LoginTest.java b/src/test/java/Testes/Sistema/LoginTest.java new file mode 100644 index 0000000..2821439 --- /dev/null +++ b/src/test/java/Testes/Sistema/LoginTest.java @@ -0,0 +1,140 @@ +package Testes.Sistema; + +import java.time.Duration; + +import org.junit.jupiter.api.AfterEach; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.By; +import org.openqa.selenium.NoSuchElementException; +import org.openqa.selenium.WebDriver; +import org.openqa.selenium.WebElement; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.support.ui.WebDriverWait; + +import io.github.bonigarcia.wdm.WebDriverManager; + + +public class LoginTest { + + private WebDriver driver; + private WebDriverWait wait; + + @BeforeEach + public void setUp() { + try { + WebDriverManager.chromedriver().setup(); + + ChromeOptions options = new ChromeOptions(); + options.addArguments("--no-sandbox"); + options.addArguments("--disable-dev-shm-usage"); + options.addArguments("--disable-web-security"); + options.addArguments("--disable-features=VizDisplayCompositor"); + + driver = new ChromeDriver(options); + driver.manage().window().maximize(); + driver.manage().timeouts().implicitlyWait(10, java.util.concurrent.TimeUnit.SECONDS); + wait = new WebDriverWait(driver, Duration.ofSeconds(10)); + + } catch (Exception e) { + System.err.println("erro webdriver: " + e.getMessage()); + } + } + + @AfterEach + public void tearDown() { + if (driver != null) { + driver.quit(); + } + } + + @Test + public void testLoginFuncionarioCompleto() { + try { + driver.get("http://localhost:8080"); + + driver.get("http://localhost:8080/view/login/login.html"); + Thread.sleep(2000); + + String tituloPagina = driver.getTitle(); + assertTrue(tituloPagina.contains("Login")); + + WebElement titulo = null; + try { + titulo = driver.findElement(By.className("titlePage")); + } catch (NoSuchElementException e1) { + try { + titulo = driver.findElement(By.tagName("h1")); + } catch (NoSuchElementException e2) { + try { + titulo = driver.findElement(By.xpath("//*[contains(text(),'Login')]")); + } catch (NoSuchElementException e3) { + System.out.println("title nao encontrado"); + } + } + } + + WebElement linkFuncionario = null; + try { + linkFuncionario = driver.findElement(By.xpath("//a[contains(@href, 'login_Funcionario.html')]")); + } catch (NoSuchElementException e1) { + try { + linkFuncionario = driver.findElement(By.xpath("//a[contains(text(), 'Funcionário') or contains(text(), 'funcionário') or contains(text(), 'Administrativo')]")); + } catch (NoSuchElementException e2) { + java.util.List links = driver.findElements(By.tagName("a")); + for (int i = 0; i < links.size(); i++) { + WebElement link = links.get(i); + System.out.println(" Link[" + i + "]: href=" + link.getAttribute("href") + + ", texto='" + link.getText() + "'"); + } + } + } + + if (linkFuncionario != null) { + linkFuncionario.click(); + } + + Thread.sleep(2000); + + String urlAtual = driver.getCurrentUrl(); + assertTrue(urlAtual.contains("login_Funcionario.html")); + WebElement campoUsuario = driver.findElement(By.id("loginInput")); + WebElement campoSenha = driver.findElement(By.id("senhaInput")); + WebElement botaoSubmit = driver.findElement(By.className("buttonSubmit")); + + assertTrue(campoUsuario.isDisplayed()); + assertTrue(campoSenha.isDisplayed()); + assertTrue(botaoSubmit.isDisplayed()); + + campoUsuario.clear(); + campoUsuario.sendKeys("admin"); + + campoSenha.clear(); + campoSenha.sendKeys("admin"); + + Thread.sleep(1000); + + assertEquals("admin", campoUsuario.getAttribute("value")); + assertEquals("admin", campoSenha.getAttribute("value")); + assertEquals("Entrar", botaoSubmit.getText()); + botaoSubmit.click(); + + Thread.sleep(3000); + String urlFinal = driver.getCurrentUrl(); + assertNotEquals("http://localhost:8080/view/login/login_Funcionario.html", + urlFinal); + + assertFalse(urlFinal.contains("login")); + String pageSource = driver.getPageSource(); + assertFalse(pageSource.isEmpty()); + + } catch (Exception e) { + System.err.println("erro no teste"); + } +} +} diff --git a/src/test/java/Testes/Sistema/SalvarBebidaSistemaTest.java b/src/test/java/Testes/Sistema/SalvarBebidaSistemaTest.java new file mode 100644 index 0000000..29176c2 --- /dev/null +++ b/src/test/java/Testes/Sistema/SalvarBebidaSistemaTest.java @@ -0,0 +1,128 @@ +package Testes.Sistema; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import java.time.Duration; + +import java.util.List; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.openqa.selenium.*; +import org.openqa.selenium.chrome.ChromeDriver; +import org.openqa.selenium.chrome.ChromeOptions; +import org.openqa.selenium.support.ui.ExpectedConditions; +import org.openqa.selenium.support.ui.Select; +import org.openqa.selenium.support.ui.WebDriverWait; + +import io.github.bonigarcia.wdm.WebDriverManager; + + + +public class SalvarBebidaSistemaTest { + + + + WebDriver driver; + + @BeforeEach + public void setUp() { + WebDriverManager.chromedriver().setup(); + + ChromeOptions options = new ChromeOptions(); + //options.addArguments("--headless=new"); // para rodar sem interface gráfica + options.addArguments("--no-sandbox"); + options.addArguments("--disable-dev-shm-usage"); + options.addArguments("--disable-gpu"); + + driver = new ChromeDriver(options); + } + + @AfterEach + public void tearDown() { + if (driver != null) { + driver.quit(); + } + } + + // Método de login reutilizável dentro da própria classe + private void loginComoFuncionario() throws InterruptedException { + driver.get("http://localhost:8080/view/login/login.html"); + Thread.sleep(1000); + + // Verifica se está na tela de login + String tituloPagina = driver.getTitle(); + if (!tituloPagina.contains("Login")) { + throw new IllegalStateException("Não está na tela de login."); + } + + // Clica no link de login de funcionário + try { + WebElement linkFuncionario = driver.findElement(By.xpath("//a[contains(@href, 'login_Funcionario.html')]")); + linkFuncionario.click(); + } catch (NoSuchElementException e) { + throw new RuntimeException("Link para login de funcionário não encontrado."); + } + + Thread.sleep(1000); + + // Esperar o campo de e-mail estar visível + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); + WebElement campoEmail = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("loginInput"))); + WebElement campoSenha = driver.findElement(By.id("senhaInput")); + + // Preencher os campos + campoEmail.sendKeys("admin"); + campoSenha.sendKeys("admin"); + + // Simula o ENTER no campo de senha para submeter o formulário + WebElement botaoEntrar = driver.findElement(By.xpath("//button[contains(text(), 'Entrar')]")); + botaoEntrar.click(); + + Thread.sleep(1000); + } + + @Test + void deveCadastrarBebida() throws InterruptedException { + // Fazer login antes de tentar cadastrar a bebida + loginComoFuncionario(); + //Thread.sleep(6000); + driver.get("http://localhost:8080/view/painel/painel.html"); + + + WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); + WebElement botaoCadastrar = wait.until( + ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'Cadastrar Bebidas')]")) + ); + botaoCadastrar.click(); + + + + Thread.sleep(6000); + // Aguarda o input 'nome' estar visível e envia o texto + WebElement campoNome = wait.until(ExpectedConditions.visibilityOfElementLocated( + By.xpath("//form[@id='addBebida']//input[@name='nome']"))); + campoNome.sendKeys("Guaraná Teste"); + + // Select para o tipo + WebElement campoTipo = wait.until(ExpectedConditions.visibilityOfElementLocated( + By.xpath("//form[@id='addBebida']//select[@name='tipo']"))); + Select selectTipo = new Select(campoTipo); + selectTipo.selectByValue("refrigerante"); + + // Outros campos + driver.findElement(By.xpath("//form[@id='addBebida']//input[@name='quantidade']")).sendKeys("15"); + driver.findElement(By.xpath("//form[@id='addBebida']//input[@name='ValorCompra']")).sendKeys("4.00"); + driver.findElement(By.xpath("//form[@id='addBebida']//input[@name='ValorVenda']")).sendKeys("6.00"); + driver.findElement(By.xpath("//form[@id='addBebida']//textarea[@name='descricao']")).sendKeys("Guaraná gelado de teste"); + + // Botão salvar + WebElement botaoSalvar = wait.until(ExpectedConditions.elementToBeClickable( + By.xpath("//form[@id='addBebida']//input[@type='button' and @name='salvar']"))); + botaoSalvar.click(); + + } + + +} \ No newline at end of file diff --git "a/src/test/java/Testes/Unit\303\241rios/EncryptadorMD5Test.java" "b/src/test/java/Testes/Unit\303\241rios/EncryptadorMD5Test.java" new file mode 100644 index 0000000..0e9e69f --- /dev/null +++ "b/src/test/java/Testes/Unit\303\241rios/EncryptadorMD5Test.java" @@ -0,0 +1,46 @@ +package Testes.Unitários; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import org.junit.jupiter.api.Test; + +import Helpers.EncryptadorMD5; + +public class EncryptadorMD5Test { + + @Test + public void testEncryptarSenhaSimples() { + EncryptadorMD5 encryptador = new EncryptadorMD5(); + String senha = "123456"; + String esperado = "e10adc3949ba59abbe56e057f20f883e"; + String resultado = encryptador.encryptar(senha); + assertEquals(esperado, resultado); + } + + @Test + public void testEncryptarSenhaVazia() { + EncryptadorMD5 encryptador = new EncryptadorMD5(); + String senha = ""; + String esperado = "d41d8cd98f00b204e9800998ecf8427e"; + String resultado = encryptador.encryptar(senha); + assertEquals(esperado, resultado); + } + + @Test + public void testEncryptarSenhaComCaracteresEspeciais() { + EncryptadorMD5 encryptador = new EncryptadorMD5(); + String senha = "senha@123"; + String esperado = "ada3c39413b4f6284c8301257812190e"; // <-- hash correto + String resultado = encryptador.encryptar(senha); + System.err.println(encryptador.encryptar(senha)); + assertEquals(esperado, resultado); + } + + + @Test + public void testEncryptarSenhaNull() { + EncryptadorMD5 encryptador = new EncryptadorMD5(); + String resultado = encryptador.encryptar(null); + assertNull(resultado); // o método atual retorna null em caso de exceção + } +} \ No newline at end of file diff --git "a/src/test/java/Testes/Unit\303\241rios/IngredientesMockitoTest.java" "b/src/test/java/Testes/Unit\303\241rios/IngredientesMockitoTest.java" new file mode 100644 index 0000000..703918c --- /dev/null +++ "b/src/test/java/Testes/Unit\303\241rios/IngredientesMockitoTest.java" @@ -0,0 +1,206 @@ +package Testes.Unitários; +import Controllers.getIngredientes; +import Controllers.removerIngrediente; +import DAO.DaoIngrediente; +import Helpers.ValidadorCookie; +import Model.Ingrediente; +import org.json.JSONObject; +import org.junit.jupiter.api.*; +import org.mockito.*; +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.*; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import Controllers.getIngredientesPorLancheCliente; +import com.google.gson.Gson; +import static org.mockito.Mockito.*; + +class IngredientesMockitoTest { + + @InjectMocks + removerIngrediente servlet; + + @Mock + DaoIngrediente daoIngrediente; + + @Mock + ValidadorCookie validadorCookie; + + @Mock + HttpServletRequest request; + + @Mock + HttpServletResponse response; + + @Mock + PrintWriter writer; + + @InjectMocks + getIngredientes servletGet; + + @InjectMocks + getIngredientesPorLancheCliente servletPorLanche; + + @BeforeEach + void setup() throws IOException { + MockitoAnnotations.openMocks(this); // Inicializa os mocks com @Mock/@InjectMocks + servlet = new removerIngrediente(daoIngrediente, validadorCookie); + servletGet = new getIngredientes(daoIngrediente, validadorCookie); + servletPorLanche = new getIngredientesPorLancheCliente(daoIngrediente); + when(response.getWriter()).thenReturn(writer); + } + + @Test + void testGetIngredientesPorLancheCliente() throws Exception { + // Simula um JSON com id do lanche + JSONObject jsonRequest = new JSONObject(); + jsonRequest.put("id", 8); + byte[] jsonBytes = jsonRequest.toString().getBytes(StandardCharsets.UTF_8); + + // Simula o corpo da requisição + when(request.getInputStream()).thenReturn( + new DelegatingServletInputStream(new ByteArrayInputStream(jsonBytes)) + ); + + // Mocka retorno do DAO + List ingredientes = new ArrayList<>(); + Ingrediente ing = new Ingrediente(); + ing.setId_ingrediente(3); + ing.setNome("Alface"); + ingredientes.add(ing); + + when(daoIngrediente.listarTodosPorLanche(8)).thenReturn(ingredientes); + + servletPorLanche.doPost(request, response); + + verify(daoIngrediente).listarTodosPorLanche(8); + + String jsonEsperado = new Gson().toJson(ingredientes); + verify(writer).print(jsonEsperado); + verify(writer).flush(); + } + + @Test + void testGetIngredientesComCookieValido() throws Exception { + // Simula um cookie válido + Cookie[] cookies = {new Cookie("token", "abc")}; + when(request.getCookies()).thenReturn(cookies); + when(validadorCookie.validarFuncionario(cookies)).thenReturn(true); + + // Simula retorno de ingredientes + List ingredientes = new ArrayList<>(); + Ingrediente ing = new Ingrediente(); + ing.setId_ingrediente(1); + ing.setNome("Tomate"); + ingredientes.add(ing); + + when(daoIngrediente.listarTodos()).thenReturn(ingredientes); + + servletGet.doGet(request, response); + + verify(daoIngrediente).listarTodos(); + String jsonEsperado = new Gson().toJson(ingredientes); + verify(writer).print(jsonEsperado); + verify(writer).flush(); + } + + @Test + void testGetIngredientesSemCookie() throws Exception { + // Simula requisição sem cookies + when(request.getCookies()).thenReturn(null); + when(validadorCookie.validarFuncionario(null)).thenReturn(false); + + servletGet.doGet(request, response); + + // Espera resposta de erro + verify(writer).println("erro"); + } + + @Test + void testIngredienteRemovidoCookieValido() throws Exception { + Cookie[] cookies = {new Cookie("token", "abc")}; + when(request.getCookies()).thenReturn(cookies); + when(validadorCookie.validarFuncionario(cookies)).thenReturn(true); + + // Simula JSON com dados do ingrediente a remover + JSONObject jsonRequest = new JSONObject(); + jsonRequest.put("id", 10); + jsonRequest.put("nome", "Alface"); + jsonRequest.put("descricao", "Verde"); + jsonRequest.put("quantidade", 100); + jsonRequest.put("ValorCompra", 5.0); + jsonRequest.put("ValorVenda", 8.0); + jsonRequest.put("tipo", "verdura"); + + byte[] jsonBytes = jsonRequest.toString().getBytes(StandardCharsets.UTF_8); + when(request.getInputStream()).thenReturn( + new DelegatingServletInputStream(new ByteArrayInputStream(jsonBytes)) + ); + + servlet.doPost(request, response); + + // Captura o ingrediente passado ao DAO para validar seus atributos + ArgumentCaptor captor = ArgumentCaptor.forClass(Ingrediente.class); + verify(daoIngrediente).remover(captor.capture()); + Ingrediente ingRemovido = captor.getValue(); + Assertions.assertEquals(10, ingRemovido.getId_ingrediente()); + Assertions.assertEquals("Alface", ingRemovido.getNome()); + Assertions.assertEquals(1, ingRemovido.getFg_ativo()); + + verify(writer).println("Ingrediente Alterado!"); + } + + @Test + void testIngredienteRemovidoCookieInvalido() throws Exception { + servlet = new removerIngrediente(daoIngrediente, validadorCookie); + + when(request.getCookies()).thenReturn(null); // Sem cookie + + // Input vazio simula POST inválido + String emptyJson = ""; + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(emptyJson.getBytes(StandardCharsets.UTF_8)); + + // Simula input stream customizado + ServletInputStream servletInputStream = new ServletInputStream() { + @Override public boolean isFinished() { return false; } + @Override public boolean isReady() { return true; } + @Override public void setReadListener(ReadListener readListener) {} + @Override public int read() throws IOException { return byteArrayInputStream.read(); } + }; + + when(request.getInputStream()).thenReturn(servletInputStream); + when(response.getWriter()).thenReturn(writer); + + servlet.doPost(request, response); + + // Espera mensagem de erro + verify(writer).println("erro"); + } + + static class DelegatingServletInputStream extends javax.servlet.ServletInputStream { + private final InputStream sourceStream; + + public DelegatingServletInputStream(InputStream sourceStream) { + this.sourceStream = sourceStream; + } + + @Override public int read() throws IOException { + return sourceStream.read(); + } + + @Override public boolean isFinished() { + try { + return sourceStream.available() == 0; + } catch (IOException e) { + return true; + } + } + + @Override public boolean isReady() { return true; } + + @Override public void setReadListener(javax.servlet.ReadListener readListener) {} + } +} diff --git a/src/test/java/integration/FluxoCompraIntegrationTest.java b/src/test/java/integration/FluxoCompraIntegrationTest.java new file mode 100644 index 0000000..267fccd --- /dev/null +++ b/src/test/java/integration/FluxoCompraIntegrationTest.java @@ -0,0 +1,311 @@ +package integration; + +import DAO.*; +import Model.*; +import org.junit.jupiter.api.*; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class FluxoCompraIntegrationTest { + + private DaoCliente daoCliente; + private DaoToken daoToken; + private DaoLanche daoLanche; + private DaoBebida daoBebida; + private DaoPedido daoPedido; + private static final String USUARIO_TESTE = "cliente_compra_test"; + private static final String SENHA_TESTE = "senha123"; + private static Cliente clienteTeste; + private static String tokenTeste; + private static Lanche lancheTeste; + private static Bebida bebidaTeste; + + @BeforeEach + void setUp() { + daoCliente = new DaoCliente(); + daoToken = new DaoToken(); + daoLanche = new DaoLanche(); + daoBebida = new DaoBebida(); + daoPedido = new DaoPedido(); + limparDadosTeste(); + } + + @Test + @Order(1) + void prepararAmbienteCompra() { + Endereco endereco = criarEnderecoTeste(); + clienteTeste = criarClienteTeste(endereco); + + assertDoesNotThrow(() -> daoCliente.salvar(clienteTeste)); + + Cliente clienteSalvo = daoCliente.pesquisaPorUsuario(clienteTeste); + assertNotNull(clienteSalvo); + assertTrue(clienteSalvo.getId_cliente() > 0); + clienteTeste = clienteSalvo; + + lancheTeste = criarLancheTeste(); + assertDoesNotThrow(() -> daoLanche.salvar(lancheTeste)); + + Lanche lancheRecuperado = daoLanche.pesquisaPorNome(lancheTeste.getNome()); + assertNotNull(lancheRecuperado); + assertEquals(lancheTeste.getNome(), lancheRecuperado.getNome()); + lancheTeste = lancheRecuperado; + + bebidaTeste = criarBebidaTeste(); + assertDoesNotThrow(() -> daoBebida.salvar(bebidaTeste)); + + Bebida bebidaRecuperada = daoBebida.pesquisaPorNome(bebidaTeste.getNome()); + assertNotNull(bebidaRecuperada); + assertEquals(bebidaTeste.getNome(), bebidaRecuperada.getNome()); + bebidaTeste = bebidaRecuperada; + + Cliente clienteLogin = new Cliente(); + clienteLogin.setUsuario(USUARIO_TESTE); + clienteLogin.setSenha(SENHA_TESTE); + + boolean loginSuccess = daoCliente.login(clienteLogin); + assertTrue(loginSuccess); + + tokenTeste = clienteTeste.getId_cliente() + "-" + Instant.now().toString(); + daoToken.salvar(tokenTeste); + + boolean tokenValido = daoToken.validar(tokenTeste); + assertTrue(tokenValido); + } + + @Test + @Order(2) + void consultarProdutosDisponiveis() { + + List lanches = daoLanche.listarTodos(); + assertNotNull(lanches); + assertFalse(lanches.isEmpty()); + + boolean lancheEncontrado = lanches.stream() + .anyMatch(l -> l.getNome().equals(lancheTeste.getNome())); + assertTrue(lancheEncontrado); + + List bebidas = daoBebida.listarTodos(); + assertNotNull(bebidas); + assertFalse(bebidas.isEmpty()); + + boolean bebidaEncontrada = bebidas.stream() + .anyMatch(b -> b.getNome().equals(bebidaTeste.getNome())); + assertTrue(bebidaEncontrada); + } + + @Test + @Order(3) + void simularCarrinhoCompra() { + int quantidadeLanche = 2; + int quantidadeBebida = 3; + + double valorLanches = lancheTeste.getValor_venda() * quantidadeLanche; + double valorBebidas = bebidaTeste.getValor_venda() * quantidadeBebida; + double valorTotalEsperado = valorLanches + valorBebidas; + + assertTrue(valorTotalEsperado > 0); + assertEquals(valorLanches + valorBebidas, valorTotalEsperado, 0.01); + } + + @Test + @Order(4) + void finalizarCompra() { + + boolean tokenValido = daoToken.validar(tokenTeste); + assertTrue(tokenValido); + + Cliente cliente = daoCliente.pesquisaPorID(String.valueOf(clienteTeste.getId_cliente())); + assertNotNull(cliente); + assertEquals(clienteTeste.getId_cliente(), cliente.getId_cliente()); + + int quantidadeLanche = 2; + int quantidadeBebida = 1; + + lancheTeste.setQuantidade(quantidadeLanche); + bebidaTeste.setQuantidade(quantidadeBebida); + + double valorTotal = (lancheTeste.getValor_venda() * quantidadeLanche) + + (bebidaTeste.getValor_venda() * quantidadeBebida); + + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(cliente); + pedido.setValor_total(valorTotal); + + assertDoesNotThrow(() -> daoPedido.salvar(pedido)); + + Pedido pedidoSalvo = daoPedido.pesquisaPorData(pedido); + assertNotNull(pedidoSalvo); + assertTrue(pedidoSalvo.getId_pedido() > 0); + assertEquals(valorTotal, pedidoSalvo.getValor_total(), 0.01); + + assertDoesNotThrow(() -> daoPedido.vincularLanche(pedidoSalvo, lancheTeste)); + + assertDoesNotThrow(() -> daoPedido.vincularBebida(pedidoSalvo, bebidaTeste)); + } + + @Test + @Order(5) + void verificarPersistenciaPedido() { + try (Connection conn = new DaoUtil().conecta()) { + PreparedStatement stmtPedido = conn.prepareStatement( + "SELECT * FROM tb_pedidos WHERE id_cliente = ? ORDER BY id_pedido DESC LIMIT 1" + ); + stmtPedido.setInt(1, clienteTeste.getId_cliente()); + ResultSet rsPedido = stmtPedido.executeQuery(); + + assertTrue(rsPedido.next()); + int idPedido = rsPedido.getInt("id_pedido"); + double valorTotal = rsPedido.getDouble("valor_total"); + + assertTrue(idPedido > 0); + assertTrue(valorTotal > 0); + + PreparedStatement stmtLanche = conn.prepareStatement( + "SELECT * FROM tb_lanches_pedido WHERE id_pedido = ? AND id_lanche = ?" + ); + stmtLanche.setInt(1, idPedido); + stmtLanche.setInt(2, lancheTeste.getId_lanche()); + ResultSet rsLanche = stmtLanche.executeQuery(); + + assertTrue(rsLanche.next()); + assertEquals(2, rsLanche.getInt("quantidade")); + + PreparedStatement stmtBebida = conn.prepareStatement( + "SELECT * FROM tb_bebidas_pedido WHERE id_pedido = ? AND id_bebida = ?" + ); + stmtBebida.setInt(1, idPedido); + stmtBebida.setInt(2, bebidaTeste.getId_bebida()); + ResultSet rsBebida = stmtBebida.executeQuery(); + + assertTrue(rsBebida.next()); + assertEquals(1, rsBebida.getInt("quantidade")); + + } catch (SQLException e) { + fail("Erro ao verificar persistência: " + e.getMessage()); + } + } + + @Test + @Order(6) + void fluxoCompletoEndToEnd() { + + assertTrue(daoToken.validar(tokenTeste)); + + Cliente cliente = daoCliente.pesquisaPorID(String.valueOf(clienteTeste.getId_cliente())); + assertNotNull(cliente); + + int quantidadeLanche = 1; + int quantidadeBebida = 2; + + double valorTotal = 0.0; + + Lanche lanche = daoLanche.pesquisaPorNome(lancheTeste.getNome()); + lanche.setQuantidade(quantidadeLanche); + valorTotal += lanche.getValor_venda() * quantidadeLanche; + + Bebida bebida = daoBebida.pesquisaPorNome(bebidaTeste.getNome()); + bebida.setQuantidade(quantidadeBebida); + valorTotal += bebida.getValor_venda() * quantidadeBebida; + + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(cliente); + pedido.setValor_total(valorTotal); + + daoPedido.salvar(pedido); + + Pedido pedidoComId = daoPedido.pesquisaPorData(pedido); + pedidoComId.setCliente(cliente); + + daoPedido.vincularLanche(pedidoComId, lanche); + daoPedido.vincularBebida(pedidoComId, bebida); + + assertTrue(pedidoComId.getId_pedido() > 0); + assertEquals(valorTotal, pedidoComId.getValor_total(), 0.01); + assertNotNull(pedidoComId.getData_pedido()); + } + + @Test + @Order(7) + void testeComprarSemTokenValido() { + daoToken.remover(tokenTeste); + + boolean tokenValido = daoToken.validar(tokenTeste); + assertFalse(tokenValido); + + Pedido pedido = new Pedido(); + pedido.setData_pedido(Instant.now().toString()); + pedido.setCliente(clienteTeste); + pedido.setValor_total(50.0); + + assertDoesNotThrow(() -> daoPedido.salvar(pedido)); + } + + + private void limparDadosTeste() { + try (Connection conn = new DaoUtil().conecta()) { + conn.createStatement().execute("DELETE FROM tb_lanches_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'))"); + conn.createStatement().execute("DELETE FROM tb_bebidas_pedido WHERE id_pedido IN (SELECT id_pedido FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'))"); + conn.createStatement().execute("DELETE FROM tb_pedidos WHERE id_cliente IN (SELECT id_cliente FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "')"); + conn.createStatement().execute("DELETE FROM tb_tokens WHERE token LIKE '" + USUARIO_TESTE + "%'"); + conn.createStatement().execute("DELETE FROM tb_clientes WHERE usuario = '" + USUARIO_TESTE + "'"); + conn.createStatement().execute("DELETE FROM tb_lanches WHERE nm_lanche = 'nomeLanche'"); + conn.createStatement().execute("DELETE FROM tb_bebidas WHERE nm_bebida = 'nomeBebida'"); + } catch (SQLException e) { + } + } + + private Endereco criarEnderecoTeste() { + Endereco endereco = new Endereco(); + endereco.setRua("Rua"); + endereco.setBairro("Bairro"); + endereco.setNumero(123); + endereco.setComplemento("Complemento"); + endereco.setCidade("Rio de Janeiro"); + endereco.setEstado("RJ"); + return endereco; + } + + private Cliente criarClienteTeste(Endereco endereco) { + Cliente cliente = new Cliente(); + cliente.setNome("nomeCliente"); + cliente.setSobrenome("sobrenomeCliente"); + cliente.setTelefone("21999999999"); + cliente.setUsuario(USUARIO_TESTE); + cliente.setSenha(SENHA_TESTE); + cliente.setFg_ativo(1); + cliente.setEndereco(endereco); + return cliente; + } + + private Lanche criarLancheTeste() { + Lanche lanche = new Lanche(); + lanche.setNome("nomeLanche"); + lanche.setDescricao("descricaoTeste"); + lanche.setValor_venda(25.90); + lanche.setFg_ativo(1); + return lanche; + } + + private Bebida criarBebidaTeste() { + Bebida bebida = new Bebida(); + bebida.setNome("nomeBebida"); + bebida.setDescricao("bebidaTeste"); + bebida.setQuantidade(10); + bebida.setValor_compra(3.00); + bebida.setValor_venda(8.50); + bebida.setTipo("Refrigerante"); + bebida.setFg_ativo(1); + return bebida; + } +} diff --git a/target/classes/Controllers/alterarBebida.class b/target/classes/Controllers/alterarBebida.class new file mode 100644 index 0000000..c509633 Binary files /dev/null and b/target/classes/Controllers/alterarBebida.class differ diff --git a/target/classes/Controllers/alterarIngrediente.class b/target/classes/Controllers/alterarIngrediente.class new file mode 100644 index 0000000..6378e63 Binary files /dev/null and b/target/classes/Controllers/alterarIngrediente.class differ diff --git a/target/classes/Controllers/alterarStatusLanchonete.class b/target/classes/Controllers/alterarStatusLanchonete.class new file mode 100644 index 0000000..42300bd Binary files /dev/null and b/target/classes/Controllers/alterarStatusLanchonete.class differ diff --git a/target/classes/Controllers/cadastro.class b/target/classes/Controllers/cadastro.class new file mode 100644 index 0000000..07c3fa8 Binary files /dev/null and b/target/classes/Controllers/cadastro.class differ diff --git a/target/classes/Controllers/comprar.class b/target/classes/Controllers/comprar.class new file mode 100644 index 0000000..57cec97 Binary files /dev/null and b/target/classes/Controllers/comprar.class differ diff --git a/target/classes/Controllers/getBebidas.class b/target/classes/Controllers/getBebidas.class new file mode 100644 index 0000000..ded0fe7 Binary files /dev/null and b/target/classes/Controllers/getBebidas.class differ diff --git a/target/classes/Controllers/getBebidasCliente.class b/target/classes/Controllers/getBebidasCliente.class new file mode 100644 index 0000000..d3937eb Binary files /dev/null and b/target/classes/Controllers/getBebidasCliente.class differ diff --git a/target/classes/Controllers/getCliente.class b/target/classes/Controllers/getCliente.class new file mode 100644 index 0000000..aeea04c Binary files /dev/null and b/target/classes/Controllers/getCliente.class differ diff --git a/target/classes/Controllers/getIngredientes.class b/target/classes/Controllers/getIngredientes.class new file mode 100644 index 0000000..6c04106 Binary files /dev/null and b/target/classes/Controllers/getIngredientes.class differ diff --git a/target/classes/Controllers/getIngredientesCliente.class b/target/classes/Controllers/getIngredientesCliente.class new file mode 100644 index 0000000..fd1b1b9 Binary files /dev/null and b/target/classes/Controllers/getIngredientesCliente.class differ diff --git a/target/classes/Controllers/getIngredientesPorLanche.class b/target/classes/Controllers/getIngredientesPorLanche.class new file mode 100644 index 0000000..c2c3de9 Binary files /dev/null and b/target/classes/Controllers/getIngredientesPorLanche.class differ diff --git a/target/classes/Controllers/getIngredientesPorLancheCliente.class b/target/classes/Controllers/getIngredientesPorLancheCliente.class new file mode 100644 index 0000000..e6ddcc3 Binary files /dev/null and b/target/classes/Controllers/getIngredientesPorLancheCliente.class differ diff --git a/target/classes/Controllers/getLanches.class b/target/classes/Controllers/getLanches.class new file mode 100644 index 0000000..f2b01d3 Binary files /dev/null and b/target/classes/Controllers/getLanches.class differ diff --git a/target/classes/Controllers/getLanchesCliente.class b/target/classes/Controllers/getLanchesCliente.class new file mode 100644 index 0000000..f4185a7 Binary files /dev/null and b/target/classes/Controllers/getLanchesCliente.class differ diff --git a/target/classes/Controllers/getRelatorioBebidas.class b/target/classes/Controllers/getRelatorioBebidas.class new file mode 100644 index 0000000..b780a68 Binary files /dev/null and b/target/classes/Controllers/getRelatorioBebidas.class differ diff --git a/target/classes/Controllers/getRelatorioGastos.class b/target/classes/Controllers/getRelatorioGastos.class new file mode 100644 index 0000000..d1bc60d Binary files /dev/null and b/target/classes/Controllers/getRelatorioGastos.class differ diff --git a/target/classes/Controllers/getRelatorioLanches.class b/target/classes/Controllers/getRelatorioLanches.class new file mode 100644 index 0000000..34250cb Binary files /dev/null and b/target/classes/Controllers/getRelatorioLanches.class differ diff --git a/target/classes/Controllers/getStatusLanchonete.class b/target/classes/Controllers/getStatusLanchonete.class new file mode 100644 index 0000000..fdc1a23 Binary files /dev/null and b/target/classes/Controllers/getStatusLanchonete.class differ diff --git a/target/classes/Controllers/login.class b/target/classes/Controllers/login.class new file mode 100644 index 0000000..633945d Binary files /dev/null and b/target/classes/Controllers/login.class differ diff --git a/target/classes/Controllers/loginFuncionario.class b/target/classes/Controllers/loginFuncionario.class new file mode 100644 index 0000000..7a1f49a Binary files /dev/null and b/target/classes/Controllers/loginFuncionario.class differ diff --git a/target/classes/Controllers/logout.class b/target/classes/Controllers/logout.class new file mode 100644 index 0000000..c616a8e Binary files /dev/null and b/target/classes/Controllers/logout.class differ diff --git a/target/classes/Controllers/removerBebida.class b/target/classes/Controllers/removerBebida.class new file mode 100644 index 0000000..971512f Binary files /dev/null and b/target/classes/Controllers/removerBebida.class differ diff --git a/target/classes/Controllers/removerIngrediente.class b/target/classes/Controllers/removerIngrediente.class new file mode 100644 index 0000000..f763ada Binary files /dev/null and b/target/classes/Controllers/removerIngrediente.class differ diff --git a/target/classes/Controllers/salvarBebida.class b/target/classes/Controllers/salvarBebida.class new file mode 100644 index 0000000..b3b9bd2 Binary files /dev/null and b/target/classes/Controllers/salvarBebida.class differ diff --git a/target/classes/Controllers/salvarFuncionario.class b/target/classes/Controllers/salvarFuncionario.class new file mode 100644 index 0000000..927d2f7 Binary files /dev/null and b/target/classes/Controllers/salvarFuncionario.class differ diff --git a/target/classes/Controllers/salvarIngrediente.class b/target/classes/Controllers/salvarIngrediente.class new file mode 100644 index 0000000..8dcbaee Binary files /dev/null and b/target/classes/Controllers/salvarIngrediente.class differ diff --git a/target/classes/Controllers/salvarLanche.class b/target/classes/Controllers/salvarLanche.class new file mode 100644 index 0000000..4c43e6b Binary files /dev/null and b/target/classes/Controllers/salvarLanche.class differ diff --git a/target/classes/Controllers/salvarLancheCliente.class b/target/classes/Controllers/salvarLancheCliente.class new file mode 100644 index 0000000..e4fb3e9 Binary files /dev/null and b/target/classes/Controllers/salvarLancheCliente.class differ diff --git a/target/classes/Controllers/tabela.class b/target/classes/Controllers/tabela.class new file mode 100644 index 0000000..1fb39d2 Binary files /dev/null and b/target/classes/Controllers/tabela.class differ diff --git a/target/classes/Controllers/validarToken.class b/target/classes/Controllers/validarToken.class new file mode 100644 index 0000000..daabaa3 Binary files /dev/null and b/target/classes/Controllers/validarToken.class differ diff --git a/target/classes/Controllers/validarTokenFunc.class b/target/classes/Controllers/validarTokenFunc.class new file mode 100644 index 0000000..0fd4589 Binary files /dev/null and b/target/classes/Controllers/validarTokenFunc.class differ diff --git a/target/classes/DAO/DaoBebida.class b/target/classes/DAO/DaoBebida.class new file mode 100644 index 0000000..1c0fa96 Binary files /dev/null and b/target/classes/DAO/DaoBebida.class differ diff --git a/target/classes/DAO/DaoCliente.class b/target/classes/DAO/DaoCliente.class new file mode 100644 index 0000000..f6e2a29 Binary files /dev/null and b/target/classes/DAO/DaoCliente.class differ diff --git a/target/classes/DAO/DaoEndereco.class b/target/classes/DAO/DaoEndereco.class new file mode 100644 index 0000000..da7e1c6 Binary files /dev/null and b/target/classes/DAO/DaoEndereco.class differ diff --git a/target/classes/DAO/DaoFuncionario.class b/target/classes/DAO/DaoFuncionario.class new file mode 100644 index 0000000..4c96f52 Binary files /dev/null and b/target/classes/DAO/DaoFuncionario.class differ diff --git a/target/classes/DAO/DaoIngrediente.class b/target/classes/DAO/DaoIngrediente.class new file mode 100644 index 0000000..d4d9635 Binary files /dev/null and b/target/classes/DAO/DaoIngrediente.class differ diff --git a/target/classes/DAO/DaoLanche.class b/target/classes/DAO/DaoLanche.class new file mode 100644 index 0000000..2e8deee Binary files /dev/null and b/target/classes/DAO/DaoLanche.class differ diff --git a/target/classes/DAO/DaoPedido.class b/target/classes/DAO/DaoPedido.class new file mode 100644 index 0000000..7b6f68c Binary files /dev/null and b/target/classes/DAO/DaoPedido.class differ diff --git a/target/classes/DAO/DaoRelatorio.class b/target/classes/DAO/DaoRelatorio.class new file mode 100644 index 0000000..9983966 Binary files /dev/null and b/target/classes/DAO/DaoRelatorio.class differ diff --git a/target/classes/DAO/DaoStatusLanchonete.class b/target/classes/DAO/DaoStatusLanchonete.class new file mode 100644 index 0000000..b4d1060 Binary files /dev/null and b/target/classes/DAO/DaoStatusLanchonete.class differ diff --git a/target/classes/DAO/DaoToken.class b/target/classes/DAO/DaoToken.class new file mode 100644 index 0000000..0930b5a Binary files /dev/null and b/target/classes/DAO/DaoToken.class differ diff --git a/target/classes/DAO/DaoUtil.class b/target/classes/DAO/DaoUtil.class new file mode 100644 index 0000000..cade0c0 Binary files /dev/null and b/target/classes/DAO/DaoUtil.class differ diff --git a/target/classes/Helpers/EncryptadorMD5.class b/target/classes/Helpers/EncryptadorMD5.class new file mode 100644 index 0000000..3d8e9a2 Binary files /dev/null and b/target/classes/Helpers/EncryptadorMD5.class differ diff --git a/target/classes/Helpers/EncryptadorMD5_to_be.java b/target/classes/Helpers/EncryptadorMD5_to_be.java new file mode 100644 index 0000000..df36e98 --- /dev/null +++ b/target/classes/Helpers/EncryptadorMD5_to_be.java @@ -0,0 +1,35 @@ +package Helpers; + +import java.math.BigInteger; +import java.security.MessageDigest; +/** + * Classe para criptografar senhas usando o algoritmo MD5. + * + * Esta classe fornece um método para criptografar uma senha em formato de hash MD5. + * O método garante que a senha seja convertida corretamente em um hash de 32 caracteres. + */ +public class EncryptadorMD5_to_be { + +public String encryptar(String senha){ + if (senha == null) { + throw new IllegalArgumentException("Senha não pode ser nula"); + } + + try { + MessageDigest m = MessageDigest.getInstance("MD5"); + m.update(senha.getBytes()); + byte[] digest = m.digest(); + BigInteger bigInt = new BigInteger(1, digest); + String hashtext = bigInt.toString(16); + + while (hashtext.length() < 32) { + hashtext = "0" + hashtext; + } + return hashtext; + + } catch (Exception e) { + throw new RuntimeException("Erro ao gerar hash MD5", e); // lança uma exceção se ocorrer um erro + } +} +} + diff --git a/target/classes/Helpers/ValidadorCookie.class b/target/classes/Helpers/ValidadorCookie.class new file mode 100644 index 0000000..7d3b98c Binary files /dev/null and b/target/classes/Helpers/ValidadorCookie.class differ diff --git a/target/classes/Model/Bebida.class b/target/classes/Model/Bebida.class new file mode 100644 index 0000000..f2dc9bd Binary files /dev/null and b/target/classes/Model/Bebida.class differ diff --git a/target/classes/Model/Cliente.class b/target/classes/Model/Cliente.class new file mode 100644 index 0000000..b42bd6b Binary files /dev/null and b/target/classes/Model/Cliente.class differ diff --git a/target/classes/Model/Endereco.class b/target/classes/Model/Endereco.class new file mode 100644 index 0000000..47a0c45 Binary files /dev/null and b/target/classes/Model/Endereco.class differ diff --git a/target/classes/Model/Funcionario.class b/target/classes/Model/Funcionario.class new file mode 100644 index 0000000..cd24377 Binary files /dev/null and b/target/classes/Model/Funcionario.class differ diff --git a/target/classes/Model/Ingrediente.class b/target/classes/Model/Ingrediente.class new file mode 100644 index 0000000..6a95e70 Binary files /dev/null and b/target/classes/Model/Ingrediente.class differ diff --git a/target/classes/Model/Lanche.class b/target/classes/Model/Lanche.class new file mode 100644 index 0000000..739f43f Binary files /dev/null and b/target/classes/Model/Lanche.class differ diff --git a/target/classes/Model/Pedido.class b/target/classes/Model/Pedido.class new file mode 100644 index 0000000..019119c Binary files /dev/null and b/target/classes/Model/Pedido.class differ diff --git a/target/classes/Model/RelatorioBebidas.class b/target/classes/Model/RelatorioBebidas.class new file mode 100644 index 0000000..401f736 Binary files /dev/null and b/target/classes/Model/RelatorioBebidas.class differ diff --git a/target/classes/Model/RelatorioGastos.class b/target/classes/Model/RelatorioGastos.class new file mode 100644 index 0000000..44000d5 Binary files /dev/null and b/target/classes/Model/RelatorioGastos.class differ diff --git a/target/classes/Model/RelatorioLanches.class b/target/classes/Model/RelatorioLanches.class new file mode 100644 index 0000000..6ec14ea Binary files /dev/null and b/target/classes/Model/RelatorioLanches.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT.war b/target/lanchonete-online-1.0-SNAPSHOT.war new file mode 100644 index 0000000..c9c1572 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT.war differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarBebida.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarBebida.class new file mode 100644 index 0000000..b5215e0 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarBebida.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarIngrediente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarIngrediente.class new file mode 100644 index 0000000..5f4f252 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarIngrediente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarStatusLanchonete.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarStatusLanchonete.class new file mode 100644 index 0000000..a52db48 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/alterarStatusLanchonete.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/cadastro.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/cadastro.class new file mode 100644 index 0000000..0814ca2 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/cadastro.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/comprar.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/comprar.class new file mode 100644 index 0000000..b186ee4 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/comprar.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidas.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidas.class new file mode 100644 index 0000000..bfcb928 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidas.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidasCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidasCliente.class new file mode 100644 index 0000000..2619806 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getBebidasCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getCliente.class new file mode 100644 index 0000000..bd582d0 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientes.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientes.class new file mode 100644 index 0000000..90e674e Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientes.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesCliente.class new file mode 100644 index 0000000..d4a77cf Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLanche.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLanche.class new file mode 100644 index 0000000..b55ff01 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLanche.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLancheCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLancheCliente.class new file mode 100644 index 0000000..21ab196 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getIngredientesPorLancheCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanches.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanches.class new file mode 100644 index 0000000..9a4aefc Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanches.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanchesCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanchesCliente.class new file mode 100644 index 0000000..b36ee76 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getLanchesCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioBebidas.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioBebidas.class new file mode 100644 index 0000000..321d7ef Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioBebidas.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioGastos.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioGastos.class new file mode 100644 index 0000000..f5f9659 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioGastos.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioLanches.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioLanches.class new file mode 100644 index 0000000..d6f2dd7 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getRelatorioLanches.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getStatusLanchonete.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getStatusLanchonete.class new file mode 100644 index 0000000..69439b9 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/getStatusLanchonete.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/login.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/login.class new file mode 100644 index 0000000..af31f2f Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/login.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/loginFuncionario.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/loginFuncionario.class new file mode 100644 index 0000000..a2b28b8 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/loginFuncionario.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/logout.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/logout.class new file mode 100644 index 0000000..018d625 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/logout.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerBebida.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerBebida.class new file mode 100644 index 0000000..bf842ac Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerBebida.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerIngrediente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerIngrediente.class new file mode 100644 index 0000000..e19c3c3 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/removerIngrediente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarBebida.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarBebida.class new file mode 100644 index 0000000..4a615ba Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarBebida.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarFuncionario.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarFuncionario.class new file mode 100644 index 0000000..6c3e610 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarFuncionario.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarIngrediente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarIngrediente.class new file mode 100644 index 0000000..5764ee6 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarIngrediente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLanche.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLanche.class new file mode 100644 index 0000000..1a493ae Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLanche.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLancheCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLancheCliente.class new file mode 100644 index 0000000..e8fc1fa Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/salvarLancheCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/tabela.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/tabela.class new file mode 100644 index 0000000..32d37a4 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/tabela.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarToken.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarToken.class new file mode 100644 index 0000000..dae65a0 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarToken.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarTokenFunc.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarTokenFunc.class new file mode 100644 index 0000000..9b67b98 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Controllers/validarTokenFunc.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoBebida.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoBebida.class new file mode 100644 index 0000000..3603093 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoBebida.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoCliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoCliente.class new file mode 100644 index 0000000..3a8a83b Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoCliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoEndereco.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoEndereco.class new file mode 100644 index 0000000..5317231 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoEndereco.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoFuncionario.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoFuncionario.class new file mode 100644 index 0000000..e2db395 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoFuncionario.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoIngrediente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoIngrediente.class new file mode 100644 index 0000000..f6a6b5b Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoIngrediente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoLanche.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoLanche.class new file mode 100644 index 0000000..14b57c3 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoLanche.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoPedido.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoPedido.class new file mode 100644 index 0000000..f7cd1c5 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoPedido.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoRelatorio.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoRelatorio.class new file mode 100644 index 0000000..98d1a85 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoRelatorio.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoStatusLanchonete.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoStatusLanchonete.class new file mode 100644 index 0000000..da8d59b Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoStatusLanchonete.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoToken.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoToken.class new file mode 100644 index 0000000..09dc4dc Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoToken.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoUtil.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoUtil.class new file mode 100644 index 0000000..8b20eaf Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/DAO/DaoUtil.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/EncryptadorMD5.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/EncryptadorMD5.class new file mode 100644 index 0000000..e1fbcc4 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/EncryptadorMD5.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/ValidadorCookie.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/ValidadorCookie.class new file mode 100644 index 0000000..8a158f8 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Helpers/ValidadorCookie.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Bebida.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Bebida.class new file mode 100644 index 0000000..6e8538a Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Bebida.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Cliente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Cliente.class new file mode 100644 index 0000000..10f5b96 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Cliente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Endereco.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Endereco.class new file mode 100644 index 0000000..aad58bb Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Endereco.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Funcionario.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Funcionario.class new file mode 100644 index 0000000..063e95b Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Funcionario.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Ingrediente.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Ingrediente.class new file mode 100644 index 0000000..4dd59cb Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Ingrediente.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Lanche.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Lanche.class new file mode 100644 index 0000000..b04d054 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Lanche.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Pedido.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Pedido.class new file mode 100644 index 0000000..7962412 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/Pedido.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioBebidas.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioBebidas.class new file mode 100644 index 0000000..c183c79 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioBebidas.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioGastos.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioGastos.class new file mode 100644 index 0000000..d4b9f51 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioGastos.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioLanches.class b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioLanches.class new file mode 100644 index 0000000..2f01711 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/classes/Model/RelatorioLanches.class differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/byte-buddy-1.15.0.jar b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/byte-buddy-1.15.0.jar new file mode 100644 index 0000000..5349b64 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/byte-buddy-1.15.0.jar differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/gson-2.8.9.jar b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/gson-2.8.9.jar new file mode 100644 index 0000000..3351867 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/gson-2.8.9.jar differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/json-20210307.jar b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/json-20210307.jar new file mode 100644 index 0000000..6583ea5 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/json-20210307.jar differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/jstl-1.2.jar b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/jstl-1.2.jar new file mode 100644 index 0000000..0fd275e Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/jstl-1.2.jar differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/postgresql-42.2.5.jar b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/postgresql-42.2.5.jar new file mode 100644 index 0000000..d89d433 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/lib/postgresql-42.2.5.jar differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/web.xml b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/web.xml new file mode 100644 index 0000000..deea1d5 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/WEB-INF/web.xml @@ -0,0 +1,256 @@ + + + + cadastro + Controllers.cadastro + + + tabela + Controllers.tabela + + + login + Controllers.login + + + salvarIngrediente + Controllers.salvarIngrediente + + + salvarBebida + Controllers.salvarBebida + + + loginFuncionario + Controllers.loginFuncionario + + + getIngredientes + Controllers.getIngredientes + + + logout + Controllers.logout + + + getBebidas + Controllers.getBebidas + + + alterarIngrediente + Controllers.alterarIngrediente + + + alterarBebida + Controllers.alterarBebida + + + removerIngrediente + Controllers.removerIngrediente + + + removerBebida + Controllers.removerBebida + + + getLanches + Controllers.getLanches + + + getLanchesCliente + Controllers.getLanchesCliente + + + validarToken + Controllers.validarToken + + + getBebidasCliente + Controllers.getBebidasCliente + + + validarTokenFunc + Controllers.validarTokenFunc + + + salvarLanche + Controllers.salvarLanche + + + getIngredientesPorLanche + Controllers.getIngredientesPorLanche + + + getIngredientesPorLancheCliente + Controllers.getIngredientesPorLancheCliente + + + getCliente + Controllers.getCliente + + + comprar + Controllers.comprar + + + getRelatorioBebidas + Controllers.getRelatorioBebidas + + + getRelatorioGastos + Controllers.getRelatorioGastos + + + getRelatorioLanches + Controllers.getRelatorioLanches + + + getIngredientesCliente + Controllers.getIngredientesCliente + + + salvarLancheCliente + Controllers.salvarLancheCliente + + + salvarFuncionario + Controllers.salvarFuncionario + + + alterarStatusLanchonete + Controllers.alterarStatusLanchonete + + + getStatusLanchonete + Controllers.getStatusLanchonete + + + cadastro + /cadastro + + + tabela + /tabela + + + login + /login + + + salvarIngrediente + /salvarIngrediente + + + salvarBebida + /salvarBebida + + + loginFuncionario + /loginFuncionario + + + getIngredientes + /getIngredientes + + + logout + /logout + + + getBebidas + /getBebidas + + + alterarIngrediente + /alterarIngrediente + + + alterarBebida + /alterarBebida + + + removerIngrediente + /removerIngrediente + + + removerBebida + /removerBebida + + + getLanches + /getLanches + + + getLanchesCliente + /getLanchesCliente + + + validarToken + /validarToken + + + getBebidasCliente + /getBebidasCliente + + + validarTokenFunc + /validarTokenFunc + + + salvarLanche + /salvarLanche + + + getIngredientesPorLanche + /getIngredientesPorLanche + + + getIngredientesPorLancheCliente + /getIngredientesPorLancheCliente + + + getCliente + /getCliente + + + comprar + /comprar + + + getRelatorioBebidas + /getRelatorioBebidas + + + getRelatorioGastos + /getRelatorioGastos + + + getRelatorioLanches + /getRelatorioLanches + + + getIngredientesCliente + /getIngredientesCliente + + + salvarLancheCliente + /salvarLancheCliente + + + salvarFuncionario + /salvarFuncionario + + + alterarStatusLanchonete + /alterarStatusLanchonete + + + getStatusLanchonete + /getStatusLanchonete + + + + 30 + + + diff --git a/target/lanchonete-online-1.0-SNAPSHOT/index.html b/target/lanchonete-online-1.0-SNAPSHOT/index.html new file mode 100644 index 0000000..225d730 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/index.html @@ -0,0 +1,24 @@ + + + + + Carregando... + + + + + +

Carregando...

+ + + diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/1.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/1.jpg new file mode 100644 index 0000000..4dc4b08 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/1.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/2.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/2.jpg new file mode 100644 index 0000000..eab4507 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/2.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/3.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/3.jpg new file mode 100644 index 0000000..098edbf Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/3.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/4.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/4.jpg new file mode 100644 index 0000000..6e1bc2f Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/bebidas/4.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/fundoplano1.png b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/fundoplano1.png new file mode 100644 index 0000000..1f0c6ab Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/fundoplano1.png differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/home.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/home.jpg new file mode 100644 index 0000000..7a5a2fe Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/home.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/keyboard.svg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/keyboard.svg new file mode 100644 index 0000000..90440e0 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/keyboard.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/1.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/1.jpg new file mode 100644 index 0000000..fe2547e Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/1.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/2.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/2.jpg new file mode 100644 index 0000000..f104633 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/2.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/3.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/3.jpg new file mode 100644 index 0000000..8be841e Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/3.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/4.jpg b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/4.jpg new file mode 100644 index 0000000..5f42dcb Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/lanches/4.jpg differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo02.png b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo02.png new file mode 100644 index 0000000..2984076 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo02.png differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo1.png b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo1.png new file mode 100644 index 0000000..c6a15c2 Binary files /dev/null and b/target/lanchonete-online-1.0-SNAPSHOT/view/assets/logo1.png differ diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.html b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.html new file mode 100644 index 0000000..2e35e4f --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.html @@ -0,0 +1,99 @@ + + + Cadastro + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+
+
+
+ + + +
+

Cadastro Rápido

+
+ +
+ + + + + +
+ + + +
+

+ + + +

+ + +
+ + + +
+
+
+ + + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.js b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.js new file mode 100644 index 0000000..c19c578 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/cadastro.js @@ -0,0 +1,41 @@ +function enviarCadastro(){ + + let usuario = document.getElementById("usuario"); + let endereco = document.getElementById("endereco"); + let dados = {}; + + if(validar(usuario) && validar(endereco)){ + dados['usuario'] = formularioParaObjeto(usuario); + dados['endereco'] = formularioParaObjeto(endereco); + requisicao("../../cadastro", resolver, JSON.stringify(dados)); + } + +} + +function formularioParaObjeto(formulario){ + let dados = Object.values(formulario).reduce( + (obj, field) => {obj[field.name] = field.value; return obj}, {}); + return dados; +} + +function validar(formulario){ + let sucesso = true; + Object.values(formulario).reduce( + (obj, field) => { + if (field.value.toString().trim() === "" && (!field.name == 'complemento')) { + alert("Você precisa preencher todos os campos para se Cadastrar! O Campo "+field.name+" Está Vazio!") + sucesso = false; + return; + } + }, {}); + return sucesso; +} + +function resolver(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + alert("Ops... Ocorreu um erro no Cadastro, Tente novamente mais Tarde!"); + } else { + alert(resposta.srcElement.responseText); + window.location.replace("../login/login.html"); + } +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/styles.css new file mode 100644 index 0000000..5bfee11 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/cadastro/styles.css @@ -0,0 +1,210 @@ +.containerCadastro { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +#usuario { + width: 100%; + height: 50vh; + display: flex; + align-items: center; + justify-content: flex-start; + flex-direction: column; +} + +#endereco { + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + margin-top: 10px; + width: 100%; + position: relative; + left: 18.3vw; +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; +} + +.containerAction { + width: 20vw; + height: 10vh; + +} + +.containerPage { + width: 100vw; + height: 100vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + overflow-y: auto; + background-color: #F6F6F6; + width: 70vw; + height: 100vh; + display: flex; + flex-direction: column; + align-items: center; +} + +.iconArrow { + width: auto; +} + +.iconArrowLeft { + width: 4vw; + display: block; +} + +#row { + width: 100%; + display: flex; + flex-direction: row; +} + +#Espaçamentotitle { + margin-top: 25px; +} + +.inputCadastroClient { + width: 100%; + height: 50vh; + display: flex; + align-items: center; + justify-content: flex-start; + flex-direction: column; +} + +.buttonLink { + width: 45%; + height: 80vh; + display: flex; + flex-direction: row; + justify-content: space-between; + align-items: flex-start; + padding-top: 20px; + +} + +.TextInput { + width: 32vw; + margin-top: 10px; + height: 7vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +.TextInputCidade { + width: 19.6vw; + height: 6vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +.TextInputBairro { + margin: 0 5px; + width: 13.6vw; + height: 6vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; + +} + +.selectEstados { + width: 12vw; + height: 6vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; + padding-right: 5px; + font-family: 'Ubuntu', sans-serif; + color: #756d6d; + + +} + +.TextInputComplemento { + width: 12vw; + height: 6vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; + +} + +.TextInputNum { + + width: 5vw; + height: 6.5vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +.buttonSubmit { + background-color: #F16262; + width: 80%; + height: 80%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; +} + +.buttonSubmitCancel { + background-color: #978D8D; + width: 80%; + height: 80%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; +} + +.containerButtonCancel { + display: flex; + width: 50%; + height: 35%; +} + +.containerButtonCad { + display: flex; + justify-content: flex-end; + width: 50%; + height: 35%; +} + +.titlePage { + font-family: 'Sansita', sans-serif; + font-size: 3.8rem; + user-select: none; + position: relative; + left: 30%; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.html b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.html new file mode 100644 index 0000000..e88a4f7 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.html @@ -0,0 +1,129 @@ + + + + Carrinho + + + + + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+
+
+
+

+
+
+

+
+
+
+

Meus pedidos

+
+
+
+ +
+
+

Total

+

0

+
+
+
+ + +
+
+
+
+
+

+
+
+

+
+
+
+
+ +

Resumo

+
+
+
+

+
+ +
+

Valor total

+

0

+ +
+ +
+
+
+
+

Tipo de pagamento

+
+
+
+ + Crédito +
+
+ + Débito +
+
+ + Dinheiro +
+
+
+
+
+

Receber o pedido

+
+
+
+ + Em casa +
+
+ + No estabelecimento +
+
+ +
+ +
+
+
+ + + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.js b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.js new file mode 100644 index 0000000..7bdce07 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/carrinho.js @@ -0,0 +1,200 @@ +function validarToken(){ + requisicao("../../validarToken", check) +} + +function check(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login.html?Action=TokenError"); + } +} + +function itemConstructor(nome, preco){ + let containerPedido = document.getElementById("containerPedido"); + + let ItemPedido = document.createElement('div'); + ItemPedido.classList.add("ItemPedido"); + + let legendaNome = document.createElement("p"); + legendaNome.classList.add('legendaNome'); + legendaNome.innerText = nome; + + let legendaPreco = document.createElement("p"); + legendaPreco.classList.add('legendaPreco'); + legendaPreco.innerText = "R$ "+parseFloat(preco); + + let contador = document.createElement('div'); + contador.classList.add("contador"); + + let buttonMinus = document.createElement("button"); + buttonMinus.classList.add("buttonRemove") + buttonMinus.innerText = "–" + buttonMinus.onclick = ()=>{minusItem(quantidade, nome, ItemPedido);}; + + let quantidade = document.createElement("p"); + quantidade.classList.add('quantidade'); + quantidade.innerText = 1; + + let buttonPlus = document.createElement("button"); + buttonPlus.classList.add("buttonRemove") + buttonPlus.innerText = "+"; + buttonPlus.onclick = ()=>{plusItem(quantidade, nome);}; + + containerPedido.appendChild(ItemPedido); + ItemPedido.appendChild(legendaNome); + ItemPedido.appendChild(legendaPreco); + ItemPedido.appendChild(contador); + contador.appendChild(buttonMinus); + contador.appendChild(quantidade); + contador.appendChild(buttonPlus); +} + +function pegarPedidos(){ + dados = {}; + valor = 0; + pegarCustomizado(); + Object.keys(sessionStorage).forEach( + (key) => { + preco = sessionStorage.getItem(key).split(";"); + itemConstructor(key, preco[0]); + dados[key] = preco; + valor += parseFloat(preco[0]); + } + ) + atualizarValor(); +} + +function atualizarValor(){ + document.getElementById("valor1").innerText = "R$ "+valor.toFixed(2); + document.getElementById("valor2").innerText = "R$ "+valor.toFixed(2); +} + +function plusItem(p, nome){ + n = parseInt(p.innerText) + 1; + p.innerText = n; + dados[nome][2] = n; + valor += parseFloat(dados[nome][0]); + atualizarValor(); +} + +function minusItem(p, nome, div){ + if(parseInt(p.innerText) > 1){ + n = parseInt(p.innerText) - 1; + p.innerText = n; + dados[nome][2] = n; + valor -= parseFloat(dados[nome][0]); + atualizarValor(); + } else { + valor -= parseFloat(dados[nome][0]); + sessionStorage.removeItem(nome); + delete dados[nome]; + div.remove(); + atualizarValor(); + } +} + +function showConteudo1(){ + cont1 = document.getElementById("conteudo1"); + cont2 = document.getElementById("conteudo2"); + + cont1.style.display = "flex"; + cont2.style.display = "none"; +} + +function showConteudo2(){ + cont1 = document.getElementById("conteudo1"); + cont2 = document.getElementById("conteudo2"); + + cont1.style.display = "none"; + cont2.style.display = "flex"; + + textoResumo(); +} + +function getUsuario(){ + requisicao("../../getCliente", setUsuarioInfo); +} + +function setUsuarioInfo(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login.html?Action=TokenError"); + } + else { + let dadosCliente = JSON.parse(resposta.srcElement.responseText); + let nome = dadosCliente[0]['nome']+" "+dadosCliente[0]['sobrenome']; + let endereco = ""; + + Object.keys(dadosCliente[1]).forEach( key => { + if(dadosCliente[1][key] && !key.includes("id_")){ + endereco += dadosCliente[1][key] + if(!key.includes("estado")){ + endereco +=", "; + } + } + }) + id = dadosCliente[0]['id_cliente']; + document.getElementById("nome").innerText = nome; + document.getElementById("endereco").innerText = endereco; + document.getElementById("nome2").innerText = nome; + document.getElementById("endereco2").innerText = endereco; + + dados['id'] = id; + } +} + +function logout(){ + requisicao("../../logout", deslogar) + deleteAllCookies(); + sessionStorage.clear(); +} + +function deslogar(resposta){ + alert(resposta.srcElement.responseText); + window.location.replace("../home/home.html"); +} + +function deleteAllCookies() { + + var cookies = document.cookie.split(";"); + for (var i = 0; i < cookies.length; i++){ + console.log(cookies[i].split("=")[0].trim()); + document.cookie = cookies[i].split("=")[0].trim()+"=; expires=Thu, 01 jan 1970 00:00:01 GTM;";} +} + +function textoResumo() { + let string = ""; + Object.keys(dados).forEach( key => { + let pontinhos = "." + if(key != "id"){ + string += "x"+dados[key][2]+pontinhos.repeat(30)+key+pontinhos.repeat(58-key.length)+"R$ "+dados[key][0]+"\n";} + }) + document.getElementById("textResumo").innerText = string; +} + +function realizarCompra(){ + console.log(dados); + requisicao("../../comprar", resolver, JSON.stringify(dados)); +} + +function resolver(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + alert("Ocorreu um Erro com seu Pedido! tente logar Novamente.") + window.location.replace("../login/login.html"); + } else { + alert(resposta.srcElement.responseText); + sessionStorage.clear(); + window.location.replace("../carrinho/carrinho.html"); + } +} + +///Teste não consigo entender + +function pegarCustomizado(){ + let queryString = window.location.search; + let urlParams = new URLSearchParams(queryString); + nome = urlParams.get('nome'); + preco = [urlParams.get('preco'), "lanche", "1"]; + if(nome){ + itemConstructor(nome, preco[0]); + dados[nome] = preco; + valor += parseFloat(preco[0]);} +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/styles.css new file mode 100644 index 0000000..72b3118 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/carrinho/styles.css @@ -0,0 +1,416 @@ +.containerLogin { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + +.containerAction { + width: 20vw; + height: 10vh; + /* background-color: beige; */ + display: flex; + justify-content: flex-end; + padding-right: 20px; + align-items: center; +} + +.buttonLogout { + width: 12vw; + height: 7vh; + border-radius: 1em; + border: none; + background-color: white; + font-family: 'Sansita', sans-serif; + font-size: 2.4rem; + color: black; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + /* background-color: aquamarine; */ + +} + +.containerAction { + width: 20vw; + height: 10vh; + /* background-color: beige; */ + +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; + display: flex; + flex-direction: column; + align-items: center; + padding-top: 45px; + justify-content: flex-start; +} + +.containerConteudo2 { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; + display: none; + flex-direction: column; + align-items: center; + padding-top: 45px; + justify-content: flex-start; +} + +.ItemPedido { + width: 100%; + display: flex; + align-items: center; + justify-content: space-around; + flex-direction: row; +} + +.itemPedidoContainer { + flex-direction: column; + display: flex; + width: 100%; + height: 100%; + overflow-y: scroll; +} + +.itemPedidoContainer:-webkit-scrollbar { + display: none; +} + +.InformacoesPessoais { + top: 12%; + position: fixed; + width: 70%; + height: 4vh; + background-color: #E5E5E5; + display: flex; + justify-content: space-between; + align-items: center; + padding: 5px; +} + +.titleTypeContainer { + font-size: 2.8rem; + font-family: 'Sansita', sans-serif; + color: #000; +} + +.nomeCliente { + height: 100%; + width: 40%; + /* background-color: #F16262; */ +} + +.enderecoCliente { + height: 100%; + width: 60%; + /* background-color: aqua; */ + text-align: right; + +} + +.legendInformacao { + font-family: 'Ubuntu', sans-serif; + color: #000; + font-weight: bold; + font-size: 1.4rem; +} + +.containerPedidos { + padding: 25px; + display: flex; + justify-content: center; + width: 50vw; + height: 50vh; + border: solid 1px #F16262; + border-radius: 20px; +} + +.containerTitle { + width: 100%; + margin-bottom: 20px; + display: flex; + justify-content: center; +} + +.containerTitle2 { + width: 100%; + margin-bottom: 5px; + display: flex; + justify-content: center; +} + +.buttonRemove { + border-radius: 1em; + width: 25px; + height: 25px; + border: none; + background-color: #F16262; + color: #FFF; + font-weight: bold; + font-family: 'Sansita', sans-serif; + font-size: 2.3rem; + padding-bottom: 5px; + display: flex; + justify-content: center; + align-items: center; +} + +.legendanome { + width: 40%; + font-size: 1.5vw; + display: block; +} + +.legendapreco { + width: 30%; + font-size: 1.5vw; + display: block; +} + +.contador { + width: 6vw; + display: flex; + flex-direction: row; + justify-content: space-between; + position: relative; + float: right; + font-size: 3.4vh; + font-weight: bolder; +} + +.buttonInputContainer { + display: flex; + align-items: center; + justify-content: space-around; + width: 70%; + height: 15%; + margin-top: 20px; + /* background-color: chartreuse; */ +} + +.buttonSubmitCancel { + background-color: #978D8D; + width: 40%; + height: 60%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.buttonVoltar { + background-color: #978D8D; + width: 13vw; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 1.7rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + float: left; + position: relative; + left: -25vw; + top: 0vh; +} + + +.buttonSubmitSalvar { + background-color: #F16262; + width: 40%; + height: 60%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.TotalCompraContainer { + width: 50%; + height: 30px; + bottom: 23%; + border-bottom-left-radius: 20px; + border-bottom-right-radius: 20px; + position: fixed; + padding: 0 20px; + background-color: #F16262; + display: flex; + justify-content: space-between; + align-items: center; +} + +.labelTotal { + font-size: 2.6rem; + font-family: 'Sansita', sans-serif; + color: #FFF; +} + +.valuePedidos { + font-family: 'Ubuntu', sans-serif; + font-size: 1.9rem; + color: #FFF; +} + +.iconArrow { + width: 100%; +} + +.iconArrowLeft { + width: 7%; +} + +.containerResumo { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + width: 100%; + height: 30%; + /* background-color: lightpink; */ +} + +.containerTextResumo { + width: 90%; + height: 65%; + margin-top: 20px; + border: solid 2px #F16262; + border-radius: 1em; + display: flex; + flex-direction: row; + justify-content: space-between; + +} + +.totalPedido { + width: 40%; + height: 100%; + background-color: #F16262; + display: flex; + flex-direction: column; + align-items: center; + justify-content: space-around; + border-top-right-radius: 10px; + border-bottom-right-radius: 10px; +} + +.containerTipoPagamento { + width: 100%; + height: 25%; + display: flex; + flex-direction: column; + justify-content: space-around; + align-items: center; + /* background-color: lightsalmon; */ +} + +.chekPagamento { + width: 80%; + margin-bottom: 20px; + display: flex; + justify-content: space-around; + align-items: center; + +} + +.checkPedido { + display: flex; + justify-content: space-around; + width: 50%; +} + +.typePagament { + width: 15px; + height: 15px; +} + + + + +.containerReciboPedido { + width: 100%; + height: 40%; + /* background-color: lightseagreen; */ + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; +} + +.buttonSubmit { + background-color: #F16262; + width: 20%; + height: 25%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2.4rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; +} + +.legendResumoContainer { + width: 60%; + padding: 10px; + display: flex; + flex-direction: column; + align-items: center; + overflow-y: scroll; +} + +.legendResumoContainer:-webkit-scrollbar { + display: none; +} + +.legendResumo { + font: 400 1.4rem 'Ubuntu', sans-serif; +} + +.titleValor { + font: 700 3.4rem 'Sansita', sans-serif; + color: #FFF; +} + +.valorCompra { + font: 400 2.4rem 'Ubuntu', sans-serif; + color: #FFF +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.html b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.html new file mode 100644 index 0000000..8e08403 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.html @@ -0,0 +1,168 @@ + + + Painel de Controle + + + + + + + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+ +
+
+ + + +
+
+

Estoque

+
+
+
+

Estoque Lanche

+
+ + + + + + + + +
IdNomeDescriçãoPreçoAtivo
+
+ +
+ +
+ +
+ +
+ +
+ + + +
+ + +

Estoque Lanche

+ + + + + + + + + + + + +
IdNomeDescriçãoQuantidadePreço de CompraPreço de VendaTipoAtivo
+
+
+

Estoque Ingredientes

+
+ + + + + + + + + + + +
IdNomeDescriçãoQuantidadePreço de CompraPreço de VendaTipoAtivo
+
+ + +
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+

Estoque Bebidas

+
+ + + + + + + + + +
IdNomeDescriçãoQuantidadePreço de CompraPreço de VendaTipoAtivo
+
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+ +
+
+
+ + + + + +
+ +
+
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.js b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.js new file mode 100644 index 0000000..56a50eb --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/estoque.js @@ -0,0 +1,280 @@ +function getInfo(){ + requisicao("../../getIngredientes", getIngredientes); + requisicao("../../getBebidas", getBebidas); + requisicao("../../getLanches", getLanches); +} + + +function getIngredientes(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + atualizarIngredientes(dados); + } + +} + +function getLanches(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + atualizarLanches(dados); + } + +} + +function getBebidas(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + atualizarBebidas(dados); + } +} + +function atualizarIngredientes(dados){ + + let tabela = document.getElementById("tabelaIngredientes"); + + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + row.onclick = () => pegarIngrediente(dados[cadastro]); + } + }); +} + +function atualizarLanches(dados){ + + let tabela = document.getElementById("tabelaLanches"); + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + row.onclick = () => pegarLanche(dados[cadastro]); + } + }); +} + +function pegarIngrediente(dados) { + document.getElementById("ingredientesID").value = dados["id_ingrediente"]; + document.getElementById("ingredientesNome").value = dados["nome"]; + document.getElementById("ingredientesDescricao").value = dados["descricao"]; + document.getElementById("ingredientesQuantidade").value = dados["quantidade"]; + document.getElementById("ingredientesPrecoCompra").value = dados["valor_compra"]; + document.getElementById("ingredientesPrecoVenda").value = dados["valor_venda"]; + document.getElementById("ingredientesTipo").value = dados["tipo"]; + showIngrediente(); +}; + +function pegarLanche(dados) { + document.getElementById("lanchesID").value = dados["id_lanche"]; + document.getElementById("lanchesNome").value = dados["nome"]; + document.getElementById("lanchesDescricao").value = dados["descricao"];; + document.getElementById("lanchesPrecoVenda").value = dados["valor_venda"]; + getIngredientesLanche(dados["id_lanche"]) + showLanche(); +}; + +function getIngredientesLanche(id){ + dados = {} + dados['id'] = id; + requisicao("../../getIngredientesPorLanche", setarIngredientes, JSON.stringify(dados)); + +} + +function setarIngredientes(resposta){ + let tabela = document.getElementById("ingredientesLanche"); + limparTabela(tabela); + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + } + }); + } +} + +function limparTabela(tabela){ + //let tableRows = tabela.getElementsByTagName('tr'); + + while(tabela.rows.length > 1) { + tabela.deleteRow(1); + } +} + +function showLanche(){ + let ingredientes = document.getElementById("editarIngredientes"); + let bebidas = document.getElementById("editarBebidas"); + let lanches = document.getElementById("editarLanches"); + lanches.style.display = 'block'; + ingredientes.style.display = 'none'; + bebidas.style.display = 'none'; +} + + +function showIngrediente(){ + let ingredientes = document.getElementById("editarIngredientes"); + let bebidas = document.getElementById("editarBebidas"); + let lanches = document.getElementById("editarLanches"); + lanches.style.display = 'none'; + ingredientes.style.display = 'block'; + bebidas.style.display = 'none'; +} + +function atualizarBebidas(dados){ + let tabela = document.getElementById("tabelaBebidas"); + + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + row.onclick = () => pegarBebida(dados[cadastro]); + } + }); + +} + +function pegarBebida(dados){ + document.getElementById("bebidasID").value = dados["id_bebida"]; + document.getElementById("bebidasNome").value = dados["nome"]; + document.getElementById("bebidasDescricao").value = dados["descricao"]; + document.getElementById("bebidasQuantidade").value = dados["quantidade"]; + document.getElementById("bebidasPrecoCompra").value = dados["valor_compra"]; + document.getElementById("bebidasPrecoVenda").value = dados["valor_venda"]; + document.getElementById("bebidasTipo").value = dados["tipo"]; + showBebida(); +} + +function showBebida(){ + let ingredientes = document.getElementById("editarIngredientes"); + let bebidas = document.getElementById("editarBebidas"); + let lanches = document.getElementById("editarLanches"); + lanches.style.display = 'none'; + ingredientes.style.display = 'none'; + bebidas.style.display = 'block'; +} + +function alterarIngrediente(){ + + let form = document.getElementById("editarIngredientes"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../alterarIngrediente", resolver, JSON.stringify(dados)); + } + +} + +function alterarBebida(){ + + let form = document.getElementById("editarBebidas"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../alterarBebida", resolver, JSON.stringify(dados)); + } + +} + +function removerIngrediente(){ + + let form = document.getElementById("editarIngredientes"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../removerIngrediente", resolver, JSON.stringify(dados)); + } + +} + +function removerBebida(){ + + let form = document.getElementById("editarBebidas"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../removerBebida", resolver, JSON.stringify(dados)); + } + +} + + +function resolver(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } else { + alert(resposta.srcElement.responseText); + window.location.reload(); + } +} + +function validar(formulario){ + let sucesso = true; + Object.values(formulario).reduce( + (obj, field) => { + if (field.value.toString().trim() === "" || field.value.toString().trim() === "Tipo") { + alert("Você precisa preencher todos os campos para se Cadastrar! O Campo "+field.name+" Está Vazio!") + sucesso = false; + return; + } + }, {}); + return sucesso; +} + +function formularioParaObjeto(formulario){ + let dados = Object.values(formulario).reduce( + (obj, field) => {obj[field.name] = field.value; return obj}, {}); + return dados; +} + +function logout(){ + deleteAllCookies(); + deleteAllSession(); + sessionStorage.clear(); + requisicao("../../logout", deslogar) +} + +function deslogar(resposta){ + alert(resposta.srcElement.responseText); + window.location.replace("../home/home.html"); +} + +function deleteAllCookies() { + + var cookies = document.cookie.split(";"); + for (var i = 0; i < cookies.length; i++){ + console.log(cookies[i].split("=")[0].trim()); + document.cookie = cookies[i].split("=")[0].trim()+"=; expires=Thu, 01 jan 1970 00:00:01 GTM;";} +} + +function deleteAllSession() { + + console.log("Ué"); + Object.keys(sessionStorage).forEach( + (key) => { + sessionStorage.removeItem(key); + } + ) +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/styles.css new file mode 100644 index 0000000..c872918 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/estoque/styles.css @@ -0,0 +1,170 @@ +#editarIngredientes { + display: none; +} + +#editarBebidas { + display: none; +} + +#editarLanches { + display: none; +} + +.containerEstoque { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + +.buttonLogout { + width: 12vw; + height: 7vh; + border-radius: 1em; + border: none; + background-color: white; + font-family: 'Sansita', sans-serif; + font-size: 2.4rem; + color: black; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + /* background-color: aquamarine; */ + +} + +.containerAction { + width: 20vw; + height: 10vh; + + display: flex; + align-items: center; + justify-content: center; + +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; + display: flex; + overflow-y: auto; + flex-direction: column; + align-items: center; + /* padding-top: 45px; */ + justify-content: flex-start; +} + + +table { + border-collapse: collapse; + table-layout: fixed; + width: 100%; + margin: 20px; + display: contents; + margin: 10vh; +} + +th, +td { + height: 1vh; + padding: 10px; + text-align: left; + border-bottom: 1px solid rgb(143, 141, 141); + + +} + +tr:hover { + background-color: rgba(37, 37, 37, 0.356); +} + +form { + margin: 10vh; + display: flexbox; + justify-content: space-evenly; +} + +label { + font-family: 'Sansita', sans-serif; + position: relative; + margin: 6vh; +} + +input { + justify-content: space-around; + flex-direction: column; +} + + + +#editarIngredientes { + display: none; +} + +#editarBebidas { + display: none; +} + +.titleTypeContainer { + font-size: 2.8rem; + font-family: 'Sansita', sans-serif; + color: #000; +} + +.containerTitle { + width: 100%; + margin-bottom: 20px; + display: flex; + justify-content: center; +} + +.containerTable { + width: 100%; + display: flex; + justify-content: center; + flex-direction: column; + align-items: flex-start; +} + +.titleTypeContainerTable { + font-size: 2.2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; +} + +.containerTitleTable { + width: 100%; + height: 5vh; + background-color: #F16262; + display: flex; + align-items: center; + justify-content: flex-start; + padding: 2px 10px; +} + +.iconArrow { + width: 100%; +} + +.iconArrowLeft { + width: 4%; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.css b/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.css new file mode 100644 index 0000000..995aab3 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.css @@ -0,0 +1,265 @@ +html { + background-color: #F6F6F6 +} + +#top { + width: 100vw; + height: 10vh; + background-color: #F16262; + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + padding-left: 25px; +} + + + +#logo { + width: 3vw; + height: 8vh; + background-color: white; + margin: 10px 25px 10px 25px; + width: 20vw; +} + + +.sobre { + align-self: flex-end; + text-align: right; +} + +.opcoes, +.sobre { + height: 8vh; + margin: 10px 25px 10px 25px; + position: relative; + top: 10%; + vertical-align: center; + color: white; + font-family: 'Sansita', sans-serif; + align-items: center; + font-size: 2vw; + white-space: nowrap; +} + +a { + padding: 0px; + margin: 0px; + text-decoration: none; + color: inherit; + font-family: 'Sansita', sans-serif; +} + +.sobre:hover { + + padding-bottom: -30px; + border-bottom: 10px solid white; +} + +.opcoes:hover { + + padding-bottom: -30px; + border-bottom: 10px solid white; +} + + +body, +html { + width: 100%; + height: 100%; + font-family: Arial, Tahoma, sans-serif; + +} + + + +:root { + font-size: 60%; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + +} + +html, +body, +#root { + height: 100vh; + margin: 0; + padding: 0; + overflow: hidden; + +} + +body {} + + +body, +input, +button, +textarea { + font: 500 1.6rem Poppins; +} + +.contHome { + height: 100vh; + width: 100vw; + background-image: url("../assets/home.jpg"); + background-color: transparent; + background-size: cover; + background-repeat: no-repeat; + background-attachment: fixed; +} + +.contFilho { + height: 90vh; + width: 100vw; + position: fixed; + display: flex; + justify-content: flex-end; + align-items: center; + /* background-color: blanchedalmond; */ +} + + +.logoHeader { + width: 12vw; + border: none; + border-radius: 10px; + background-size: cover; + background-repeat: no-repeat; + +} + +#imagemLogo2 { + width: 19vw; + height: 9vh; + position: relative; + left: -3vw; + top: 0.5vh; +} + + +.contFilho2 { + /* background-color: aqua; */ + + width: 32vw; + height: 90vh; + margin-right: 70px; + /* margin-bottom: 130px; */ + + display: flex; + flex-direction: column; + align-items: center; +} + +.logo { + + width: 30vw; + height: 26vh; + margin-top: 20px; + border: none; + background-color: transparent; +} + +#imagemLogo { + width: 22.5vw; + height: 19vw; + position: relative; + top: -15vh; + left: 3.3vw; + -webkit-filter: drop-shadow(6px 10px 25px rgba(0, 0, 0, 0.5)); + filter: url("data:image/svg+xml;utf8,#drop-shadow"); + -ms-filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=2, OffY=15, Color='#444')"; + filter: "progid:DXImageTransform.Microsoft.Dropshadow(OffX=2, OffY=15, Color='#444')"; +} + +.esp1, +.esp2 { + + width: 20vw; + height: 10px; + margin: 10px 0; + background: #FFFFFF; + border-radius: 20px; +} + +.fantasia { + + width: 100%; + height: 40vh; + + + flex-direction: column; + display: flex; + align-items: center; + justify-content: space-around; + text-align: center; + padding-bottom: 10px; + + color: #FFFFFF; + + opacity: 0.75; + +} + +.legendLogo { + font-family: 'Sansita', sans-serif; + font-size: 4.3rem; + + +} + +.legendAtendimento { + font-family: 'Sansita', sans-serif; + font-size: 1.9rem; +} + +.desc { + + width: 445px; + height: 47px; + left: 894px; + top: 813px; + margin-top: 10px; + text-align: center; + + color: #BCB2B2; + +} + + +.button { + margin-top: 10px; + width: 175px; + height: 61px; + left: 1035px; + top: 695px; + border: none; + font-family: 'Sansita', sans-serif; + font-size: 2rem; + color: #FFF; + cursor: pointer; + background: #F16262; + border-radius: 30px; +} + + + + +footer { + clear: both; + width: 700px; + margin: 0 auto; + font-size: 0.75em; + text-align: center; + background-color: #ECECEC; + padding: 5px; + position: absolute; + bottom: 0; + width: 100%; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.html b/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.html new file mode 100644 index 0000000..c083361 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/home/home.html @@ -0,0 +1,60 @@ + + + + + + + + + Lanchonete + + + + + +
+ +
+
+ + + +
+
+ +
+ + + +
+ +

+ + Hamburgueria +
+ & +
+ Porções +

+ +
+ + +
+ +
+

+ + Atendimento das 19:00 às 02:00
+ Entrega das 19:00 às 23:00

+ +

+
+ + +
+
+ + + + diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.html b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.html new file mode 100644 index 0000000..7acfc5b --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.html @@ -0,0 +1,66 @@ + + + Login + + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+
+
+ + + + +
+
+

Login

+ + + + +
+ + +
+ +
+ +
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.js b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.js new file mode 100644 index 0000000..4106b3c --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login.js @@ -0,0 +1,57 @@ +function enviarLogin(){ + + let usuario = document.getElementById("loginInput").value; + let senha = document.getElementById("senhaInput").value; + + if(usuario && senha){ + + let dados = {}; + + dados['usuario'] = usuario; + dados['senha'] = senha; + + + requisicao("../../login", resolver, JSON.stringify(dados)); + } else { + alert("Digite as Informações!"); + } + +} + + +function resolver(resposta){ + if(resposta.srcElement.responseText.localeCompare("erro") == -1){ + let queryString = window.location.search; + let urlParams = new URLSearchParams(queryString); + if(urlParams.get('Action')){ + if(urlParams.get('Action').localeCompare("montarLanche") == 0){ + window.location.replace("../montarLanche/montarLanche.html"); + } else { + window.location.replace(resposta.srcElement.responseText);} + } else { + window.location.replace(resposta.srcElement.responseText); + } + } else { + alert("Erro ao Logar! Tente novamente. Se Cadastre se não possuir uma conta!"); + } +} + + +function validarToken(){ + requisicao("../../validarToken", check) +} + +function check(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + console.log("Token Inválido"); + } else { + let queryString = window.location.search; + let urlParams = new URLSearchParams(queryString); + if(urlParams.get('Action')){ + if(urlParams.get('Action').localeCompare("montarLanche") == 0){ + window.location.replace("../montarLanche/montarLanche.html"); + } else { + window.location.replace("../carrinho/carrinho.html");} + } else {window.location.replace("../carrinho/carrinho.html");} + } +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/login/login_Funcionario.html b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login_Funcionario.html new file mode 100644 index 0000000..1d776ff --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/login/login_Funcionario.html @@ -0,0 +1,81 @@ + + + Login + + + + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+
+
+ + + + +
+
+

Login Administrativo

+ + + + +
+ + +
+ +
+ +
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/login/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/login/styles.css new file mode 100644 index 0000000..7f762db --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/login/styles.css @@ -0,0 +1,115 @@ +.containerLogin { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + /* background-color: aquamarine; */ + +} + +.containerAction { + width: 20vw; + height: 10vh; + /* background-color: beige; */ + +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; +} + +.iconArrow { + width: 100%; +} + +.inputLogin { + width: 100%; + height: 40vh; + /* background-color: blue; */ + display: flex; + align-items: center; + justify-content: center; + flex-direction: column; +} + +.buttonLink { + width: 100%; + height: 45vh; + /* background-color: brown; */ + display: flex; + justify-content: flex-start; + flex-direction: column; + align-items: center; + +} + +.buttonSubmit { + background-color: #F16262; + width: 15%; + height: 20%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2.2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; +} + +.TextInput { + width: 30vw; + margin-top: 25px; + height: 8vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding: 15px; + +} + +#loginInput { + margin-top: 30px; +} + + +.iconArrowLeft { + width: 7%; +} + +.titlePage { + font-family: 'Sansita', sans-serif; + font-size: 3.8rem; + user-select: none; +} + +.linkNewCreate { + text-decoration: none; + color: #F16262; + font-family: 'Ubuntu', sans-serif; + font-size: 2rem; + +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.html b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.html new file mode 100644 index 0000000..b5feae2 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.html @@ -0,0 +1,40 @@ + + + + + Cardápio + + + + + + + + + +
+ +
+
+
+

Em Breve...
Aguardem Novidades!

+
+
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.js b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.js new file mode 100644 index 0000000..0a01c15 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/menu.js @@ -0,0 +1,265 @@ +function loadData(){ + requisicao("../../getStatusLanchonete", verificarStatusAntesDeCarregar); +} + +function verificarStatusAntesDeCarregar(response) { + if (response.srcElement.responseText !== "erro") { + try { + const data = JSON.parse(response.srcElement.responseText); + if (data.status === "ABERTO") { + requisicao("../../getLanchesCliente", getLanches); + requisicao("../../getBebidasCliente", getBebidas); + } else { + alert("A lanchonete está fechada no momento. Por favor, tente novamente mais tarde."); + } + } catch (e) { + console.error("Erro ao processar resposta:", e); + alert("Erro ao processar resposta do servidor. Tente novamente mais tarde."); + } + } +} + +function divConstructor(dados){ + + let screen = document.getElementById("screen"); + + let divLanche = document.createElement('div'); + divLanche.classList.add("divLanche"); + + let row = document.createElement('div'); + row.classList.add("row"); + + let divImagem = document.createElement('div'); + divImagem.classList.add("divImagem"); + + let img = document.createElement('img'); + img.classList.add("lancheIMG"); + img.setAttribute("src", imagemAleatoriaLanche()); + + let divConteudo = document.createElement('div'); + divConteudo.classList.add("divConteudo"); + + let tituloLanche = document.createElement('h1'); + tituloLanche.classList.add("tituloLanche"); + tituloLanche.innerText = dados['nome']; + + let row2 = document.createElement('div'); + row2.classList.add("row"); + + let descricaoLanche = document.createElement('div'); + descricaoLanche.classList.add("descricaoLanche"); + + let p = document.createElement("p"); + p.classList.add("textoDescricao"); + p.innerText = dados['descricao']; + + let preco = document.createElement("p"); + preco.classList.add("preco"); + preco.innerText = "R$ "+dados['valor_venda']; + + let column = document.createElement('div'); + column.classList.add("column"); + + let botaoLanche1 = document.createElement("button"); + botaoLanche1.classList.add("botaoLanche"); + botaoLanche1.innerText = "Veja os Ingredientes" + botaoLanche1.onclick = () => {showIngredientes(dados['id_lanche']); + campoSelecionado = p;}; + + + let botaoLanche2 = document.createElement("button"); + botaoLanche2.classList.add("botaoLanche"); + botaoLanche2.innerText = "Adicionar ao Carrinho" + botaoLanche2.onclick = () => {lancheProCarrinho(dados['nome'], dados['valor_venda']);}; + + screen.appendChild(divLanche); + divLanche.appendChild(row); + row.appendChild(divImagem); + divImagem.appendChild(img); + row.appendChild(divConteudo); + divConteudo.appendChild(tituloLanche); + divConteudo.appendChild(row2); + row2.appendChild(descricaoLanche); + descricaoLanche.appendChild(p); + descricaoLanche.appendChild(preco); + row2.appendChild(column); + column.appendChild(botaoLanche1); + column.appendChild(botaoLanche2); +} + +function divConstructorBebidas(dados){ + + let screen = document.getElementById("screenBebidas"); + + let divLanche = document.createElement('div'); + divLanche.classList.add("divLanche"); + + let row = document.createElement('div'); + row.classList.add("row"); + + let divImagem = document.createElement('div'); + divImagem.classList.add("divImagem"); + + let img = document.createElement('img'); + img.classList.add("lancheIMG"); + img.setAttribute("src", imagemAleatoriaBebida()); + + let divConteudo = document.createElement('div'); + divConteudo.classList.add("divConteudo"); + + let tituloLanche = document.createElement('h1'); + tituloLanche.classList.add("tituloLanche"); + tituloLanche.innerText = dados['nome']; + + let row2 = document.createElement('div'); + row2.classList.add("row"); + + let descricaoLanche = document.createElement('div'); + descricaoLanche.classList.add("descricaoLanche"); + + let p = document.createElement("p"); + p.classList.add("textoDescricao"); + p.innerText = dados['descricao']; + + let preco = document.createElement("p"); + preco.classList.add("preco"); + preco.innerText = "R$ "+dados['valor_venda']; + + let column = document.createElement('div'); + column.classList.add("column"); + + let botaoLanche1 = document.createElement("button"); + botaoLanche1.classList.add("botaoLanche"); + botaoLanche1.innerText = "Tipo: "+dados['tipo'].capitalize(); + + let botaoLanche2 = document.createElement("button"); + botaoLanche2.classList.add("botaoLanche"); + botaoLanche2.innerText = "Adicionar ao Carrinho" + botaoLanche2.onclick = () => {bebidaProCarrinho(dados['nome'], dados['valor_venda']);}; + + screen.appendChild(divLanche); + divLanche.appendChild(row); + row.appendChild(divImagem); + divImagem.appendChild(img); + row.appendChild(divConteudo); + divConteudo.appendChild(tituloLanche); + divConteudo.appendChild(row2); + row2.appendChild(descricaoLanche); + descricaoLanche.appendChild(p); + descricaoLanche.appendChild(preco); + row2.appendChild(column); + column.appendChild(botaoLanche1); + column.appendChild(botaoLanche2); +} + +function getLanches(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + alert("Ocorreu um erro com nosso Sistema! Tente novamente mais tarde.") + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + + Object.keys(dados).forEach( lanche => { + divConstructor(dados[lanche])} + ) + } + +} + +function getBebidas(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + alert("Ocorreu um erro com nosso Sistema! Tente novamente mais tarde.") + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + + Object.keys(dados).forEach( lanche => { + divConstructorBebidas(dados[lanche])} + ) + } + +} + +function imagemAleatoriaLanche(){ + n = Math.floor(Math.random() * 4) + 1 + return "../assets/lanches/" + n + ".jpg"; +} + +function imagemAleatoriaBebida(){ + n = Math.floor(Math.random() * 4) + 1 + return "../assets/bebidas/" + n + ".jpg"; +} + +function showBebidas(){ + + let lanches = document.getElementById("screen"); + let bebidas = document.getElementById("screenBebidas"); + let porcoes = document.getElementById("screenPorcoes"); + + lanches.style.display = 'none'; + bebidas.style.display = 'block'; + porcoes.style.display = 'none'; + +} + +function showLanches(){ + + let lanches = document.getElementById("screen"); + let bebidas = document.getElementById("screenBebidas"); + let porcoes = document.getElementById("screenPorcoes"); + + lanches.style.display = 'block'; + bebidas.style.display = 'none'; + porcoes.style.display = 'none'; + +} + +function showPorcoes(){ + + let lanches = document.getElementById("screen"); + let bebidas = document.getElementById("screenBebidas"); + let porcoes = document.getElementById("screenPorcoes"); + + lanches.style.display = 'none'; + bebidas.style.display = 'none'; + porcoes.style.display = 'block'; + +} + +String.prototype.capitalize = function() { + return this.charAt(0).toUpperCase() + this.slice(1); +} + + +function showIngredientes(id){ + getIngredientesLanche(id); +} + +function getIngredientesLanche(id){ + dados = {} + dados['id'] = id; + requisicao("../../getIngredientesPorLancheCliente", mostrarIngredientes, JSON.stringify(dados)); +} + +function mostrarIngredientes(resposta){ + dados = JSON.parse(resposta.srcElement.responseText); + let string=""; + Object.keys(dados).forEach(ingrediente => { + string += "-"+dados[ingrediente]['nome']+"\r\n"} + ) + campoSelecionado.innerText = string; +} + +function lancheProCarrinho(nome, preco){ + console.log("Ativado") + sessionStorage.setItem(nome, preco+";lanche;1"); + alert("Lanche salvo! Faça login no Carrinho para Prosseguir ou Removê-lo"); +} + +function bebidaProCarrinho(nome, preco,){ + console.log("Ativado") + sessionStorage.setItem(nome, preco+";bebida;1"); + alert("Bebida salva! Faça login no Carrinho para Prosseguir ou Removê-lo"); +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/menu/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/styles.css new file mode 100644 index 0000000..776a305 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/menu/styles.css @@ -0,0 +1,237 @@ +body { + margin: 0px; + padding: 0px; +} + +#content { + display: flex; + flex-direction: column; + align-items: center; +} + +#top { + width: 100%; + height: 12vh; + background-color: #F16262; + display: flex; + flex-direction: row; +} + + + +.logo { + + width: 30vw; + height: 26vh; + margin-top: 20px; + border: none; + background-color: transparent; +} + +#imagemLogo2 { + width: 19vw; + height: 9vh; + position: relative; + left: -1.1vw; + top: 1.1vh; +} + + +.opcoes { + width: 3vw; + height: 8vh; + margin: 10px 25px 10px 25px; + position: relative; + top: 10%; + text-align: center; + vertical-align: center; + width: 15vw; + color: white; + font-family: 'Sansita', sans-serif; + align-items: center; + font-size: 2vw; + white-space: nowrap; +} + +a { + padding: 0px; + margin: 0px; + text-decoration: none; + color: inherit; + font-family: 'Sansita', sans-serif; +} + +.opcoes:hover { + + padding-bottom: -30px; + border-bottom: 10px solid white; +} + +#carrinho { + width: 3vw; + height: 8vh; + background-color: white; + margin: 10px 25px 10px 25px; + width: 20vw; + border-radius: 30px; + float: right; + color: black; + align-items: center; + text-align: center; + font-family: 'Sansita', sans-serif; + font-size: 2vw; + white-space: nowrap; + vertical-align: center; + +} + +#carrinho a { + position: relative; + top: 10%; +} + +#background { + height: 88vh; + width: 100%; + background-color: white; + align-items: center; + background-image: url("../assets/fundoplano1.png"); + background-repeat: repeat; + background-size: auto; + display: flex; + justify-content: center; +} + +#screen { + width: 60vw; + height: 88vh; + background-color: white; + overflow-y: scroll; + scrollbar-color: white; + +} + +#screen::-webkit-scrollbar { + display: none; +} + +#screenBebidas { + width: 60vw; + height: 88vh; + background-color: white; + overflow-y: scroll; + scrollbar-color: white; + display: none; +} + +#screenBebidas::-webkit-scrollbar { + display: none; +} + +#screenPorcoes { + width: 60vw; + height: 88vh; + background-color: white; + overflow-y: scroll; + scrollbar-color: white; + display: none; +} + +#screenPorcoes::-webkit-scrollbar { + display: none; +} + +.divLanche { + width: 100%; + height: 30vh; + margin-top: 20px; + margin-bottom: 20px; + display: block; + /*background-color: rgba(167, 156, 156, 0.116);*/ +} + +.row { + display: flex; + flex-direction: row; +} + +.column { + display: flex; + flex-direction: column; +} + +.divImagem { + display: block; + margin: 3vw; + width: 13vw; + height: 23vh; + margin-right: 0vw; +} + +.lancheIMG { + width: 13vw; + height: 100%; + border-radius: 10%; +} + +.divConteudo { + display: block; + margin: 3vh; + width: 70%; + height: 23vh; +} + +.tituloLanche { + font-size: 2vw; + margin: 1vw; + margin-left: 0.5vw; + margin-bottom: 0.5vh; + border-bottom: 2px solid black; +} + +.descricaoLanche { + background-color: rgba(238, 134, 116, 0.301); + width: 28vw; + height: 17.5vh; + margin: 0.5vw; + border-radius: 10px; + display: block; + color: rgb(70, 70, 70); + +} + +.textoDescricao::-webkit-scrollbar { + display: none; +} + + +.textoDescricao { + margin: 5px; + height: 100%; + overflow-y: scroll; +} + +.preco { + position: relative; + top: -9vh; + float: right; + color: red; + font-size: 22px; +} + +.botaoLanche { + width: 10vw; + height: 6vh; + margin: 2vh; + background-color: cornsilk; + border-radius: 6px; + color: rgb(70, 70, 70); + font-size: 12px; +} + +.emBreve { + position: relative; + top: 30%; + text-align: center; + color: black; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.html b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.html new file mode 100644 index 0000000..15fb5e8 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.html @@ -0,0 +1,70 @@ + + + Painel de Controle + + + + + + + + + + + +
+
+ + +
+ +
+
+
+
+
+ +
+
+ + + +
+
+
+ +
+
+
+

Monte agora seu lanche!

+
+
+ +
+
+

Defina o seu lanche

+
+
+ + +
+
+

Escolha o seu pão

+
+
+ +
+
+

Vamos turbinar ?

+
+
+ +
+
+ + + +
+ \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.js b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.js new file mode 100644 index 0000000..609b19f --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/montarLanche.js @@ -0,0 +1,157 @@ + +function getInfo(){ +requisicao("../../getIngredientesCliente", getIngredientes); +} + +function getIngredientes(resposta){ + + dadosLanche = {}; + dadosLanche['ingredientes'] = {}; + valor = 0; + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + Object.keys(dados).forEach( ingrediente => { + if(dados[ingrediente]['tipo'] == 'pao'){ + option = document.createElement('option'); + option.innerText=dados[ingrediente]['nome']; + document.getElementById('SelectPao').add(option); + } else { + createIngredienteDiv(dados[ingrediente])} + }) + } + +} + +function createIngredienteDiv(dados){ + + let ingredientes = document.getElementById("ingredientes"); + + let opcIngredientes = document.createElement('div'); + opcIngredientes.classList.add("opcIngredientes"); + + let nameValue = document.createElement('div'); + nameValue.classList.add('nameValue'); + + let legendIngrediente = document.createElement('p'); + legendIngrediente.classList.add('legendIngrediente'); + legendIngrediente.innerHTML = dados['nome']+"
R$ "+dados['valor_venda']; + + let containerIncremento = document.createElement('div'); + containerIncremento.classList.add('containerIncremento'); + + let contador = document.createElement('div'); + contador.classList.add('contador'); + + let p = document.createElement('p'); + p.classList.add('legendIngrediente'); + p.innerText = 0; + + let buttonplus = document.createElement('button'); + buttonplus.classList.add('buttonIcons'); + buttonplus.type = "button"; + buttonplus.onclick = ()=>{plusItem(p, dados['nome'], dados['valor_venda']);}; + + let plus = document.createElement('p'); + plus.classList.add('icon'); + plus.innerText = " +"; + + let buttonminus = document.createElement('button'); + buttonminus.classList.add('buttonIcons'); + buttonminus.type = "button"; + buttonminus.onclick = ()=>{minusItem(p, dados['nome'], dados['valor_venda']);}; + + let minus = document.createElement('p'); + minus.classList.add('icon'); + minus.innerText = "– "; + + + + ingredientes.appendChild(opcIngredientes); + opcIngredientes.appendChild(nameValue); + nameValue.appendChild(legendIngrediente); + opcIngredientes.appendChild(containerIncremento); + containerIncremento.appendChild(contador); + contador.appendChild(buttonminus); + buttonminus.appendChild(minus); + contador.appendChild(p); + contador.appendChild(buttonplus); + buttonplus.appendChild(plus); + +} + +function plusItem(p, nome, valorI){ + n = parseInt(p.innerText) + 1; + p.innerText = n; + + dadosLanche['ingredientes'][nome] = p.innerText; + valor += parseFloat(valorI); + atualizarValor(); +} + +function minusItem(p, nome, valorI){ + if(parseInt(p.innerText) > 0){ + n = parseInt(p.innerText) - 1; + p.innerText = n; + + dadosLanche[nome] = p.innerText; + + valor -= parseFloat(valorI); + atualizarValor(); + if(p.innerText == "0"){ + delete dadosLanche['ingredientes'][nome]; + } + } +} + +function atualizarValor(){ + document.getElementById("valor1").innerText = "R$ "+valor.toFixed(2); +} + +function salvarLanche(){ + + let dados = {}; + + if(validarLanche()){ + console.log(dadosLanche); + requisicao("../../salvarLancheCliente", resolver, JSON.stringify(dadosLanche)); + } + +} + +function validarLanche(){ + let nome = document.getElementById("nomeLanche"); + let descricao = document.getElementById("textArea3"); + let pao = document.getElementById("SelectPao"); + let resultado = true; + if(nome.value == ""){ + alert("Campo Nome Vazio!") + resultado = false; + } + if(descricao.value == ""){ + alert("Campo Descrição Vazio!") + resultado = false; + } + if(pao.selectedIndex == 0){ + alert("Campo Pão Vazio!") + resultado = false; + } + if(resultado){ + dadosLanche['nome'] = nome.value; + dadosLanche['descricao'] = descricao.value; + dadosLanche['ingredientes'][pao.value] = 1 ; + } + return resultado; +} + +function resolver(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login.html"); + } else { + window.location.replace(resposta.srcElement.responseText); + + } +} diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/styles.css new file mode 100644 index 0000000..1b00977 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/montarLanche/styles.css @@ -0,0 +1,277 @@ +.containerMontar { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + +.containerAgrupados { + width: 100%; + height: 5vh; + margin-bottom: 10px; + display: flex; + justify-content: space-between; +} + +.titleTypeContainer { + font-size: 2.8rem; + font-family: 'Sansita', sans-serif; + color: #000; + text-align: center; +} + +.containerEspaco { + height: 100%; + width: 35%; + display: flex; + align-items: center; + justify-content: center; +} + +.containerEspacoB { + display: flex; + align-items: flex-start; + justify-content: flex-start; + height: 100%; + width: 70%; + +} + + +.containerValue { + width: 40%; + height: 60%; + display: flex; + border: 1px solid #F16262; + border-radius: 1em; + padding: 5px 0 5px 0; + align-items: center; + flex-direction: column; +} + +.buttonLogout { + width: 12vw; + height: 7vh; + border-radius: 1em; + border: none; + background-color: white; + font-family: 'Sansita', sans-serif; + font-size: 2.4rem; + color: black; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + /* background-color: aquamarine; */ + +} + +.containerAction { + width: 20vw; + height: 10vh; + + display: flex; + align-items: center; + justify-content: center; + +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; + display: block; + overflow-y: scroll; + flex-direction: column; + align-items: center; + /* padding-top: 45px; */ + justify-content: flex-start; +} + +.iconArrow { + width: 100%; +} + +.iconArrowLeft { + width: 4%; +} + +.legendValue { + font-family: 'Ubuntu', sans-serif; + color: #FFF; + font-size: 1.8rem; + +} + +.containerValueLanche { + margin-top: 10%; + width: 100%; + display: flex; + align-items: center; + justify-content: center; + background-color: #F16262; +} + +.legendTitleContainer { + font-family: 'Sansita', sans-serif; + font-size: 2.2rem; + color: black; + user-select: none; +} + +.titleTypeContainerTable { + font-size: 2.2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; +} + +.containerTitleTable { + width: 100%; + height: 5vh; + margin: 10px 0; + background-color: #F16262; + display: flex; + align-items: center; + justify-content: flex-start; + padding: 2px 10px; +} + +.TextInput { + width: 32vw; + margin-top: 10px; + height: 7vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +#SelectPao { + margin-bottom: 10px; +} + + +.opcIngredientes { + width: 75%; + border-radius: 1em; + height: 8vh; + border: solid 2px #F16262; + margin: 15px 0; + padding: 2px 15px; + display: flex; + justify-content: space-between; + align-items: center; +} + +.contador { + width: 8vw; + height: 5vh; + border: 2px solid #000; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 2px 15px; +} + +.buttonIcons { + border: none; + background-color: Transparent; +} + +.legendIngrediente { + font-family: 'Sansita', sans-serif; + font-size: 1.5rem; + color: #676464; +} + +.buttonInputContainer { + display: flex; + align-items: center; + justify-content: space-around; + height: 15%; + margin-top: 10px; + /* background-color: chartreuse; */ +} + +.buttonSubmitCancel { + background-color: #978D8D; + width: 30%; + height: 90%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + + + +.buttonSubmitSalvar { + background-color: #F16262; + width: 30%; + height: 90%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.containerInputSelect { + align-items: center; + flex-direction: column; + display: flex; +} + +#textArea3 { + resize: none; + height: 10vh; + padding-top: 5px; + margin-bottom: 20px; +} + +#ingredientes { + display: flex; + flex-direction: column; + overflow-y: scroll; + height: 27vh; + width: 100%; + align-items: center; +} + +#ingredientes::-webkit-scrollbar { + display: none; +} + + +.icon { + font-size: 2vw; + font-weight: bold; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.html b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.html new file mode 100644 index 0000000..a97afc5 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.html @@ -0,0 +1,258 @@ + + + + + Painel de Controle + + + + + + + + + + + +
+
+ + +
+ +
+
+
+
+
+ +
+

Lanchonete Code Burguer's

+ +
+
+
+

Gerenciamento de serviços

+
+
+ + +
+ +
+
+
+

Cadastro de Items

+
+
+ +
+ + +
+ +
+ + +
+
+ + +
+ +
+ +
+
+

Cadastro de Ingredientes

+
+ +
+ +
+ + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+ +
+
+

Cadastro de Bebidas

+
+ +
+ +
+ + + + + + + + + + + + + + +
+ + +
+ +
+
+
+
+
+

Cadastro de Funcionários

+
+ +
+ +
+ + + + + + + + + + + + + + + +
+ + +
+ +
+
+ +
+ +
+
+

+
+
+ + +
+
+

Cadastro de lanches

+
+ +
+
+

Preço do Lanche

+
+
+

R$

+
+
+ +
+ +
+ +
+ + +
+ +
+

Ingredientes

+
+
+
+ + + +
+ +
+
+ +
+ + + + + +
+
+
+

Valor gasto

+

R$ 20,00

+
+
+

Aberto agora!

+
+
+

Valor com lucro

+ +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.js b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.js new file mode 100644 index 0000000..3ad4dcb --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/painel.js @@ -0,0 +1,414 @@ +function validarToken(){ + sessionStorage.clear(); + requisicao("../../validarTokenFunc", check) +} + +function check(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } +} + +function showCadIngredienteDiv(){ + + + let tip = document.getElementById("Agrupado"); + let div = document.getElementById("CadIngredientes"); + let div2 = document.getElementById("CadBebidas"); + let div3 = document.getElementById("CadFuncionarios"); + let div4 = document.getElementById("CadLanches"); + + tip.style.display = 'none'; + div.style.display = 'block'; + div2.style.display = 'none'; + div3.style.display = 'none'; + div4.style.display = 'none'; +} + +function showCadBebidaDiv(){ + + let tip = document.getElementById("Agrupado"); + let div = document.getElementById("CadBebidas"); + let div2 = document.getElementById("CadIngredientes"); + let div3 = document.getElementById("CadFuncionarios"); + let div4 = document.getElementById("CadLanches"); + + + tip.style.display = 'none'; + div.style.display = 'block'; + div2.style.display = 'none'; + div3.style.display = 'none'; + div4.style.display = 'none'; + +} + +function showInicioDiv(){ + + let tip = document.getElementById("Agrupado"); + let div = document.getElementById("CadBebidas"); + let div2 = document.getElementById("CadIngredientes"); + let div3 = document.getElementById("CadFuncionarios"); + let div4 = document.getElementById("CadLanches"); + + + tip.style.display = 'block'; + div.style.display = 'none'; + div2.style.display = 'none'; + div3.style.display = 'none'; + div4.style.display = 'none'; +} + +function salvarIngrediente(){ + + let form = document.getElementById("addIngrediente"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../salvarIngrediente", resolver, JSON.stringify(dados)); + + } + +} + +function salvarBebida(){ + + let form = document.getElementById("addBebida"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + requisicao("../../salvarBebida", resolver, JSON.stringify(dados)); + + } + +} + +function salvarFuncionario(){ + + let form = document.getElementById("addFuncionario"); + let dados = {}; + + if(validar(form)){ + dados = formularioParaObjeto(form); + console.log(dados); + requisicao("../../salvarFuncionario", resolver, JSON.stringify(dados)); + + } + +} + +function showCadLanches(){ + //CadLanches + + let tip = document.getElementById("Agrupado"); + let div = document.getElementById("CadLanches"); + let div2 = document.getElementById("CadBebidas"); + let div3 = document.getElementById("CadFuncionarios"); + let div4 = document.getElementById("CadIngredientes"); + //let divStatus = document.getElementById("statusId") + //let divStatus2 = document.getElementById("statusId2") + //let divcenter = document.getElementById("footerId"); + + + tip.style.display = 'none'; + div.style.display = 'block'; + div2.style.display = 'none'; + div3.style.display = 'none'; + div4.style.display = 'none'; + //divStatus.style.display = 'flex'; + //divStatus2.style.display = 'flex'; + //divcenter.style.justifyContent = 'space-around'; + + + requisicao("../../getIngredientes", getIngredientes); + +} + +function resolver(resposta){ + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } else { + alert(resposta.srcElement.responseText); + window.location.reload(); + } +} + +function logout(){ + deleteAllCookies(); + deleteAllSession(); + sessionStorage.clear(); + requisicao("../../logout", deslogar) +} + +function deslogar(resposta){ + alert(resposta.srcElement.responseText); + window.location.replace("../home/home.html"); +} + +function deleteAllCookies() { + + var cookies = document.cookie.split(";"); + for (var i = 0; i < cookies.length; i++){ + console.log(cookies[i].split("=")[0].trim()); + document.cookie = cookies[i].split("=")[0].trim()+"=; expires=Thu, 01 jan 1970 00:00:01 GTM;";} +} + +function deleteAllSession() { + + console.log("Ué"); + Object.keys(sessionStorage).forEach( + (key) => { + sessionStorage.removeItem(key); + } + ) +} + +function showCadFuncionario(){ + + let tip = document.getElementById("Agrupado"); + let div = document.getElementById("CadLanches"); + let div2 = document.getElementById("CadBebidas"); + let div3 = document.getElementById("CadFuncionarios") + + + tip.style.display = 'none'; + div.style.display = 'none'; + div2.style.display = 'none'; + div3.style.display = 'block'; +} + +function formularioParaObjeto(formulario){ + let dados = Object.values(formulario).reduce( + (obj, field) => {obj[field.name] = field.value; return obj}, {}); + return dados; +} + +function validar(formulario){ + let sucesso = true; + Object.values(formulario).reduce( + (obj, field) => { + if (field.value.toString().trim() === "" || field.value.toString().trim() === "Tipo") { + alert("Você precisa preencher todos os campos para se Cadastrar! O Campo "+field.name+" Está Vazio!") + sucesso = false; + return; + } + }, {}); + return sucesso; +} + +function getIngredientes(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + Object.keys(dados).forEach( ingrediente => { + if(dados[ingrediente]['tipo'] == 'pao'){ + option = document.createElement('option'); + option.innerText=dados[ingrediente]['nome']; + document.getElementById('selectPao').add(option); + } else { + createIngredienteDiv(dados[ingrediente])} + }) + } + +} + +function createIngredienteDiv(dados){ + + let ingredientes = document.getElementById("ingredientes"); + + let opcIngredientes = document.createElement('div'); + opcIngredientes.classList.add("opcIngredientes"); + + let nameValue = document.createElement('div'); + nameValue.classList.add('nameValue'); + + let legendIngrediente = document.createElement('p'); + legendIngrediente.classList.add('legendIngrediente'); + legendIngrediente.innerHTML = dados['nome']+"
R$ "+dados['valor_venda']; + + let containerIncremento = document.createElement('div'); + containerIncremento.classList.add('containerIncremento'); + + let contador = document.createElement('div'); + contador.classList.add('contador'); + + let p = document.createElement('p'); + p.classList.add('legendIngrediente'); + p.innerText = 0; + + let buttonplus = document.createElement('button'); + buttonplus.classList.add('buttonIcons'); + buttonplus.type = "button"; + buttonplus.onclick = ()=>{plusItem(p, dados['nome']);}; + + let plus = document.createElement('p'); + plus.classList.add('icon'); + plus.innerText = " +"; + + let buttonminus = document.createElement('button'); + buttonminus.classList.add('buttonIcons'); + buttonminus.type = "button"; + buttonminus.onclick = ()=>{minusItem(p, dados['nome']);}; + + let minus = document.createElement('p'); + minus.classList.add('icon'); + minus.innerText = "– "; + + + + ingredientes.appendChild(opcIngredientes); + opcIngredientes.appendChild(nameValue); + nameValue.appendChild(legendIngrediente); + opcIngredientes.appendChild(containerIncremento); + containerIncremento.appendChild(contador); + contador.appendChild(buttonminus); + buttonminus.appendChild(minus); + contador.appendChild(p); + contador.appendChild(buttonplus); + buttonplus.appendChild(plus); + +} + +function plusItem(p, nome){ + n = parseInt(p.innerText) + 1; + p.innerText = n; + + sessionStorage.setItem(nome, p.innerText); + +} + +function minusItem(p, nome){ + if(parseInt(p.innerText) > 0){ + n = parseInt(p.innerText) - 1; + p.innerText = n; + + sessionStorage.setItem(nome, p.innerText); + } +} + +function salvarLanche(){ + + let dados = {}; + + if(validarLanche()){ + dados = dadosDoLanche(); + console.log(dados); + sessionStorage.clear() + requisicao("../../salvarLanche", resolver, JSON.stringify(dados)); + window.location.reload(); + } + +} + + +function validarLanche(){ + let nome = document.getElementById("nomeLanche"); + let descricao = document.getElementById("textArea3"); + let pao = document.getElementById("selectPao"); + let valor = document.getElementById("ValorLanche"); + let resultado = true; + if(nome.value == ""){ + alert("Campo Nome Vazio!") + resultado = false; + } + if(descricao.value == ""){ + alert("Campo Descrição Vazio!") + resultado = false; + } + if(pao.selectedIndex == 0){ + alert("Campo Pão Vazio!") + resultado = false; + } + if(valor.value == 0){ + alert("Campo Valor Vazio!") + resultado = false; + } + return resultado; +} + +function dadosDoLanche(){ + let dados = {}; + let ingredientes = {}; + + let nome = document.getElementById("nomeLanche"); + let descricao = document.getElementById("textArea3"); + let pao = document.getElementById("selectPao"); + let valor = document.getElementById("ValorLanche"); + + dados['nome'] = nome.value; + dados['descricao'] = descricao.value; + dados['ValorVenda'] = parseFloat(valor.value); + + ingredientes[pao.value] = "1"; + Object.keys(sessionStorage).forEach( + (key) => { + ingredientes[key] = sessionStorage.getItem(key); + } + ) + dados['ingredientes'] = ingredientes; + return dados +} + +function abrirLanchonete() { + requisicao("../../alterarStatusLanchonete", atualizarStatusLanchonete, JSON.stringify({status: "ABERTO"})); +} + +function fecharLanchonete() { + requisicao("../../alterarStatusLanchonete", atualizarStatusLanchonete, JSON.stringify({status: "FECHADO"})); +} + +function atualizarStatusLanchonete(response) { + const resposta = response.srcElement.responseText; + console.log("Resposta do servidor:", resposta); + + if (resposta === "erro" || resposta.includes("Status inválido")) { + console.error("Erro ao alterar status:", resposta); + return; + } + + try { + const data = JSON.parse(resposta); + console.log("Dados parseados:", data); + + // Procura o elemento dentro do footer + const footer = document.querySelector(".footerPainel"); + const statusElement = footer.querySelector(".legendStatus"); + console.log("Elemento de status encontrado:", statusElement); + + if (statusElement) { + const novoTexto = data.status === "ABERTO" ? "Aberto agora!" : "Fechado agora!"; + console.log("Atualizando texto para:", novoTexto); + + // Força a atualização do DOM + statusElement.innerHTML = novoTexto; + statusElement.style.display = 'none'; + statusElement.offsetHeight; // Força um reflow + statusElement.style.display = ''; + + // Atualiza também o outro elemento se existir + const outroStatus = document.querySelectorAll(".legendStatus"); + outroStatus.forEach(el => { + if (el !== statusElement) { + el.innerHTML = novoTexto; + } + }); + } else { + console.error("Elemento .legendStatus não encontrado!"); + } + } catch (e) { + console.error("Erro ao processar resposta:", e); + } +} + +function verificarStatusLanchonete() { + requisicao("../../getStatusLanchonete", atualizarStatusLanchonete); +} + +// Adicionar chamada para verificar status ao carregar a página +document.addEventListener('DOMContentLoaded', function() { + verificarStatusLanchonete(); +}) diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/painel/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/styles.css new file mode 100644 index 0000000..46b29a2 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/painel/styles.css @@ -0,0 +1,538 @@ +.containerPainel { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png"); +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + display: flex; + justify-content: space-around; + align-items: center; + + /* background-color: aquamarine; */ + +} + +.navButton { + text-align: center; + font-family: 'Sansita', sans-serif; + font-size: 2rem; + text-decoration: none; + color: white; +} + +.navButton:hover { + padding-bottom: 2px; + border-bottom: 4px solid white; +} + +.containerAction { + width: 20vw; + height: 10vh; + /* background-color: beige; */ + display: flex; + justify-content: flex-end; + padding-right: 20px; + align-items: center; +} + +.buttonLogout { + width: 12vw; + height: 7vh; + border-radius: 1em; + border: none; + background-color: white; + font-family: 'Sansita', sans-serif; + font-size: 2.4rem; + color: black; +} + +.containerAgrupado { + width: 100%; + height: 100%; +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #F6F6F6; + width: 70vw; + height: 88vh; + display: flex; + flex-direction: column; +} + +.titleLanchonete { + width: 100%; + height: 10vh; + display: flex; + justify-content: center; + align-items: center; + /* background-color: khaki; */ +} + +.titlePage { + font-family: 'Sansita', sans-serif; + font-size: 3.2rem; + color: black; + user-select: none; +} + +.containerGerenciador { + width: 100%; + height: 25vh; + flex-direction: column; + display: flex; + align-items: center; + /* background-color: lightblue; */ +} + +.containerButtons { + width: 70%; + height: 25vh; + /* background-color: lightseagreen; */ + display: flex; + align-items: center; + justify-content: space-around; +} + +.containerButtons1 { + width: 35%; + height: 35vh; + display: flex; + align-items: center; + flex-direction: column; + justify-content: space-around; + /* background-color: yellow; */ +} + +.containerButtons2 { + width: 35%; + height: 35vh; + display: flex; + align-items: center; + flex-direction: column; + justify-content: space-around; + /* background-color: yellow; */ +} + +.ButtonsGroupsCadastro { + width: 70%; + height: 30vh; + display: flex; + justify-content: space-around; + +} + +.buttonGerenciador { + border: none; + background-color: #F16262; + border-radius: 1em; + width: 15vw; + height: 14vh; + font-family: 'Sansita', sans-serif; + font-size: 2.5rem; + color: white; + cursor: pointer; + /* display: flex; */ + padding: 10px; + /* align-items: center; */ + /* justify-content: center; */ + + +} + +.titleContainer { + width: 100%; + height: 6vh; + background-color: #F16262; + display: flex; + align-items: center; + padding-left: 20px; + justify-content: flex-start; +} + +.legendTitle { + font-family: 'Sansita', sans-serif; + font-size: 2.5rem; + color: white; + +} + +.cadastroItems { + width: 100%; + height: 42vh; + /* background-color: lightcoral; */ + flex-direction: column; + display: flex; + align-items: center; +} + +.footerPainel { + width: 70%; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; + position: fixed; + padding: 3px 15px; + bottom: 0px; +} + +.StatusLanchonete { + width: 20vw; + height: 9vh; + background-color: white; + display: flex; + align-items: center; + justify-content: center; + border-radius: 0.5em; +} + +.containerFooter { + width: 100%; + display: flex; + align-items: center; + justify-content: space-around; + +} + +.StatusInfo2 { + border-radius: 0.5em; + width: 10vw; + height: 9vh; + background-color: #F16262; + border: 1px solid #FFF; + flex-direction: column; + padding: 5px; + display: none; + align-items: center; + justify-content: space-between; + +} + +.StatusInfo { + padding: 5px; + border-radius: 0.5em; + width: 10vw; + height: 9vh; + background-color: #F16262; + border: 1px solid #FFF; + flex-direction: column; + display: none; + align-items: center; + justify-content: space-between; +} + +.inputValorLucro { + width: 6vw; + height: 5vh; + border: none; + background-color: #F16262; + font-family: 'Ubuntu', sans-serif; + color: #FFF; + font-size: 1.4rem; + padding-left: 5px; + +} + +.legendStatusValue { + font-family: 'Ubuntu', sans-serif; + color: #FFF; + font-size: 1.4rem; + margin-bottom: 5px; +} + +.legendStatus { + font-family: 'Ubuntu', sans-serif; + font-size: 1.9rem; + color: #0CD008; + user-select: none; +} + + + +.containerCadItems { + width: 100%; + height: 90%; + display: none; + flex-direction: column; +} + +.titleCadPainel { + margin-top: 20px; + display: flex; + justify-content: center; + align-items: center; + height: 10%; + width: 100%; +} + +.form { + width: 100%; + height: 90%; + display: flex; + justify-content: center; +} + +.formItems { + width: 70%; + height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: flex-start; + /* background-color: aqua; */ + /* padding: 0 20%; */ +} + +.TextInput { + width: 32vw; + margin-top: 10px; + height: 7vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +#textArea1 { + resize: none; + height: 10vh; + padding-top: 5px; + margin-bottom: 20px; +} + +#textArea2 { + resize: none; + height: 10vh; + padding-top: 5px; + margin-bottom: 20px; +} + +#textArea3 { + resize: none; + height: 10vh; + padding-top: 5px; + margin-bottom: 20px; +} + +.buttonInputContainer { + display: flex; + align-items: center; + justify-content: space-around; + width: 70%; + height: 15%; + /* background-color: chartreuse; */ +} + +.buttonSubmitCancel { + background-color: #978D8D; + width: 40%; + height: 60%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + + + +.buttonSubmitSalvar { + background-color: #F16262; + width: 40%; + height: 60%; + border: none; + border-radius: 20px; + margin-bottom: 25px; + font-size: 2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; +} + +.containerInputs { + width: 32vw; + height: 10vh; + display: flex; + align-items: center; + justify-content: space-between; +} + +.TextInputLanche { + width: 15vw; + height: 7vh; + + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; +} + +.containerTitlePageLanche { + padding-left: 10px; + width: 70vw; + display: flex; + align-items: center; + height: 5vh; + background-color: #F16262; +} + +.titleContainerLanche { + font-size: 2.2rem; + font-family: 'Sansita', sans-serif; + color: #FFF; +} + +.opcIngredientes { + width: 85%; + border-radius: 1em; + height: 8vh; + border: solid 2px #F16262; + margin: 15px 0; + padding: 2px 15px; + display: flex; + justify-content: space-between; + align-items: center; +} + +.legendIngrediente { + font-family: 'Sansita', sans-serif; + font-size: 1.5rem; + color: #676464; +} + +.contador { + width: 8vw; + height: 5vh; + border: 2px solid #000; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: space-between; + padding: 2px 15px; +} + +.buttonIcons { + border: none; + background-color: Transparent; +} + +.legendStatusInfo { + font-size: 1.3rem; + font-family: 'Sansita', sans-serif; + color: #FFF; + /* text-align: center; */ +} + +#ingredientes { + display: flex; + flex-direction: column; + overflow-y: scroll; + height: 27vh; + width: 100%; + align-items: center; +} + +#ingredientes::-webkit-scrollbar { + display: none; +} + +.icon { + font-size: 2vw; + font-weight: bold; +} + + + + +.containerGastos { + width: 13vw; + height: 19vh; + border: 1px solid #F16262; + /* background-color: cyan; */ + flex-direction: column; + display: flex; + align-items: center; + border-radius: 1em; + position: absolute; + top: 25vh; + right: 18vw; +} + +.containerLucro { + width: 20%; + height: 70%; + border: solid 1px #F16262; + border-radius: 1em; + flex-direction: column; + display: flex; + align-items: center; + /* background-color: darkblue; */ + +} + +.titleLucro { + margin-bottom: 15px; +} + +.titleContainerLucro { + font-family: 'Sansita', sans-serif; + font-size: 2.2rem; + color: black; + user-select: none; + +} + +.inputPreco { + width: 10vw; + margin-top: 10px; + height: 4.5vh; + border: 1px solid #BDBDBD; + border-radius: 10px; + padding-left: 15px; + position: relative; + top: -0.8vh; + align-items: center; + +} + +.legendGastos { + font-family: 'Ubuntu', sans-serif; + color: #FFF; + font-size: 1.4rem; + +} + +.LabelGastos { + width: 100%; + height: 5vh; + background-color: #F16262; + display: flex; + justify-content: center; + align-items: center; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.html b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.html new file mode 100644 index 0000000..34a7846 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.html @@ -0,0 +1,88 @@ + + + Relatórios + + + + + + + + + + + + + +
+
+ +
+ +
+
+ +
+
+
+ +
+
+ + + +
+
+

Relatório Geral

+
+
+ + + + + + +
GastosVendasLucro
+

Relatório Bebidas por Pedidos

+ + + + + + + + + + + + + +
ID PedidoClienteBebidaQuantidadeCusto BebidaValor Venda BebidaLucro por BebidaCusto PedidoValor Venda PedidoLucro Pedido
+

Relatório Lanches Detalhado

+ + + + + + + + + + + + + + + +
LancheIngredienteQuantidadeCusto(Por Ingrediente)Venda(Por Ingrediente)Lucro(Por Ingrediente)Custo(Lanche)Venda(Ingredientes)Lucro(Ingredientes)Lucro(Lanche)Venda(Lanche)Lucro Total
+ + +
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.js b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.js new file mode 100644 index 0000000..ad90131 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/relatorio.js @@ -0,0 +1,77 @@ +function getInfo(){ + requisicao("../../getRelatorioLanches", getRelLanches); + requisicao("../../getRelatorioBebidas", getRelBebidas); + requisicao("../../getRelatorioGastos", getRelGastos); +} + +function getRelLanches(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + attRelatorioLanches(dados); + } + +} + +function attRelatorioLanches(dados){ + + let tabela = document.getElementById("tbRelatorioLanches"); + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + } + }); +} + +function getRelBebidas(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + attRelatorioBebidas(dados); + } + +} + +function attRelatorioBebidas(dados){ + + let tabela = document.getElementById("tbRelatorioBebidas"); + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + } + }); +} + +function getRelGastos(resposta){ + + if(resposta.srcElement.responseText.includes("erro")){ + window.location.replace("../login/login_Funcionario.html?Action=TokenError"); + } + else { + dados = JSON.parse(resposta.srcElement.responseText); + attRelatorioGastos(dados); + } + +} + +function attRelatorioGastos(dados){ + + let tabela = document.getElementById("tbRelatorioGastos"); + + Object.keys(dados).forEach(cadastro => { + let row = tabela.insertRow(1); + for (let key in dados[cadastro]) { + row.insertCell().innerHTML = dados[cadastro][key]; + } + }); +} diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/styles.css new file mode 100644 index 0000000..bd1809b --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/relatorio/styles.css @@ -0,0 +1,99 @@ +table{ + border-collapse: collapse; + table-layout: fixed; + height: 100px; + overflow-y: auto; + margin: 20px; + display: block; +} + +th, +td { + height: 1vh; + padding: 6px; + text-align: left; + border-bottom: 1px solid rgb(143, 141, 141); + + +} + +tr:hover { + background-color: rgba(37, 37, 37, 0.356); +} + +.containerRelatorio { + width: 100vw; + height: 100vh; + background-image: url("../assets/fundoplano1.png") +} + +.headerPage { + width: 100vw; + height: 12vh; + background-color: #F16262; + display: flex; + align-items: center; +} + +.buttonLogout { + width: 12vw; + height: 7vh; + border-radius: 1em; + border: none; + background-color: white; + font-family: 'Sansita', sans-serif; + font-size: 2.4rem; + color: black; +} + + +.containerNavButton { + width: 60vw; + height: 10vh; + /* background-color: aquamarine; */ + +} + +.containerAction { + width: 20vw; + height: 10vh; + + display: flex; + align-items: center; + justify-content: center; + +} +.containerTable { + width: 100%; + display: flex; + justify-content: center; + flex-direction: column; + align-items: flex-start; +} + +.containerPage { + width: 100vw; + height: 88vh; + display: flex; + align-items: center; + justify-content: center; +} + +.containerConteudo { + background-color: #FFF; + width: 95vw; + height: 88vh; + display: flex; + overflow-y: auto; + flex-direction: column; + align-items: flex-start; + /* padding-top: 45px; */ + justify-content: flex-start; +} + +.titleTypeContainer { + font-size: 2.8rem; + font-family: 'Sansita', sans-serif; + color: #000; + margin-left: 10px; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/scripts/conexao.js b/target/lanchonete-online-1.0-SNAPSHOT/view/scripts/conexao.js new file mode 100644 index 0000000..9a2bbd8 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/scripts/conexao.js @@ -0,0 +1,50 @@ +function requisicao(caminho, funcaoResposta, dados = null, metodo = 'POST'){ + try + { + //Inicia o Objeto que faz o Request + asyncRequest = new XMLHttpRequest(); + asyncRequest.withCredentials = true; + //prepara a requisição pro servlet com o Caminho dele e o tipo de Request + asyncRequest.open(metodo, caminho, true); + asyncRequest.withCredentials = true; + + // Adiciona headers necessários + if (dados) { + asyncRequest.setRequestHeader('Content-Type', 'application/json'); + } + + //Seta a função a ser chamada quando a comunicação for feita e a resposta chegar + asyncRequest.onload = funcaoResposta; + + //Manda os dados, se ouver algum, ou Null se nada for especificado + asyncRequest.send(dados); + + } + catch(exception) + { + alert("Request Falho!"); + console.log(exception); + } +} + +function printarResposta(resposta){ + + //Fiz essa função aqui só pra printar os dados que forem recebidos de volta + console.log(resposta); +} + +function alertarResposta(resposta){ + + //E essa pra mostrar com um alerta + alert(resposta.srcElement.responseText); + console.log(resposta); +} + + +///////////////// +function get_cookie(name){ + return document.cookie.split(';').some(c => { + return c.trim().startsWith(name + '='); + }); +} + diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/sobre.html b/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/sobre.html new file mode 100644 index 0000000..39a4c2b --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/sobre.html @@ -0,0 +1,37 @@ + + + + + Cardápio + + + + + + + + + + +
+
+ + + +
+
+
+
+

Sobre o Projeto

+
+

Com o objetivo de desenvolver a capacidade dos alunos e obter nota na disciplina APS (Atividades Práticas Supervisionadas), foi proposto um projeto de desenvolvimento de um sistema para uma lanchonete online, onde o administrador consiga controlar os pedidos da lanchonete e emitir relatórios. A lanchonete devera permitir o cadastro dos usuários, para que eles possam realizar seus pedidos, e o cadastro de produtos, que ficariam por parte do administrador. Após o cadastro, cliente poderá utilizar os ingredientes cadastrados para criar seu lanche personalizado. O sistema deverá fazer o controle dos pedidos de forma que agrade os clientes, e controlar tambem o estoque de produtos.

+
+
+
+
+ + \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/styles.css b/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/styles.css new file mode 100644 index 0000000..317cc06 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/sobre/styles.css @@ -0,0 +1,127 @@ +body { + margin: 0px; + padding: 0px; +} + +#content { + display: flex; + flex-direction: column; + align-items: center; +} + +#top { + width: 100vw; + height: 10vh; + background-color: #F16262; + display: flex; + flex-direction: row; + align-items: center; + justify-content: space-between; + padding-left: 25px; +} + + + +.logo { + + width: 30vw; + height: 26vh; + margin-top: 20px; + border: none; + background-color: transparent; +} + +#imagemLogo2 { + width: 19vw; + height: 9vh; + position: relative; + left: -0.1vw; + top: 1.1vh; +} + + +.opcoes { + height: 8vh; + margin: 10px 25px 10px 25px; + position: relative; + top: 10%; + vertical-align: center; + color: white; + font-family: 'Sansita', sans-serif; + align-items: center; + font-size: 2vw; + white-space: nowrap; +} + +a { + padding: 0px; + margin: 0px; + text-decoration: none; + color: inherit; + font-family: 'Sansita', sans-serif; +} + +.opcoes:hover { + + padding-bottom: -30px; + border-bottom: 10px solid white; +} + + + + + +#background { + height: 88vh; + width: 100%; + background-color: white; + align-items: center; + background-image: url("../assets/fundoplano1.png"); + background-repeat: repeat; + background-size: auto; + display: flex; + justify-content: center; +} + +#screen { + width: 60vw; + height: 88vh; + background-color: white; + overflow-y: scroll; + scrollbar-color: white; + +} + +#screen::-webkit-scrollbar { + display: none; +} + +h1 { + text-align: center; + font-size: 32px; +} + +p { + font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; + font-size: 0.9em; + color: #555; + line-height: 1.8; + margin-left: 50px; + margin-right: 50px; + font-size: 16px; + text-align: justify; +} + +hr.solid { + border-top: 3px solid #bbb; + margin-left: 8vw; + margin-right: 8vw; + margin-bottom: 8vh; +} + +body { + height: 100vh; + margin: 0; + padding: 0; + overflow: hidden; +} \ No newline at end of file diff --git a/target/lanchonete-online-1.0-SNAPSHOT/view/styles/global.css b/target/lanchonete-online-1.0-SNAPSHOT/view/styles/global.css new file mode 100644 index 0000000..8b36cd8 --- /dev/null +++ b/target/lanchonete-online-1.0-SNAPSHOT/view/styles/global.css @@ -0,0 +1,75 @@ +:root { + font-size: 60%; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; + +} + +html, +body, +#root { + height: 100vh; + margin: 0; + padding: 0; + overflow: hidden; + +} + +body {} + +#root { + display: flex; + align-items: center; + justify-content: center; +} + +body, +input, +button, +textarea { + font: 500 1.6rem Poppins; +} + +.container { + width: 90vw; + max-width: 700px; +} + + +@media(min-width: 700px) { + :root { + font-size: 62.5%; + } +} + +.logo { + + width: 30vw; + height: 26vh; + margin-top: 20px; + border: none; + background-color: transparent; +} + +#imagemLogo2 { + width: 19vw; + height: 9vh; + position: relative; + left: -1.1vw; + top: 1.1vh; +} + +.containerLogo { + width: 20vw; + height: 10vh; + border-radius: 10px; + margin: 10px; + /* background-color: aqua; */ + position: relative; + left: -0.7vw; + top: -1vh; +} \ No newline at end of file diff --git a/target/maven-archiver/pom.properties b/target/maven-archiver/pom.properties new file mode 100644 index 0000000..6529bb4 --- /dev/null +++ b/target/maven-archiver/pom.properties @@ -0,0 +1,3 @@ +artifactId=lanchonete-online +groupId=com.lanchonete +version=1.0-SNAPSHOT diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..81d403f --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1,53 @@ +Controllers\getBebidasCliente.class +Controllers\loginFuncionario.class +Model\Endereco.class +Controllers\comprar.class +Controllers\salvarBebida.class +Model\RelatorioGastos.class +DAO\DaoPedido.class +Model\Pedido.class +DAO\DaoStatusLanchonete.class +DAO\DaoEndereco.class +Controllers\cadastro.class +Controllers\getCliente.class +Controllers\getIngredientesPorLanche.class +Controllers\salvarLancheCliente.class +DAO\DaoCliente.class +Controllers\salvarIngrediente.class +Model\RelatorioLanches.class +Controllers\salvarFuncionario.class +Controllers\validarTokenFunc.class +Controllers\logout.class +Controllers\getBebidas.class +DAO\DaoToken.class +DAO\DaoFuncionario.class +Controllers\login.class +Controllers\alterarBebida.class +Controllers\getLanchesCliente.class +Controllers\getLanches.class +Helpers\EncryptadorMD5.class +Controllers\getIngredientes.class +Model\Ingrediente.class +Controllers\getRelatorioLanches.class +Controllers\getStatusLanchonete.class +Controllers\removerBebida.class +Controllers\getRelatorioBebidas.class +Controllers\removerIngrediente.class +Controllers\tabela.class +Model\Cliente.class +Controllers\alterarIngrediente.class +Controllers\salvarLanche.class +Model\Funcionario.class +Model\Lanche.class +Controllers\getIngredientesCliente.class +Model\Bebida.class +DAO\DaoBebida.class +Model\RelatorioBebidas.class +DAO\DaoIngrediente.class +Controllers\validarToken.class +Controllers\getIngredientesPorLancheCliente.class +Controllers\alterarStatusLanchonete.class +DAO\DaoLanche.class +Helpers\ValidadorCookie.class +Controllers\getRelatorioGastos.class +DAO\DaoRelatorio.class diff --git a/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..27ffec5 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1,54 @@ +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\salvarBebida.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoBebida.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Ingrediente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Bebida.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getLanches.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\RelatorioLanches.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Helpers\ValidadorCookie.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\loginFuncionario.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\removerIngrediente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoUtil.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\cadastro.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\alterarBebida.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getRelatorioGastos.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Cliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\removerBebida.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getIngredientesPorLancheCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoFuncionario.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\validarTokenFunc.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\alterarIngrediente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getLanchesCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\RelatorioGastos.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\RelatorioBebidas.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Funcionario.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Pedido.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getRelatorioBebidas.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\login.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getIngredientesPorLanche.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoIngrediente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\comprar.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\salvarLanche.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoLanche.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoRelatorio.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\validarToken.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getRelatorioLanches.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Helpers\EncryptadorMD5.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getIngredientes.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Endereco.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\tabela.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoPedido.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\salvarFuncionario.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\alterarStatusLanchonete.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoToken.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Model\Lanche.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getIngredientesCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\logout.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getBebidas.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoEndereco.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\salvarLancheCliente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\DAO\DaoStatusLanchonete.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getStatusLanchonete.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\salvarIngrediente.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\java\Controllers\getBebidasCliente.java diff --git a/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst b/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst new file mode 100644 index 0000000..1805244 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/createdFiles.lst @@ -0,0 +1,4 @@ +DAO\DaoClienteTest.class +DAO\ClienteControllerTest$1.class +DAO\ClienteControllerTest$DelegatingServletInputStream.class +DAO\ClienteControllerTest.class diff --git a/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst b/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst new file mode 100644 index 0000000..c754a16 --- /dev/null +++ b/target/maven-status/maven-compiler-plugin/testCompile/default-testCompile/inputFiles.lst @@ -0,0 +1,2 @@ +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\test\java\DAO\ClienteControllerTest.java +C:\Users\daniel.pereira\IdeaProjects\APS-04-Lanchonete-Online-em-Java\src\test\java\DAO\DaoClienteTest.java diff --git a/target/surefire-reports/DAO.ClienteControllerTest.txt b/target/surefire-reports/DAO.ClienteControllerTest.txt new file mode 100644 index 0000000..aa4a583 --- /dev/null +++ b/target/surefire-reports/DAO.ClienteControllerTest.txt @@ -0,0 +1,4 @@ +------------------------------------------------------------------------------- +Test set: DAO.ClienteControllerTest +------------------------------------------------------------------------------- +Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.197 s - in DAO.ClienteControllerTest diff --git a/target/surefire-reports/DAO.DaoClienteTest.txt b/target/surefire-reports/DAO.DaoClienteTest.txt new file mode 100644 index 0000000..6972f7c --- /dev/null +++ b/target/surefire-reports/DAO.DaoClienteTest.txt @@ -0,0 +1,4 @@ +------------------------------------------------------------------------------- +Test set: DAO.DaoClienteTest +------------------------------------------------------------------------------- +Tests run: 10, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.78 s - in DAO.DaoClienteTest diff --git a/target/surefire-reports/TEST-DAO.ClienteControllerTest.xml b/target/surefire-reports/TEST-DAO.ClienteControllerTest.xml new file mode 100644 index 0000000..a3b3997 --- /dev/null +++ b/target/surefire-reports/TEST-DAO.ClienteControllerTest.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/target/surefire-reports/TEST-DAO.DaoClienteTest.xml b/target/surefire-reports/TEST-DAO.DaoClienteTest.xml new file mode 100644 index 0000000..da490b1 --- /dev/null +++ b/target/surefire-reports/TEST-DAO.DaoClienteTest.xml @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/target/test-classes/DAO/BebidaTest.class b/target/test-classes/DAO/BebidaTest.class new file mode 100644 index 0000000..9b65652 Binary files /dev/null and b/target/test-classes/DAO/BebidaTest.class differ diff --git a/target/test-classes/DAO/ClienteControllerTest$1.class b/target/test-classes/DAO/ClienteControllerTest$1.class new file mode 100644 index 0000000..ab6d8a9 Binary files /dev/null and b/target/test-classes/DAO/ClienteControllerTest$1.class differ diff --git a/target/test-classes/DAO/ClienteControllerTest$DelegatingServletInputStream.class b/target/test-classes/DAO/ClienteControllerTest$DelegatingServletInputStream.class new file mode 100644 index 0000000..d91fb14 Binary files /dev/null and b/target/test-classes/DAO/ClienteControllerTest$DelegatingServletInputStream.class differ diff --git a/target/test-classes/DAO/ClienteControllerTest.class b/target/test-classes/DAO/ClienteControllerTest.class new file mode 100644 index 0000000..432c16f Binary files /dev/null and b/target/test-classes/DAO/ClienteControllerTest.class differ diff --git a/target/test-classes/DAO/DaoClienteTest.class b/target/test-classes/DAO/DaoClienteTest.class new file mode 100644 index 0000000..d9112cb Binary files /dev/null and b/target/test-classes/DAO/DaoClienteTest.class differ diff --git a/target/webapp/WEB-INF/web.xml b/target/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..deea1d5 --- /dev/null +++ b/target/webapp/WEB-INF/web.xml @@ -0,0 +1,256 @@ + + + + cadastro + Controllers.cadastro + + + tabela + Controllers.tabela + + + login + Controllers.login + + + salvarIngrediente + Controllers.salvarIngrediente + + + salvarBebida + Controllers.salvarBebida + + + loginFuncionario + Controllers.loginFuncionario + + + getIngredientes + Controllers.getIngredientes + + + logout + Controllers.logout + + + getBebidas + Controllers.getBebidas + + + alterarIngrediente + Controllers.alterarIngrediente + + + alterarBebida + Controllers.alterarBebida + + + removerIngrediente + Controllers.removerIngrediente + + + removerBebida + Controllers.removerBebida + + + getLanches + Controllers.getLanches + + + getLanchesCliente + Controllers.getLanchesCliente + + + validarToken + Controllers.validarToken + + + getBebidasCliente + Controllers.getBebidasCliente + + + validarTokenFunc + Controllers.validarTokenFunc + + + salvarLanche + Controllers.salvarLanche + + + getIngredientesPorLanche + Controllers.getIngredientesPorLanche + + + getIngredientesPorLancheCliente + Controllers.getIngredientesPorLancheCliente + + + getCliente + Controllers.getCliente + + + comprar + Controllers.comprar + + + getRelatorioBebidas + Controllers.getRelatorioBebidas + + + getRelatorioGastos + Controllers.getRelatorioGastos + + + getRelatorioLanches + Controllers.getRelatorioLanches + + + getIngredientesCliente + Controllers.getIngredientesCliente + + + salvarLancheCliente + Controllers.salvarLancheCliente + + + salvarFuncionario + Controllers.salvarFuncionario + + + alterarStatusLanchonete + Controllers.alterarStatusLanchonete + + + getStatusLanchonete + Controllers.getStatusLanchonete + + + cadastro + /cadastro + + + tabela + /tabela + + + login + /login + + + salvarIngrediente + /salvarIngrediente + + + salvarBebida + /salvarBebida + + + loginFuncionario + /loginFuncionario + + + getIngredientes + /getIngredientes + + + logout + /logout + + + getBebidas + /getBebidas + + + alterarIngrediente + /alterarIngrediente + + + alterarBebida + /alterarBebida + + + removerIngrediente + /removerIngrediente + + + removerBebida + /removerBebida + + + getLanches + /getLanches + + + getLanchesCliente + /getLanchesCliente + + + validarToken + /validarToken + + + getBebidasCliente + /getBebidasCliente + + + validarTokenFunc + /validarTokenFunc + + + salvarLanche + /salvarLanche + + + getIngredientesPorLanche + /getIngredientesPorLanche + + + getIngredientesPorLancheCliente + /getIngredientesPorLancheCliente + + + getCliente + /getCliente + + + comprar + /comprar + + + getRelatorioBebidas + /getRelatorioBebidas + + + getRelatorioGastos + /getRelatorioGastos + + + getRelatorioLanches + /getRelatorioLanches + + + getIngredientesCliente + /getIngredientesCliente + + + salvarLancheCliente + /salvarLancheCliente + + + salvarFuncionario + /salvarFuncionario + + + alterarStatusLanchonete + /alterarStatusLanchonete + + + getStatusLanchonete + /getStatusLanchonete + + + + 30 + + +