Skip to content

Commit

Permalink
add mail notification to customer when an order is stored #19
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin POCHAT authored and Benjamin POCHAT committed Feb 17, 2021
1 parent e04d066 commit 1dc6ddf
Show file tree
Hide file tree
Showing 16 changed files with 425 additions and 123 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.localeat.core.commons;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public interface NotificationService<T> {

static final Logger LOGGER = LoggerFactory.getLogger(NotificationService.class);

String getSubject(T object);

String getRecipient(T object);

Object[] getTemplateValues(T object);

EmailService getEmailService();

String getBodyTemplatePath();

default public void notify(T object) {
String recipient = getRecipient(object);
String subject = getSubject(object);
String body = getBody(object);
sendMail(recipient, subject, body);
};

default String getBody(T object){
String bodyTemplate = getBodyTemplate();
Object[] bodyTemplateVariables = getTemplateValues(object);
String body = String.format(bodyTemplate, bodyTemplateVariables);
return body;
}

default String getBodyTemplate() {
try {
return Files.lines(Paths.get(getClass().getClassLoader().getResource(getBodyTemplatePath()).toURI())).collect(Collectors.joining());
} catch (IOException | URISyntaxException composingMailException) {
LOGGER.error("An exception occured while composing an email.", composingMailException);
return null;
}
}

default void sendMail(String recipient, String subject, String body) {
try {
getEmailService().sendMail(recipient, subject, body);
} catch (MessagingException messagingException) {
LOGGER.error("An exception occured while sending an email.", messagingException);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

@Entity
@Table(name = "addresses")
class Address {
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_id_generator")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,5 @@ public OrderStatus getStatus() {
public void setStatus(OrderStatus status) {
this.status = status;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ public class OrderController {
private DeliveryController deliveryController;

@Autowired
private OrderNotificationService orderNotificationService;
private OrderNotificationToCustomerService orderNotificationToCustomerService;

@Autowired
private OrderNotificationToBreederService orderNotificationToBreederService;

@PostMapping(path = "/accounts/{account}/orders")
public Order createOrder(@PathParam("account") Account account, @RequestBody Order order){
Expand All @@ -37,7 +40,8 @@ public Order createOrder(@PathParam("account") Account account, @RequestBody Ord
Delivery delivery = deliveryRepository.findById(order.getDelivery().getId()).orElseThrow();
deliveryController.updateQuantitySoldInBatches(delivery);
Order orderSaved = orderRepository.save(order);
orderNotificationService.notifyByMail(orderSaved);
orderNotificationToBreederService.notify(orderSaved);
orderNotificationToCustomerService.notify(orderSaved);
return orderSaved;
}

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
package com.localeat.core.domains.order;

import com.localeat.core.commons.EmailService;
import com.localeat.core.commons.NotificationService;
import com.localeat.core.config.http.HttpConfig;
import com.localeat.core.domains.actor.Breeder;
import com.localeat.core.domains.actor.BreederRepository;
import com.localeat.core.domains.product.Batch;
import com.localeat.core.domains.product.BatchRepository;
import com.localeat.core.domains.slaughter.Slaughter;
import com.localeat.core.domains.slaughter.SlaughterRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class OrderNotificationToBreederService implements NotificationService<Order> {

private static final Logger LOGGER = LoggerFactory.getLogger(OrderNotificationToBreederService.class);

@Autowired
private BatchRepository batchRepository;

@Autowired
private SlaughterRepository slaughterRepository;

@Autowired
private BreederRepository breederRepository;

@Autowired
private EmailService emailService;

@Autowired
HttpConfig httpConfig;

@Override
public String getSubject(Order object) {
return "Nouvelle commande sur ViandeEnDirect.eu";
}

@Override
public String getRecipient(Order order) {
Slaughter slaughter = slaughterRepository.findByDelivery(order.getDelivery());
Iterable<Breeder> breeders = breederRepository.findBreedersByFarm(slaughter.getAnimal().getFinalFarm());
return StreamSupport.stream(breeders.spliterator(), false).map(Breeder::getEmail).collect(Collectors.joining(","));
}

@Override
public String getBodyTemplatePath() {
return "html/notification/notification_to_breeder_body_template.html";
}

@Override
public EmailService getEmailService() {
return emailService;
}

@Override
public Object[] getTemplateValues(Order order) {
Object[] templateValues = {
order.getId(),
httpConfig.getUserInterfaceUrl(),
order.getCustomer().getFirstName(),
order.getCustomer().getName(),
order.getCustomer().getEmail(),
order.getCustomer().getPhoneNumber(),
getTotalPrice(order),
getTotalWeight(order)
};
return templateValues;
}

private double getTotalPrice(Order order) {
return order.getOrderedItems().stream()
.mapToDouble(item -> {
Batch batch = batchRepository.findById(item.getBatch().getId()).orElseThrow();
return item.getQuantity() * batch.getProduct().getUnitPrice() * batch.getProduct().getNetWeight();
})
.sum();
}

private double getTotalWeight(Order order) {
return order.getOrderedItems().stream().mapToDouble(item -> {
Batch batch = batchRepository.findById(item.getBatch().getId()).orElseThrow();
return item.getQuantity() * batch.getProduct().getNetWeight();
}).sum();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.localeat.core.domains.order;

import com.localeat.core.commons.EmailService;
import com.localeat.core.commons.NotificationService;
import com.localeat.core.config.http.HttpConfig;
import com.localeat.core.domains.actor.BreederRepository;
import com.localeat.core.domains.delivery.Delivery;
import com.localeat.core.domains.delivery.DeliveryRepository;
import com.localeat.core.domains.product.Batch;
import com.localeat.core.domains.product.BatchRepository;
import com.localeat.core.domains.slaughter.Slaughter;
import com.localeat.core.domains.slaughter.SlaughterRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static java.util.Optional.ofNullable;

@Service
public class OrderNotificationToCustomerService implements NotificationService<Order> {

private static final Logger LOGGER = LoggerFactory.getLogger(OrderNotificationToCustomerService.class);

@Autowired
private BatchRepository batchRepository;

@Autowired
private SlaughterRepository slaughterRepository;

@Autowired
private DeliveryRepository deliveryRepository;

@Autowired
private BreederRepository breederRepository;

@Autowired
private EmailService emailService;

@Autowired
HttpConfig httpConfig;

@Override
public EmailService getEmailService() {
return emailService;
}

@Override
public String getSubject(Order order) {
return "Confirmation de votre commande sur ViandeEnDirect.eu";
}

@Override
public String getRecipient(Order order) {
return order.getCustomer().getEmail();
}

@Override
public String getBodyTemplatePath() {
return "html/notification/notification_to_customer_body_template.html";
}

@Override
public Object[] getTemplateValues(Order order) {
Slaughter slaughter = slaughterRepository.findByDelivery(order.getDelivery());
Delivery delivery = deliveryRepository.findById(slaughter.getDelivery().getId()).orElseThrow();
Object[] bodyTemplateValues = {
order.getId(),
httpConfig.getUserInterfaceUrl(),
getTotalPrice(order),
getTotalWeight(order),
delivery.getDeliveryStart(),
delivery.getDeliveryEnd(),
delivery.getDeliveryAddress().getName(),
ofNullable(delivery.getDeliveryAddress().getAddressLine1()).orElse(""),
ofNullable(delivery.getDeliveryAddress().getAddressLine2()).orElse(""),
ofNullable(delivery.getDeliveryAddress().getAddressLine3()).orElse(""),
ofNullable(delivery.getDeliveryAddress().getAddressLine4()).orElse(""),
delivery.getDeliveryAddress().getZipCode(),
delivery.getDeliveryAddress().getCity()
};
return bodyTemplateValues;
}

private double getTotalPrice(Order order) {
return order.getOrderedItems().stream()
.mapToDouble(item -> {
Batch batch = batchRepository.findById(item.getBatch().getId()).orElseThrow();
return item.getQuantity() * batch.getProduct().getUnitPrice() * batch.getProduct().getNetWeight();
})
.sum();
}

private double getTotalWeight(Order order) {
return order.getOrderedItems().stream().mapToDouble(item -> {
Batch batch = batchRepository.findById(item.getBatch().getId()).orElseThrow();
return item.getQuantity() * batch.getProduct().getNetWeight();
}).sum();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<meta charset="UTF-8">
<div>La commande n° %s a été enregistrée sur <a href='%s'>ViandeEnDirect.eu</a>.</div>
<div>
<ul>
<li>Client :
<ul>
<li>Nom : %s %s</li>
<li>Email : %s</li>
<li>Téléphone : %s</li>
</ul>
</li>
<li>Montant de la commande : %s €TTC</li>
<li>Quantité commandée : %s kg</li>
</ul>
</div>
Loading

0 comments on commit 1dc6ddf

Please sign in to comment.