Skip to content

Commit

Permalink
Merge pull request #8 from diegosneves/feat/invoices
Browse files Browse the repository at this point in the history
feat(envio de email) 🔖 Remover o código da estratégia de pagamento e melhorar a lógica de negócios
  • Loading branch information
diegosneves authored Dec 24, 2023
2 parents d54293c + c4a9e8a commit 4324677
Show file tree
Hide file tree
Showing 32 changed files with 546 additions and 149 deletions.
36 changes: 18 additions & 18 deletions .github/workflows/ci-main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,24 @@ jobs:
- name: Run Tests
run: mvn test
#TODO Descomentar essa linha apos as variaveis serem inseridas no Github e o dockerfile estar pronto...
# - name: Set up QEMU
# uses: docker/setup-qemu-action@v2
#
# - name: Set up Docker Buildx
# uses: docker/setup-buildx-action@v2
#
# - name: Login to DockerHub
# uses: docker/login-action@v2
# with:
# username: ${{ secrets.DOCKERHUB_USERNAME }}
# password: ${{ secrets.DOCKERHUB_TOKEN }}
#
# - name: Build and push
# id: docker_build
# uses: docker/build-push-action@v4
# with:
# push: true
# tags: diegoneves/racha-pedido:latest
- name: Set up QEMU
uses: docker/setup-qemu-action@v2

- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2

- name: Login to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}

- name: Build and push
id: docker_build
uses: docker/build-push-action@v4
with:
push: true
tags: diegoneves/racha-pedido:latest


# - name: Build and push
Expand Down
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,35 @@ lanches ou refeições solicitados por meio de aplicativos de entrega como iFood

[//]: # ( TODO Inserir os dados do docker-compose aqui...)
```yaml
Docker-compose em construção...
version: '3.9'

services:
email_server:
image: diegoneves/email-server:latest
restart: always
container_name: email_server
networks:
- pedido-bridge
ports:
- "8081:8081"

racha-pedido-app:
image: diegoneves/racha-pedido:latest
container_name: racha-pedido
ports:
- "8080:8080"
depends_on:
- email_server
networks:
- pedido-bridge
environment:
- EMAIL_HOST=email_server
- EMAIL_PORT=8081


networks:
pedido-bridge:
driver: bridge
```
Lembre-se de estar no diretório onde o seu arquivo `docker-compose.yaml` está localizado antes de executar esses comandos.
Expand Down
29 changes: 29 additions & 0 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
version: '3.9'

services:
email_server:
image: diegoneves/email-server:latest
restart: always
container_name: email_server
networks:
- pedido-bridge
ports:
- "8081:8081"

racha-pedido-app:
image: diegoneves/racha-pedido:latest
container_name: racha-pedido
ports:
- "8080:8080"
depends_on:
- email_server
networks:
- pedido-bridge
environment:
- EMAIL_HOST=email_server
- EMAIL_PORT=8081


networks:
pedido-bridge:
driver: bridge
17 changes: 17 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,23 @@
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.2.0</version>
</dependency>

<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-mail</artifactId>-->
<!-- </dependency>-->

<!-- &lt;!&ndash; Thymeleaf Dependency &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-thymeleaf</artifactId>-->
<!-- </dependency>-->

<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-configuration-processor</artifactId>-->
<!-- <optional>true</optional>-->
<!-- </dependency>-->
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package diegosneves.github.rachapedido.adapter;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Getter(AccessLevel.PROTECTED)
@Setter(AccessLevel.PROTECTED)
public abstract class HttpAdapter {

protected RestTemplateSimpleWebClient restTemplateSimpleWebClient;
protected HttpHeaders headers;

protected HttpAdapter() {
this.headers = new HttpHeaders();
this.headers.setContentType(MediaType.APPLICATION_JSON);
this.headers.setAccept(List.of(MediaType.APPLICATION_JSON));
this.restTemplateSimpleWebClient = new RestTemplateSimpleWebClient();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package diegosneves.github.rachapedido.adapter;

import lombok.Getter;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Getter
public class RestTemplateSimpleWebClient {

private final RestTemplate restTemplate;

public RestTemplateSimpleWebClient() {
this.restTemplate = new RestTemplate();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package diegosneves.github.rachapedido.adapter;

import diegosneves.github.rachapedido.core.BankAccount;
import diegosneves.github.rachapedido.exceptions.ErroHandler;
import diegosneves.github.rachapedido.model.Item;
import diegosneves.github.rachapedido.model.NotificationEmail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;

import java.util.List;

@Component
@Slf4j
public class SendEmailAdapter extends HttpAdapter {

private final String url;

@Autowired
public SendEmailAdapter(@Value("${spring.api.url.send-email}") String url) {
this.url = url;
}

public void sendNotificationEmail(NotificationEmail notificationEmail) {
// Item itemII = Item.builder()
// .name("Item II")
// .price(2.00)
// .build();
//
// Item itemIII = Item.builder()
// .name("Item III")
// .price(8.00)
// .build();
// notificationEmail = NotificationEmail.builder()
// .email("[email protected]")
// .consumerName("Diego Neves")
// .total(10.00)
// .itens(List.of(itemII, itemIII))
// .link(BankAccount.PICPAY.paymentLink())
// .build();

try {
String response = this.restTemplateSimpleWebClient
.getRestTemplate()
.postForEntity(this.url, notificationEmail, String.class)
.getBody();
log.info(response);
} catch (RestClientException e) {
log.error(ErroHandler.EMAIL_SEND_FAILURE.errorMessage(notificationEmail.getEmail()), e);
}

}

}
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
package diegosneves.github.rachapedido.config;

import diegosneves.github.rachapedido.dto.ExceptionDTO;
import diegosneves.github.rachapedido.exceptions.CalculateInvoiceException;
import diegosneves.github.rachapedido.exceptions.CloseOrderException;
import diegosneves.github.rachapedido.exceptions.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
Expand Down Expand Up @@ -37,4 +36,22 @@ public ResponseEntity<ExceptionDTO> orderRelatedFaileures(CalculateInvoiceExcept
return ResponseEntity.status(CalculateInvoiceException.ERROR.getHttpStatusCode()).body(dto);
}

@ExceptionHandler(ConstructorDefaultUndefinedException.class)
public ResponseEntity<ExceptionDTO> mapperRelatedFaileures(ConstructorDefaultUndefinedException exception) {
ExceptionDTO dto = new ExceptionDTO(exception.getMessage(), ConstructorDefaultUndefinedException.ERROR.getStatusCodeValue());
return ResponseEntity.status(ConstructorDefaultUndefinedException.ERROR.getHttpStatusCode()).body(dto);
}

@ExceptionHandler(MapperFailureException.class)
public ResponseEntity<ExceptionDTO> mapperRelatedFaileures(MapperFailureException exception) {
ExceptionDTO dto = new ExceptionDTO(exception.getMessage(), MapperFailureException.ERROR.getStatusCodeValue());
return ResponseEntity.status(MapperFailureException.ERROR.getHttpStatusCode()).body(dto);
}

@ExceptionHandler(PersonConstraintsException.class)
public ResponseEntity<ExceptionDTO> consumerRelatedFaileures(PersonConstraintsException exception) {
ExceptionDTO dto = new ExceptionDTO(exception.getMessage(), PersonConstraintsException.ERROR.getStatusCodeValue());
return ResponseEntity.status(PersonConstraintsException.ERROR.getHttpStatusCode()).body(dto);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public SplitInvoiceController(@Autowired SplitInvoiceService service) {

@Override
public ResponseEntity<SplitInvoiceResponse> splitInvoice(SplitInvoiceRequest request) {
SplitInvoiceResponse response = this.service.splitInvoice(request); // TODO - Criar a regra de negocio
SplitInvoiceResponse response = this.service.splitInvoice(request);
return ResponseEntity.ok(response);
}
}
22 changes: 22 additions & 0 deletions src/main/java/diegosneves/github/rachapedido/core/BankAccount.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package diegosneves.github.rachapedido.core;

import com.fasterxml.jackson.annotation.JsonProperty;

public enum BankAccount {

@JsonProperty(value = "nubank")
NUBANK("https://nubank.com.br/cobrar/5h2au/658235a8-f38a-4cf5-881c-1de7114d66c7"),
@JsonProperty(value = "picpay")
PICPAY("https://app.picpay.com/user/diego.neves215");

private final String billingLink;

BankAccount(String billingLink) {
this.billingLink = billingLink;
}

public String paymentLink() {
return this.billingLink;
}

}
16 changes: 0 additions & 16 deletions src/main/java/diegosneves/github/rachapedido/core/PagBank.java

This file was deleted.

This file was deleted.

23 changes: 23 additions & 0 deletions src/main/java/diegosneves/github/rachapedido/dto/InvoiceDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,29 @@

import lombok.*;

/**
* A classe {@link InvoiceDTO} representa um objeto de transferência de dados de fatura (DTO).
* Ela contém informações sobre o nome do consumidor, valor consumido, valor total a pagar e a porcentagem do total da fatura consumida.
*
* <p>Este objeto possui os seguintes campos:
* <ul>
* <li><b>consumerName</b>: Um {@link String} que representa o nome do consumidor.</li>
* <li><b>valueConsumed</b>: Um {@link Double} que representa o valor consumido pelo consumidor.</li>
* <li><b>totalPayable</b>: Um {@link Double} que representa o valor total a pagar na fatura.</li>
* <li><b>percentageConsumedTotalBill</b>: Um {@link Double} que representa a porcentagem do total da fatura consumida.</li>
* </ul>
* </p>
* Exemplo de Uso:
* <pre>{@code
* InvoiceDTO dto = new InvoiceDTO();
* dto.setConsumerName("João da Silva");
* dto.setValueConsumed(100.0);
* dto.setTotalPayable(90.0);
* dto.setPercentageConsumedTotalBill(90.0);
* }</pre>
*
* @author diegosneves
*/
@NoArgsConstructor
@AllArgsConstructor
@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public enum DiscountType {
}

public Double discountAmount(Double value) {
return this.calculation == 0.0 ? 0.0 : value / this.calculation;
return this.calculation == 0.0 ? this.calculation : value / this.calculation;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@
public enum ErroHandler {

CONSTRUCTOR_DEFAULT_UNDEFINED("Classe [ %s ] deve declarar um construtor padrão.", HttpStatus.NOT_IMPLEMENTED),
NULL_BUYER("O Objeto [ %s ] não deve ser nulo.", HttpStatus.BAD_REQUEST),
ORDER_FAILED("Houve um erro no fechamento do pedido: [ %s ].", HttpStatus.BAD_REQUEST), // TODO - Buscar deixar os demais nessa forma mais generica
INVOICE_FAILED("Ocorreu uma falha durante a execução do cálculo da fatura: [ %s ].", HttpStatus.BAD_REQUEST), // TODO - Buscar deixar os demais nessa forma mais generica
CLASS_MAPPING_FAILURE("Ocorreu um erro ao tentar mapear a classe [ %s ].", HttpStatus.INTERNAL_SERVER_ERROR);
PERSON_CONSTRAINTS("Ocorreu um erro com as validações relacionadas ao consumidor: [ %s ].", HttpStatus.BAD_REQUEST),
ORDER_FAILED("Houve um erro no fechamento do pedido: [ %s ].", HttpStatus.BAD_REQUEST),
INVOICE_FAILED("Ocorreu uma falha durante a execução do cálculo da fatura: [ %s ].", HttpStatus.BAD_REQUEST),
EMAIL_SEND_FAILURE("Falha ao enviar o email de notificação para: [ %s ].", HttpStatus.SERVICE_UNAVAILABLE),
CLASS_MAPPING_FAILURE("Falha ao tentar mapear a classe [ %s ].", HttpStatus.INTERNAL_SERVER_ERROR);

private final String message;
private final HttpStatus httpStatus;
Expand Down
Loading

0 comments on commit 4324677

Please sign in to comment.