diff --git a/backend/.gitignore b/backend/.gitignore new file mode 100644 index 0000000..2288458 --- /dev/null +++ b/backend/.gitignore @@ -0,0 +1,3 @@ +.idea +achados-e-perdidos.iml +target \ No newline at end of file diff --git a/backend/HELP.md b/backend/HELP.md new file mode 100644 index 0000000..16b22a7 --- /dev/null +++ b/backend/HELP.md @@ -0,0 +1,23 @@ +# Read Me First +The following was discovered as part of building this project: + +* The original package name 'com.desafio.achados-e-perdidos' is invalid and this project uses 'com.desafio.achadoseperdidos' instead. + +# Getting Started + +### Reference Documentation +For further reference, please consider the following sections: + +* [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) +* [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/) +* [Create an OCI image](https://docs.spring.io/spring-boot/docs/2.4.0/maven-plugin/reference/html/#build-image) +* [Spring Web](https://docs.spring.io/spring-boot/docs/2.4.0/reference/htmlsingle/#boot-features-developing-web-applications) +* [Validation](https://docs.spring.io/spring-boot/docs/2.4.0/reference/htmlsingle/#boot-features-validation) + +### Guides +The following guides illustrate how to use some features concretely: + +* [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) +* [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) +* [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) + diff --git a/backend/README.md b/backend/README.md new file mode 100644 index 0000000..751f06f --- /dev/null +++ b/backend/README.md @@ -0,0 +1,88 @@ +# Lost and Found + +Essa aplicação fornece uma interface REST para cadastro de itens (achados ou perdidos), por uma pessoa. + +## Como usar + +Antes de tudo, é necessário ter algumas dependências instaladas. + +### Dependências + +- Java (>= 8) +- Maven + +### Executando a api + +```bash +$ cd backend +$ mvn spring-boot:run +``` + +### Executando os testes +```bash +$ cd backend +$ mvn test +``` + +### Endpoints + +Há dois principais recursos na API: `person` e `item`. Esses são, respectivamente, uma pessoa cadastrada no sistema e seu(s) iten(s) achado(s) ou perdido(s).
+ +Endpoints para `person`:
+ +| Method | Endpoint | Descrição | +|--------|------------------------------|----------------------------------------------------| +| GET | /person?id= | Obtém uma pessoa pelo seu referente id. | +| POST | /person | Cria uma pessoa | +| PATCH | /person/`{id}`/lost-item | Adiciona um novo item (perdido) por uma pessoa. | +| PATCH | /person`{id}`/found-item | Adiciona um novo item (encontrado) por uma pessoa. | + + +### Requests + +POST /person + +```json + { + "name": "Wellisson Gomes", + "email": "wellisson@mail.com", + "telephone": "83 9 8765-4321" + } +``` + +PATCH /person/`{id}`/lost-item + +```json + { + "name": "celular", + "description": "Celular dourado, tem um trinco na tela", + "category": "eletrônico", + "city": "Campina Grande", + "state": "paraiba" + } +``` + +PATCH /person/`{id}`/found-item + +De forma análoga a anterior. + +Endpoints para `item`: + +| Method | Endpoint | Descrição | +|--------|------------------------------|----------------------------------------------------| +| GET | /items?`filter`= | Obtém todos os items presentes. Caso queira, é possível passar um filtro como parametro, mas é opcional. Os filtros possíveis são: `name`, `category`, `city`, `state` e `lost`. Um exemplo: /items?`category`= `eletrônico`. Retorna todos os items que são da categoria eletrônico| +| PUT | /item/`{id}` | Edita as informações de um item existente. | + +### Requests + +PUT /item/`{id}` + +```json + { + "name": "celular", + "description": "Celular dourado, bloqueio de tela um cachorro", + "category": "eletrônico", + "city": "Campina Grande", + "state": "paraiba" + } +``` \ No newline at end of file diff --git a/backend/mvnw b/backend/mvnw new file mode 100755 index 0000000..a16b543 --- /dev/null +++ b/backend/mvnw @@ -0,0 +1,310 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven 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)`" +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 + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + 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 $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + 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 + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +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/backend/mvnw.cmd b/backend/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/backend/mvnw.cmd @@ -0,0 +1,182 @@ +@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 Maven 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 keystroke 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 by 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.5.6/maven-wrapper-0.5.6.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% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%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/backend/pom.xml b/backend/pom.xml new file mode 100644 index 0000000..ae977df --- /dev/null +++ b/backend/pom.xml @@ -0,0 +1,63 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.0 + + + com.desafio + achados-e-perdidos + 0.0.1-SNAPSHOT + achados-e-perdidos + Achados e perdidos project + + + 11 + + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-data-jpa + 2.3.5.RELEASE + + + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplication.java b/backend/src/main/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplication.java new file mode 100644 index 0000000..758a5e0 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplication.java @@ -0,0 +1,13 @@ +package com.desafio.achadoseperdidos; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AchadosEPerdidosApplication { + + public static void main(String[] args) { + SpringApplication.run(AchadosEPerdidosApplication.class, args); + } + +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/constants/Messages.java b/backend/src/main/java/com/desafio/achadoseperdidos/constants/Messages.java new file mode 100644 index 0000000..466201d --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/constants/Messages.java @@ -0,0 +1,10 @@ +package com.desafio.achadoseperdidos.constants; + +public class Messages { + public static final class Exception { + public static final String THERE_ARE_MORE_THAN_ONE_FILTER = "There are more than one filter."; + public static final String ITEM_NOT_FOUND_D = "Item with id: %s not found."; + public static final String PERSON_NOT_FOUND_D = "Person with id: %s not found."; + public static final String EMAIL_ALREADY_EXISTS_S = "A person with email: %s already exists."; + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/controllers/ItemController.java b/backend/src/main/java/com/desafio/achadoseperdidos/controllers/ItemController.java new file mode 100644 index 0000000..4ea8033 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/controllers/ItemController.java @@ -0,0 +1,28 @@ +package com.desafio.achadoseperdidos.controllers; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.*; + +@RestController +public class ItemController { + @Autowired + private ItemService itemService; + + @GetMapping("/items") + public ResponseEntity> getAllItems(@RequestParam(required = false) Map allRequestsParams) { + return new ResponseEntity<>(itemService.getAllItems(allRequestsParams), HttpStatus.OK); + } + + @PutMapping("/item/{itemId}") + public ResponseEntity updateItem(@PathVariable UUID itemId, @Valid @RequestBody ItemDTO itemDTO) { + return new ResponseEntity<>(itemService.updateItem(itemId, itemDTO), HttpStatus.OK); + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/controllers/PersonController.java b/backend/src/main/java/com/desafio/achadoseperdidos/controllers/PersonController.java new file mode 100644 index 0000000..34fd272 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/controllers/PersonController.java @@ -0,0 +1,40 @@ +package com.desafio.achadoseperdidos.controllers; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.dto.PersonDTO; +import com.desafio.achadoseperdidos.entities.Person; +import com.desafio.achadoseperdidos.services.interfaces.PersonService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.validation.Valid; +import java.util.UUID; + +@RestController +@RequestMapping("/person") +public class PersonController { + @Autowired + private PersonService personService; + + @GetMapping + public ResponseEntity getPerson(@RequestParam UUID id) { + return new ResponseEntity<>(personService.getPersonById(id), HttpStatus.OK); + } + + @PostMapping() + public ResponseEntity createPerson(@Valid @RequestBody PersonDTO personDTO) { + return new ResponseEntity<>(personService.savePerson(personDTO), HttpStatus.CREATED); + } + + @PatchMapping("/{personId}/lost-item") + public ResponseEntity addLostItemToPerson(@PathVariable UUID personId, @Valid @RequestBody ItemDTO itemDTO){ + return new ResponseEntity<>(personService.addLostItemToPerson(personId, itemDTO), HttpStatus.OK); + } + + @PatchMapping("/{personId}/found-item") + public ResponseEntity addFoundItemToPerson(@PathVariable UUID personId, @Valid @RequestBody ItemDTO itemDTO){ + return new ResponseEntity<>(personService.addFoundItemToPerson(personId, itemDTO), HttpStatus.OK); + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/dto/ItemDTO.java b/backend/src/main/java/com/desafio/achadoseperdidos/dto/ItemDTO.java new file mode 100644 index 0000000..1cd1fcf --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/dto/ItemDTO.java @@ -0,0 +1,35 @@ +package com.desafio.achadoseperdidos.dto; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@Getter +@Setter +public class ItemDTO { + @NotNull @NotEmpty @NotBlank + private String name; + + @NotNull @NotEmpty @NotBlank + private String description; + + @NotNull @NotEmpty @NotBlank + private String category; + + @NotNull @NotEmpty @NotBlank + private String city; + + @NotNull @NotEmpty @NotBlank + private String state; + + public ItemDTO(String name, String description, String category, String city, String state) { + this.name = name; + this.description = description; + this.category = category; + this.city = city; + this.state = state; + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/dto/PersonDTO.java b/backend/src/main/java/com/desafio/achadoseperdidos/dto/PersonDTO.java new file mode 100644 index 0000000..308e378 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/dto/PersonDTO.java @@ -0,0 +1,28 @@ +package com.desafio.achadoseperdidos.dto; + +import lombok.Getter; +import lombok.Setter; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@Getter +@Setter +public class PersonDTO { + + @NotNull @NotBlank @NotEmpty + private String name; + + @NotNull @NotBlank @NotEmpty + private String email; + + @NotNull @NotBlank @NotEmpty + private String telephone; + + public PersonDTO(String name, String email, String telephone) { + this.name = name; + this.email = email; + this.telephone = telephone; + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/entities/Item.java b/backend/src/main/java/com/desafio/achadoseperdidos/entities/Item.java new file mode 100644 index 0000000..b8f3f48 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/entities/Item.java @@ -0,0 +1,66 @@ +package com.desafio.achadoseperdidos.entities; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.Type; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import java.util.Objects; +import java.util.UUID; + +@Getter +@Setter +@Entity +public class Item { + @Id + @GeneratedValue(strategy= GenerationType.AUTO) + @Type(type="org.hibernate.type.UUIDCharType") + private UUID id; + private String name; + private String description; + private String category; + private String city; + private String state; + private Boolean lost; + + public Item() {} + + public Item(UUID id, String name, String description, String category, String city, String state, Boolean lost) { + this(name, description, category, city, state, lost); + this.id = id; + } + + public Item(String name, String description, String category, String city, String state, Boolean lost) { + this.name = name; + this.description = description; + this.category = category; + this.city = city; + this.state = state; + this.lost = lost; + } + + public Item(ItemDTO itemDTO) { + this.name = itemDTO.getName(); + this.description = itemDTO.getDescription(); + this.category = itemDTO.getCategory(); + this.city = itemDTO.getCity(); + this.state = itemDTO.getState(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Item item = (Item) o; + return Objects.equals(id, item.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/entities/Person.java b/backend/src/main/java/com/desafio/achadoseperdidos/entities/Person.java new file mode 100644 index 0000000..36632a9 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/entities/Person.java @@ -0,0 +1,57 @@ +package com.desafio.achadoseperdidos.entities; + +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.Type; + +import javax.persistence.*; +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +@Getter +@Setter +@Entity +public class Person { + @Id + @GeneratedValue(strategy= GenerationType.AUTO) + @Type(type="org.hibernate.type.UUIDCharType") + private UUID id; + private String name; + private String email; + private String telephone; + @OneToMany + private Set lostItems; + @OneToMany + private Set foundItems; + + public Person() {} + + + public Person(UUID id, String name, String email, String telephone) { + this(name, email, telephone); + this.id = id; + } + + public Person(String name, String email, String telephone) { + this.name = name; + this.email = email; + this.telephone = telephone; + this.lostItems = new HashSet<>(); + this.foundItems = new HashSet<>(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Person person = (Person) o; + return Objects.equals(id, person.id); + } + + @Override + public int hashCode() { + return Objects.hash(id); + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/enums/Filter.java b/backend/src/main/java/com/desafio/achadoseperdidos/enums/Filter.java new file mode 100644 index 0000000..f91edc6 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/enums/Filter.java @@ -0,0 +1,15 @@ +package com.desafio.achadoseperdidos.enums; + +public enum Filter { + NAME("name"), CATEGORY("category"), CITY("city"), STATE("state"), LOST("lost"); + + private String filter; + + Filter(String filter) { + this.filter = filter; + } + + public String getFilter() { + return filter; + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/repositories/ItemRepository.java b/backend/src/main/java/com/desafio/achadoseperdidos/repositories/ItemRepository.java new file mode 100644 index 0000000..f920dd1 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/repositories/ItemRepository.java @@ -0,0 +1,9 @@ +package com.desafio.achadoseperdidos.repositories; + +import com.desafio.achadoseperdidos.entities.Item; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.UUID; + +public interface ItemRepository extends JpaRepository { +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/repositories/PersonRepository.java b/backend/src/main/java/com/desafio/achadoseperdidos/repositories/PersonRepository.java new file mode 100644 index 0000000..40e255c --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/repositories/PersonRepository.java @@ -0,0 +1,11 @@ +package com.desafio.achadoseperdidos.repositories; + +import com.desafio.achadoseperdidos.entities.Person; +import org.springframework.data.jpa.repository.JpaRepository; + +import java.util.Optional; +import java.util.UUID; + +public interface PersonRepository extends JpaRepository { + Optional findByEmail(String email); +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/services/ItemServiceImpl.java b/backend/src/main/java/com/desafio/achadoseperdidos/services/ItemServiceImpl.java new file mode 100644 index 0000000..39d2a65 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/services/ItemServiceImpl.java @@ -0,0 +1,156 @@ +package com.desafio.achadoseperdidos.services; + +import com.desafio.achadoseperdidos.constants.Messages; +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.enums.Filter; +import com.desafio.achadoseperdidos.repositories.ItemRepository; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import exceptions.BadRequestException; +import exceptions.NoContentException; +import exceptions.NotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; +import java.util.stream.Collectors; + +@Service +public class ItemServiceImpl implements ItemService { + @Autowired + private ItemRepository itemRepository; + + @Override + public Item createItem(Item item) { + return itemRepository.save(item); + } + + @Override + public List getAllItems(Map mapWithKeyToFilterItems) { + List itemList = itemRepository.findAll(); + validateEmptyList(itemList); + + boolean hasFilter = mapWithKeyToFilterItems.size() != 0; + if(hasFilter) { + itemList = getFilteredItems(mapWithKeyToFilterItems, itemList); + } + + return itemList; + } + + private void validateEmptyList(List itemList) { + if(itemList.isEmpty()) { + throw new NoContentException(); + } + } + + private List getFilteredItems(Map mapWithKeyToFilterItems, List itemList) { + validateFilds(mapWithKeyToFilterItems); + itemList = itemList.stream() + .filter(item -> itemHasEqualValue(item, mapWithKeyToFilterItems)) + .collect(Collectors.toList()); + validateEmptyList(itemList); + return itemList; + } + + private boolean itemHasEqualValue(Item item, Map mapWithKeyToFilterItems) { + Set fields = new HashSet<>(Arrays.asList("name", "category", "city", "state", "lost")); + + checkIfIsValidField(fields, mapWithKeyToFilterItems); + + for (String field : fields) { + if(hasField(field, mapWithKeyToFilterItems)) { + return equalsValue(item, field, mapWithKeyToFilterItems); + } + } + + return false; + } + + private void checkIfIsValidField(Set fields, Map mapWithKeyToFilterItems) { + boolean isValidField = false; + for (String field : fields) { + boolean fieldExists = mapWithKeyToFilterItems.keySet().contains(field); + if(fieldExists) { + isValidField = true; + } + } + + if(!isValidField) { + throw new NoContentException(); + } + } + + private boolean equalsValue(Item item, String field, Map fildToFilter) { + boolean equalsValue; + Filter filter = Filter.valueOf(field.toUpperCase()); + switch (filter) { + case NAME: + equalsValue = fildToFilter.get(field).equals(item.getName()); + break; + case CATEGORY: + equalsValue = fildToFilter.get(field).equals(item.getCategory()); + break; + case CITY: + equalsValue = fildToFilter.get(field).equals(item.getCity()); + break; + case STATE: + equalsValue = fildToFilter.get(field).equals(item.getState()); + break; + case LOST: + Boolean lost = Boolean.parseBoolean(fildToFilter.get(field)); + equalsValue = lost.equals(item.getLost()); + break; + default: + equalsValue = false; + } + + return equalsValue; + } + + private boolean hasField(String field, Map map) { + return map.get(field) != null; + } + + private void validateFilds(Map fildToFilter) { + boolean hasTwoOrMoreFildsToFilter = fildToFilter.size() > 1; + if(hasTwoOrMoreFildsToFilter) { + throw new BadRequestException(Messages.Exception.THERE_ARE_MORE_THAN_ONE_FILTER); + } + } + + @Override + public Item updateItem(UUID itemId, ItemDTO itemDTO) { + Item currentItem = getItemById(itemId); + currentItem = updateAllInfoItem(itemDTO, currentItem); + + itemRepository.save(currentItem); + return currentItem; + } + + private Item updateAllInfoItem(ItemDTO item, Item currentItem) { + currentItem.setName(item.getName()); + currentItem.setCategory(item.getCategory()); + currentItem.setDescription(item.getDescription()); + currentItem.setCity(item.getCity()); + currentItem.setState(item.getState()); + + return currentItem; + } + + private Item getItemById(UUID itemId) { + Optional optionalItem = itemRepository.findById(itemId); + + checkIfItemExists(itemId, optionalItem); + + Item item = optionalItem.get(); + return item; + } + + private void checkIfItemExists(UUID itemId, Optional optionalItem) { + boolean itemExists = optionalItem.isPresent(); + if(!itemExists) { + throw new NotFoundException(String.format(Messages.Exception.ITEM_NOT_FOUND_D, itemId)); + } + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/services/PersonServiceImpl.java b/backend/src/main/java/com/desafio/achadoseperdidos/services/PersonServiceImpl.java new file mode 100644 index 0000000..eee98ef --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/services/PersonServiceImpl.java @@ -0,0 +1,93 @@ +package com.desafio.achadoseperdidos.services; + +import com.desafio.achadoseperdidos.constants.Messages; +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.dto.PersonDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.entities.Person; +import com.desafio.achadoseperdidos.repositories.PersonRepository; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import com.desafio.achadoseperdidos.services.interfaces.PersonService; +import exceptions.BadRequestException; +import exceptions.NotFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +@Service +public class PersonServiceImpl implements PersonService { + @Autowired + private PersonRepository personRepository; + + @Autowired + private ItemService itemService; + + @Override + public Person getPersonById(UUID id) { + Optional optionalPerson = personRepository.findById(id); + + checkIfPersonExists(id, optionalPerson); + + Person person = optionalPerson.get(); + return person; + } + + private void checkIfPersonExists(UUID id, Optional optionalPerson) { + boolean personExists = optionalPerson.isPresent(); + if(!personExists) { + throw new NotFoundException(String.format(Messages.Exception.PERSON_NOT_FOUND_D, id)); + } + } + + @Override + public Person savePerson(PersonDTO personDTO) { + String email = personDTO.getEmail(); + + checkIfEmailAlreadyExists(email); + + Person person = new Person(personDTO.getName(), personDTO.getEmail(), personDTO.getTelephone()); + return personRepository.save(person); + } + + private void checkIfEmailAlreadyExists(String email) { + boolean emailAlreadyExists = personRepository.findByEmail(email).isPresent(); + if(emailAlreadyExists) { + throw new BadRequestException(String.format(Messages.Exception.EMAIL_ALREADY_EXISTS_S, email)); + } + } + + @Override + public Person addLostItemToPerson(UUID personId, ItemDTO itemDTO) { + Person person = getPersonById(personId); + Set lostItemsSet = person.getLostItems(); + + Item item = new Item(itemDTO); + item.setLost(true); + + addItemToPerson(person, item, lostItemsSet); + + return person; + } + + @Override + public Person addFoundItemToPerson(UUID personId, ItemDTO itemDTO) { + Person person = getPersonById(personId); + Set foundItemsSet = person.getFoundItems(); + + Item item = new Item(itemDTO); + item.setLost(false); + + addItemToPerson(person, item, foundItemsSet); + + return person; + } + + private void addItemToPerson(Person person, Item item, Set items) { + Item currentItem = itemService.createItem(item); + items.add(currentItem); + personRepository.save(person); + } +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/ItemService.java b/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/ItemService.java new file mode 100644 index 0000000..a1d20a0 --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/ItemService.java @@ -0,0 +1,16 @@ +package com.desafio.achadoseperdidos.services.interfaces; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.entities.Item; + +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public interface ItemService { + Item createItem(Item item); + + List getAllItems(Map fieldToFilter); + + Item updateItem(UUID itemId, ItemDTO itemDTO); +} diff --git a/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/PersonService.java b/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/PersonService.java new file mode 100644 index 0000000..f4c50ee --- /dev/null +++ b/backend/src/main/java/com/desafio/achadoseperdidos/services/interfaces/PersonService.java @@ -0,0 +1,17 @@ +package com.desafio.achadoseperdidos.services.interfaces; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.dto.PersonDTO; +import com.desafio.achadoseperdidos.entities.Person; + +import java.util.UUID; + +public interface PersonService { + Person getPersonById(UUID id); + + Person savePerson(PersonDTO personDTO); + + Person addLostItemToPerson(UUID personId, ItemDTO itemDTO); + + Person addFoundItemToPerson(UUID personId, ItemDTO itemDTO); +} diff --git a/backend/src/main/java/exceptions/BadRequestException.java b/backend/src/main/java/exceptions/BadRequestException.java new file mode 100644 index 0000000..7e6ca1f --- /dev/null +++ b/backend/src/main/java/exceptions/BadRequestException.java @@ -0,0 +1,11 @@ +package exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.BAD_REQUEST) +public class BadRequestException extends RuntimeException{ + public BadRequestException(String message) { + super(message); + } +} diff --git a/backend/src/main/java/exceptions/NoContentException.java b/backend/src/main/java/exceptions/NoContentException.java new file mode 100644 index 0000000..009f3d8 --- /dev/null +++ b/backend/src/main/java/exceptions/NoContentException.java @@ -0,0 +1,11 @@ +package exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NO_CONTENT) +public class NoContentException extends RuntimeException { + public NoContentException() { + super(); + } +} diff --git a/backend/src/main/java/exceptions/NotFoundException.java b/backend/src/main/java/exceptions/NotFoundException.java new file mode 100644 index 0000000..17c36b8 --- /dev/null +++ b/backend/src/main/java/exceptions/NotFoundException.java @@ -0,0 +1,11 @@ +package exceptions; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value = HttpStatus.NOT_FOUND) +public class NotFoundException extends RuntimeException { + public NotFoundException(String message) { + super(message); + } +} diff --git a/backend/src/main/resources/application.properties b/backend/src/main/resources/application.properties new file mode 100644 index 0000000..5d0fc26 --- /dev/null +++ b/backend/src/main/resources/application.properties @@ -0,0 +1,12 @@ +# H2 +spring.h2.console.enabled=true +spring.h2.console.path=/h2 + +# Datasource +spring.datasource.url=jdbc:h2:file:~/workspace/achados-e-perdidos +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver +spring.jpa.hibernate.ddl-auto=create + +server.error.include-message=always diff --git a/backend/src/test/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplicationTests.java b/backend/src/test/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplicationTests.java new file mode 100644 index 0000000..2eb96b6 --- /dev/null +++ b/backend/src/test/java/com/desafio/achadoseperdidos/AchadosEPerdidosApplicationTests.java @@ -0,0 +1,13 @@ +package com.desafio.achadoseperdidos; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AchadosEPerdidosApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/backend/src/test/java/com/desafio/achadoseperdidos/controllers/ItemControllerTest.java b/backend/src/test/java/com/desafio/achadoseperdidos/controllers/ItemControllerTest.java new file mode 100644 index 0000000..4fcdda8 --- /dev/null +++ b/backend/src/test/java/com/desafio/achadoseperdidos/controllers/ItemControllerTest.java @@ -0,0 +1,146 @@ +package com.desafio.achadoseperdidos.controllers; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import com.fasterxml.jackson.databind.ObjectMapper; +import exceptions.NoContentException; +import exceptions.NotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static java.nio.charset.StandardCharsets.ISO_8859_1; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.mockito.Mockito.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +@WebMvcTest(controllers = ItemController.class) +class ItemControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper = new ObjectMapper(); + + @MockBean + private ItemService itemService; + + private List itemList; + + private Item item; + + @BeforeEach + void setUp() { + this.itemList = new LinkedList<>(); + itemList.add(new Item("boneco", "boneco perdido na praça", "brinquedo", "campina grande", "paraiba", true)); + itemList.add(new Item("bola", "bola achada na praia", "futebol", "joão pessoa", "paraiba", false)); + itemList.add(new Item("celular", "celular perdido na praça", "eletronico", "campina grande", "paraiba", true)); + + this.item = new Item(UUID.fromString("5c166647-b030-43bb-9f27-cf295bf1f151"), "tablet", "tablet perdido na praça", "eletronico", "campina grande", "paraiba", true); + } + + @Test + void shouldFetchAllItemsWithOutFilter() throws Exception { + when(itemService.getAllItems(anyMap())).thenReturn(itemList); + + MvcResult mvcResult = this.mockMvc.perform(get("/items")) + .andExpect(status().isOk()) + .andReturn(); + + String jsonResponse = mvcResult.getResponse().getContentAsString(); + jsonResponse = toUTF_8(jsonResponse); + String jsonRequest = objectMapper.writeValueAsString(itemList); + + assertEquals(jsonRequest, jsonResponse); + } + + @Test + void shouldReturnsAllItemsFilteredWithValidFilter() throws Exception { + List filteredList = new LinkedList<>(); + filteredList.add(new Item("boneco", "boneco perdido na praça", "brinquedo", "campina grande", "paraiba", true)); + filteredList.add(new Item("celular", "celular perdido na praça", "eletronico", "campina grande", "paraiba", true)); + + Map filterToCity = new HashMap<>(); + filterToCity.put("city", "campina grande"); + when(itemService.getAllItems(eq(filterToCity))).thenReturn(filteredList); + + MvcResult mvcResult = this.mockMvc.perform(get("/items").queryParam("city", "campina grande")) + .andExpect(status().isOk()) + .andReturn(); + + String jsonResponse = mvcResult.getResponse().getContentAsString(); + jsonResponse = toUTF_8(jsonResponse); + String jsonRequest = objectMapper.writeValueAsString(filteredList); + + assertEquals(jsonRequest, jsonResponse); + } + + @Test + void shouldReturns204WhenCallingWithInvalidParam() throws Exception { + Map invalidParam = new HashMap<>(); + invalidParam.put("invalid", "invalid"); + when(itemService.getAllItems(eq(invalidParam))).thenThrow(new NoContentException()); + + MvcResult mvcResult = this.mockMvc.perform(get("/items") + .param("invalid", "invalid")) + .andExpect(status().isNoContent()) + .andReturn(); + } + + @Test + void shouldReturns404WhenIdDoesNotExists() throws Exception { + when(itemService.updateItem(eq(UUID.fromString("2db18d4f-2d41-4640-9caa-3f9899e4c4c2")), any(ItemDTO.class))).thenThrow(new NotFoundException("")); + + ItemDTO itemDTO = new ItemDTO("celular", "celular achado", "eletronico", "campina grande", "paraiba"); + mockMvc.perform(put("/item/2db18d4f-2d41-4640-9caa-3f9899e4c4c2") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(itemDTO))) + .andExpect(status().isNotFound()); + } + + @Test + void shouldUpdateItem() throws Exception { + when(itemService.createItem(eq(item))).thenReturn(item); + + Item currentItem = itemService.createItem(item); + + ItemDTO itemDTO = new ItemDTO("celular", "celular achado", "eletronico", "campina grande", "paraiba"); + mockMvc.perform(put("/item/" + currentItem.getId()) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(itemDTO))) + .andExpect(status().isOk()); + } + + @Test + void shouldReturn400WhenIsMissingField() throws Exception { + when(itemService.createItem(eq(item))).thenReturn(item); + + Item currentItem = itemService.createItem(item); + + ItemDTO itemDTO = new ItemDTO("", null, "eletronico", "campina grande", "paraiba"); + mockMvc.perform(put("/item/" + currentItem.getId()) + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(itemDTO))) + .andExpect(status().isBadRequest()); + } + + private String toUTF_8(String string) { + byte[] stringBytes = string.getBytes(ISO_8859_1); + String stringResult = new String(stringBytes, UTF_8); + + return stringResult; + } +} \ No newline at end of file diff --git a/backend/src/test/java/com/desafio/achadoseperdidos/controllers/PersonControllerTest.java b/backend/src/test/java/com/desafio/achadoseperdidos/controllers/PersonControllerTest.java new file mode 100644 index 0000000..39e2882 --- /dev/null +++ b/backend/src/test/java/com/desafio/achadoseperdidos/controllers/PersonControllerTest.java @@ -0,0 +1,167 @@ +package com.desafio.achadoseperdidos.controllers; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.dto.PersonDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.entities.Person; +import com.desafio.achadoseperdidos.services.interfaces.PersonService; +import com.fasterxml.jackson.databind.ObjectMapper; +import exceptions.BadRequestException; +import exceptions.NotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import static org.mockito.Mockito.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; + +import java.util.UUID; + +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; + +import static org.junit.jupiter.api.Assertions.*; + +@WebMvcTest(controllers = PersonController.class) +class PersonControllerTest { + @Autowired + private MockMvc mockMvc; + + @Autowired + private ObjectMapper objectMapper = new ObjectMapper(); + + @MockBean + private PersonService personService; + + private Person person; + private PersonDTO personDTO; + private Item lostItem; + private Item foundItem; + private ItemDTO itemDTO; + + private static final String UUID_STRING = "5c166647-b030-43bb-9f27-cf295bf1f151"; + private UUID uuid; + + @BeforeEach + void setUp() { + this.uuid = UUID.fromString(UUID_STRING); + + this.person = new Person(uuid, "validName", "valid@mail.com", "83 9 1234-5678"); + this.personDTO = new PersonDTO("validPerson", "validPerson@mail.com", "83 9 8743-1234"); + this.lostItem = new Item("validItem", "perdido na esqueina", "desconhecido", "cg", "pb", true); + this.foundItem = new Item("validItem", "perdido na esqueina", "desconhecido", "cg", "pb", false); + this.itemDTO = new ItemDTO("validItem", "perdido na esqueina", "desconhecido", "cg", "pb"); + } + + @Test + void shouldReturnsAPersonById() throws Exception { + when(personService.getPersonById(eq(uuid))).thenReturn(person); + + String response = mockMvc.perform(get("/person").queryParam("id", UUID_STRING)) + .andExpect(status().isOk()) + .andReturn() + .getResponse() + .getContentAsString(); + + String expectedPerson = objectMapper.writeValueAsString(person); + assertEquals(expectedPerson, response); + } + + @Test + void shouldReturns404IfPersonDoesNotExists() throws Exception { + when(personService.getPersonById(eq(uuid))).thenThrow(new NotFoundException("")); + + mockMvc.perform(get("/person").queryParam("id", UUID_STRING)) + .andExpect(status().isNotFound()); + } + + @Test + void shouldCreateAnewPerson() throws Exception { + when(personService.savePerson(any(PersonDTO.class))).thenReturn(person); + + MvcResult result = mockMvc.perform(post("/person") + .content(objectMapper.writeValueAsString(personDTO)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isCreated()) + .andReturn(); + + String response = result.getResponse().getContentAsString(); + + String expectedPerson = objectMapper.writeValueAsString(person); + assertEquals(expectedPerson, response); + } + + @Test + void shouldReturns400IfInvalidNameIsProvided() throws Exception { + PersonDTO personDTO = new PersonDTO("", "valid@mail.com", "83 9 87432112"); + + when(personService.savePerson(personDTO)).thenThrow(new BadRequestException("")); + + mockMvc.perform(post("/person") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(personDTO))) + .andExpect(status().isBadRequest()); + } + + @Test + void shouldReturns400IfInvalidEmailIsProvided() throws Exception { + PersonDTO personDTO = new PersonDTO("validName", "", "83 9 87432112"); + + when(personService.savePerson(personDTO)).thenThrow(new BadRequestException("")); + + mockMvc.perform(post("/person") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(personDTO))) + .andExpect(status().isBadRequest()); + } + + @Test + void shouldReturns400IfInvalidTelephoneIsProvided() throws Exception { + PersonDTO personDTO = new PersonDTO("validName", "valid@mail.com", ""); + + when(personService.savePerson(personDTO)).thenThrow(new BadRequestException("")); + + mockMvc.perform(post("/person") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(personDTO))) + .andExpect(status().isBadRequest()); + } + + @Test + void shouldAddLostItemToPerson() throws Exception { + person.getLostItems().add(lostItem); + + when(personService.addLostItemToPerson(eq(uuid), any(ItemDTO.class))).thenReturn(person); + + MvcResult result = mockMvc.perform(patch("/person/" + UUID_STRING + "/lost-item") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(itemDTO))) + .andExpect(status().isOk()) + .andReturn(); + + String response = result.getResponse().getContentAsString(); + String expectedPerson = objectMapper.writeValueAsString(person); + assertEquals(expectedPerson, response); + } + + @Test + void shouldAddFoundItemToPerson() throws Exception { + person.getLostItems().add(foundItem); + + when(personService.addFoundItemToPerson(eq(uuid), any(ItemDTO.class))).thenReturn(person); + + MvcResult result = mockMvc.perform(patch("/person/" + UUID_STRING + "/found-item") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(itemDTO))) + .andExpect(status().isOk()) + .andReturn(); + + String response = result.getResponse().getContentAsString(); + String expectedPerson = objectMapper.writeValueAsString(person); + assertEquals(expectedPerson, response); + } +} \ No newline at end of file diff --git a/backend/src/test/java/com/desafio/achadoseperdidos/services/ItemServiceImplTest.java b/backend/src/test/java/com/desafio/achadoseperdidos/services/ItemServiceImplTest.java new file mode 100644 index 0000000..90988dc --- /dev/null +++ b/backend/src/test/java/com/desafio/achadoseperdidos/services/ItemServiceImplTest.java @@ -0,0 +1,163 @@ +package com.desafio.achadoseperdidos.services; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.repositories.ItemRepository; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import exceptions.NoContentException; +import exceptions.NotFoundException; +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 static org.mockito.Mockito.*; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.*; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +class ItemServiceImplTest { + @Mock + private ItemRepository itemRepository; + @InjectMocks + private ItemService itemService = new ItemServiceImpl(); + + private List itemList; + + private UUID uuid; + + private static final String UUID_STRING = "5c166647-b030-43bb-9f27-cf295bf1f151"; + + @BeforeEach + void setUp() { + this.itemList = new LinkedList<>(); + itemList.add(new Item("item1", "belo item1", "category1", "campina grande", "PB", false)); + itemList.add(new Item("item2", "belo item2", "category2", "joão pessoa", "PE", true)); + + this.uuid = UUID.fromString(UUID_STRING); + } + + @Test + void shouldSaveAItem() { + Item item = new Item("validName", "validDescription", "validCategory", "campina grande", "PB", false); + when(itemRepository.save(any(Item.class))).thenReturn(item); + + Item currentItem = itemService.createItem(new Item("something", "test@test.com", "testCategory", "campina grande", "PB", true)); + + assertEquals(item.getId(), currentItem.getId()); + assertEquals(item.getCategory(), currentItem.getCategory()); + assertEquals(item.getDescription(), currentItem.getDescription()); + assertEquals(item.getLost(), currentItem.getLost()); + } + + @Test + void shouldReturnsAllItemsWithoutFilters() { + when(itemRepository.findAll()).thenReturn(itemList); + + List currentItemsList = itemService.getAllItems(new HashMap<>()); + + assertEquals(currentItemsList, itemList); + } + + @Test + void shouldReturnsAllItemsWithFilterByName() { + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("name", "item1"); + List currentItemsList = itemService.getAllItems(mapToFilter); + + assertEquals(1, currentItemsList.size()); + assertEquals(false, currentItemsList.get(0).getLost()); + } + + @Test + void shouldReturnsAllItemsWithFilterByCategory() { + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("category", "category2"); + List currentItemsList = itemService.getAllItems(mapToFilter); + + assertEquals(1, currentItemsList.size()); + assertEquals(true, currentItemsList.get(0).getLost()); + } + + @Test + void shouldReturnsAllItemsWithFilterByCity() { + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("city", "campina grande"); + List currentItemsList = itemService.getAllItems(mapToFilter); + + assertEquals(1, currentItemsList.size()); + assertEquals(false, currentItemsList.get(0).getLost()); + } + + @Test + void shouldReturnsAllItemsWithFilterByState() { + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("state", "PE"); + List currentItemsList = itemService.getAllItems(mapToFilter); + + assertEquals(1, currentItemsList.size()); + assertEquals(true, currentItemsList.get(0).getLost()); + } + + @Test + void shouldReturnsAllItemsWithFilterByLost() { + List lostItems = new ArrayList<>(); + lostItems.add(new Item("item1", "belo item1", "category1", "campina grande", "PB", false)); + + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("lost", "false"); + List currentItemsList = itemService.getAllItems(mapToFilter); + + assertEquals(1, currentItemsList.size()); + assertEquals(false, currentItemsList.get(0).getLost()); + assertEquals(lostItems, currentItemsList); + } + + @Test + void shouldThrowAnErrorWhenCallingWithInvalidFilter() { + when(itemRepository.findAll()).thenReturn(itemList); + + Map mapToFilter = new HashMap<>(); + mapToFilter.put("description", "belo item1"); + assertThrows(NoContentException.class, () -> { + List currentItemsList = itemService.getAllItems(mapToFilter); + }); + } + + @Test + void shouldUpdateAnItemThatExists() { + Item item = new Item("item1", "belo item1", "category1", "campina grande", "PB", false); + when(itemRepository.findById(eq(uuid))).thenReturn(Optional.of(item)); + + ItemDTO itemDTO = new ItemDTO("itemModified", "item top", "category", "campina grande", "PB"); + Item currentItem = itemService.updateItem(uuid, itemDTO); + + assertEquals("itemModified", currentItem.getName()); + assertEquals("item top", currentItem.getDescription()); + assertEquals("category", currentItem.getCategory()); + assertEquals(false, currentItem.getLost()); + } + + @Test + void shouldThrowAnErrorWhenAnItemDoesNotExists() { + when(itemRepository.findById(eq(uuid))).thenReturn(Optional.empty()); + + ItemDTO itemDTO = new ItemDTO("itemModified", "item top", "category", "campina grande", "PB"); + assertThrows(NotFoundException.class, () -> { + itemService.updateItem(uuid, itemDTO); + }); + } +} \ No newline at end of file diff --git a/backend/src/test/java/com/desafio/achadoseperdidos/services/PersonServiceImplTest.java b/backend/src/test/java/com/desafio/achadoseperdidos/services/PersonServiceImplTest.java new file mode 100644 index 0000000..28b93f2 --- /dev/null +++ b/backend/src/test/java/com/desafio/achadoseperdidos/services/PersonServiceImplTest.java @@ -0,0 +1,129 @@ +package com.desafio.achadoseperdidos.services; + +import com.desafio.achadoseperdidos.dto.ItemDTO; +import com.desafio.achadoseperdidos.dto.PersonDTO; +import com.desafio.achadoseperdidos.entities.Item; +import com.desafio.achadoseperdidos.entities.Person; +import com.desafio.achadoseperdidos.repositories.PersonRepository; +import com.desafio.achadoseperdidos.services.interfaces.ItemService; +import com.desafio.achadoseperdidos.services.interfaces.PersonService; +import exceptions.BadRequestException; +import exceptions.NotFoundException; +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 static org.mockito.Mockito.*; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(MockitoExtension.class) +class PersonServiceImplTest { + @Mock + private PersonRepository personRepository; + @Mock + private ItemService itemService; + + @InjectMocks + private PersonService personService = new PersonServiceImpl(); + + private static final String UUID_STRING = "5c166647-b030-43bb-9f27-cf295bf1f151"; + private UUID uuid; + + private Person person; + private Item item; + + @BeforeEach + void setUp() { + this.uuid = UUID.fromString(UUID_STRING); + this.person = new Person("validName", "validEmail@mail.com", "(83) 9 1234-5678"); + this.item = new Item("validName", "validDescription", "validCategory", "campina grande", "PB", false); + } + + @Test + void shouldThrowErrorCallingGetPersonByIdWhenIdNotExists() { + when(personRepository.findById(eq(uuid))).thenReturn(Optional.empty()); + assertThrows(NotFoundException.class, () -> { + personService.getPersonById(uuid); + }); + } + + @Test + void shouldReturnsPersonSuccessFullyWithGetPersonById() { + when(personRepository.findById(eq(uuid))).thenReturn(Optional.of(person)); + + Person currentPerson = personService.getPersonById(uuid); + + assertEquals("validName", currentPerson.getName()); + assertEquals("validEmail@mail.com", currentPerson.getEmail()); + assertEquals("(83) 9 1234-5678", currentPerson.getTelephone()); + assertEquals(new HashSet<>(), currentPerson.getFoundItems()); + assertEquals(new HashSet<>(), currentPerson.getLostItems()); + } + + @Test + void shouldThrowErrorCallingSavePersonWhenEmailAlredyExists() { + when(personRepository.findByEmail("validEmail@mail.com")).thenReturn(Optional.of(person)); + assertThrows(BadRequestException.class, () -> { + personService.savePerson(new PersonDTO("otherName", "validEmail@mail.com", "(83) 9 3214-2512")); + }); + } + + @Test + void shouldReturnsAPersonWhenCallingSavePerson() { + when(personRepository.findByEmail("validEmail@mail.com")).thenReturn(Optional.empty()); + when(personRepository.save(any(Person.class))).thenReturn(person); + + PersonDTO personDTO = new PersonDTO("validName", "validEmail@mail.com", "(83) 9 1234-5678"); + Person currentPerson = personService.savePerson(personDTO); + + assertEquals("validName", person.getName()); + assertEquals("validEmail@mail.com", person.getEmail()); + assertEquals("(83) 9 1234-5678", person.getTelephone()); + assertEquals(new HashSet<>(), person.getFoundItems()); + assertEquals(new HashSet<>(), person.getLostItems()); + } + + @Test + void addLostItemToPersonTest() { + when(personRepository.findById(eq(uuid))).thenReturn(Optional.of(person)); + when(itemService.createItem(any(Item.class))).thenReturn(item); + + ItemDTO itemDTO = new ItemDTO("validName", "validDescription", "validCategory", "campina grande", "PB"); + Person currentPerson = personService.addLostItemToPerson(uuid, itemDTO); + + Set itemSet = new HashSet<>(); + itemSet.add(item); + + assertEquals("validName", currentPerson.getName()); + assertEquals("validEmail@mail.com", currentPerson.getEmail()); + assertEquals("(83) 9 1234-5678", currentPerson.getTelephone()); + assertEquals(itemSet, currentPerson.getLostItems()); + assertEquals(new HashSet<>(), currentPerson.getFoundItems()); + } + + @Test + void addFoundItemToPersonTest() { + when(personRepository.findById(eq(uuid))).thenReturn(Optional.of(person)); + when(itemService.createItem(any(Item.class))).thenReturn(item); + + ItemDTO itemDTO = new ItemDTO("validName", "validDescription", "validCategory", "campina grande", "PB"); + Person currentPerson = personService.addFoundItemToPerson(uuid, itemDTO); + + Set itemSet = new HashSet<>(); + itemSet.add(item); + + assertEquals("validName", currentPerson.getName()); + assertEquals("validEmail@mail.com", currentPerson.getEmail()); + assertEquals("(83) 9 1234-5678", currentPerson.getTelephone()); + assertEquals(itemSet, currentPerson.getFoundItems()); + assertEquals(new HashSet<>(), currentPerson.getLostItems()); + } +} \ No newline at end of file