Subversion Repositories SmartDukaan

Rev

Rev 4384 | Rev 5229 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package in.shop2020.util;

import in.shop2020.metamodel.core.Entity;
import in.shop2020.metamodel.definitions.Catalog;
import in.shop2020.metamodel.definitions.DefinitionsContainer;
import in.shop2020.metamodel.util.CreationUtils;
import in.shop2020.model.v1.catalog.Item;
import in.shop2020.model.v1.catalog.status;
import in.shop2020.model.v1.user.ItemCouponDiscount;
import in.shop2020.thrift.clients.CatalogClient;
import in.shop2020.thrift.clients.PromotionClient;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;


/**
 * Command line utility to generate xml file for partners
 * 
 * @author rajveer
 *
 */
public class ProductListGenerator {
        
        private String[] xmlIndentation = {"", "    ", "        ", "            ","                "};
        public Map<Long, List<Item>> entityIdItemMap;
        DefinitionsContainer defContainer = Catalog.getInstance().getDefinitionsContainer();
        
        public ProductListGenerator(Map<Long, List<Item>> entityIdItemMap) throws Exception {
                this.entityIdItemMap = entityIdItemMap;
        }
        
        
        /**
         * Get the url of the entity
         * @param expEntity
         * @return url
         */
        private String getProductURL(long entityId, Item item){
                //long rootCategoryId = catm.getCategory(item.getCategory()).getParent_category_id();
                in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
                
                String url = "http://www.saholic.com/" + parentCategory.getLabel().toLowerCase().replace(' ', '-') + "/";
                String productUrl = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "").toLowerCase().replace(' ', '-')
        + "-" + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "").toLowerCase().replace(' ', '-') 
            + "-" + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() + " ": "" ).toLowerCase().replace(' ', '-')
        + "-" + entityId;
                productUrl = productUrl.replaceAll("/", "-");
                url = url + productUrl;
                url = url.replaceAll("-+", "-");
                return url;
        }

        
    
        /**
         * Get the minimum mrp of the items
         * @param items
         * @return
         */
        private double getMinMRP(List<Item> items){
        double minPrice = Double.MAX_VALUE;
        for(Item item: items){
            if(minPrice > item.getMrp()){
                minPrice =  item.getMrp();
            }
        }
        return minPrice;
    }
        
        
    
        /**
         * Get the minimum price of the items
         * @param items
         * @return
         */
        private double getMinPrice(List<Item> items){
        double minPrice = Double.MAX_VALUE;
        for(Item item: items){
            if(minPrice > item.getSellingPrice()){
                minPrice = item.getSellingPrice();
            }
        }
        return minPrice;
    }

        /**
         * Check whether product is mobile or not
         * @param item
         * @return
         */
        private boolean isMobile(Item item){
                in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
                return parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY;
        }
        
        /**
         * Checks whether a product is laptop or not
         */
        private boolean isLaptop(Item item) {
                in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
                return parentCategory.getID() == Utils.LAPTOPS_CATEGORY;
        }
        
        /**
         * 
         * @param item
         * @return
         */
        private String getProductTitle(Item item){
                String title = ((item.getBrand() != null) ? item.getBrand().trim() + " " : "")
                + ((item.getModelName() != null) ? item.getModelName().trim() + " " : "")
                + (( item.getModelNumber() != null ) ? item.getModelNumber().trim() : "" );
                title = title.replaceAll("  ", " ");
                return title;
        }
    
        /**
         * get xml feed for partner sites
         * @param irDataXMLSnippets
         * @throws Exception
         */
        private void getProductsXML(ArrayList<String> irDataXMLSnippets) throws Exception{
                for(Long entityId: entityIdItemMap.keySet()){
                        List<Item> items = entityIdItemMap.get(entityId);
                        Item firstItem = items.get(0);
                        if(!isMobile(firstItem)){
                                continue;
                        }
                        
                        irDataXMLSnippets.add(this.xmlIndentation[1] + "<products>");   
                        
                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
                        
                        String title = getProductTitle(firstItem);
                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");

                        String url = getProductURL(entityId, firstItem);
                                                
                        String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator +
                                          "website" + File.separator + entityId + File.separator + "icon.jpg";

                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");

                        
                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductPrice>" + getMinPrice(items) + "</ProductPrice>");
                        
                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + getMinMRP(items) + "</ProductMRP>");
                        
                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
                        
                        irDataXMLSnippets.add(this.xmlIndentation[1] + "</products>");          
                }
        }
        
        /**
         * Generate the xml list of all the active phones and store in a file
         * @throws Exception
         */
        public void generateProductsListXML() throws Exception {
                ArrayList<String> productXMLSnippets = new ArrayList<String>();
                productXMLSnippets.add("<saholic.com>");
                
                getProductsXML(productXMLSnippets);
                
                productXMLSnippets.add("</saholic.com>");
                
                String productDataXML = StringUtils.join(productXMLSnippets, "\n");
                
                Utils.info(productDataXML);
                
                // Write it to file
                String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "saholicmobilephones.xml";
                DBUtils.store(productDataXML, productXMLFilename);
        }




        /**
         * get xml feed for partner sites
         * @param irDataXMLSnippets
         * @throws Exception
         */
        private void getProductsJavascript(StringBuffer sb) throws Exception{

                Map<String, Long> mobilePhones = new HashMap<String, Long>();
                Map<String, Long> laptops = new HashMap<String, Long>();
                
                for(Long entityId: entityIdItemMap.keySet())    {
                        Item item = entityIdItemMap.get(entityId).get(0);
                        
                        if (isMobile(item))     {
                                mobilePhones.put(getProductTitle(item), entityId);
                        }
                        else if (isLaptop(item))        {
                                laptops.put(getProductTitle(item), entityId);
                        }
                }
                Map<String, Map<String, Long>> products = new HashMap<String, Map<String,Long>>();
                products.put("mobiles", mobilePhones);
                products.put("laptops", laptops);
                sb.append(new JSONObject(products));
        }
        
        
        /**
         * Generate the javascript list of all the active phones and store in a file
         * @throws Exception
         */
        public void generateProductListJavascript() throws Exception {
                StringBuffer productsJavascript = new StringBuffer();
                
                productsJavascript.append("var productIdNames=");
                
                getProductsJavascript(productsJavascript);
                
                productsJavascript.append(";");
                
                // Write it to file
                String productXMLFilename = Utils.EXPORT_JAVASCRIPT_CONTENT_PATH + "saholicmobilephones.js";
                DBUtils.store(productsJavascript.toString(), productXMLFilename);
        }
        
        public static void main(String[] args) throws Exception {
                CatalogClient cl = new CatalogClient();
                in.shop2020.model.v1.catalog.InventoryService.Client client = cl.getClient();
                
                List<Item> items = cl.getClient().getAllItemsByStatus(status.ACTIVE);
                items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED));
                items.addAll(cl.getClient().getAllItemsByStatus(status.PAUSED_BY_RISK));

                Map<Long, List<Item>> entityIdItemMap1 = new HashMap<Long, List<Item>>();
                ProductListGenerator pl = new ProductListGenerator(entityIdItemMap1);
                pl.populateEntityIdItemMap(items);
                pl.generateProductXMLForDisplayAds();
        }

    private void populateEntityIdItemMap(List<Item> items){
        Date toDate = new Date();
        for(Item item: items){
            //TODO Can be removed as we are checking in calling function
            if(!(item.getItemStatus()==status.ACTIVE || item.getItemStatus()==status.CONTENT_COMPLETE || item.getItemStatus() == status.PAUSED)){
                continue;
            }
            if(toDate.getTime() < item.getStartDate() ||  item.getSellingPrice() == 0){
                continue;
            }
            List<Item> itemList = entityIdItemMap.get(item.getCatalogItemId());
            if(itemList == null){
                itemList = new ArrayList<Item>();
            }
            itemList.add(item);
            entityIdItemMap.put(item.getCatalogItemId(), itemList);
        }

        //Remove all items which have not been updated since last content generation.
        List<Long> removeEntities = new ArrayList<Long>();
        for(Long entityId:entityIdItemMap.keySet()){
            boolean isValidEntity = false;
            //If any one of the items has been updated before current timestamp, than we generate content for whole entity
            for(Item item: entityIdItemMap.get(entityId)){
                if(item.getUpdatedOn() > 0){
                    isValidEntity = true;
                }
            }
            if(!isValidEntity){
                removeEntities.add(entityId);
            }
        }
        for(Long entityId: removeEntities){
            entityIdItemMap.remove(entityId);
        }
    }


        /**
         * Generate the xml list of all the active phones and store in a file
         * @throws Exception
         */
        public void generateProductXMLForDisplayAds() throws Exception {
                Utils.info("Generating Product XML for display ads");
                List<String> productXMLSnippets = new ArrayList<String>();
                productXMLSnippets.add("<saholic.com>");
                List<Long> itemIds = new ArrayList<Long>();

                Utils.info("Entity Ids: " + entityIdItemMap.keySet());
                
                for(Long entityId: entityIdItemMap.keySet()){
                        List<Item> items = entityIdItemMap.get(entityId);
                        Item firstItem = items.get(0);
                        Utils.info("first Item: " + firstItem);
                        
                        if(isMobile(firstItem) || isLaptop(firstItem)) {
                                itemIds.add(firstItem.getId());
                        }
                }

                PromotionClient promotionClient = new PromotionClient();
                in.shop2020.model.v1.user.PromotionService.Client promotionServiceClient = promotionClient.getClient();
                
                List<ItemCouponDiscount> itemsCouponsAndDiscounts = promotionServiceClient.getItemDiscountMap(itemIds);
                
                Map<Long, ItemCouponDiscount> couponsAndDiscounts = new HashMap<Long, ItemCouponDiscount>();
                
                for (ItemCouponDiscount itemCouponDiscount: itemsCouponsAndDiscounts) {
                        couponsAndDiscounts.put(itemCouponDiscount.getItemId(), itemCouponDiscount);
                }
                Utils.info("Entity IDs: " + entityIdItemMap.keySet());
                
                for(Long entityId: entityIdItemMap.keySet()) {
                        List<Item> items = entityIdItemMap.get(entityId);
                        Item firstItem = items.get(0);
                        
                        Utils.info("First Item: " + firstItem);
                        
                        if(!isMobile(firstItem) && !isLaptop(firstItem)){
                                continue;
                        }
                        
                        productXMLSnippets.add(this.xmlIndentation[1] + "<products>");  
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSKU>" + entityId + "</ProductSKU>");
                        
                        String title = getProductTitle(firstItem);
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductName>" + title + "</ProductName>");

                        String url = getProductURL(entityId, firstItem);
                        
                        String imageUrl = "http://static" + ((entityId+1)%3) + ".saholic.com" + File.separator + "images" + File.separator + entityId + File.separator + "icon.jpg";    
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductURL>" + url + "</ProductURL>");

                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductImageURL>" + imageUrl + "</ProductImageURL>");
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductMRP>" + firstItem.getMrp() + "</ProductMRP>");
                        
                        double minPrice = getMinPrice(items);
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductSellingPrice>" + (int)minPrice  + "</ProductSellingPrice>");
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDiscount>" + (int)((firstItem.getMrp()-minPrice)/firstItem.getMrp()*100) + "</ProductDiscount>");
                        
                        long itemId = firstItem.getId();
                        
                        if(couponsAndDiscounts.containsKey(itemId))     {
                                
                                ItemCouponDiscount itemCouponDiscount = couponsAndDiscounts.get(itemId);

                                productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons>");
                                productXMLSnippets.add(this.xmlIndentation[3] + "<Coupon>");
                                productXMLSnippets.add(this.xmlIndentation[4] + "<CouponCode>" + itemCouponDiscount.getCouponCode() + "</CouponCode>");
                                productXMLSnippets.add(this.xmlIndentation[4] + "<PriceAfterCoupon>" + (int)(minPrice - itemCouponDiscount.getDiscount()) + "</PriceAfterCoupon>");
                                productXMLSnippets.add(this.xmlIndentation[3] + "</Coupon>");
                                productXMLSnippets.add(this.xmlIndentation[2] + "</ProductCoupons>");
                                
                        } else  {
                                productXMLSnippets.add(this.xmlIndentation[2] + "<ProductCoupons />");
                        }
                        
                        String description = "";
                        Entity entity = CreationUtils.getEntity(entityId);
                        if(entity!=null){
                                if(entity.getSlide(130001) !=null){
                                        description = StringEscapeUtils.escapeXml(entity.getSlide(130001).getFreeformContent().getFreeformText());
                                }
                        }
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ProductDescription>" + description + "</ProductDescription>");
                        
                        productXMLSnippets.add(this.xmlIndentation[1] + "</products>"); 
                }
                
                productXMLSnippets.add("</saholic.com>");
                
                String productDataXML = StringUtils.join(productXMLSnippets, "\n");
                
                Utils.info(productDataXML);
                
                // Write it to file
                String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "advertismentapi.xml";
                DBUtils.store(productDataXML, productXMLFilename);
        }
}