Search in sources :

Example 6 with NotFoundEx

use of com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx 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 7 with NotFoundEx

use of com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx 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)

Example 8 with NotFoundEx

use of com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx in project 2021-msk-food-delivery by netcracker-edu.

the class ProductPositionServiceImpl1 method shipProductPositions.

@Override
public void shipProductPositions(Long orderId, ProductPositionsShipmentDTO productPositionsShipmentDTO) {
    Optional<Order> optionalOrder = orderRepo.findById(orderId);
    if (optionalOrder.isEmpty())
        throw new NotFoundEx(String.valueOf(orderId));
    Order order = optionalOrder.get();
    Long orderWarehouseId = order.getWarehouse().getId();
    List<ProductPositionsShipmentDTO.ProductPositionAmountPair> positionAmountPairs = productPositionsShipmentDTO.getPositionAmountPairs();
    checkIdsUnique(positionAmountPairs);
    checkPositionsExist(positionAmountPairs, orderWarehouseId);
    checkPositionsCurrentAmount(positionAmountPairs);
    // if everything is ok, we can finally manipulate with database
    // updating order status
    order.setStatus(OrderStatus.DELIVERING);
    orderRepo.save(order);
    shipPositionsFromWarehouse(positionAmountPairs);
}
Also used : Order(com.ncedu.fooddelivery.api.v1.entities.order.Order)

Example 9 with NotFoundEx

use of com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx in project 2021-msk-food-delivery by netcracker-edu.

the class ProductPositionController method shipProductPositionsFromOrder.

@PatchMapping("/api/v1/order/{id}/productPositions/currentAmount")
@PreAuthorize("hasAnyAuthority('ADMIN', 'MODERATOR')")
public ResponseEntity<?> shipProductPositionsFromOrder(@Min(value = 1) @Max(value = Long.MAX_VALUE) @PathVariable(name = "id") Long id, @Valid @RequestBody ProductPositionsShipmentDTO productPositionsShipmentDTO, @AuthenticationPrincipal User user) {
    Order order = orderService.getOrder(id);
    if (order == null)
        throw new NotFoundEx(String.valueOf(id));
    if (user.getRole() == Role.MODERATOR) {
        if (!user.getModerator().getWarehouseId().equals(order.getWarehouse().getId()))
            throw new CustomAccessDeniedException();
    }
    productPositionService.shipProductPositions(id, productPositionsShipmentDTO);
    return new ResponseEntity<>(HttpStatus.OK);
}
Also used : Order(com.ncedu.fooddelivery.api.v1.entities.order.Order) ResponseEntity(org.springframework.http.ResponseEntity) NotFoundEx(com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx) CustomAccessDeniedException(com.ncedu.fooddelivery.api.v1.errors.security.CustomAccessDeniedException) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 10 with NotFoundEx

use of com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx in project 2021-msk-food-delivery by netcracker-edu.

the class OrderServiceImpl1 method countOrderCost.

@Override
public Double[] countOrderCost(CoordsDTO geo, HashMap<Long, Integer> pairs, Long clientWarehouseId) {
    WarehouseInfoDTO warehouse = warehouseService.getNearestWarehouse(geo.getLat(), geo.getLon());
    if (warehouse == null)
        throw new NotFoundEx(String.format("Lat: %s; lon: %s", geo.getLat().toString(), geo.getLon().toString()));
    Long warehouseId = warehouse.getId();
    if (!warehouseId.equals(clientWarehouseId))
        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 : pairs.entrySet()) {
        Long productId = pair.getKey();
        Integer requestedAmount = pair.getValue();
        // 'findByProductIdAndWarehouseIdWithLock' sets lock on every product position in result set. So no one
        // other thread
        // will be able to interact with these positions before whole transaction will complete.
        List<ProductPosition> productPositions = productPositionRepo.findByProductIdAndWarehouseIdWithLock(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 = productPositions.get(0).getProduct();
            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 Double[] { 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)

Aggregations

NotFoundEx (com.ncedu.fooddelivery.api.v1.errors.notfound.NotFoundEx)20 Test (org.junit.jupiter.api.Test)12 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)12 ProductPosition (com.ncedu.fooddelivery.api.v1.entities.productPosition.ProductPosition)6 CustomAccessDeniedException (com.ncedu.fooddelivery.api.v1.errors.security.CustomAccessDeniedException)6 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 OrderProductPosition (com.ncedu.fooddelivery.api.v1.entities.orderProductPosition.OrderProductPosition)3 AlreadyExistsException (com.ncedu.fooddelivery.api.v1.errors.badrequest.AlreadyExistsException)3 PasswordsMismatchException (com.ncedu.fooddelivery.api.v1.errors.badrequest.PasswordsMismatchException)3 ResponseEntity (org.springframework.http.ResponseEntity)3 WarehouseInfoDTO (com.ncedu.fooddelivery.api.v1.dto.warehouseDTOs.WarehouseInfoDTO)2 Client (com.ncedu.fooddelivery.api.v1.entities.Client)2 Order (com.ncedu.fooddelivery.api.v1.entities.order.Order)2 BadFileExtensionException (com.ncedu.fooddelivery.api.v1.errors.badrequest.BadFileExtensionException)2 ProductAvailabilityEx (com.ncedu.fooddelivery.api.v1.errors.orderRegistration.ProductAvailabilityEx)2 WarehouseCoordsBindingEx (com.ncedu.fooddelivery.api.v1.errors.orderRegistration.WarehouseCoordsBindingEx)2 IOException (java.io.IOException)2 UserChangeInfoDTO (com.ncedu.fooddelivery.api.v1.dto.user.UserChangeInfoDTO)1 File (com.ncedu.fooddelivery.api.v1.entities.File)1 Product (com.ncedu.fooddelivery.api.v1.entities.Product)1