├── .gitignore ├── build.gradle.kts ├── docker-compose.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main ├── java │ └── br │ │ └── com │ │ └── fullcycle │ │ └── hexagonal │ │ ├── Main.java │ │ ├── controllers │ │ ├── CustomerController.java │ │ ├── EventController.java │ │ └── PartnerController.java │ │ ├── dtos │ │ ├── CustomerDTO.java │ │ ├── EventDTO.java │ │ ├── PartnerDTO.java │ │ ├── SubscribeDTO.java │ │ └── TicketDTO.java │ │ ├── models │ │ ├── Customer.java │ │ ├── Event.java │ │ ├── Partner.java │ │ ├── Ticket.java │ │ └── TicketStatus.java │ │ ├── repositories │ │ ├── CustomerRepository.java │ │ ├── EventRepository.java │ │ ├── PartnerRepository.java │ │ └── TicketRepository.java │ │ └── services │ │ ├── CustomerService.java │ │ ├── EventService.java │ │ └── PartnerService.java └── resources │ ├── application-test.properties │ └── application.properties └── test └── java └── br └── com └── fullcycle └── hexagonal ├── MainTests.java └── controllers ├── CustomerControllerTest.java ├── EventControllerTest.java └── PartnerControllerTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | java 3 | id("org.springframework.boot") version "3.1.2" 4 | id("io.spring.dependency-management") version "1.1.2" 5 | } 6 | 7 | group = "br.com.fullcycle" 8 | version = "0.0.1-SNAPSHOT" 9 | 10 | java { 11 | sourceCompatibility = JavaVersion.VERSION_17 12 | } 13 | 14 | repositories { 15 | mavenCentral() 16 | } 17 | 18 | dependencies { 19 | implementation("io.hypersistence:hypersistence-tsid:2.1.0") 20 | implementation("org.springframework.boot:spring-boot-starter-data-jpa") 21 | implementation("org.springframework.boot:spring-boot-starter-graphql") 22 | implementation("org.springframework.boot:spring-boot-starter-web") 23 | 24 | runtimeOnly("com.mysql:mysql-connector-j") 25 | 26 | testImplementation("org.springframework.boot:spring-boot-starter-test") 27 | testImplementation("org.springframework:spring-webflux") 28 | testImplementation("org.springframework.graphql:spring-graphql-test") 29 | 30 | testRuntimeOnly("com.h2database:h2") 31 | } 32 | 33 | tasks.withType { 34 | useJUnitPlatform() 35 | } 36 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | mysql: 5 | image: mysql:8.0.30-debian 6 | ports: 7 | - 3306:3306 8 | environment: 9 | - MYSQL_ROOT_PASSWORD=root 10 | - MYSQL_DATABASE=events -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devfullcycle/MBA-hexagonal-architecture/0818c8fc8a1d73bf55873c39d831b7991f0bbb36/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 87 | 88 | # Use the maximum available, or set MAX_FD != -1 to use that value. 89 | MAX_FD=maximum 90 | 91 | warn () { 92 | echo "$*" 93 | } >&2 94 | 95 | die () { 96 | echo 97 | echo "$*" 98 | echo 99 | exit 1 100 | } >&2 101 | 102 | # OS specific support (must be 'true' or 'false'). 103 | cygwin=false 104 | msys=false 105 | darwin=false 106 | nonstop=false 107 | case "$( uname )" in #( 108 | CYGWIN* ) cygwin=true ;; #( 109 | Darwin* ) darwin=true ;; #( 110 | MSYS* | MINGW* ) msys=true ;; #( 111 | NONSTOP* ) nonstop=true ;; 112 | esac 113 | 114 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 115 | 116 | 117 | # Determine the Java command to use to start the JVM. 118 | if [ -n "$JAVA_HOME" ] ; then 119 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 120 | # IBM's JDK on AIX uses strange locations for the executables 121 | JAVACMD=$JAVA_HOME/jre/sh/java 122 | else 123 | JAVACMD=$JAVA_HOME/bin/java 124 | fi 125 | if [ ! -x "$JAVACMD" ] ; then 126 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 127 | 128 | Please set the JAVA_HOME variable in your environment to match the 129 | location of your Java installation." 130 | fi 131 | else 132 | JAVACMD=java 133 | if ! command -v java >/dev/null 2>&1 134 | then 135 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 136 | 137 | Please set the JAVA_HOME variable in your environment to match the 138 | location of your Java installation." 139 | fi 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 147 | # shellcheck disable=SC3045 148 | MAX_FD=$( ulimit -H -n ) || 149 | warn "Could not query maximum file descriptor limit" 150 | esac 151 | case $MAX_FD in #( 152 | '' | soft) :;; #( 153 | *) 154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 155 | # shellcheck disable=SC3045 156 | ulimit -n "$MAX_FD" || 157 | warn "Could not set maximum file descriptor limit to $MAX_FD" 158 | esac 159 | fi 160 | 161 | # Collect all arguments for the java command, stacking in reverse order: 162 | # * args from the command line 163 | # * the main class name 164 | # * -classpath 165 | # * -D...appname settings 166 | # * --module-path (only if needed) 167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 168 | 169 | # For Cygwin or MSYS, switch paths to Windows format before running java 170 | if "$cygwin" || "$msys" ; then 171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 173 | 174 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 175 | 176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 177 | for arg do 178 | if 179 | case $arg in #( 180 | -*) false ;; # don't mess with options #( 181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 182 | [ -e "$t" ] ;; #( 183 | *) false ;; 184 | esac 185 | then 186 | arg=$( cygpath --path --ignore --mixed "$arg" ) 187 | fi 188 | # Roll the args list around exactly as many times as the number of 189 | # args, so each arg winds up back in the position where it started, but 190 | # possibly modified. 191 | # 192 | # NB: a `for` loop captures its iteration list before it begins, so 193 | # changing the positional parameters here affects neither the number of 194 | # iterations, nor the values presented in `arg`. 195 | shift # remove old arg 196 | set -- "$@" "$arg" # push replacement arg 197 | done 198 | fi 199 | 200 | 201 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 202 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 203 | 204 | # Collect all arguments for the java command; 205 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 206 | # shell script including quotes and variable substitutions, so put them in 207 | # double quotes to make sure that they get re-expanded; and 208 | # * put everything else in single quotes, so that it's not re-expanded. 209 | 210 | set -- \ 211 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 212 | -classpath "$CLASSPATH" \ 213 | org.gradle.wrapper.GradleWrapperMain \ 214 | "$@" 215 | 216 | # Stop when "xargs" is not available. 217 | if ! command -v xargs >/dev/null 2>&1 218 | then 219 | die "xargs is not available" 220 | fi 221 | 222 | # Use "xargs" to parse quoted args. 223 | # 224 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 225 | # 226 | # In Bash we could simply go: 227 | # 228 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 229 | # set -- "${ARGS[@]}" "$@" 230 | # 231 | # but POSIX shell has neither arrays nor command substitution, so instead we 232 | # post-process each arg (as a line of input to sed) to backslash-escape any 233 | # character that might be a shell metacharacter, then use eval to reverse 234 | # that process (while maintaining the separation between arguments), and wrap 235 | # the whole thing up as a single "set" statement. 236 | # 237 | # This will of course break if any of these variables contains a newline or 238 | # an unmatched quote. 239 | # 240 | 241 | eval "set -- $( 242 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 243 | xargs -n1 | 244 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 245 | tr '\n' ' ' 246 | )" '"$@"' 247 | 248 | exec "$JAVACMD" "$@" 249 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mba-hexagonal-arch" 2 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/Main.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Main { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Main.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/controllers/CustomerController.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.CustomerDTO; 4 | import br.com.fullcycle.hexagonal.models.Customer; 5 | import br.com.fullcycle.hexagonal.services.CustomerService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.net.URI; 11 | 12 | @RestController 13 | @RequestMapping(value = "customers") 14 | public class CustomerController { 15 | 16 | @Autowired 17 | private CustomerService customerService; 18 | 19 | @PostMapping 20 | public ResponseEntity create(@RequestBody CustomerDTO dto) { 21 | if (customerService.findByCpf(dto.getCpf()).isPresent()) { 22 | return ResponseEntity.unprocessableEntity().body("Customer already exists"); 23 | } 24 | if (customerService.findByEmail(dto.getEmail()).isPresent()) { 25 | return ResponseEntity.unprocessableEntity().body("Customer already exists"); 26 | } 27 | 28 | var customer = new Customer(); 29 | customer.setName(dto.getName()); 30 | customer.setCpf(dto.getCpf()); 31 | customer.setEmail(dto.getEmail()); 32 | 33 | customer = customerService.save(customer); 34 | 35 | return ResponseEntity.created(URI.create("/customers/" + customer.getId())).body(customer); 36 | } 37 | 38 | @GetMapping("/{id}") 39 | public ResponseEntity get(@PathVariable Long id) { 40 | var customer = customerService.findById(id); 41 | if (customer.isEmpty()) { 42 | return ResponseEntity.notFound().build(); 43 | } 44 | 45 | return ResponseEntity.ok(customer.get()); 46 | } 47 | } -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/controllers/EventController.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.EventDTO; 4 | import br.com.fullcycle.hexagonal.dtos.SubscribeDTO; 5 | import br.com.fullcycle.hexagonal.models.Event; 6 | import br.com.fullcycle.hexagonal.models.Ticket; 7 | import br.com.fullcycle.hexagonal.models.TicketStatus; 8 | import br.com.fullcycle.hexagonal.services.CustomerService; 9 | import br.com.fullcycle.hexagonal.services.EventService; 10 | import br.com.fullcycle.hexagonal.services.PartnerService; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.http.ResponseEntity; 13 | import org.springframework.transaction.annotation.Transactional; 14 | import org.springframework.web.bind.annotation.*; 15 | 16 | import java.time.Instant; 17 | import java.time.LocalDate; 18 | import java.time.format.DateTimeFormatter; 19 | 20 | import static org.springframework.http.HttpStatus.CREATED; 21 | 22 | @RestController 23 | @RequestMapping(value = "events") 24 | public class EventController { 25 | 26 | @Autowired 27 | private CustomerService customerService; 28 | 29 | @Autowired 30 | private EventService eventService; 31 | 32 | @Autowired 33 | private PartnerService partnerService; 34 | 35 | @PostMapping 36 | @ResponseStatus(CREATED) 37 | public Event create(@RequestBody EventDTO dto) { 38 | var event = new Event(); 39 | event.setDate(LocalDate.parse(dto.getDate(), DateTimeFormatter.ISO_DATE)); 40 | event.setName(dto.getName()); 41 | event.setTotalSpots(dto.getTotalSpots()); 42 | 43 | var partner = partnerService.findById(dto.getPartner().getId()); 44 | if (partner.isEmpty()) { 45 | throw new RuntimeException("Partner not found"); 46 | } 47 | event.setPartner(partner.get()); 48 | 49 | return eventService.save(event); 50 | } 51 | 52 | @Transactional 53 | @PostMapping(value = "/{id}/subscribe") 54 | public ResponseEntity subscribe(@PathVariable Long id, @RequestBody SubscribeDTO dto) { 55 | 56 | var maybeCustomer = customerService.findById(dto.getCustomerId()); 57 | if (maybeCustomer.isEmpty()) { 58 | return ResponseEntity.unprocessableEntity().body("Customer not found"); 59 | } 60 | 61 | var maybeEvent = eventService.findById(id); 62 | if (maybeEvent.isEmpty()) { 63 | return ResponseEntity.notFound().build(); 64 | } 65 | 66 | var maybeTicket = eventService.findTicketByEventIdAndCustomerId(id, dto.getCustomerId()); 67 | if (maybeTicket.isPresent()) { 68 | return ResponseEntity.unprocessableEntity().body("Email already registered"); 69 | } 70 | 71 | var customer = maybeCustomer.get(); 72 | var event = maybeEvent.get(); 73 | 74 | if (event.getTotalSpots() < event.getTickets().size() + 1) { 75 | throw new RuntimeException("Event sold out"); 76 | } 77 | 78 | var ticket = new Ticket(); 79 | ticket.setEvent(event); 80 | ticket.setCustomer(customer); 81 | ticket.setReservedAt(Instant.now()); 82 | ticket.setStatus(TicketStatus.PENDING); 83 | 84 | event.getTickets().add(ticket); 85 | 86 | eventService.save(event); 87 | 88 | return ResponseEntity.ok(new EventDTO(event)); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/controllers/PartnerController.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.PartnerDTO; 4 | import br.com.fullcycle.hexagonal.models.Partner; 5 | import br.com.fullcycle.hexagonal.services.PartnerService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.ResponseEntity; 8 | import org.springframework.web.bind.annotation.*; 9 | 10 | import java.net.URI; 11 | 12 | @RestController 13 | @RequestMapping(value = "partners") 14 | public class PartnerController { 15 | 16 | @Autowired 17 | private PartnerService partnerService; 18 | 19 | @PostMapping 20 | public ResponseEntity create(@RequestBody PartnerDTO dto) { 21 | if (partnerService.findByCnpj(dto.getCnpj()).isPresent()) { 22 | return ResponseEntity.unprocessableEntity().body("Partner already exists"); 23 | } 24 | if (partnerService.findByEmail(dto.getEmail()).isPresent()) { 25 | return ResponseEntity.unprocessableEntity().body("Partner already exists"); 26 | } 27 | 28 | var partner = new Partner(); 29 | partner.setName(dto.getName()); 30 | partner.setCnpj(dto.getCnpj()); 31 | partner.setEmail(dto.getEmail()); 32 | 33 | partner = partnerService.save(partner); 34 | 35 | return ResponseEntity.created(URI.create("/partners/" + partner.getId())).body(partner); 36 | } 37 | 38 | @GetMapping("/{id}") 39 | public ResponseEntity get(@PathVariable Long id) { 40 | var partner = partnerService.findById(id); 41 | if (partner.isEmpty()) { 42 | return ResponseEntity.notFound().build(); 43 | } 44 | 45 | return ResponseEntity.ok(partner.get()); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/dtos/CustomerDTO.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.dtos; 2 | 3 | import br.com.fullcycle.hexagonal.models.Customer; 4 | 5 | public class CustomerDTO { 6 | private Long id; 7 | private String name; 8 | private String cpf; 9 | private String email; 10 | 11 | public CustomerDTO() { 12 | } 13 | 14 | public CustomerDTO(Customer customer) { 15 | this.id = customer.getId(); 16 | this.name = customer.getName(); 17 | this.cpf = customer.getCpf(); 18 | this.email = customer.getEmail(); 19 | } 20 | 21 | public Long getId() { 22 | return id; 23 | } 24 | 25 | public void setId(Long id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public String getCpf() { 38 | return cpf; 39 | } 40 | 41 | public void setCpf(String cpf) { 42 | this.cpf = cpf; 43 | } 44 | 45 | public String getEmail() { 46 | return email; 47 | } 48 | 49 | public void setEmail(String email) { 50 | this.email = email; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/dtos/EventDTO.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.dtos; 2 | 3 | import br.com.fullcycle.hexagonal.models.Event; 4 | 5 | import java.time.format.DateTimeFormatter; 6 | 7 | public class EventDTO { 8 | 9 | private Long id; 10 | private String name; 11 | private String date; 12 | private int totalSpots; 13 | private PartnerDTO partner; 14 | 15 | public EventDTO() { 16 | } 17 | 18 | public EventDTO(Event event) { 19 | this.id = event.getId(); 20 | this.name = event.getName(); 21 | this.date = event.getDate().format(DateTimeFormatter.ISO_DATE); 22 | this.totalSpots = event.getTotalSpots(); 23 | this.partner = new PartnerDTO(event.getPartner()); 24 | } 25 | 26 | public Long getId() { 27 | return id; 28 | } 29 | 30 | public void setId(Long id) { 31 | this.id = id; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | public String getDate() { 43 | return date; 44 | } 45 | 46 | public void setDate(String date) { 47 | this.date = date; 48 | } 49 | 50 | public int getTotalSpots() { 51 | return totalSpots; 52 | } 53 | 54 | public void setTotalSpots(int totalSpots) { 55 | this.totalSpots = totalSpots; 56 | } 57 | 58 | public PartnerDTO getPartner() { 59 | return partner; 60 | } 61 | 62 | public void setPartner(PartnerDTO partner) { 63 | this.partner = partner; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/dtos/PartnerDTO.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.dtos; 2 | 3 | import br.com.fullcycle.hexagonal.models.Partner; 4 | 5 | public class PartnerDTO { 6 | private Long id; 7 | private String name; 8 | private String cnpj; 9 | private String email; 10 | 11 | public PartnerDTO() { 12 | } 13 | 14 | public PartnerDTO(Long id) { 15 | this.id = id; 16 | } 17 | 18 | public PartnerDTO(Partner partner) { 19 | this.id = partner.getId(); 20 | this.name = partner.getName(); 21 | this.cnpj = partner.getCnpj(); 22 | this.email = partner.getEmail(); 23 | } 24 | 25 | public Long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(Long id) { 30 | this.id = id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public void setName(String name) { 38 | this.name = name; 39 | } 40 | 41 | public String getCnpj() { 42 | return cnpj; 43 | } 44 | 45 | public void setCnpj(String cnpj) { 46 | this.cnpj = cnpj; 47 | } 48 | 49 | public String getEmail() { 50 | return email; 51 | } 52 | 53 | public void setEmail(String email) { 54 | this.email = email; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/dtos/SubscribeDTO.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.dtos; 2 | 3 | public class SubscribeDTO { 4 | 5 | private Long customerId; 6 | 7 | public Long getCustomerId() { 8 | return customerId; 9 | } 10 | 11 | public void setCustomerId(Long customerId) { 12 | this.customerId = customerId; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/dtos/TicketDTO.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.dtos; 2 | 3 | import br.com.fullcycle.hexagonal.models.Ticket; 4 | import br.com.fullcycle.hexagonal.models.TicketStatus; 5 | 6 | import java.time.Instant; 7 | 8 | public class TicketDTO { 9 | private Long id; 10 | private int spot; 11 | private CustomerDTO customer; 12 | private EventDTO event; 13 | private TicketStatus status; 14 | private Instant paidAt; 15 | private Instant reservedAt; 16 | 17 | public TicketDTO() { 18 | } 19 | 20 | public TicketDTO(Ticket ticket) { 21 | this.id = ticket.getId(); 22 | this.customer = new CustomerDTO(ticket.getCustomer()); 23 | this.event = new EventDTO(ticket.getEvent()); 24 | this.status = ticket.getStatus(); 25 | this.paidAt = ticket.getPaidAt(); 26 | this.reservedAt = ticket.getReservedAt(); 27 | } 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public void setId(Long id) { 34 | this.id = id; 35 | } 36 | 37 | public int getSpot() { 38 | return spot; 39 | } 40 | 41 | public void setSpot(int spot) { 42 | this.spot = spot; 43 | } 44 | 45 | public CustomerDTO getCustomer() { 46 | return customer; 47 | } 48 | 49 | public void setCustomer(CustomerDTO customer) { 50 | this.customer = customer; 51 | } 52 | 53 | public EventDTO getEvent() { 54 | return event; 55 | } 56 | 57 | public void setEvent(EventDTO event) { 58 | this.event = event; 59 | } 60 | 61 | public TicketStatus getStatus() { 62 | return status; 63 | } 64 | 65 | public void setStatus(TicketStatus status) { 66 | this.status = status; 67 | } 68 | 69 | public Instant getPaidAt() { 70 | return paidAt; 71 | } 72 | 73 | public void setPaidAt(Instant paidAt) { 74 | this.paidAt = paidAt; 75 | } 76 | 77 | public Instant getReservedAt() { 78 | return reservedAt; 79 | } 80 | 81 | public void setReservedAt(Instant reservedAt) { 82 | this.reservedAt = reservedAt; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/models/Customer.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.models; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.Table; 7 | 8 | import java.util.Objects; 9 | 10 | import static jakarta.persistence.GenerationType.*; 11 | 12 | @Entity 13 | @Table(name = "customers") 14 | public class Customer { 15 | 16 | @Id 17 | @GeneratedValue(strategy = IDENTITY) 18 | private Long id; 19 | 20 | private String name; 21 | 22 | private String cpf; 23 | 24 | private String email; 25 | 26 | public Customer() { 27 | } 28 | 29 | public Customer(Long id, String name, String cpf, String email) { 30 | this.id = id; 31 | this.name = name; 32 | this.cpf = cpf; 33 | this.email = email; 34 | } 35 | 36 | public Long getId() { 37 | return id; 38 | } 39 | 40 | public void setId(Long id) { 41 | this.id = id; 42 | } 43 | 44 | public String getName() { 45 | return name; 46 | } 47 | 48 | public void setName(String name) { 49 | this.name = name; 50 | } 51 | 52 | public String getCpf() { 53 | return cpf; 54 | } 55 | 56 | public void setCpf(String cpf) { 57 | this.cpf = cpf; 58 | } 59 | 60 | public String getEmail() { 61 | return email; 62 | } 63 | 64 | public void setEmail(String email) { 65 | this.email = email; 66 | } 67 | 68 | @Override 69 | public boolean equals(Object o) { 70 | if (this == o) return true; 71 | if (o == null || getClass() != o.getClass()) return false; 72 | Customer customer = (Customer) o; 73 | return Objects.equals(id, customer.id); 74 | } 75 | 76 | @Override 77 | public int hashCode() { 78 | return Objects.hash(id); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/models/Event.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.models; 2 | 3 | import jakarta.persistence.*; 4 | 5 | import java.time.LocalDate; 6 | import java.util.HashSet; 7 | import java.util.Objects; 8 | import java.util.Set; 9 | 10 | import static jakarta.persistence.GenerationType.IDENTITY; 11 | 12 | @Entity 13 | @Table(name = "events") 14 | public class Event { 15 | 16 | @Id 17 | @GeneratedValue(strategy = IDENTITY) 18 | private Long id; 19 | 20 | private String name; 21 | 22 | private LocalDate date; 23 | 24 | private int totalSpots; 25 | 26 | @ManyToOne(fetch = FetchType.LAZY) 27 | private Partner partner; 28 | 29 | @OneToMany(cascade = CascadeType.ALL, mappedBy = "event") 30 | private Set tickets; 31 | 32 | public Event() { 33 | this.tickets = new HashSet<>(); 34 | } 35 | 36 | public Event(Long id, String name, LocalDate date, int totalSpots, Set tickets) { 37 | this.id = id; 38 | this.name = name; 39 | this.date = date; 40 | this.totalSpots = totalSpots; 41 | this.tickets = tickets != null ? tickets : new HashSet<>(); 42 | } 43 | 44 | public Long getId() { 45 | return id; 46 | } 47 | 48 | public void setId(Long id) { 49 | this.id = id; 50 | } 51 | 52 | public String getName() { 53 | return name; 54 | } 55 | 56 | public void setName(String name) { 57 | this.name = name; 58 | } 59 | 60 | public LocalDate getDate() { 61 | return date; 62 | } 63 | 64 | public void setDate(LocalDate date) { 65 | this.date = date; 66 | } 67 | 68 | public int getTotalSpots() { 69 | return totalSpots; 70 | } 71 | 72 | public void setTotalSpots(int totalSpots) { 73 | this.totalSpots = totalSpots; 74 | } 75 | 76 | public Partner getPartner() { 77 | return partner; 78 | } 79 | 80 | public void setPartner(Partner partner) { 81 | this.partner = partner; 82 | } 83 | 84 | public Set getTickets() { 85 | return tickets; 86 | } 87 | 88 | public void setTickets(Set tickets) { 89 | this.tickets = tickets; 90 | } 91 | 92 | @Override 93 | public boolean equals(Object o) { 94 | if (this == o) return true; 95 | if (o == null || getClass() != o.getClass()) return false; 96 | Event event = (Event) o; 97 | return Objects.equals(id, event.id); 98 | } 99 | 100 | @Override 101 | public int hashCode() { 102 | return Objects.hash(id); 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/models/Partner.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.models; 2 | 3 | import jakarta.persistence.Entity; 4 | import jakarta.persistence.GeneratedValue; 5 | import jakarta.persistence.Id; 6 | import jakarta.persistence.Table; 7 | 8 | import static jakarta.persistence.GenerationType.IDENTITY; 9 | 10 | @Entity 11 | @Table(name = "partners") 12 | public class Partner { 13 | 14 | @Id 15 | @GeneratedValue(strategy = IDENTITY) 16 | private Long id; 17 | 18 | private String name; 19 | 20 | private String cnpj; 21 | 22 | private String email; 23 | 24 | public Partner() { 25 | } 26 | 27 | public Partner(Long id, String name, String cnpj, String email) { 28 | this.id = id; 29 | this.name = name; 30 | this.cnpj = cnpj; 31 | this.email = email; 32 | } 33 | 34 | public Long getId() { 35 | return id; 36 | } 37 | 38 | public void setId(Long id) { 39 | this.id = id; 40 | } 41 | 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | public String getCnpj() { 51 | return cnpj; 52 | } 53 | 54 | public void setCnpj(String cnpj) { 55 | this.cnpj = cnpj; 56 | } 57 | 58 | public String getEmail() { 59 | return email; 60 | } 61 | 62 | public void setEmail(String email) { 63 | this.email = email; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/models/Ticket.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.models; 2 | 3 | import jakarta.persistence.*; 4 | 5 | import java.time.Instant; 6 | import java.util.Objects; 7 | 8 | import static jakarta.persistence.GenerationType.IDENTITY; 9 | 10 | @Entity 11 | @Table(name = "tickets") 12 | public class Ticket { 13 | 14 | @Id 15 | @GeneratedValue(strategy = IDENTITY) 16 | private Long id; 17 | 18 | @ManyToOne(fetch = FetchType.LAZY) 19 | private Customer customer; 20 | 21 | @ManyToOne(fetch = FetchType.LAZY) 22 | private Event event; 23 | 24 | @Enumerated(EnumType.STRING) 25 | private TicketStatus status; 26 | 27 | private Instant paidAt; 28 | 29 | private Instant reservedAt; 30 | 31 | public Ticket() { 32 | } 33 | 34 | public Ticket(Long id, Customer customer, Event event, TicketStatus status, Instant paidAt, Instant reservedAt) { 35 | this.id = id; 36 | this.customer = customer; 37 | this.event = event; 38 | this.status = status; 39 | this.paidAt = paidAt; 40 | this.reservedAt = reservedAt; 41 | } 42 | 43 | public Long getId() { 44 | return id; 45 | } 46 | 47 | public void setId(Long id) { 48 | this.id = id; 49 | } 50 | 51 | public Customer getCustomer() { 52 | return customer; 53 | } 54 | 55 | public void setCustomer(Customer customer) { 56 | this.customer = customer; 57 | } 58 | 59 | public Event getEvent() { 60 | return event; 61 | } 62 | 63 | public void setEvent(Event event) { 64 | this.event = event; 65 | } 66 | 67 | public TicketStatus getStatus() { 68 | return status; 69 | } 70 | 71 | public void setStatus(TicketStatus status) { 72 | this.status = status; 73 | } 74 | 75 | public Instant getPaidAt() { 76 | return paidAt; 77 | } 78 | 79 | public void setPaidAt(Instant paidAt) { 80 | this.paidAt = paidAt; 81 | } 82 | 83 | public Instant getReservedAt() { 84 | return reservedAt; 85 | } 86 | 87 | public void setReservedAt(Instant reservedAt) { 88 | this.reservedAt = reservedAt; 89 | } 90 | 91 | @Override 92 | public boolean equals(Object o) { 93 | if (this == o) return true; 94 | if (o == null || getClass() != o.getClass()) return false; 95 | Ticket ticket = (Ticket) o; 96 | return Objects.equals(customer, ticket.customer) && Objects.equals(event, ticket.event); 97 | } 98 | 99 | @Override 100 | public int hashCode() { 101 | return Objects.hash(customer, event); 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/models/TicketStatus.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.models; 2 | 3 | public enum TicketStatus { 4 | PENDING, PROCESSING, PAID; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/repositories/CustomerRepository.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.repositories; 2 | 3 | import br.com.fullcycle.hexagonal.models.Customer; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface CustomerRepository extends CrudRepository { 9 | 10 | Optional findByCpf(String cpf); 11 | 12 | Optional findByEmail(String email); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/repositories/EventRepository.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.repositories; 2 | 3 | import br.com.fullcycle.hexagonal.models.Event; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | public interface EventRepository extends CrudRepository { 7 | 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/repositories/PartnerRepository.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.repositories; 2 | 3 | import br.com.fullcycle.hexagonal.models.Partner; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface PartnerRepository extends CrudRepository { 9 | 10 | Optional findByCnpj(String cnpj); 11 | 12 | Optional findByEmail(String email); 13 | } -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/repositories/TicketRepository.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.repositories; 2 | 3 | import br.com.fullcycle.hexagonal.models.Ticket; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | import java.util.Optional; 7 | 8 | public interface TicketRepository extends CrudRepository { 9 | 10 | Optional findByEventIdAndCustomerId(Long id, Long customerId); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/services/CustomerService.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.services; 2 | 3 | import br.com.fullcycle.hexagonal.models.Customer; 4 | import br.com.fullcycle.hexagonal.repositories.CustomerRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.Optional; 10 | 11 | @Service 12 | public class CustomerService { 13 | 14 | @Autowired 15 | private CustomerRepository repository; 16 | 17 | @Transactional 18 | public Customer save(Customer customer) { 19 | return repository.save(customer); 20 | } 21 | 22 | public Optional findById(Long id) { 23 | return repository.findById(id); 24 | } 25 | 26 | public Optional findByCpf(String cpf) { 27 | return repository.findByCpf(cpf); 28 | } 29 | 30 | public Optional findByEmail(String email) { 31 | return repository.findByEmail(email); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/services/EventService.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.services; 2 | 3 | import br.com.fullcycle.hexagonal.models.Event; 4 | import br.com.fullcycle.hexagonal.models.Ticket; 5 | import br.com.fullcycle.hexagonal.repositories.EventRepository; 6 | import br.com.fullcycle.hexagonal.repositories.TicketRepository; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Service; 9 | import org.springframework.transaction.annotation.Transactional; 10 | 11 | import java.util.Optional; 12 | 13 | @Service 14 | public class EventService { 15 | 16 | @Autowired 17 | private CustomerService customerService; 18 | 19 | @Autowired 20 | private EventRepository eventRepository; 21 | 22 | @Autowired 23 | private TicketRepository ticketRepository; 24 | 25 | @Transactional 26 | public Event save(Event event) { 27 | return eventRepository.save(event); 28 | } 29 | 30 | public Optional findById(Long id) { 31 | return eventRepository.findById(id); 32 | } 33 | 34 | public Optional findTicketByEventIdAndCustomerId(Long id, Long customerId) { 35 | return ticketRepository.findByEventIdAndCustomerId(id, customerId); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/br/com/fullcycle/hexagonal/services/PartnerService.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.services; 2 | 3 | import br.com.fullcycle.hexagonal.models.Partner; 4 | import br.com.fullcycle.hexagonal.repositories.PartnerRepository; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | import org.springframework.transaction.annotation.Transactional; 8 | 9 | import java.util.Optional; 10 | 11 | @Service 12 | public class PartnerService { 13 | 14 | @Autowired 15 | private PartnerRepository repository; 16 | 17 | @Transactional 18 | public Partner save(Partner customer) { 19 | return repository.save(customer); 20 | } 21 | 22 | public Optional findById(Long id) { 23 | return repository.findById(id); 24 | } 25 | 26 | public Optional findByCnpj(String cnpj) { 27 | return repository.findByCnpj(cnpj); 28 | } 29 | 30 | public Optional findByEmail(String email) { 31 | return repository.findByEmail(email); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/resources/application-test.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:adm_videos_test;MODE=MYSQL;DATABASE_TO_LOWER=TRUE 2 | spring.datasource.driver-class-name=org.h2.Driver -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:mysql://localhost:3306/events 2 | spring.datasource.username=root 3 | spring.datasource.password=root 4 | spring.jpa.hibernate.ddl-auto=update 5 | spring.jpa.open-in-view=false 6 | spring.jpa.show-sql=true -------------------------------------------------------------------------------- /src/test/java/br/com/fullcycle/hexagonal/MainTests.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | import org.springframework.test.context.ActiveProfiles; 6 | 7 | @ActiveProfiles("test") 8 | @SpringBootTest 9 | class MainTests { 10 | 11 | @Test 12 | void contextLoads() { 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/test/java/br/com/fullcycle/hexagonal/controllers/CustomerControllerTest.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.CustomerDTO; 4 | import br.com.fullcycle.hexagonal.repositories.CustomerRepository; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.junit.jupiter.api.*; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.test.context.ActiveProfiles; 12 | import org.springframework.test.web.servlet.MockMvc; 13 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 14 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 | 16 | @ActiveProfiles("test") 17 | @AutoConfigureMockMvc 18 | @SpringBootTest 19 | public class CustomerControllerTest { 20 | 21 | @Autowired 22 | private MockMvc mvc; 23 | 24 | @Autowired 25 | private ObjectMapper mapper; 26 | 27 | @Autowired 28 | private CustomerRepository customerRepository; 29 | 30 | @AfterEach 31 | void tearDown() { 32 | customerRepository.deleteAll(); 33 | } 34 | 35 | @Test 36 | @DisplayName("Deve criar um cliente") 37 | public void testCreate() throws Exception { 38 | 39 | var customer = new CustomerDTO(); 40 | customer.setCpf("12345678901"); 41 | customer.setEmail("john.doe@gmail.com"); 42 | customer.setName("John Doe"); 43 | 44 | final var result = this.mvc.perform( 45 | MockMvcRequestBuilders.post("/customers") 46 | .contentType(MediaType.APPLICATION_JSON) 47 | .content(mapper.writeValueAsString(customer)) 48 | ) 49 | .andExpect(MockMvcResultMatchers.status().isCreated()) 50 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 51 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 52 | .andReturn().getResponse().getContentAsByteArray(); 53 | 54 | var actualResponse = mapper.readValue(result, CustomerDTO.class); 55 | Assertions.assertEquals(customer.getName(), actualResponse.getName()); 56 | Assertions.assertEquals(customer.getCpf(), actualResponse.getCpf()); 57 | Assertions.assertEquals(customer.getEmail(), actualResponse.getEmail()); 58 | } 59 | 60 | @Test 61 | @DisplayName("Não deve cadastrar um cliente com CPF duplicado") 62 | public void testCreateWithDuplicatedCPFShouldFail() throws Exception { 63 | 64 | var customer = new CustomerDTO(); 65 | customer.setCpf("12345678901"); 66 | customer.setEmail("john.doe@gmail.com"); 67 | customer.setName("John Doe"); 68 | 69 | // Cria o primeiro cliente 70 | this.mvc.perform( 71 | MockMvcRequestBuilders.post("/customers") 72 | .contentType(MediaType.APPLICATION_JSON) 73 | .content(mapper.writeValueAsString(customer)) 74 | ) 75 | .andExpect(MockMvcResultMatchers.status().isCreated()) 76 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 77 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 78 | .andReturn().getResponse().getContentAsByteArray(); 79 | 80 | customer.setEmail("john2@gmail.com"); 81 | 82 | // Tenta criar o segundo cliente com o mesmo CPF 83 | this.mvc.perform( 84 | MockMvcRequestBuilders.post("/customers") 85 | .contentType(MediaType.APPLICATION_JSON) 86 | .content(mapper.writeValueAsString(customer)) 87 | ) 88 | .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity()) 89 | .andExpect(MockMvcResultMatchers.content().string("Customer already exists")); 90 | } 91 | 92 | @Test 93 | @DisplayName("Não deve cadastrar um cliente com e-mail duplicado") 94 | public void testCreateWithDuplicatedEmailShouldFail() throws Exception { 95 | 96 | var customer = new CustomerDTO(); 97 | customer.setCpf("12345618901"); 98 | customer.setEmail("john.doe@gmail.com"); 99 | customer.setName("John Doe"); 100 | 101 | // Cria o primeiro cliente 102 | this.mvc.perform( 103 | MockMvcRequestBuilders.post("/customers") 104 | .contentType(MediaType.APPLICATION_JSON) 105 | .content(mapper.writeValueAsString(customer)) 106 | ) 107 | .andExpect(MockMvcResultMatchers.status().isCreated()) 108 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 109 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 110 | .andReturn().getResponse().getContentAsByteArray(); 111 | 112 | customer.setCpf("99999918901"); 113 | 114 | // Tenta criar o segundo cliente com o mesmo CPF 115 | this.mvc.perform( 116 | MockMvcRequestBuilders.post("/customers") 117 | .contentType(MediaType.APPLICATION_JSON) 118 | .content(mapper.writeValueAsString(customer)) 119 | ) 120 | .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity()) 121 | .andExpect(MockMvcResultMatchers.content().string("Customer already exists")); 122 | } 123 | 124 | @Test 125 | @DisplayName("Deve obter um cliente por id") 126 | public void testGet() throws Exception { 127 | 128 | var customer = new CustomerDTO(); 129 | customer.setCpf("12345678901"); 130 | customer.setEmail("john.doe@gmail.com"); 131 | customer.setName("John Doe"); 132 | 133 | final var createResult = this.mvc.perform( 134 | MockMvcRequestBuilders.post("/customers") 135 | .contentType(MediaType.APPLICATION_JSON) 136 | .content(mapper.writeValueAsString(customer)) 137 | ) 138 | .andReturn().getResponse().getContentAsByteArray(); 139 | 140 | var customerId = mapper.readValue(createResult, CustomerDTO.class).getId(); 141 | 142 | final var result = this.mvc.perform( 143 | MockMvcRequestBuilders.get("/customers/{id}", customerId) 144 | ) 145 | .andExpect(MockMvcResultMatchers.status().isOk()) 146 | .andReturn().getResponse().getContentAsByteArray(); 147 | 148 | var actualResponse = mapper.readValue(result, CustomerDTO.class); 149 | Assertions.assertEquals(customerId, actualResponse.getId()); 150 | Assertions.assertEquals(customer.getName(), actualResponse.getName()); 151 | Assertions.assertEquals(customer.getCpf(), actualResponse.getCpf()); 152 | Assertions.assertEquals(customer.getEmail(), actualResponse.getEmail()); 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /src/test/java/br/com/fullcycle/hexagonal/controllers/EventControllerTest.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.EventDTO; 4 | import br.com.fullcycle.hexagonal.dtos.PartnerDTO; 5 | import br.com.fullcycle.hexagonal.dtos.SubscribeDTO; 6 | import br.com.fullcycle.hexagonal.models.Customer; 7 | import br.com.fullcycle.hexagonal.models.Partner; 8 | import br.com.fullcycle.hexagonal.repositories.CustomerRepository; 9 | import br.com.fullcycle.hexagonal.repositories.EventRepository; 10 | import br.com.fullcycle.hexagonal.repositories.PartnerRepository; 11 | import com.fasterxml.jackson.databind.ObjectMapper; 12 | import org.junit.jupiter.api.*; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 15 | import org.springframework.boot.test.context.SpringBootTest; 16 | import org.springframework.http.MediaType; 17 | import org.springframework.test.context.ActiveProfiles; 18 | import org.springframework.test.web.servlet.MockMvc; 19 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 20 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 21 | import org.springframework.transaction.annotation.Transactional; 22 | 23 | @ActiveProfiles("test") 24 | @AutoConfigureMockMvc 25 | @SpringBootTest 26 | class EventControllerTest { 27 | 28 | @Autowired 29 | private MockMvc mvc; 30 | 31 | @Autowired 32 | private ObjectMapper mapper; 33 | 34 | @Autowired 35 | private CustomerRepository customerRepository; 36 | 37 | @Autowired 38 | private PartnerRepository partnerRepository; 39 | 40 | @Autowired 41 | private EventRepository eventRepository; 42 | 43 | private Customer johnDoe; 44 | private Partner disney; 45 | 46 | @BeforeEach 47 | void setUp() { 48 | johnDoe = customerRepository.save(new Customer(null, "John Doe", "123", "john@gmail.com")); 49 | disney = partnerRepository.save(new Partner(null, "Disney", "456", "disney@gmail.com")); 50 | } 51 | 52 | @AfterEach 53 | void tearDown() { 54 | eventRepository.deleteAll(); 55 | customerRepository.deleteAll(); 56 | partnerRepository.deleteAll(); 57 | } 58 | 59 | @Test 60 | @DisplayName("Deve criar um evento") 61 | public void testCreate() throws Exception { 62 | 63 | var event = new EventDTO(); 64 | event.setDate("2021-01-01"); 65 | event.setName("Disney on Ice"); 66 | event.setTotalSpots(100); 67 | event.setPartner(new PartnerDTO(disney.getId())); 68 | 69 | final var result = this.mvc.perform( 70 | MockMvcRequestBuilders.post("/events") 71 | .contentType(MediaType.APPLICATION_JSON) 72 | .content(mapper.writeValueAsString(event)) 73 | ) 74 | .andExpect(MockMvcResultMatchers.status().isCreated()) 75 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 76 | .andReturn().getResponse().getContentAsByteArray(); 77 | 78 | var actualResponse = mapper.readValue(result, EventDTO.class); 79 | Assertions.assertEquals(event.getDate(), actualResponse.getDate()); 80 | Assertions.assertEquals(event.getTotalSpots(), actualResponse.getTotalSpots()); 81 | Assertions.assertEquals(event.getName(), actualResponse.getName()); 82 | } 83 | 84 | @Test 85 | @Transactional 86 | @DisplayName("Deve comprar um ticket de um evento") 87 | public void testReserveTicket() throws Exception { 88 | 89 | var event = new EventDTO(); 90 | event.setDate("2021-01-01"); 91 | event.setName("Disney on Ice"); 92 | event.setTotalSpots(100); 93 | event.setPartner(new PartnerDTO(disney.getId())); 94 | 95 | final var createResult = this.mvc.perform( 96 | MockMvcRequestBuilders.post("/events") 97 | .contentType(MediaType.APPLICATION_JSON) 98 | .content(mapper.writeValueAsString(event)) 99 | ) 100 | .andExpect(MockMvcResultMatchers.status().isCreated()) 101 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 102 | .andReturn().getResponse().getContentAsByteArray(); 103 | 104 | var eventId = mapper.readValue(createResult, EventDTO.class).getId(); 105 | 106 | var sub = new SubscribeDTO(); 107 | sub.setCustomerId(johnDoe.getId()); 108 | 109 | this.mvc.perform( 110 | MockMvcRequestBuilders.post("/events/{id}/subscribe", eventId) 111 | .contentType(MediaType.APPLICATION_JSON) 112 | .content(mapper.writeValueAsString(sub)) 113 | ) 114 | .andExpect(MockMvcResultMatchers.status().isOk()) 115 | .andReturn().getResponse().getContentAsByteArray(); 116 | 117 | var actualEvent = eventRepository.findById(eventId).get(); 118 | Assertions.assertEquals(1, actualEvent.getTickets().size()); 119 | } 120 | } -------------------------------------------------------------------------------- /src/test/java/br/com/fullcycle/hexagonal/controllers/PartnerControllerTest.java: -------------------------------------------------------------------------------- 1 | package br.com.fullcycle.hexagonal.controllers; 2 | 3 | import br.com.fullcycle.hexagonal.dtos.PartnerDTO; 4 | import br.com.fullcycle.hexagonal.repositories.PartnerRepository; 5 | import com.fasterxml.jackson.databind.ObjectMapper; 6 | import org.junit.jupiter.api.*; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 9 | import org.springframework.boot.test.context.SpringBootTest; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.test.context.ActiveProfiles; 12 | import org.springframework.test.web.servlet.MockMvc; 13 | import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 14 | import org.springframework.test.web.servlet.result.MockMvcResultMatchers; 15 | 16 | @ActiveProfiles("test") 17 | @AutoConfigureMockMvc 18 | @SpringBootTest 19 | public class PartnerControllerTest { 20 | 21 | @Autowired 22 | private MockMvc mvc; 23 | 24 | @Autowired 25 | private ObjectMapper mapper; 26 | 27 | @Autowired 28 | private PartnerRepository partnerRepository; 29 | 30 | @AfterEach 31 | void tearDown() { 32 | partnerRepository.deleteAll(); 33 | } 34 | 35 | @Test 36 | @DisplayName("Deve criar um parceiro") 37 | public void testCreate() throws Exception { 38 | 39 | var partner = new PartnerDTO(); 40 | partner.setCnpj("41536538000100"); 41 | partner.setEmail("john.doe@gmail.com"); 42 | partner.setName("John Doe"); 43 | 44 | final var result = this.mvc.perform( 45 | MockMvcRequestBuilders.post("/partners") 46 | .contentType(MediaType.APPLICATION_JSON) 47 | .content(mapper.writeValueAsString(partner)) 48 | ) 49 | .andExpect(MockMvcResultMatchers.status().isCreated()) 50 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 51 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 52 | .andReturn().getResponse().getContentAsByteArray(); 53 | 54 | var actualResponse = mapper.readValue(result, PartnerDTO.class); 55 | Assertions.assertEquals(partner.getName(), actualResponse.getName()); 56 | Assertions.assertEquals(partner.getCnpj(), actualResponse.getCnpj()); 57 | Assertions.assertEquals(partner.getEmail(), actualResponse.getEmail()); 58 | } 59 | 60 | @Test 61 | @DisplayName("Não deve cadastrar um parceiro com CNPJ duplicado") 62 | public void testCreateWithDuplicatedCPFShouldFail() throws Exception { 63 | 64 | var partner = new PartnerDTO(); 65 | partner.setCnpj("41536538000100"); 66 | partner.setEmail("john.doe@gmail.com"); 67 | partner.setName("John Doe"); 68 | 69 | // Cria o primeiro parceiro 70 | this.mvc.perform( 71 | MockMvcRequestBuilders.post("/partners") 72 | .contentType(MediaType.APPLICATION_JSON) 73 | .content(mapper.writeValueAsString(partner)) 74 | ) 75 | .andExpect(MockMvcResultMatchers.status().isCreated()) 76 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 77 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 78 | .andReturn().getResponse().getContentAsByteArray(); 79 | 80 | partner.setEmail("john2@gmail.com"); 81 | 82 | // Tenta criar o segundo parceiro com o mesmo CPF 83 | this.mvc.perform( 84 | MockMvcRequestBuilders.post("/partners") 85 | .contentType(MediaType.APPLICATION_JSON) 86 | .content(mapper.writeValueAsString(partner)) 87 | ) 88 | .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity()) 89 | .andExpect(MockMvcResultMatchers.content().string("Partner already exists")); 90 | } 91 | 92 | @Test 93 | @DisplayName("Não deve cadastrar um parceiro com e-mail duplicado") 94 | public void testCreateWithDuplicatedEmailShouldFail() throws Exception { 95 | 96 | var partner = new PartnerDTO(); 97 | partner.setCnpj("41536538000100"); 98 | partner.setEmail("john.doe@gmail.com"); 99 | partner.setName("John Doe"); 100 | 101 | // Cria o primeiro parceiro 102 | this.mvc.perform( 103 | MockMvcRequestBuilders.post("/partners") 104 | .contentType(MediaType.APPLICATION_JSON) 105 | .content(mapper.writeValueAsString(partner)) 106 | ) 107 | .andExpect(MockMvcResultMatchers.status().isCreated()) 108 | .andExpect(MockMvcResultMatchers.header().exists("Location")) 109 | .andExpect(MockMvcResultMatchers.jsonPath("$.id").isNumber()) 110 | .andReturn().getResponse().getContentAsByteArray(); 111 | 112 | partner.setCnpj("66666538000100"); 113 | 114 | // Tenta criar o segundo parceiro com o mesmo CNPJ 115 | this.mvc.perform( 116 | MockMvcRequestBuilders.post("/partners") 117 | .contentType(MediaType.APPLICATION_JSON) 118 | .content(mapper.writeValueAsString(partner)) 119 | ) 120 | .andExpect(MockMvcResultMatchers.status().isUnprocessableEntity()) 121 | .andExpect(MockMvcResultMatchers.content().string("Partner already exists")); 122 | } 123 | 124 | @Test 125 | @DisplayName("Deve obter um parceiro por id") 126 | public void testGet() throws Exception { 127 | 128 | var partner = new PartnerDTO(); 129 | partner.setCnpj("41536538000100"); 130 | partner.setEmail("john.doe@gmail.com"); 131 | partner.setName("John Doe"); 132 | 133 | final var createResult = this.mvc.perform( 134 | MockMvcRequestBuilders.post("/partners") 135 | .contentType(MediaType.APPLICATION_JSON) 136 | .content(mapper.writeValueAsString(partner)) 137 | ) 138 | .andReturn().getResponse().getContentAsByteArray(); 139 | 140 | var partnerId = mapper.readValue(createResult, PartnerDTO.class).getId(); 141 | 142 | final var result = this.mvc.perform( 143 | MockMvcRequestBuilders.get("/partners/{id}", partnerId) 144 | ) 145 | .andExpect(MockMvcResultMatchers.status().isOk()) 146 | .andReturn().getResponse().getContentAsByteArray(); 147 | 148 | var actualResponse = mapper.readValue(result, PartnerDTO.class); 149 | Assertions.assertEquals(partnerId, actualResponse.getId()); 150 | Assertions.assertEquals(partner.getName(), actualResponse.getName()); 151 | Assertions.assertEquals(partner.getCnpj(), actualResponse.getCnpj()); 152 | Assertions.assertEquals(partner.getEmail(), actualResponse.getEmail()); 153 | } 154 | } 155 | --------------------------------------------------------------------------------