Subversion Repositories SmartDukaan

Rev

Rev 28170 | Rev 29261 | Go to most recent revision | View as "text/plain" | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.spice.profitmandi.dao.cart;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.user.Cart;
import com.spice.profitmandi.dao.entity.user.CartLine;
import com.spice.profitmandi.dao.entity.user.User;
import com.spice.profitmandi.dao.model.CartItem;
import com.spice.profitmandi.dao.model.CartItemResponseModel;
import com.spice.profitmandi.dao.model.CartMessage;
import com.spice.profitmandi.dao.model.CartResponse;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.dtr.FofoStoreRepository;
import com.spice.profitmandi.dao.repository.fofo.CurrentInventorySnapshotRepository;
import com.spice.profitmandi.dao.repository.user.CartLineRepository;
import com.spice.profitmandi.dao.repository.user.CartRepository;
import com.spice.profitmandi.dao.repository.user.UserRepository;
import com.spice.profitmandi.service.inventory.SaholicInventoryService;

@Component
public class CartServiceImpl implements CartService {

        private static final Set<Integer> tagIds = new HashSet<>(Arrays.asList(4));

        private static final Logger logger = LogManager.getLogger(CartServiceImpl.class);

        @Autowired
        CartRepository cartRepository;

        @Autowired
        CartLineRepository cartLineRepository;

        @Autowired
        FofoStoreRepository fofoStoreRepository;

        @Autowired
        TagListingRepository tagListingRepository;

        @Autowired
        UserRepository saholicUserRepository;

        @Autowired
        ItemRepository itemRepository;

        @Autowired
        SaholicInventoryService saholicInventoryService;

        @Autowired
        CurrentInventorySnapshotRepository currentInventorySnapshotRepository;

        @Override
        public CartModel addToCart(int cartId, int itemId, int quantity, float sellingPrice) {
                CartLine cartItem = cartLineRepository.selectByCartItem(cartId, itemId);
                if (cartItem == null) {
                        this.createCartItem(cartId, itemId, quantity, sellingPrice);
                } else {
                        cartItem.setQuantity(quantity);
                        cartItem.setActualPrice(sellingPrice);
                }
                return null;
        }

        private void createCartItem(int cartId, int itemId, int quantity, float sellingPrice) {
                CartLine cartLine = new CartLine();
                cartLine.setActualPrice(sellingPrice);
                cartLine.setCartId(cartId);
                cartLine.setQuantity(quantity);
                // TODO: Estmiate Logic
                cartLine.setEstimate(2);
                cartLineRepository.persist(cartLine);

        }

        @Override
        public boolean clearCart(int cartId) throws ProfitMandiBusinessException {
                List<CartLine> cartLines = cartLineRepository.selectAllByCart(cartId);
                cartLines.stream().forEach(cartLine -> cartLineRepository.delete(cartLine));
                Cart cart = cartRepository.selectById(cartId);

                cart.setUpdateTimestamp(LocalDateTime.now());
                cart.setCheckoutTimestamp(null);
                cart.setTotalPrice(0);
                cart.setWalletAmount(0);
                return true;
        }

        @Override
        public CartModel getCart(int cartId) {
                // TODO Auto-generated method stub
                return null;
        }

        // As of now it only works for Fofo Partners need to be refactored later
        private Map<Integer, Integer> getAvailabilityMap(User user, Set<Integer> itemIds) {
                Map<Integer, Integer> itemAvailabilityMap = new HashMap<>();
                List<TagListing> tags = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds);
                tags.stream().forEach(tagListing -> {
                        if (!tagListing.isActive() || tagListing.isHotDeals()) {
                                // show actual values here
                        } else {
                                itemAvailabilityMap.put(tagListing.getItemId(), 100);
                        }
                });
                return itemAvailabilityMap;
        }

        // As of now it only works for Fofo Partners need to be refactored later
        private Map<Integer, Integer> getMinBuyQtyMap(User user, Set<Integer> itemIds) {
                List<Item> items = itemRepository.selectByIds(itemIds);
                return items.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getCategoryId() == 10020 ? 1 : 10));
        }

        // As of now it only works for Fofo Partners need to be refactored later
        private Map<Integer, Float> getPriceMap(User user, Set<Integer> itemIds) {
                List<TagListing> tags = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds);
                return tags.stream().collect(Collectors.toMap(x -> x.getItemId(), x -> x.getSellingPrice()));

        }

        @Override
        public CartResponse getCartValidation(int cartId) throws ProfitMandiBusinessException {
                /*
                 * # No need to validate duplicate items since there are only two ways # to add
                 * items to a cart and both of them check whether the item being # added is a
                 * duplicate of an already existing item.
                 */

                Cart cart = cartRepository.selectById(cartId);
                List<CartLine> cartLines = cartLineRepository.selectAllByCart(cartId);

                User saholicUser = saholicUserRepository.selectByCartId(cartId);

                int totalQty = 0;
                double totalAmount = 0;
                CartResponse cartResponse = new CartResponse();
                List<CartMessage> cartMessages = new ArrayList<>();
                List<CartItemResponseModel> cartItemModels = new ArrayList<>();
                cartResponse.setCartMessages(cartMessages);
                cartResponse.setCartItems(cartItemModels);

                int cartMessageChanged = 0;
                int cartMessageOOS = 0;
                int cartMessageUndeliverable = 0;

                Set<Integer> itemIds = cartLines.stream().map(x -> x.getItemId()).collect(Collectors.toSet());
                logger.info("iteme ids -- {}", itemIds);
                List<TagListing> tagListings = tagListingRepository.selectByItemIdsAndTagIds(itemIds, tagIds);
                Map<Integer, TagListing> tagListingsMap = tagListings.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x));

                cart.setTotalPrice(0);
                int nonAccessoryQuantity = 0;
                for (CartLine cartLine : cartLines) {
                        boolean itemQuantityChanged = false;
                        CartItemResponseModel cartItemResponseModel = new CartItemResponseModel();
                        int oldEstimate = cartLine.getEstimate();
                        int itemId = cartLine.getItemId();
                        Item item = null;
                        try {
                                item = itemRepository.selectById(itemId);
                                cartItemResponseModel.setTitle(item.getItemDescriptionNoColor());
                        } catch (ProfitMandiBusinessException e) {
                                e.printStackTrace();
                                logger.info("Error finding item with id {}", itemId);
                                cartLineRepository.delete(cartLine);
                                continue;
                        }
                        cartItemResponseModel.setItemId(itemId);
                        cartItemResponseModel.setQuantity(0);
                        cartItemResponseModel.setColor(item.getColor());
                        List<CartItemMessage> cartItemMessages = new ArrayList<>();
                        cartItemResponseModel.setCartItemMessages(cartItemMessages);
                        cartItemResponseModel.setCatalogItemId(item.getCatalogItemId());
                        cartItemResponseModel.setMinBuyQuantity(1);
                        cartItemResponseModel.setQuantityStep(1);
                        cartItemResponseModel.setMaxQuantity(0);

                        /*
                         * int netAvailability = itemAvailabilityMap.get(itemId).stream()
                         * .collect(Collectors.summingInt(x -> x.getNetavailability()));
                         */
                        int availability = 30;
                        if (availability < cartLine.getQuantity()) {
                                cartLine.setQuantity(availability);
                                itemQuantityChanged = true;
                        }
                        cartItemResponseModel.setMaxQuantity(Math.max(availability, 100));
                        if (availability < cartItemResponseModel.getMinBuyQuantity()) {
                                cartItemResponseModel.setMinBuyQuantity(availability);
                        }
                        if (cartLine.getQuantity() < cartItemResponseModel.getMinBuyQuantity()) {
                                itemQuantityChanged = true;
                                cartLine.setQuantity(cartItemResponseModel.getMinBuyQuantity());
                        }

                        if (cartLine.getQuantity() > cartItemResponseModel.getMaxQuantity()) {
                                itemQuantityChanged = true;
                                cartLine.setQuantity(cartItemResponseModel.getMaxQuantity());
                        }
                        cartLine.setActualPrice(tagListingsMap.get(itemId).getSellingPrice());
                        if (item.getCategoryId() == 10006 || item.getCategoryId() == 10010) {
                                nonAccessoryQuantity += cartItemResponseModel.getQuantity();
                                cartItemResponseModel.setCategoryName("mobile");
                        }
                        cartItemResponseModel.setSellingPrice(cartLine.getActualPrice());

                        if (availability > 0) {
                                cart.setTotalPrice(cart.getTotalPrice() + (cartLine.getActualPrice() * cartLine.getQuantity()));
                                cartItemResponseModel.setQuantity(cartLine.getQuantity());
                                cartItemResponseModel.setEstimate(2);
                                if (itemQuantityChanged) {
                                        cartMessageChanged += 1;
                                        if (oldEstimate != cartItemResponseModel.getEstimate()) {
                                                cartLine.setEstimate(cartItemResponseModel.getEstimate());
                                                cart.setUpdateTimestamp(LocalDateTime.now());
                                                totalAmount += cartLine.getActualPrice() * cartLine.getQuantity();
                                        }
                                }
                        } else {
                                cartItemResponseModel.setQuantity(0);
                                cartMessageOOS += 1;
                                CartItemMessage cartItemMessage = new CartItemMessage();
                                cartItemMessage.setType("danger");
                                cartItemMessage.setMessageText("Out of Stock");
                                cartItemMessages.add(cartItemMessage);
                                cartLineRepository.delete(cartLine);
                        }
                        totalQty += cartItemResponseModel.getQuantity();

                        if (cartItemMessages.size() > 0) {
                                cartResponse.getCartItems().add(0, cartItemResponseModel);
                        } else {
                                cartResponse.getCartItems().add(cartItemResponseModel);
                        }
                }
                if (cart.getCheckoutTimestamp() != null) {
                        if (cart.getUpdateTimestamp().isBefore(cart.getCheckoutTimestamp())) {
                                cart.setCheckoutTimestamp(null);
                        }
                }
                cartResponse.setTotalQty(totalQty);
                cartResponse.setTotalAmount(totalAmount);
                cartResponse.setNonAccessoryQuantity(nonAccessoryQuantity);
                cartResponse.setShippingCharge(0);
                cartResponse.setCartMessageChanged(cartMessageChanged);
                cartResponse.setCartMessageOOS(cartMessageOOS);
                cartResponse.setCartMessageUndeliverable(cartMessageUndeliverable);
                cartResponse.setCod(false);
                return cartResponse;
        }

        @Override
        public void addItemsToCart(int cartId, List<CartItem> cartItems) throws ProfitMandiBusinessException {
                logger.info("cart items {}", cartItems);
                cartItems = cartItems.stream().filter(x -> x.getQuantity() > 0).collect(Collectors.toList());
                Map<Integer, Integer> itemQuantityMap = cartItems.stream()
                                .collect(Collectors.toMap(x -> x.getItemId(), x -> x.getQuantity()));
                List<CartLine> cartLines = cartLineRepository.selectAllByCart(cartId);
                // Delete cartLines with 0 values
                for (CartLine cartLine : cartLines) {
                        Integer quantity = itemQuantityMap.get(cartLine.getItemId());
                        if (quantity == null || quantity.intValue() == 0) {
                                cartLineRepository.delete(cartLine);
                        } else {
                                cartLine.setQuantity(itemQuantityMap.get(cartLine.getItemId()));
                                cartLine.setUpdateTimestapm(LocalDateTime.now());
                        }
                }
                for (CartItem cartItem : cartItems) {
                        if (cartLineRepository.selectByCartItem(cartId, cartItem.getItemId()) == null) {
                                CartLine cartLineNew = new CartLine();
                                cartLineNew.setItemId(cartItem.getItemId());
                                cartLineNew.setQuantity(cartItem.getQuantity());
                                cartLineNew.setCartId(cartId);
                                cartLineNew.setCreateTimestamp(LocalDateTime.now());
                                cartLineRepository.persist(cartLineNew);
                        }
                }

        }

        @Override
        public void addAddressToCart(int cartId, long addressId) throws ProfitMandiBusinessException {
                Cart cart = cartRepository.selectById(cartId);
                cart.setAddressId((int) addressId);

        }

        @Override
        public void addShoppingBag(int cartId, long qty) {
                CartLine cl = new CartLine();
                cl.setItemId(32046);
                cl.setQuantity((int) qty);
                cl.setCartId(cartId);
                cl.setCreateTimestamp(LocalDateTime.now());
                cl.setDataProtectionAmount(0);
                cl.setEstimate(0);
                cl.setInsuranceAmount((float) 0);
                cl.setDataProtectionInsurer(0);
                cl.setActualPrice((float) 0.01 * qty);
                cartLineRepository.persist(cl);

        }

        @Override
        public CartModel removeFromCart(int cartId, int itemId) {
                // TODO Auto-generated method stub
                return null;
        }

}