Search in sources :

Example 11 with Product

use of com.ncedu.fooddelivery.api.v1.entities.Product in project 2021-msk-food-delivery by netcracker-edu.

the class ProductUtils method createProductDTOListFromPage.

public static List<ProductDTO> createProductDTOListFromPage(Page<Product> page) {
    List<Product> products = page.getContent();
    List<ProductDTO> productsDTO = new ArrayList<>();
    for (Product p : products) {
        productsDTO.add(createProductDTO(p));
    }
    return productsDTO;
}
Also used : ArrayList(java.util.ArrayList) Product(com.ncedu.fooddelivery.api.v1.entities.Product) ProductDTO(com.ncedu.fooddelivery.api.v1.dto.product.ProductDTO)

Example 12 with Product

use of com.ncedu.fooddelivery.api.v1.entities.Product in project 2021-msk-food-delivery by netcracker-edu.

the class OrderServiceImpl1 method reserveProductPositions.

private void reserveProductPositions(List<ProductPosition> productPositions, Integer requestedAmount, Map<Long, Double> productPosPriceMap, Map<Long, Integer> productPosAmountMap) {
    Product product = productPositions.get(0).getProduct();
    Double productCost = product.getPrice() - product.getDiscount();
    Integer ship = 0;
    for (int i = 0; i < productPositions.size() && !ship.equals(requestedAmount); i++) {
        ProductPosition currentPos = productPositions.get(i);
        if ((requestedAmount - ship) <= currentPos.getCurrentAmount()) {
            currentPos.setCurrentAmount(currentPos.getCurrentAmount() - (requestedAmount - ship));
            productPositionRepo.save(currentPos);
            productPosAmountMap.put(currentPos.getId(), requestedAmount - ship);
            productPosPriceMap.put(currentPos.getId(), (requestedAmount - ship) * productCost);
            break;
        } else {
            ship += currentPos.getCurrentAmount();
            productPosAmountMap.put(currentPos.getId(), currentPos.getCurrentAmount());
            productPosPriceMap.put(currentPos.getId(), productCost * (currentPos.getCurrentAmount()));
            currentPos.setCurrentAmount(0);
            productPositionRepo.save(currentPos);
        }
    }
}
Also used : OrderProductPosition(com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition) ProductPosition(com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition)

Example 13 with Product

use of com.ncedu.fooddelivery.api.v1.entities.Product in project 2021-msk-food-delivery by netcracker-edu.

the class OrderServiceImpl1 method countOrderCost.

@Override
public CountOrderCostResponseDTO countOrderCost(CountOrderCostRequestDTO dto) {
    WarehouseInfoDTO warehouse = warehouseService.getNearestWarehouse(dto.getGeo().getLat(), dto.getGeo().getLon());
    if (warehouse == null)
        throw new NotFoundEx(String.format("{Lat: %s; lon: %s}", dto.getGeo().getLat().toString(), dto.getGeo().getLon().toString()));
    Long warehouseId = warehouse.getId();
    if (!warehouseId.equals(dto.getWarehouseId()))
        throw new WarehouseCoordsBindingEx();
    Map<Long, Integer> productsAvailableAmounts = new HashMap<>();
    Double overallOrderCost = 0.0;
    Double overallOrderDiscount = 0.0;
    Double orderHighDemandCoeff;
    boolean enoughProductPositions = true;
    for (Map.Entry<Long, Integer> pair : dto.getProductAmountPairs().entrySet()) {
        Long productId = pair.getKey();
        Integer requestedAmount = pair.getValue();
        List<ProductPosition> productPositions = productPositionRepo.findByProductIdAndWarehouseId(productId, warehouseId);
        // filtering expired product positions
        productPositions = productPositions.stream().filter(new Predicate<ProductPosition>() {

            @Override
            public boolean test(ProductPosition productPosition) {
                Short expirationDays = productPosition.getProduct().getExpirationDays();
                Date manufactureDate = productPosition.getManufactureDate();
                Calendar c = Calendar.getInstance();
                c.setTime(manufactureDate);
                c.add(Calendar.DATE, expirationDays);
                if (c.before(Calendar.getInstance()))
                    return false;
                return true;
            }
        }).collect(Collectors.toList());
        Integer overallAmount = 0;
        for (ProductPosition pos : productPositions) {
            overallAmount += pos.getCurrentAmount();
        }
        if (overallAmount < requestedAmount) {
            productsAvailableAmounts.put(productId, overallAmount);
            enoughProductPositions = false;
        }
        if (enoughProductPositions) {
            // product price count
            Product product = productRepo.findById(productId).get();
            Double productDiscount = product.getDiscount();
            Double productPrice = product.getPrice();
            overallOrderCost += requestedAmount * (productPrice - productDiscount);
            overallOrderDiscount += productDiscount * requestedAmount;
        }
    }
    if (!enoughProductPositions) {
        throw new ProductAvailabilityEx(productsAvailableAmounts);
    }
    orderHighDemandCoeff = countHighDemandCoeff(warehouseId);
    overallOrderCost = Math.round(overallOrderCost * orderHighDemandCoeff * 100.0) / 100.0;
    return new CountOrderCostResponseDTO(overallOrderCost, overallOrderDiscount, orderHighDemandCoeff);
}
Also used : ProductAvailabilityEx(com.ncedu.fooddelivery.api.v1.errors.orderRegistration.ProductAvailabilityEx) WarehouseCoordsBindingEx(com.ncedu.fooddelivery.api.v1.errors.orderRegistration.WarehouseCoordsBindingEx) NotFoundEx(com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx) OrderProductPosition(com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition) ProductPosition(com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition) WarehouseInfoDTO(com.ncedu.fooddelivery.api.v1.dto.warehouseDTOs.WarehouseInfoDTO)

Example 14 with Product

use of com.ncedu.fooddelivery.api.v1.entities.Product in project 2021-msk-food-delivery by netcracker-edu.

the class OrderServiceImpl1 method createOrder.

@Override
@Transactional
public areCreatedDTO createOrder(CreateOrderDTO dto, User user) {
    checkOrderDataActuality(dto);
    Long warehouseId = dto.getWarehouseId();
    Geometry coords = geometryFactory.createPoint(new Coordinate(dto.getGeo().getLon().doubleValue(), dto.getGeo().getLat().doubleValue()));
    HashMap<Long, Integer> pairs = dto.getProductAmountPairs();
    Object[] productPosMaps = getProductPositionsData(pairs, warehouseId);
    // we will use later Maps below to reserve product positions from warehouse and put them in order(s)
    HashMap<Long, Double> productPosPriceMap = (HashMap<Long, Double>) productPosMaps[0];
    HashMap<Long, Integer> productPosAmountMap = (HashMap<Long, Integer>) productPosMaps[1];
    Double orderWeight = countOrderWeight(pairs);
    if (orderWeight > 15000d) {
        int neededCouriersAmount = (int) Math.ceil(orderWeight / 15000d);
        List<ProductPosition> productPositions = getSortedProductPositions(productPosAmountMap);
        // we've got sorted by weight sequence of product positions, so we can put them into different orders
        List<Order> orders = new ArrayList<>();
        for (int i = 0; i < neededCouriersAmount; i++) {
            Order order = buildOrder(user, coords, dto, productPositions);
            // attaching courier and then order status = 'courier_appointed'
            Courier courier;
            try {
                courier = courierService.findFreeCourier(warehouseId);
            } catch (CourierAvailabilityEx ex) {
                for (Order o : orders) {
                    // DB trigger will return all reserved product
                    o.setStatus(OrderStatus.CANCELLED);
                    // positions back to warehouse
                    orderRepo.save(o);
                }
                throw ex;
            }
            order.setCourier(courier);
            order.setStatus(OrderStatus.COURIER_APPOINTED);
            orders.add(orderRepo.save(order));
        }
        return new areCreatedDTO(orders.stream().map(order -> order.getId()).collect(Collectors.toList()));
    } else {
        Order order = buildOrder(user, coords, dto, productPosPriceMap, productPosAmountMap);
        // attaching courier and then order status = 'courier_appointed'
        Courier courier;
        try {
            courier = courierService.findFreeCourier(warehouseId);
        } catch (CourierAvailabilityEx ex) {
            // DB trigger will return all reserved product positions back
            order.setStatus(OrderStatus.CANCELLED);
            // to warehouse
            orderRepo.save(order);
            throw ex;
        }
        order.setCourier(courier);
        order.setStatus(OrderStatus.COURIER_APPOINTED);
        orderRepo.save(order);
        return new areCreatedDTO(List.of(order.getId()));
    }
}
Also used : Order(com.ncedu.fooddelivery.api.v1.entities.order.Order) CourierAvailabilityEx(com.ncedu.fooddelivery.api.v1.errors.orderRegistration.CourierAvailabilityEx) Geometry(com.vividsolutions.jts.geom.Geometry) Coordinate(com.vividsolutions.jts.geom.Coordinate) com.ncedu.fooddelivery.api.v1.dto.areCreatedDTO(com.ncedu.fooddelivery.api.v1.dto.areCreatedDTO) OrderProductPosition(com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition) ProductPosition(com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition) Transactional(org.springframework.transaction.annotation.Transactional)

Example 15 with Product

use of com.ncedu.fooddelivery.api.v1.entities.Product in project 2021-msk-food-delivery by netcracker-edu.

the class ProductPositionServiceImpl1 method convertToProductPosition.

public ProductPosition convertToProductPosition(AcceptSupplyDTO acceptSupplyDTO) {
    Optional<Product> productOptional = productRepo.findById(acceptSupplyDTO.getProductId());
    Optional<Warehouse> warehouseOptional = warehouseRepo.findById(acceptSupplyDTO.getWarehouseId());
    if (warehouseOptional.isEmpty())
        throw new NotFoundEx(String.valueOf(acceptSupplyDTO.getWarehouseId()));
    if (productOptional.isEmpty())
        throw new NotFoundEx(String.valueOf(acceptSupplyDTO.getProductId()));
    Product product = productOptional.get();
    Warehouse warehouse = warehouseOptional.get();
    ProductPosition productPosition = new ProductPosition(null, product, warehouse, acceptSupplyDTO.getWarehouseSection(), acceptSupplyDTO.getSupplyAmount(), acceptSupplyDTO.getSupplyAmount(), acceptSupplyDTO.getManufactureDate(), acceptSupplyDTO.getSupplierInvoice(), acceptSupplyDTO.getSupplierName(), acceptSupplyDTO.getIsInvoicePaid(), acceptSupplyDTO.getManufactureDate());
    if (acceptSupplyDTO.getIsInvoicePaid() == null) {
        productPosition.setIsInvoicePaid(false);
    }
    return productPosition;
}
Also used : OrderProductPosition(com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition) ProductPosition(com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition)

Aggregations

Product (com.ncedu.fooddelivery.api.v1.entities.Product)17 Test (org.junit.jupiter.api.Test)12 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)12 WarehouseInfoDTO (com.ncedu.fooddelivery.api.v1.dto.warehouseDTOs.WarehouseInfoDTO)10 OrderProductPosition (com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition)9 ProductPosition (com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition)9 Product (entities.Product)9 ProductDTO (com.ncedu.fooddelivery.api.v1.dto.product.ProductDTO)8 SearchProductDTO (com.ncedu.fooddelivery.api.v1.dto.product.SearchProductDTO)7 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)6 Point (com.vividsolutions.jts.geom.Point)5 Pageable (org.springframework.data.domain.Pageable)5 BigDecimal (java.math.BigDecimal)4 ArrayList (java.util.ArrayList)4 CoordsDTO (com.ncedu.fooddelivery.api.v1.dto.CoordsDTO)3 NotFoundEx (com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx)3 PageImpl (org.springframework.data.domain.PageImpl)3 com.ncedu.fooddelivery.api.v1.dto.isCreatedDTO (com.ncedu.fooddelivery.api.v1.dto.isCreatedDTO)2 Order (com.ncedu.fooddelivery.api.v1.entities.order.Order)2 ProductAvailabilityEx (com.ncedu.fooddelivery.api.v1.errors.orderRegistration.ProductAvailabilityEx)2