Subversion Repositories SmartDukaan

Rev

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

package com.spice.profitmandi.web.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.spice.profitmandi.common.exception.ProfitMandiBusinessException;
import com.spice.profitmandi.common.model.ItemDescriptionModel;
import com.spice.profitmandi.common.model.PriceDropModel;
import com.spice.profitmandi.common.util.ExcelUtils;
import com.spice.profitmandi.dao.entity.catalog.Item;
import com.spice.profitmandi.dao.entity.catalog.TagListing;
import com.spice.profitmandi.dao.entity.fofo.InventoryItem;
import com.spice.profitmandi.dao.entity.inventory.VendorItemPricing;
import com.spice.profitmandi.dao.entity.transaction.LineItemImei;
import com.spice.profitmandi.dao.entity.transaction.PriceDrop;
import com.spice.profitmandi.dao.entity.transaction.PriceDropIMEI;
import com.spice.profitmandi.dao.repository.catalog.ItemRepository;
import com.spice.profitmandi.dao.repository.catalog.TagListingRepository;
import com.spice.profitmandi.dao.repository.inventory.VendorItemPricingRepository;
import com.spice.profitmandi.dao.repository.transaction.LineItemImeisRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropIMEIRepository;
import com.spice.profitmandi.dao.repository.transaction.PriceDropRepository;
import com.spice.profitmandi.service.inventory.InventoryService;
import com.spice.profitmandi.service.pricing.PriceDropService;
import com.spice.profitmandi.service.transaction.TransactionService;
import com.spice.profitmandi.service.wallet.WalletService;
import com.spice.profitmandi.web.util.MVCResponseSender;

import in.shop2020.model.v1.order.WalletReferenceType;

@Controller
@Transactional
public class PriceDropController {

        private static final Logger LOGGER = LogManager.getLogger(PriceDropController.class);

        @Autowired
        private PriceDropRepository priceDropRepository;

        @Autowired
        private PriceDropIMEIRepository priceDropIMEIRepository;
        
        @Autowired
        private VendorItemPricingRepository vendorItemPricingRepository;

        @Autowired
        private PriceDropService priceDropService;

        @Autowired
        @Qualifier("fofoInventoryService")
        private InventoryService inventoryService;
        
        @Autowired
        private MVCResponseSender mvcResponseSender;

        @Autowired
        private WalletService walletService;

        @Autowired
        private LineItemImeisRepository lineItemImeisRepository;
        
        @Autowired
        private TagListingRepository tagListingRepository;
        
        @Autowired
        private TransactionService transactionService;

        @Autowired
        @Qualifier("catalogItemRepository")
        private ItemRepository itemRepository;

        @RequestMapping(value = "/getItemDescription", method = RequestMethod.GET)
        public String getItemDescription(HttpServletRequest request, Model model) throws Throwable{

                List<TagListing> tagListings = tagListingRepository.selectAll(false);
                Map<Integer, TagListing> tagListingMap = new HashMap<>();
                List<ItemDescriptionModel> customItems = new ArrayList<>();
                for(TagListing tagListing : tagListings) {
                        tagListing.setItemDescription(itemRepository.selectById(tagListing.getItemId()).getItemDescription());
                        tagListingMap.put(tagListing.getItemId(), tagListing);
                        ItemDescriptionModel itemDescriptionModel = new ItemDescriptionModel();
                        itemDescriptionModel.setItemId(tagListing.getItemId());
                        itemDescriptionModel.setItemDescription(tagListing.getItemDescription() + "(" + tagListing.getItemId()   +")");
                        customItems.add(itemDescriptionModel);  
                }
                
                List<PriceDrop> priceDrops = priceDropRepository.selectAll();
                model.addAttribute("tagListingMap", tagListingMap);
                model.addAttribute("customItems", new JSONArray(customItems).toString());
                model.addAttribute("priceDrops", priceDrops);
                return "price-drop";

        }

        @RequestMapping(value = "/downloadPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
        public ResponseEntity<?> downloadPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
                        Model model) throws ProfitMandiBusinessException {

                PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
                List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByPriceDropId(priceDrop.getId());
                List<String> imeis = priceDropIMEIs.stream().map(x -> x.getImei()).collect(Collectors.toList());
                List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByIMEI(imeis);
                Map<String, String> priceDropIMEIfofoId = priceDropService.getIMEIandRetailerName(lineItemImeis, priceDrop);
                if (priceDropIMEIfofoId.size() > 0) {
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        ExcelUtils.writePriceDrop(priceDropIMEIfofoId, priceDrop.getItemId(), byteArrayOutputStream);
                        final HttpHeaders headers = new HttpHeaders();
                        // private static final String CONTENT_TYPE_XLSX =
                        // "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        // headers.set("Content-Type", "application/vnd.ms-excel");
                        headers.set("Content-disposition", "inline; filename=priceDrop" + priceDrop.getId() + ".xlsx");
                        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
                        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
                } else {
                        throw new ProfitMandiBusinessException("priceDropId", priceDropId, "No IMEI is Eligible For PriceDrop");
                }

        }

        @RequestMapping(value = "/paymentAgainstPriceDrop/{priceDropId}/{processedamount}", method = RequestMethod.POST)
        public String paymentAgainstPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
                        @PathVariable int processedamount, Model model) throws Exception {

                
                int noOfIMEIForPartner = 1;
                Map<Integer, Integer> noOfPriceDropToPartners = new HashMap<>();
                PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
                Item item = itemRepository.selectById(priceDrop.getItemId());
                List<PriceDropIMEI> priceDropIMEIs = priceDropIMEIRepository.selectByPriceDropId(priceDrop.getId());
                List<String> imeis = priceDropIMEIs.stream().map(x -> x.getImei()).collect(Collectors.toList());
                List<LineItemImei> lineItemImeis = lineItemImeisRepository.selectByIMEI(imeis);
                Map<String, Integer> priceDropIMEIfofoIds = priceDropService.getIMEIAndfofoIdForPriceDrop(lineItemImeis,
                                priceDrop);
                if (priceDropIMEIfofoIds.size() > 0) {
                        for (Map.Entry<String, Integer> priceDropIMEIAndFofoId : priceDropIMEIfofoIds.entrySet()) {
                                int fofoId = priceDropIMEIAndFofoId.getValue();
                                if (noOfPriceDropToPartners.containsKey(fofoId)) {
                                        noOfPriceDropToPartners.put(fofoId, noOfPriceDropToPartners.get(fofoId) + 1);
                                } else {
                                        noOfPriceDropToPartners.put(fofoId, noOfIMEIForPartner);
                                }

                        }
                        for (Map.Entry<Integer, Integer> noOfPriceDropToPartner : noOfPriceDropToPartners.entrySet()) {
                                String description = String.format("Price Drop amount added for %s, total %d pcs.",
                                                item.getItemDescription(), noOfPriceDropToPartner.getValue());
                                walletService.addAmountToWallet(noOfPriceDropToPartner.getKey(), priceDrop.getId(),
                                                WalletReferenceType.PRICE_DROP, description,
                                                (noOfPriceDropToPartner.getValue() * processedamount));
                                LOGGER.info(
                                                "Price Drop amount [{}] has been added with retailerId [{}]'s wallet, referenceId [{}], No Of serialNumber [{}]",
                                                (noOfPriceDropToPartner.getValue() * processedamount), noOfPriceDropToPartner.getKey(),
                                                priceDrop.getId(), noOfPriceDropToPartner.getValue());
                        }
                        priceDrop.setProcessTimestamp(LocalDateTime.now());
                        priceDrop.setPartnerPayout(processedamount);
                        priceDropRepository.persist(priceDrop);
                        model.addAttribute("response", mvcResponseSender.createResponseString(true));
                        return "response";
                } else {
                        priceDrop.setProcessTimestamp(LocalDateTime.now());
                        model.addAttribute("response", mvcResponseSender.createResponseString(false));
                        return "false";
                }
        }

        @RequestMapping(value = "/priceDrop", method = RequestMethod.POST)
        public String addPriceDrop(HttpServletRequest request, Model model, @RequestBody PriceDropModel priceDropModel) throws Exception {
                boolean response = false;
                if(this.validatePriceDrop(priceDropModel)) {
                        TagListing tagListing = tagListingRepository.selectByItemId(priceDropModel.getItemId());
                        float newDp = tagListing.getSellingPrice() - priceDropModel.getPd();
                        if(newDp > 0) {
                                List<Item> allItems = null;
                                Item currentItem = itemRepository.selectById(priceDropModel.getItemId());
                                if(priceDropModel.isAllColors()) {
                                        allItems = itemRepository.selectAllByCatalogItemId(currentItem.getCatalogItemId());
                                        
                                } else {
                                        allItems=Arrays.asList(currentItem);
                                }
                                for(Item item : allItems) {
                                        TagListing itemTagListing = tagListingRepository.selectByItemId(item.getId());
                                        if(itemTagListing == null) continue;
                                        itemTagListing.setSellingPrice(newDp);
                                        itemTagListing.setMop(priceDropModel.getMop());
                                        tagListingRepository.persist(tagListing);
                                        List<VendorItemPricing> vipList = vendorItemPricingRepository.selectAll(item.getId());
                                        for(VendorItemPricing vip : vipList) {
                                                vip.setDp(newDp);
                                                vip.setMop(priceDropModel.getMop());
                                                vip.setNlc(priceDropModel.getNlc());
                                                vip.setTp(priceDropModel.getTp());
                                                vendorItemPricingRepository.persist(vip);
                                        }
                                        PriceDrop priceDrop = new PriceDrop();
                                        priceDrop.setAffectedOn(priceDropModel.getAffectedDate());
                                        priceDrop.setAmount(priceDropModel.getPd());
                                        priceDrop.setCreatedOn(LocalDateTime.now());
                                        priceDrop.setItemId(item.getId());
                                        priceDropRepository.persist(priceDrop);
                                        transactionService.updatePriceDrop(item.getId(), newDp);
                                }
                                response = true;
                        } else {
                                throw new ProfitMandiBusinessException("Price Drop", priceDropModel.getPd(), "Price Drop Cannot be more than Current DP");
                        }
                }
                model.addAttribute("response", mvcResponseSender.createResponseString(response));
                return "response";
        }
        @RequestMapping(value = "/downloadtotalPriceDropIMEI/{priceDropId}", method = RequestMethod.GET)
        public ResponseEntity<?> downloadTotalPriceDropIMEI(HttpServletRequest request, @PathVariable int priceDropId,
                        Model model) throws ProfitMandiBusinessException {

                PriceDrop priceDrop = priceDropRepository.selectById(priceDropId);
                Map<String, String> priceDropIMEIAndItemId = this.getpriceDropIMEIAndItemDescription(priceDrop);
                if (priceDropIMEIAndItemId.size() > 0) {
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        ExcelUtils.writePriceDropForAllIMEI(priceDropIMEIAndItemId, byteArrayOutputStream);
                        final HttpHeaders headers = new HttpHeaders();
                        headers.set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        headers.set("Content-disposition", "inline; filename=totalPriceDropIMEI" + priceDrop.getItemId() + ".xlsx");
                        headers.setContentLength(byteArrayOutputStream.toByteArray().length);
                        final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                        final InputStreamResource inputStreamResource = new InputStreamResource(inputStream);
                        return new ResponseEntity<InputStreamResource>(inputStreamResource, headers, HttpStatus.OK);
                } else {
                        priceDrop.setProcessTimestamp(LocalDateTime.now());
                        throw new ProfitMandiBusinessException("IMEI", 1, "IMEI not Found For PriceDrop");
                }
        }

        private boolean validatePriceDrop(PriceDropModel priceDropModel) throws ProfitMandiBusinessException {
                if(priceDropModel.getMop() > 0 && priceDropModel.getMop() > 0 && priceDropModel.getNlc() > 0 && priceDropModel.getTp() > 0 && priceDropModel.getNlc() > 0) {
                        return true;
                }
                return false;
        }
        private Map<String, String> getpriceDropIMEIAndItemDescription(PriceDrop priceDrop)
                        throws ProfitMandiBusinessException {
                Map<String, String> priceDropIMEIAndItemId = new LinkedHashMap<>();
                List<InventoryItem> inventoryInStock = inventoryService.getInventoryInStock(priceDrop.getItemId(), priceDrop.getAffectedOn());
                return priceDropIMEIAndItemId;
        }

}