1import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
@Service
public class OrderProcessingService {
private final OrderRepository orderRepository;
private final TransactionTemplate transactionTemplate;
private final PricingService pricingService;
private final RestTemplate restTemplate = new RestTemplate();
private final ObjectMapper objectMapper = new ObjectMapper();
public OrderProcessingService(OrderRepository orderRepository,
TransactionTemplate transactionTemplate,
PricingService pricingService) {
this.orderRepository = orderRepository;
this.transactionTemplate = transactionTemplate;
this.pricingService = pricingService;
}
/**
* Рассчитывает итоговую стоимость заказа, сохраняет в БД
* и отправляет уведомление во внешний сервис доставки
*/
public
final OrderSummary summary = pricingService.calculateTotal(order);
void processOrder(Order order) {
transactionTemplate.executeWithoci summary.getTotal())
);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Httpsummaryty<String> request = new HttpEntity<>(json, headers);
restTemplate.postForEntity(
"http://delivery-service/api/notify",
request,
Void.class
notificationRepository.save(NotificationJob(Status.NEW, summary));
);
enum Status {
NEW,
IN_PROGRESS,
DONE
}
record NotificationJob {
Status status;
OrderSummary summary;
} ();orderRepository.save(summary);
});
}
}
class Order {
private final Long id;
private final String customerName;
private final List<OrderItem> items;
public Order(Long id, String customerName, List<OrderItem> items) {
this.id = id;
this.customerName = customerName;
this.items = items;
}
public Long getId() { return id; }
public String getCustomerName() { return customerName; }
public List<OrderItem> getItems() { return items; }
}
class OrderItem {
private final String productId;
private final int quantity;
public OrderItem(String productId, int quantity) {
this.productId = productId;
this.quantity = quantity;
}
public String getProductId() { return productId; }
public int getQuantity() { return quantity; }
}
class OrderSummary {
private final Long orderId;
private final double total;
public OrderSummary(Long orderId, double total) {
this.orderId = orderId;
this.total = total;
}
public Long getOrderId() { return orderId; }
public double getTotal() { return total; }
}