CsvExportService.java

package cz.vsb.crm.service.export;

import cz.vsb.crm.model.Order;
import cz.vsb.crm.model.Product;
import cz.vsb.crm.repository.OrderRepository;
import cz.vsb.crm.repository.ProductRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;

@Service
public class CsvExportService {

    private final ProductRepository productRepository;
    private final OrderRepository orderRepository;

    public CsvExportService(ProductRepository productRepository, OrderRepository orderRepository) {
        this.productRepository = productRepository;
        this.orderRepository = orderRepository;
    }

    @Transactional(readOnly = true)
    public void writeProducts(OutputStream outputStream) {
        PrintWriter writer = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)));
        writer.println("id,name,description,price,stock,deactivatedAt");
        try (Stream<Product> products = productRepository.streamAllBy()) {
            products.forEach(product -> writer.println(String.join(",",
                    CsvSupport.escape(product.getId()),
                    CsvSupport.escape(product.getName()),
                    CsvSupport.escape(product.getDescription()),
                    CsvSupport.escape(product.getPrice()),
                    CsvSupport.escape(product.getStock()),
                    CsvSupport.escape(product.getDeactivatedAt()))));
        }
        writer.flush();
    }

    @Transactional(readOnly = true)
    public void writeOrders(OutputStream outputStream) {
        PrintWriter writer = new PrintWriter(new BufferedWriter(
                new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)));
        writer.println("id,account,createdBy,orderDate,status,orderType,totalAmount");
        try (Stream<Order> orders = orderRepository.streamAllBy()) {
            orders.forEach(order -> writer.println(String.join(",",
                    CsvSupport.escape(order.getId()),
                    CsvSupport.escape(order.getAccount() != null ? order.getAccount().getCompanyName() : null),
                    CsvSupport.escape(order.getCreatedBy() != null ? order.getCreatedBy().getUsername() : null),
                    CsvSupport.escape(order.getOrderDate()),
                    CsvSupport.escape(order.getStatus()),
                    CsvSupport.escape(order.getOrderType()),
                    CsvSupport.escape(order.getTotalAmount()))));
        }
        writer.flush();
    }
}