#need to handle it when the stock is null

6 messages · Page 1 of 1 (latest)

barren laurel
#

get an error when the stock is 0 but not sure how to fix it
java.lang.NullPointerException: Cannot invoke "com.example.todoappdeel3.models.OrderProduct.getQuantity()" because "orderProduct" is null

old cairnBOT
#

This post has been reserved for your question.

Hey @barren laurel! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

barren laurel
#
  @Transactional
    public RetourDTO createRetour(RetourDTO retourDTO, String userName) {
        final CustomUser customUser = userRepository.findByEmail(userName).orElseThrow();

        final Order order = orderRepository.findById(retourDTO.getOrderId()).orElseThrow();
        final Product product = productRepository.findById(retourDTO.getOrderProductId()).orElseThrow();

        // if the order does not exist -> error
        // if item not in order -> error
        final OrderProduct orderProduct = orderProductRepository.findByOrderAndProduct(order, product);

        // decrement item quantity
        if(orderProduct.getQuantity() > 0) orderProduct.setQuantity(orderProduct.getQuantity() - 1);

        // create retour
        final Retour retour = Retour
            .builder()
            .order(order)
            .status("placed")
            .customUser(customUser)
            .reason(retourDTO.getReason())
            .product(orderProduct.getProduct())
            .date(LocalDate.now())
            .build();
        retourRepository.save(retour);
        orderProductRepository.save(orderProduct);

        if(orderProduct.getQuantity() == 0) {
            order.getOrderProducts().remove(orderProduct);
            orderProductRepository.delete(orderProduct);
        }

        // if no items in order, then delete order
        if(order.getOrderProducts().isEmpty()) {
            // orderRepository.delete(order);
            order.setStatus("retour and empty");
            orderRepository.save(order);
        }

        return retour.getDto();
    }
barren laurel
#

let me know if you have any questions 🙂

left zinc
#

I guess that findByOrderAndProduct returns null