Skip to content

Commit

Permalink
Implement new email service RESEND (#476)
Browse files Browse the repository at this point in the history
* Implement @slf4j for logging

* Change some logging type from warn to info

* Disable logging file

* Implement new email service RESEND

* Fix tests

* Fix integration tests

* Add body message in the lista de productos email

* Fix test
  • Loading branch information
belluccifranco authored Jan 22, 2024
1 parent 454dfbb commit 615863a
Show file tree
Hide file tree
Showing 18 changed files with 443 additions and 546 deletions.
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
<newrelic-agent.version>8.5.0</newrelic-agent.version>
<mercadopago.version>2.1.4</mercadopago.version>
<google-gson.version>2.8.9</google-gson.version>
<resend.version>2.2.1</resend.version>
<sonar.exclusions>
src/main/java/sic/modelo/**,
src/main/java/sic/exception/**
Expand Down Expand Up @@ -169,6 +170,11 @@
<artifactId>gson</artifactId>
<version>${google-gson.version}</version>
</dependency>
<dependency>
<groupId>com.resend</groupId>
<artifactId>resend-java</artifactId>
<version>${resend.version}</version>
</dependency>
</dependencies>

<build>
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/sic/service/IEmailService.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,5 @@ public interface IEmailService {
boolean isServicioConfigurado();

void enviarEmail(String toEmail, String bcc, String subject, String mensaje,
byte[] byteArray, String attachmentDescription);
byte[] byteArray, String attachmentName);
}
24 changes: 24 additions & 0 deletions src/main/java/sic/service/impl/EmailServiceFactory.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package sic.service.impl;

import org.springframework.stereotype.Component;
import sic.exception.ServiceException;
import sic.service.IEmailService;
import java.util.Map;

@Component
public class EmailServiceFactory {

private final Map<String, IEmailService> emailServices;

public EmailServiceFactory(Map<String, IEmailService> emailServices) {
this.emailServices = emailServices;
}

public IEmailService getEmailService(String emailServiceProvider) {
var emailService = emailServices.get(emailServiceProvider);
if (emailService == null) {
throw new ServiceException("Proveedor de email no soportado!");
}
return emailService;
}
}
25 changes: 15 additions & 10 deletions src/main/java/sic/service/impl/FacturaVentaServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
Expand Down Expand Up @@ -34,10 +35,13 @@
@Slf4j
public class FacturaVentaServiceImpl implements IFacturaVentaService {

@Value("${EMAIL_DEFAULT_PROVIDER}")
private String emailDefaultProvider;

private final FacturaVentaRepository facturaVentaRepository;
private final ITaxationService taxationService;
private final IReciboService reciboService;
private final IEmailService emailService;
private final EmailServiceFactory emailServiceFactory;
private final IPedidoService pedidoService;
private final IUsuarioService usuarioService;
private final IClienteService clienteService;
Expand All @@ -59,7 +63,7 @@ public FacturaVentaServiceImpl(
FacturaVentaRepository facturaVentaRepository,
ITaxationService taxationService,
IReciboService reciboService,
IEmailService emailService,
EmailServiceFactory emailServiceFactory,
IPedidoService pedidoService,
IUsuarioService usuarioService,
IClienteService clienteService,
Expand All @@ -73,7 +77,7 @@ public FacturaVentaServiceImpl(
this.facturaVentaRepository = facturaVentaRepository;
this.reciboService = reciboService;
this.taxationService = taxationService;
this.emailService = emailService;
this.emailServiceFactory = emailServiceFactory;
this.pedidoService = pedidoService;
this.usuarioService = usuarioService;
this.clienteService = clienteService;
Expand Down Expand Up @@ -511,13 +515,14 @@ public void enviarFacturaVentaPorEmail(long idFactura) {
messageSource.getMessage(
"mensaje_correo_factura_sin_pedido", null, Locale.getDefault());
}
emailService.enviarEmail(
facturaVenta.getCliente().getEmail(),
"",
"Su Factura de Compra",
bodyEmail,
this.getReporteFacturaVenta(factura),
"Reporte.pdf");
emailServiceFactory.getEmailService(emailDefaultProvider)
.enviarEmail(
facturaVenta.getCliente().getEmail(),
"",
"Su Factura de Compra",
bodyEmail,
this.getReporteFacturaVenta(factura),
"Factura.pdf");
log.info(
"El mail de la factura serie {} nro {} se envió.",
factura.getNumSerie(),
Expand Down
17 changes: 9 additions & 8 deletions src/main/java/sic/service/impl/GmailEmailServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Transport;
import sic.exception.BusinessServiceException;
import sic.exception.ServiceException;
import sic.service.IEmailService;
import java.util.Locale;
import java.util.Properties;

@Service
@Service("gmail")
public class GmailEmailServiceImpl implements IEmailService {

@Value("${GMAIL_USERNAME}")
Expand All @@ -29,7 +28,6 @@ public class GmailEmailServiceImpl implements IEmailService {
@Value("${GMAIL_PASSWORD}")
private String gmailPassword;

private static final String MENSAJE_SERVICIO_NO_CONFIGURADO = "El servicio de GMail no se encuentra configurado";
private final MessageSource messageSource;

@Autowired
Expand All @@ -46,8 +44,11 @@ public boolean isServicioConfigurado() {
@Override
@Async
public void enviarEmail(String toEmail, String bcc, String subject, String mensaje,
byte[] byteArray, String attachmentDescription) {
if (!isServicioConfigurado()) throw new ServiceException(MENSAJE_SERVICIO_NO_CONFIGURADO);
byte[] byteArray, String attachmentName) {
if (!isServicioConfigurado()) {
throw new ServiceException(messageSource.getMessage(
"mensaje_correo_gmail_no_configurado", null, Locale.getDefault()));
}
var props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Expand All @@ -69,12 +70,12 @@ protected PasswordAuthentication getPasswordAuthentication() {
helper.setText(mensaje);
if (byteArray != null) {
var byteArrayDataSource = new ByteArrayDataSource(byteArray, "application/pdf");
helper.addAttachment(attachmentDescription, byteArrayDataSource);
helper.addAttachment(attachmentName, byteArrayDataSource);
}
Transport.send(helper.getMimeMessage());
} catch (MessagingException | MailException ex) {
throw new BusinessServiceException(
messageSource.getMessage("mensaje_correo_error", null, Locale.getDefault()), ex);
throw new ServiceException(messageSource.getMessage(
"mensaje_correo_error", null, Locale.getDefault()), ex);
}
}
}
55 changes: 30 additions & 25 deletions src/main/java/sic/service/impl/PedidoServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
Expand Down Expand Up @@ -40,12 +41,15 @@
@Slf4j
public class PedidoServiceImpl implements IPedidoService {

@Value("${EMAIL_DEFAULT_PROVIDER}")
private String emailDefaultProvider;

private final PedidoRepository pedidoRepository;
private final RenglonPedidoRepository renglonPedidoRepository;
private final IUsuarioService usuarioService;
private final IClienteService clienteService;
private final IProductoService productoService;
private final IEmailService emailService;
private final EmailServiceFactory emailServiceFactory;
private final IReciboService reciboService;
private final ICuentaCorrienteService cuentaCorrienteService;
private final ModelMapper modelMapper;
Expand All @@ -62,7 +66,7 @@ public PedidoServiceImpl(
IUsuarioService usuarioService,
IClienteService clienteService,
IProductoService productoService,
IEmailService emailService,
EmailServiceFactory emailServiceFactory,
IReciboService reciboService,
ICuentaCorrienteService cuentaCorrienteService,
ModelMapper modelMapper,
Expand All @@ -74,7 +78,7 @@ public PedidoServiceImpl(
this.usuarioService = usuarioService;
this.clienteService = clienteService;
this.productoService = productoService;
this.emailService = emailService;
this.emailServiceFactory = emailServiceFactory;
this.reciboService = reciboService;
this.cuentaCorrienteService = cuentaCorrienteService;
this.modelMapper = modelMapper;
Expand Down Expand Up @@ -167,25 +171,25 @@ public long generarNumeroPedido(Sucursal sucursal) {
@Override
@Transactional
public Pedido guardar(Pedido pedido, List<Recibo> recibos) {
Cliente clienteDeUsuario = clienteService.getClientePorIdUsuario(pedido.getUsuario().getIdUsuario());
if (pedido.getCliente().equals(clienteDeUsuario) && pedido.getUsuario().getRoles().contains(Rol.VENDEDOR) &&
pedido.getDescuentoPorcentaje().compareTo(BigDecimal.ZERO) > 0) {
var clienteDeUsuario = clienteService.getClientePorIdUsuario(pedido.getUsuario().getIdUsuario());
if (pedido.getCliente().equals(clienteDeUsuario)
&& pedido.getUsuario().getRoles().contains(Rol.VENDEDOR)
&& pedido.getDescuentoPorcentaje().compareTo(BigDecimal.ZERO) > 0) {
throw new BusinessServiceException(
messageSource.getMessage(
"mensaje_no_se_puede_guardar_pedido_con_descuento_usuario_cliente_iguales", null, Locale.getDefault()));
"mensaje_no_se_puede_guardar_pedido_con_descuento_usuario_cliente_iguales",
null, Locale.getDefault()));
}
if (pedido.getFecha() == null) {
pedido.setFecha(LocalDateTime.now());
}
BigDecimal importe = BigDecimal.ZERO;
var importe = BigDecimal.ZERO;
for (RenglonPedido renglon : pedido.getRenglones()) {
importe = importe.add(renglon.getImporte()).setScale(5, RoundingMode.HALF_UP);
}
BigDecimal recargoNeto =
importe.multiply(pedido.getRecargoPorcentaje()).divide(CIEN, 15, RoundingMode.HALF_UP);
BigDecimal descuentoNeto =
importe.multiply(pedido.getDescuentoPorcentaje()).divide(CIEN, 15, RoundingMode.HALF_UP);
BigDecimal total = importe.add(recargoNeto).subtract(descuentoNeto);
var recargoNeto = importe.multiply(pedido.getRecargoPorcentaje()).divide(CIEN, 15, RoundingMode.HALF_UP);
var descuentoNeto = importe.multiply(pedido.getDescuentoPorcentaje()).divide(CIEN, 15, RoundingMode.HALF_UP);
var total = importe.add(recargoNeto).subtract(descuentoNeto);
pedido.setSubTotal(importe);
pedido.setRecargoNeto(recargoNeto);
pedido.setDescuentoNeto(descuentoNeto);
Expand Down Expand Up @@ -214,18 +218,19 @@ public Pedido guardar(Pedido pedido, List<Recibo> recibos) {
log.info("El Pedido {} se guardó correctamente.", pedido);
String emailCliente = pedido.getCliente().getEmail();
if (emailCliente != null && !emailCliente.isEmpty()) {
emailService.enviarEmail(
emailCliente,
"",
"Nuevo Pedido Ingresado",
messageSource.getMessage(
"mensaje_correo_pedido_recibido",
new Object[] {
pedido.getCliente().getNombreFiscal(), "Pedido Nº " + pedido.getNroPedido()
},
Locale.getDefault()),
this.getReportePedido(pedido.getIdPedido()),
"Reporte.pdf");
emailServiceFactory.getEmailService(emailDefaultProvider)
.enviarEmail(
emailCliente,
"",
"Nuevo Pedido Ingresado",
messageSource.getMessage(
"mensaje_correo_pedido_recibido",
new Object[]{
pedido.getCliente().getNombreFiscal(), "Pedido Nº " + pedido.getNroPedido()
},
Locale.getDefault()),
this.getReportePedido(pedido.getIdPedido()),
"Pedido.pdf");
log.info("El mail del pedido nro {} se envió.", pedido.getNroPedido());
}
return pedido;
Expand Down
25 changes: 15 additions & 10 deletions src/main/java/sic/service/impl/ProductoServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.querydsl.core.BooleanBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.*;
Expand Down Expand Up @@ -40,6 +41,9 @@
@Slf4j
public class ProductoServiceImpl implements IProductoService {

@Value("${EMAIL_DEFAULT_PROVIDER}")
private String emailDefaultProvider;

private final ProductoRepository productoRepository;
private final ProductoFavoritoRepository productoFavoritoRepository;
private static final BigDecimal CIEN = new BigDecimal("100");
Expand All @@ -54,7 +58,7 @@ public class ProductoServiceImpl implements IProductoService {
private final IPedidoService pedidoService;
private final IClienteService clienteService;
private final IUsuarioService usuarioService;
private final IEmailService emailService;
private final EmailServiceFactory emailServiceFactory;
private static final int TAMANIO_PAGINA_DEFAULT = 25;
private static final String MENSAJE_ERROR_ACTUALIZAR_STOCK_PRODUCTO_ELIMINADO = "mensaje_error_actualizar_stock_producto_eliminado";
private static final String PRODUCTO_SIN_IMAGEN = "/producto_sin_imagen.png";
Expand All @@ -77,7 +81,7 @@ public ProductoServiceImpl(
IPedidoService pedidoService,
IClienteService clienteService,
IUsuarioService usuarioService,
IEmailService emailService,
EmailServiceFactory emailServiceFactory,
MessageSource messageSource,
CustomValidator customValidator,
JasperReportsHandler jasperReportsHandler) {
Expand All @@ -93,7 +97,7 @@ public ProductoServiceImpl(
this.pedidoService = pedidoService;
this.clienteService = clienteService;
this.usuarioService = usuarioService;
this.emailService = emailService;
this.emailServiceFactory = emailServiceFactory;
this.messageSource = messageSource;
this.customValidator = customValidator;
this.jasperReportsHandler = jasperReportsHandler;
Expand Down Expand Up @@ -1101,13 +1105,14 @@ public void procesarReporteListaDePrecios(BusquedaProductoCriteria criteria, lon

@Override
public void enviarListaDeProductosPorEmail(String mailTo, byte[] listaDeProductos, FormatoReporte formato) {
emailService.enviarEmail(
mailTo,
"",
"Listado de productos",
"",
listaDeProductos,
"ListaDeProductos." + formato.toString());
emailServiceFactory.getEmailService(emailDefaultProvider)
.enviarEmail(
mailTo,
"",
"Listado de productos",
"Adjunto se encuentra el listado de productos solicitado",
listaDeProductos,
"ListaDeProductos." + formato.toString());
}

@Override
Expand Down
Loading

0 comments on commit 615863a

Please sign in to comment.