diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a2a3040a --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/** +!**/src/test/** + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 00000000..72308aa4 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,114 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, +software distributed under the License is distributed on an +"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, either express or implied. See the License for the +specific language governing permissions and limitations +under the License. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader { + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 00000000..01e67997 Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..cd0d451c --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/README.md b/README.md index 15d8f685..b747e1ee 100644 --- a/README.md +++ b/README.md @@ -1,76 +1,113 @@ -# Show me the code - -### # DESAFIO: - -API REST para Gestão de Gastos! - -``` -Funcionalidade: Integração de gastos por cartão - Apenas sistemas credenciados poderão incluir novos gastos - É esperado um volume de 100.000 inclusões por segundo - Os gastos, serão informados atraves do protoloco JSON, seguindo padrão: - { "descricao": "alfanumerico", "valor": double americano, "codigousuario": numerico, "data": Data dem formato UTC } -``` -``` -Funcionalidade: Listagem de gastos* - Dado que acesso como um cliente autenticado que pode visualizar os gastos do cartão - Quando acesso a interface de listagem de gastos - Então gostaria de ver meus gastos mais atuais. - -*Para esta funcionalidade é esperado 2.000 acessos por segundo. -*O cliente espera ver gastos realizados a 5 segundos atrás. -``` -``` -Funcionalidade: Filtro de gastos - Dado que acesso como um cliente autenticado - E acessei a interface de listagem de gastos - E configure o filtro de data igual a 27/03/1992 - Então gostaria de ver meus gastos apenas deste dia. -``` -``` -Funcionalidade: Categorização de gastos - Dado que acesso como um cliente autenticado - Quando acesso o detalhe de um gasto - E este não possui uma categoria - Então devo conseguir incluir uma categoria para este -``` -``` -Funcionalidade: Sugestão de categoria - Dado que acesso como um cliente autenticado - Quando acesso o detalhe do gasto que não possui categoria - E começo a digitar a categoria que desejo - Então uma lista de sugestões de categoria deve ser exibida, estas baseadas em categorias já informadas por outro usuários. -``` -``` -Funcionalidade: Categorização automatica de gasto - No processo de integração de gastos, a categoria deve ser incluida automaticamente - caso a descrição de um gasto seja igual a descrição de qualquer outro gasto já categorizado pelo cliente - o mesmo deve receber esta categoria no momento da inclusão do mesmo -``` -### # Avaliação - -Você será avaliado pela usabilidade, por respeitar o design e pela arquitetura da API. -É esperado que você consiga explicar as decisões que tomou durante o desenvolvimento através de commits. - -* Springboot - Java - Maven (preferêncialmente) ([https://projects.spring.io/spring-boot/](https://projects.spring.io/spring-boot/)) -* RESTFul ([https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/](https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/)) -* DDD ([https://airbrake.io/blog/software-design/domain-driven-design](https://airbrake.io/blog/software-design/domain-driven-design)) -* Microservices ([https://martinfowler.com/microservices/](https://martinfowler.com/microservices/)) -* Testes unitários, teste o que achar importante (De preferência JUnit + Mockito). Mas pode usar o que você tem mais experiência, só nos explique o que ele tem de bom. -* SOAPUI para testes de carga ([https://www.soapui.org/load-testing/concept.html](https://www.soapui.org/load-testing/concept.html)) -* Uso de diferentes formas de armazenamento de dados (REDIS, Cassandra, Solr/Lucene) -* Uso do git -* Diferencial: Criptografia de comunicação, com troca de chaves. ([http://noiseprotocol.org/](http://noiseprotocol.org/)) -* Diferencial: CQRS ([https://martinfowler.com/bliki/CQRS.html](https://martinfowler.com/bliki/CQRS.html)) -* Diferencial: Docker File + Docker Compose (com dbs) para rodar seus jars. - -### # Observações gerais - -Adicione um arquivo [README.md](http://README.md) com os procedimentos para executar o projeto. -Pedimos que trabalhe sozinho e não divulgue o resultado na internet. - -Faça um fork desse desse repositório em seu Github e nos envie um Pull Request com o resultado, por favor informe por qual empresa você esta se candidatando. - -### # Importante: não há prazo de entrega, faça com qualidade! - -# BOA SORTE! +# Show me the code + +### # Instruções para rodar o Projeto: + +Baixar o projeto na máquina local. +No CMD navegar até a pasta do projeto. +rodar o comando mvn spring-boot:run +(É necessário ter o maven instalado no computador). + +A Aplicação irá iniciar e já estará pronta para receber requisiões. +(O banco utilizado foi o banco em memória H2 para facilitar o uso. Não é necessária configuração). + +Funcionalidade: Login +EndPoint: (POST) /auth: +(Irá retornar o Bearer Token necessário para todas próximas requisições) +``` +Exemplo de JSON: +{ + "email": "user@email.com", + "password": "123456" +} +``` + +Funcionalidade: Integração de gastos por cartão +EndPoint: (POST) "/gastos": +(Retorna status 200 OK) + +``` + Exemplo de JSON: +[ + { + "descricao": "Novo Gasto", + "valor": 999.99, + "codigousuario": 1, + "data": "2013-08-12T18:00:00" + }, + { + "descricao": "Compras Mensais Extra", + "valor": 29.99, + "codigousuario": 1, + "data": "1999-08-12T18:00:00" + } +] +``` + +Funcionalidade: Detalhes do Gasto +EndPoint: (GET) "/gastos/{id}": +(Retorna Dados do gasto do usuário autenticado conforme id passado) +``` +Não é necessário passar nehum dado no corpo da requisição +``` + +Funcionalidade: Listagem de gastos +EndPoint: (GET) "/gastos": +(Retorna JSON com Gastos do Usuário que fez a requisição) +``` +Não é necessário passar nehum dado no corpo da requisição +``` + +Funcionalidade: Filtro de gastos por Data +EndPoint: GET "/gastos?data" +(Retorna JSON com Gastos do Usuário para a data passada) +``` +Exemplo de Requisição: "/gastos?data=2019-08-04" +``` + +Funcionalidade: Categorização de gastos +EndPoint: (POST) "/gastos/{id}" (id do gasto) +(Retorna status 200 OK) +``` + Exemplo de JSON: +{ + "descricao": "Alimentacao" +} +``` +Funcionalidade: Sugestão de categoria +EndPoint: (GET) "/categorias/{descricao}" (descricao da categoria. Não é neccesário a descrição completa.) +(Retorna sugestão de categoria) +``` +Não é necessário passar nehum dado no corpo da requisição +``` + +Funcionalidade: Categorização automatica de gasto +``` +Está implementada no momento de integração dos gastos +``` +### # Avaliação + +Você será avaliado pela usabilidade, por respeitar o design e pela arquitetura da API. +É esperado que você consiga explicar as decisões que tomou durante o desenvolvimento através de commits. + +* Springboot - Java - Maven (preferêncialmente) ([https://projects.spring.io/spring-boot/](https://projects.spring.io/spring-boot/)) +* RESTFul ([https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/](https://blog.mwaysolutions.com/2014/06/05/10-best-practices-for-better-restful-api/)) +* DDD ([https://airbrake.io/blog/software-design/domain-driven-design](https://airbrake.io/blog/software-design/domain-driven-design)) +* Microservices ([https://martinfowler.com/microservices/](https://martinfowler.com/microservices/)) +* Testes unitários, teste o que achar importante (De preferência JUnit + Mockito). Mas pode usar o que você tem mais experiência, só nos explique o que ele tem de bom. +* SOAPUI para testes de carga ([https://www.soapui.org/load-testing/concept.html](https://www.soapui.org/load-testing/concept.html)) +* Uso de diferentes formas de armazenamento de dados (REDIS, Cassandra, Solr/Lucene) +* Uso do git +* Diferencial: Criptografia de comunicação, com troca de chaves. ([http://noiseprotocol.org/](http://noiseprotocol.org/)) +* Diferencial: CQRS ([https://martinfowler.com/bliki/CQRS.html](https://martinfowler.com/bliki/CQRS.html)) +* Diferencial: Docker File + Docker Compose (com dbs) para rodar seus jars. + +### # Observações gerais + +Adicione um arquivo [README.md](http://README.md) com os procedimentos para executar o projeto. +Pedimos que trabalhe sozinho e não divulgue o resultado na internet. + +Faça um fork desse desse repositório em seu Github e nos envie um Pull Request com o resultado, por favor informe por qual empresa você esta se candidatando. + +### # Importante: não há prazo de entrega, faça com qualidade! + +# BOA SORTE! diff --git a/mvnw b/mvnw new file mode 100644 index 00000000..8b9da3b8 --- /dev/null +++ b/mvnw @@ -0,0 +1,286 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 00000000..fef5a8f7 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,161 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..86c2c1e1 --- /dev/null +++ b/pom.xml @@ -0,0 +1,81 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.7.RELEASE + + + br.com.santander + gastos + 0.0.1-SNAPSHOT + gastos + Demo project for Spring Boot + + + 1.8 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-cache + + + + org.springframework.boot + spring-boot-starter-security + + + + io.jsonwebtoken + jjwt + 0.9.1 + + + + com.h2database + h2 + + + + org.springframework.boot + spring-boot-starter-data-redis + 2.1.2.RELEASE + + + + org.springframework.boot + spring-boot-devtools + runtime + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/br/com/santander/gastos/GastosApplication.java b/src/main/java/br/com/santander/gastos/GastosApplication.java new file mode 100644 index 00000000..eb2d5ee6 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/GastosApplication.java @@ -0,0 +1,15 @@ +package br.com.santander.gastos; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.web.config.EnableSpringDataWebSupport; + +@SpringBootApplication +@EnableSpringDataWebSupport +public class GastosApplication { + + public static void main(String[] args) { + SpringApplication.run(GastosApplication.class, args); + } + +} diff --git a/src/main/java/br/com/santander/gastos/config/security/AuthService.java b/src/main/java/br/com/santander/gastos/config/security/AuthService.java new file mode 100644 index 00000000..af19edec --- /dev/null +++ b/src/main/java/br/com/santander/gastos/config/security/AuthService.java @@ -0,0 +1,33 @@ +package br.com.santander.gastos.config.security; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; + +import br.com.santander.gastos.model.User; +import br.com.santander.gastos.repository.UserRepository; + + +@Service +public class AuthService implements UserDetailsService { + + @Autowired + private UserRepository userRepository; + + @Override + public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { + + Optional user = userRepository.findByEmail(email); + + if(user.isPresent()){ + return user.get(); + } + + throw new UsernameNotFoundException("User not found."); + } + +} diff --git a/src/main/java/br/com/santander/gastos/config/security/SecurityConfigurations.java b/src/main/java/br/com/santander/gastos/config/security/SecurityConfigurations.java new file mode 100644 index 00000000..1ac1c9b6 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/config/security/SecurityConfigurations.java @@ -0,0 +1,63 @@ +package br.com.santander.gastos.config.security; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; + +import br.com.santander.gastos.repository.UserRepository; + +@EnableWebSecurity +@Configuration +public class SecurityConfigurations extends WebSecurityConfigurerAdapter { + + @Autowired + AuthService authService; + + @Autowired + private TokenService tokenService; + + @Autowired + private UserRepository userRepository; + + @Override + @Bean + protected AuthenticationManager authenticationManager() throws Exception { + return super.authenticationManager(); + } + + //Autenticação + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.userDetailsService(authService).passwordEncoder(new BCryptPasswordEncoder()); + } + + //Autorização + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers(HttpMethod.POST, "/auth").permitAll() + .antMatchers("/h2-console/**").permitAll() + .anyRequest().authenticated() + .and().headers().frameOptions().sameOrigin() + .and().cors() + .and().csrf().disable() + .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + .and().addFilterBefore(new TokenAuthFilter(tokenService, userRepository), UsernamePasswordAuthenticationFilter.class); + } + + //Arquivos (js, css, jpg) + @Override + public void configure(WebSecurity web) throws Exception { + web.ignoring().antMatchers("/**.html", "/v2/api-docs", "/webjars/**", "/configuration/**", "/swagger-resources/**"); + } +} diff --git a/src/main/java/br/com/santander/gastos/config/security/TokenAuthFilter.java b/src/main/java/br/com/santander/gastos/config/security/TokenAuthFilter.java new file mode 100644 index 00000000..50c576f4 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/config/security/TokenAuthFilter.java @@ -0,0 +1,71 @@ +package br.com.santander.gastos.config.security; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.OncePerRequestFilter; + +import br.com.santander.gastos.model.User; +import br.com.santander.gastos.repository.UserRepository; + +public class TokenAuthFilter extends OncePerRequestFilter { + + private TokenService tokenService; + + private UserRepository userRepository; + + + public TokenAuthFilter(TokenService tokenService, UserRepository userRepository) { + this.tokenService = tokenService; + this.userRepository = userRepository; + } + + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) + throws ServletException, IOException { + + String token = getToken(request); + + boolean isValid = tokenService.isTokenValid(token); + + if(isValid){ + authenticateClient(token); + } + + filterChain.doFilter(request, response); + } + + + private void authenticateClient(String token) { + + Long userId = tokenService.getUserId(token); + + User user = userRepository.findById(userId).get(); + + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); + + SecurityContextHolder.getContext().setAuthentication(authentication); + } + + + private String getToken(HttpServletRequest request) { + + String token = request.getHeader("Authorization"); + + if(token == null || token.isEmpty() || !token.startsWith("Bearer ")){ + return null; + } + + return token.substring(7, token.length()); + } + + + +} diff --git a/src/main/java/br/com/santander/gastos/config/security/TokenService.java b/src/main/java/br/com/santander/gastos/config/security/TokenService.java new file mode 100644 index 00000000..13cfefa8 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/config/security/TokenService.java @@ -0,0 +1,57 @@ +package br.com.santander.gastos.config.security; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; + +import java.util.Date; + +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.stereotype.Service; + +import br.com.santander.gastos.model.User; + + +@Service +public class TokenService { + + @Value("${gastos.jwt.expiration}") + private String expiration; + + @Value("${gastos.jwt.secret}") + private String secret; + + public String generateToken(Authentication authentication) { + + User loggedUser = (User) authentication.getPrincipal(); + Date today = new Date(); + Date expirationDate = new Date(today.getTime() + Long.valueOf(expiration)); + + return Jwts.builder() + .setIssuer("API do Fórum") + .setSubject(loggedUser.getId().toString()) + .setIssuedAt(today) + .setExpiration(expirationDate) + .signWith(SignatureAlgorithm.HS256, secret) + .compact(); + + } + + public boolean isTokenValid(String token) { + + try { + Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token); + + return true; + } catch (Exception e) { + return false; + } + } + + public Long getUserId(String token) { + Claims claims = Jwts.parser().setSigningKey(this.secret).parseClaimsJws(token).getBody(); + + return Long.valueOf(claims.getSubject()); + } +} diff --git a/src/main/java/br/com/santander/gastos/controller/AuthController.java b/src/main/java/br/com/santander/gastos/controller/AuthController.java new file mode 100644 index 00000000..6c17a632 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/AuthController.java @@ -0,0 +1,46 @@ +package br.com.santander.gastos.controller; + +import javax.validation.Valid; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.AuthenticationException; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import br.com.santander.gastos.config.security.TokenService; +import br.com.santander.gastos.controller.form.LoginForm; +import br.com.santander.gastos.vo.TokenVO; + +@RestController +@RequestMapping("/auth") +public class AuthController { + + @Autowired + private AuthenticationManager authManager; + + @Autowired + private TokenService tokenService; + + @PostMapping + public ResponseEntity auth(@RequestBody @Valid LoginForm form) { + UsernamePasswordAuthenticationToken dadosLogin = form.converter(); + + try { + Authentication authentication = authManager.authenticate(dadosLogin); + + String token = tokenService.generateToken(authentication); + + return ResponseEntity.ok(new TokenVO(token, "Bearer")); + + } catch (AuthenticationException e) { + return ResponseEntity.badRequest().build(); + } + + } +} diff --git a/src/main/java/br/com/santander/gastos/controller/CategoriaController.java b/src/main/java/br/com/santander/gastos/controller/CategoriaController.java new file mode 100644 index 00000000..05a0edf7 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/CategoriaController.java @@ -0,0 +1,31 @@ +package br.com.santander.gastos.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import br.com.santander.gastos.service.CategoriaService; +import br.com.santander.gastos.vo.CategoriaVO; + +@RestController +@RequestMapping("/categorias") +public class CategoriaController { + + @Autowired + CategoriaService categoriaService; + + @GetMapping("/{descricao}") + public ResponseEntity> sugestaoCategoria(@PathVariable String descricao){ + + List listaCategorias = categoriaService.findByDescricao(descricao); + + return new ResponseEntity<>(listaCategorias, HttpStatus.OK); + } + +} diff --git a/src/main/java/br/com/santander/gastos/controller/GastosController.java b/src/main/java/br/com/santander/gastos/controller/GastosController.java new file mode 100644 index 00000000..3494f6c8 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/GastosController.java @@ -0,0 +1,115 @@ +package br.com.santander.gastos.controller; + +import java.util.List; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import br.com.santander.gastos.controller.form.CategoriaForm; +import br.com.santander.gastos.controller.form.GastoForm; +import br.com.santander.gastos.model.Gasto; +import br.com.santander.gastos.model.User; +import br.com.santander.gastos.repository.CategoriaRepository; +import br.com.santander.gastos.repository.GastoRepository; +import br.com.santander.gastos.repository.UserRepository; +import br.com.santander.gastos.service.GastoService; +import br.com.santander.gastos.service.UserService; +import br.com.santander.gastos.vo.GastoVO; + +@RestController +@RequestMapping("/gastos") +public class GastosController { + + @Autowired + private GastoRepository gastoRepository; + + @Autowired + private CategoriaRepository categoriaRepository; + + @Autowired + private UserRepository userRepository; + + @Autowired + private GastoService gastoService; + + @Autowired + private UserService userService; + + @GetMapping + @ResponseBody + public ResponseEntity> listarGastos(@RequestParam(required = false) String data) { + + String userName = userService.getUsuarioLogado(); + + Optional user = userService.findByEmail(userName); + + List listaGastos; + if(data == null) { + listaGastos = gastoService.findByIdUsuarioOrderByDataDesc(user.get().getId()); + + return new ResponseEntity<>(GastoVO.converter(listaGastos), HttpStatus.OK); + }else { + listaGastos = gastoService.findByDate(user.get().getId(), data); + + return new ResponseEntity<>(GastoVO.converter(listaGastos), HttpStatus.OK); + } + + } + + @GetMapping("/{id}") + public ResponseEntity detalhar(@PathVariable Long id) { + + String userName = userService.getUsuarioLogado(); + + Optional user = userService.findByEmail(userName); + + Optional gasto = gastoService.findById(user.get().getId(), id); + + if(gasto.isPresent()) { + return ResponseEntity.ok(new GastoVO(gasto.get())); + } + + return ResponseEntity.notFound().build(); + } + + @PostMapping(consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) + @Transactional + public ResponseEntity cadastrarGasto(@RequestBody List listaGastos) { + + for(GastoForm gasto : listaGastos){ + Gasto novoGasto = gasto.converter(); + gastoService.save(novoGasto); + } + return ResponseEntity.status(HttpStatus.OK).build(); + } + + @PostMapping("/{id}") + public ResponseEntity AssociarCategoria(@PathVariable Long id, @RequestBody CategoriaForm categoria) { + + String userName = userService.getUsuarioLogado(); + + Optional user = userService.findByEmail(userName); + + Optional gasto = gastoService.findById(user.get().getId(), id); + + if(gasto.isPresent()){ + if(gasto.get().getCategoria() == null) { + gasto = categoria.incluirCategoria(gasto, gastoRepository, categoriaRepository); + gastoService.save(gasto.get()); + } + } + return ResponseEntity.status(HttpStatus.OK).build(); + } +} diff --git a/src/main/java/br/com/santander/gastos/controller/form/CategoriaForm.java b/src/main/java/br/com/santander/gastos/controller/form/CategoriaForm.java new file mode 100644 index 00000000..eda58771 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/form/CategoriaForm.java @@ -0,0 +1,42 @@ +package br.com.santander.gastos.controller.form; + +import java.util.Optional; + +import br.com.santander.gastos.model.Categoria; +import br.com.santander.gastos.model.Gasto; +import br.com.santander.gastos.repository.CategoriaRepository; +import br.com.santander.gastos.repository.GastoRepository; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class CategoriaForm { + + @JsonProperty("descricao") + private String descricao; + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + this.descricao = descricao; + } + + public Optional incluirCategoria(Optional gasto, GastoRepository gastoRepository, CategoriaRepository categoriaRepository) { + + Categoria cat = categoriaRepository.findByDescricao(this.descricao); + + if(cat != null){ + gasto.get().setCategoria(cat); + }else{ + cat = new Categoria(); + cat.setDescricao(this.descricao); + + categoriaRepository.save(cat); + + gasto.get().setCategoria(cat); + } + + return gasto; + } +} diff --git a/src/main/java/br/com/santander/gastos/controller/form/GastoForm.java b/src/main/java/br/com/santander/gastos/controller/form/GastoForm.java new file mode 100644 index 00000000..a830c861 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/form/GastoForm.java @@ -0,0 +1,54 @@ +package br.com.santander.gastos.controller.form; + +import java.time.LocalDateTime; + +import br.com.santander.gastos.model.Gasto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; + +public class GastoForm { + + @JsonProperty("descricao") + private String descricao; + + @JsonProperty("valor") + private double valor; + + @JsonProperty("codigousuario") + private Long codigousuario; + + @JsonProperty("data") + @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") + private LocalDateTime data; + + public Gasto converter() { + return new Gasto(this.getCodigoUsuario(), this.getData(), this.getValor(), this.getDescricao(), null); + } + + public String getDescricao() { + return descricao; + } + public void setDescricao(String descricao) { + this.descricao = descricao; + } + public double getValor() { + return valor; + } + public void setValor(double valor) { + this.valor = valor; + } + public Long getCodigoUsuario() { + return codigousuario; + } + public void setCodigoUsuario(Long codigousuario) { + this.codigousuario = codigousuario; + } + public LocalDateTime getData() { + return data; + } + public void setData(LocalDateTime data) { + this.data = data; + } + +} diff --git a/src/main/java/br/com/santander/gastos/controller/form/LoginForm.java b/src/main/java/br/com/santander/gastos/controller/form/LoginForm.java new file mode 100644 index 00000000..59523cd0 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/controller/form/LoginForm.java @@ -0,0 +1,26 @@ +package br.com.santander.gastos.controller.form; + +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; + +public class LoginForm { + + private String email; + private String password; + + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + public UsernamePasswordAuthenticationToken converter() { + return new UsernamePasswordAuthenticationToken(email,password); + } +} diff --git a/src/main/java/br/com/santander/gastos/model/Categoria.java b/src/main/java/br/com/santander/gastos/model/Categoria.java new file mode 100644 index 00000000..0e5ea27f --- /dev/null +++ b/src/main/java/br/com/santander/gastos/model/Categoria.java @@ -0,0 +1,32 @@ +package br.com.santander.gastos.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class Categoria { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String descricao; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + this.descricao = descricao; + } + +} diff --git a/src/main/java/br/com/santander/gastos/model/Gasto.java b/src/main/java/br/com/santander/gastos/model/Gasto.java new file mode 100644 index 00000000..19d5477d --- /dev/null +++ b/src/main/java/br/com/santander/gastos/model/Gasto.java @@ -0,0 +1,88 @@ +package br.com.santander.gastos.model; + +import java.time.LocalDateTime; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; + +@Entity +public class Gasto { + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long Id; + + private Long idUsuario; + + private LocalDateTime data; + + private double valor; + + private String descricao; + + @ManyToOne + private Categoria categoria; + + + public Gasto(){ + + } + + public Gasto(Long idUsuario, LocalDateTime data, double valor, String descricao, Categoria categoria) { + this.idUsuario = idUsuario; + this.data = data; + this.valor = valor; + this.descricao = descricao; + this.categoria = categoria; + } + + public Long getId() { + return Id; + } + + public void setId(Long id) { + Id = id; + } + + public Long getIdUsuario() { + return idUsuario; + } + + public void setIdUsuario(Long idUsuario) { + this.idUsuario = idUsuario; + } + + public LocalDateTime getData() { + return data; + } + + public void setData(LocalDateTime data) { + this.data = data; + } + + public double getValor() { + return valor; + } + + public void setValor(double valor) { + this.valor = valor; + } + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + this.descricao = descricao; + } + + public Categoria getCategoria() { + return categoria; + } + + public void setCategoria(Categoria categoria) { + this.categoria = categoria; + } +} diff --git a/src/main/java/br/com/santander/gastos/model/Profile.java b/src/main/java/br/com/santander/gastos/model/Profile.java new file mode 100644 index 00000000..76681ad4 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/model/Profile.java @@ -0,0 +1,39 @@ +package br.com.santander.gastos.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +import org.springframework.security.core.GrantedAuthority; + +@Entity +public class Profile implements GrantedAuthority { + + private static final long serialVersionUID = -6683879421499369119L; + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + + @Override + public String getAuthority() { + return name; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/src/main/java/br/com/santander/gastos/model/User.java b/src/main/java/br/com/santander/gastos/model/User.java new file mode 100644 index 00000000..eb96daa0 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/model/User.java @@ -0,0 +1,148 @@ +package br.com.santander.gastos.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.FetchType; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + + +@Entity +public class User implements UserDetails { + + private static final long serialVersionUID = -5617909948372378386L; + + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + private String email; + private String password; + private String cpf; + + @ManyToMany(fetch = FetchType.EAGER) + private List profiles = new ArrayList<>(); + + public User() { + } + + public User (String name, String email, String password, String cpf) { + this.name = name; + this.email = email; + this.password = new BCryptPasswordEncoder().encode(password); + this.cpf = cpf; + } + + @Override + public Collection getAuthorities() { + return this.profiles; + } + + @Override + public String getPassword() { + return this.password; + } + + @Override + public String getUsername() { + return this.email; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getCpf() { + return cpf; + } + + public void setCpf(String cpf) { + this.cpf = cpf; + } + + public void setPassword(String password) { + this.password = password; + } + + public List getProfiles() { + return profiles; + } + + public void setProfiles(List profiles) { + this.profiles = profiles; + } + +} diff --git a/src/main/java/br/com/santander/gastos/repository/CategoriaRepository.java b/src/main/java/br/com/santander/gastos/repository/CategoriaRepository.java new file mode 100644 index 00000000..2c707dec --- /dev/null +++ b/src/main/java/br/com/santander/gastos/repository/CategoriaRepository.java @@ -0,0 +1,17 @@ +package br.com.santander.gastos.repository; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import br.com.santander.gastos.model.Categoria; + +public interface CategoriaRepository extends JpaRepository { + + Categoria findByDescricao(String descricao); + + @Query("SELECT c FROM Categoria c WHERE UPPER(c.descricao) LIKE CONCAT('%',UPPER(:descricao),'%')") + List findCategoriasByDescricao(@Param("descricao") String descricao); +} diff --git a/src/main/java/br/com/santander/gastos/repository/GastoRepository.java b/src/main/java/br/com/santander/gastos/repository/GastoRepository.java new file mode 100644 index 00000000..bba0bddc --- /dev/null +++ b/src/main/java/br/com/santander/gastos/repository/GastoRepository.java @@ -0,0 +1,24 @@ +package br.com.santander.gastos.repository; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; + +import br.com.santander.gastos.model.Gasto; + +public interface GastoRepository extends JpaRepository { + + List findByIdUsuarioOrderByDataDesc(Long id); + + @Query("SELECT g FROM Gasto g WHERE g.idUsuario = :id AND g.data >= :date AND g.data <= :dateFim order by g.data DESC") + List findGastosByDate(@Param("id") Long id, @Param("date") LocalDateTime date, @Param("dateFim") LocalDateTime dateFim); + + @Query("SELECT g FROM Gasto g WHERE g.idUsuario = :idUsuario AND g.id = :idGasto") + Optional findById(@Param("idUsuario") Long idUsuario, @Param("idGasto") Long idGasto); + + Optional findFirstByDescricao(String descricao); +} diff --git a/src/main/java/br/com/santander/gastos/repository/UserRepository.java b/src/main/java/br/com/santander/gastos/repository/UserRepository.java new file mode 100644 index 00000000..6fa274e0 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/repository/UserRepository.java @@ -0,0 +1,12 @@ +package br.com.santander.gastos.repository; + +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import br.com.santander.gastos.model.User; + +public interface UserRepository extends JpaRepository { + + Optional findByEmail(String email); +} diff --git a/src/main/java/br/com/santander/gastos/service/CategoriaService.java b/src/main/java/br/com/santander/gastos/service/CategoriaService.java new file mode 100644 index 00000000..735b28b3 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/CategoriaService.java @@ -0,0 +1,12 @@ +package br.com.santander.gastos.service; + +import java.util.List; + +import br.com.santander.gastos.vo.CategoriaVO; + + +public interface CategoriaService { + + List findByDescricao(String descricao); + +} diff --git a/src/main/java/br/com/santander/gastos/service/CategoriaServiceImpl.java b/src/main/java/br/com/santander/gastos/service/CategoriaServiceImpl.java new file mode 100644 index 00000000..688c8db8 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/CategoriaServiceImpl.java @@ -0,0 +1,26 @@ +package br.com.santander.gastos.service; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import br.com.santander.gastos.model.Categoria; +import br.com.santander.gastos.repository.CategoriaRepository; +import br.com.santander.gastos.vo.CategoriaVO; + +@Service +public class CategoriaServiceImpl implements CategoriaService { + + @Autowired + CategoriaRepository categoriaRepository; + + @Override + public List findByDescricao(String descricao) { + List listaCategorias = categoriaRepository.findCategoriasByDescricao(descricao); + + List listaCategoriasVO = CategoriaVO.converter(listaCategorias); + + return listaCategoriasVO; + } +} diff --git a/src/main/java/br/com/santander/gastos/service/GastoService.java b/src/main/java/br/com/santander/gastos/service/GastoService.java new file mode 100644 index 00000000..7416ffea --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/GastoService.java @@ -0,0 +1,18 @@ +package br.com.santander.gastos.service; + +import java.util.List; +import java.util.Optional; + +import br.com.santander.gastos.model.Gasto; + +public interface GastoService { + + List findByIdUsuarioOrderByDataDesc(Long id); + + List findByDate(Long id, String data); + + Optional findById(Long userId, Long gastoId); + + void save(Gasto novoGasto); + +} diff --git a/src/main/java/br/com/santander/gastos/service/GastoServiceImpl.java b/src/main/java/br/com/santander/gastos/service/GastoServiceImpl.java new file mode 100644 index 00000000..f7e0b25e --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/GastoServiceImpl.java @@ -0,0 +1,80 @@ +package br.com.santander.gastos.service; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.ZoneId; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import br.com.santander.gastos.model.Gasto; +import br.com.santander.gastos.repository.GastoRepository; + +@Service +public class GastoServiceImpl implements GastoService { + + Date date = new Date(); + Date dateFim = new Date(); + + + @Autowired + private GastoRepository gastoRepository; + + @Override + public List findByIdUsuarioOrderByDataDesc(Long id) { + return gastoRepository.findByIdUsuarioOrderByDataDesc(id); + } + + @Override + public List findByDate(Long userId, String data) { + + tratarDatas(data); + + return gastoRepository.findGastosByDate(userId, + date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(), + dateFim.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()); + } + + private void tratarDatas(String data) { + + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + + try { + date = sdf.parse(data); + } catch (ParseException e) { + System.out.println("Erro ao converter data: " + e.getMessage()); + } + + Calendar dateEnd = new GregorianCalendar(); + dateEnd.setTime(date); + dateEnd.set(Calendar.HOUR, 23); + dateEnd.set(Calendar.MINUTE, 59); + dateEnd.set(Calendar.SECOND, 59); + dateFim = dateEnd.getTime(); + + } + + @Override + public Optional findById(Long userId, Long gastoId) { + return gastoRepository.findById(userId, gastoId); + } + + @Override + public void save(Gasto novoGasto) { + + if(novoGasto.getDescricao() != null && !novoGasto.getDescricao().isEmpty()) { + + Optional listaGasto = gastoRepository.findFirstByDescricao(novoGasto.getDescricao()); + + listaGasto.ifPresent(g -> novoGasto.setCategoria(g.getCategoria())); + } + + gastoRepository.save(novoGasto); + } + +} diff --git a/src/main/java/br/com/santander/gastos/service/UserService.java b/src/main/java/br/com/santander/gastos/service/UserService.java new file mode 100644 index 00000000..1e3abb77 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/UserService.java @@ -0,0 +1,13 @@ +package br.com.santander.gastos.service; + +import java.util.Optional; + +import br.com.santander.gastos.model.User; + +public interface UserService { + + String getUsuarioLogado(); + + Optional findByEmail(String userName); + +} diff --git a/src/main/java/br/com/santander/gastos/service/UserServiceImpl.java b/src/main/java/br/com/santander/gastos/service/UserServiceImpl.java new file mode 100644 index 00000000..77646ec1 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/service/UserServiceImpl.java @@ -0,0 +1,38 @@ +package br.com.santander.gastos.service; + +import java.util.Optional; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Service; + +import br.com.santander.gastos.model.User; +import br.com.santander.gastos.repository.UserRepository; + +@Service +public class UserServiceImpl implements UserService { + + @Autowired + private UserRepository userRepository; + + @Override + public String getUsuarioLogado() { + + Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); + + if(principal instanceof UserDetails) { + return ((UserDetails) principal).getUsername(); + } else { + return principal.toString(); + } + + } + + @Override + public Optional findByEmail(String userName) { + + return userRepository.findByEmail(userName); + } + +} diff --git a/src/main/java/br/com/santander/gastos/vo/CategoriaVO.java b/src/main/java/br/com/santander/gastos/vo/CategoriaVO.java new file mode 100644 index 00000000..a3c9f4fe --- /dev/null +++ b/src/main/java/br/com/santander/gastos/vo/CategoriaVO.java @@ -0,0 +1,34 @@ +package br.com.santander.gastos.vo; + +import java.util.List; +import java.util.stream.Collectors; + +import br.com.santander.gastos.model.Categoria; + +public class CategoriaVO { + + private Long id; + private String descricao; + + public CategoriaVO(Categoria categoria) { + this.id = categoria.getId(); + this.descricao = categoria.getDescricao(); + } + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + public String getDescricao() { + return descricao; + } + public void setDescricao(String descricao) { + this.descricao = descricao; + } + + public static List converter(List listaCategorias) { + return listaCategorias.stream().map(CategoriaVO::new).collect(Collectors.toList()); + } +} diff --git a/src/main/java/br/com/santander/gastos/vo/GastoVO.java b/src/main/java/br/com/santander/gastos/vo/GastoVO.java new file mode 100644 index 00000000..843e2b34 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/vo/GastoVO.java @@ -0,0 +1,89 @@ +package br.com.santander.gastos.vo; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +import br.com.santander.gastos.model.Categoria; +import br.com.santander.gastos.model.Gasto; + +public class GastoVO { + + private Long id; + + private Long idUsuario; + + private LocalDateTime data; + + private double valor; + + private String descricao; + + private Categoria categoria; + + public GastoVO(Gasto gasto){ + this.id = gasto.getId(); + this.idUsuario = gasto.getIdUsuario(); + this.data = gasto.getData(); + this.valor = gasto.getValor(); + this.descricao = gasto.getDescricao(); + this.categoria = new Categoria(); + if(gasto.getCategoria() != null){ + this.categoria.setId(gasto.getCategoria().getId()); + this.categoria.setDescricao(gasto.getCategoria().getDescricao()); + } + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Long getIdUsuario() { + return idUsuario; + } + + public void setIdUsuario(Long idUsuario) { + this.idUsuario = idUsuario; + } + + public LocalDateTime getData() { + return data; + } + + public void setData(LocalDateTime data) { + this.data = data; + } + + public double getValor() { + return valor; + } + + public void setValor(double valor) { + this.valor = valor; + } + + public String getDescricao() { + return descricao; + } + + public void setDescricao(String descricao) { + this.descricao = descricao; + } + + public static List converter(List listaGastos) { + return listaGastos.stream().map(GastoVO::new).collect(Collectors.toList()); + } + + public Categoria getCategoria() { + return categoria; + } + + public void setCategoria(Categoria categoria) { + this.categoria = categoria; + } + +} diff --git a/src/main/java/br/com/santander/gastos/vo/TokenVO.java b/src/main/java/br/com/santander/gastos/vo/TokenVO.java new file mode 100644 index 00000000..204d8047 --- /dev/null +++ b/src/main/java/br/com/santander/gastos/vo/TokenVO.java @@ -0,0 +1,20 @@ +package br.com.santander.gastos.vo; + +public class TokenVO { + + private String type; + private String token; + + public TokenVO(String token, String type) { + this.token = token; + this.type = type; + } + + public String getType() { + return type; + } + + public String getToken() { + return token; + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 00000000..c3929e7b --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,17 @@ +# Datasource +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.url=jdbc:h2:mem:gastos +spring.datasource.username=sa +spring.datasource.password= + +# Jpa +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=update + +# H2 +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +# Jwt +gastos.jwt.secret=n18beizXILyC5WtDJUAnIIMczoh8X0uY3nrVTjFENqrJpPCtckx5nt5CHw62 +gastos.jwt.expiration=172800000 diff --git a/src/main/resources/data.sql b/src/main/resources/data.sql new file mode 100644 index 00000000..6857c5da --- /dev/null +++ b/src/main/resources/data.sql @@ -0,0 +1,39 @@ +INSERT INTO USER(name, email, password, cpf) +VALUES('Rafael', 'rafael@gmail.com', '$2a$10$mnDScYY5JddnRUG.kbqSK.0tBPu5DW4DQe64liAC0Ztd4x1N3hBfi', '13630757723'); + +INSERT INTO USER(name, email, password, cpf) +VALUES('User', 'user@email.com', '$2a$10$mnDScYY5JddnRUG.kbqSK.0tBPu5DW4DQe64liAC0Ztd4x1N3hBfi', '13630757723'); + +INSERT INTO CATEGORIA(descricao) VALUES ('Transporte'); +INSERT INTO CATEGORIA(descricao) VALUES ('Alimentacao'); +INSERT INTO CATEGORIA(descricao) VALUES ('Saude'); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (1, '2019-05-05 18:00:00', 149.99, 'Compras Mensais Extra', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (1, '2019-08-04 18:00:00', 29.99, 'Compras Lojas Americanas', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (1, '2019-08-04 10:00:00', 333.00, 'Compra Mi Band', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (1, '2019-08-04 22:00:00', 80.00, 'Ifood', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (1, '2019-08-05 22:00:00', 10.00, 'Ifood', null); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (2, '2019-05-05 18:00:00', 149.99, 'Compras Mensais Extra', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (2, '2019-08-04 18:00:00', 29.99, 'Compras Lojas Americanas', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (2, '2019-08-04 10:00:00', 333.00, 'Compra Mi Band', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (2, '2019-08-04 22:00:00', 80.00, 'Ifood', 2); + +INSERT INTO GASTO(id_usuario, data, valor, descricao, categoria_id) +VALUES (2, '2019-08-05 22:00:00', 10.00, 'Ifood', 2); \ No newline at end of file diff --git a/src/test/java/br/com/santander/gastos/GastosApplicationTests.java b/src/test/java/br/com/santander/gastos/GastosApplicationTests.java new file mode 100644 index 00000000..8d9197c9 --- /dev/null +++ b/src/test/java/br/com/santander/gastos/GastosApplicationTests.java @@ -0,0 +1,16 @@ +package br.com.santander.gastos; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class GastosApplicationTests { + + @Test + public void contextLoads() { + } + +} diff --git a/src/test/java/br/com/santander/gastos/GastosControllerTest.java b/src/test/java/br/com/santander/gastos/GastosControllerTest.java new file mode 100644 index 00000000..8aed0d4b --- /dev/null +++ b/src/test/java/br/com/santander/gastos/GastosControllerTest.java @@ -0,0 +1,64 @@ +package br.com.santander.gastos; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; + +import java.time.LocalDateTime; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import br.com.santander.gastos.model.Gasto; +import br.com.santander.gastos.repository.GastoRepository; +import br.com.santander.gastos.service.GastoService; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class GastosControllerTest { + + @Autowired + public WebApplicationContext context; + + private MockMvc mvc; + + private Gasto gasto; + + @Autowired + private GastoService service; + + @MockBean + private GastoRepository repository; + + @Before + public void setup() { + this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build(); + + gasto = new Gasto(); + gasto.setDescricao("Primeiro Gasto"); + gasto.setValor(new Double(1.0)); + gasto.setIdUsuario(Long.valueOf(1)); + gasto.setData(LocalDateTime.now()); + } + + @Test + public void cadastrarGasto() { + service.save(gasto); + verify(repository).save(gasto); + } + + @Test + public void buscarGastos() { + Long userId = Long.valueOf(1); + List listaGastos = service.findByIdUsuarioOrderByDataDesc(userId); + assertTrue(listaGastos.size() > 0); + } +}