Subversion Repositories SmartDukaan

Rev

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

package in.shop2020.util;

import in.shop2020.logistics.DeliveryType;
import in.shop2020.logistics.LogisticsInfo;
import in.shop2020.logistics.LogisticsService;
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.LogisticsClient;
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;
        private static final String DEFAULT_PINCODE = "110001";
        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 tablet or not
         */
        private boolean isTablet(Item item) {
                in.shop2020.metamodel.definitions.Category parentCategory = defContainer.getCategory(item.getCategory()).getParentCategory();
                return parentCategory.getID() == Utils.TABLETS_CATEGORY;
        }
        
        /**
         * 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{
                LogisticsService.Client prod_client = null;
                try {
                        LogisticsClient logistics_prod = new LogisticsClient("logistics_service_prod_server_host","logistics_service_prod_server_port");
                        prod_client = logistics_prod.getClient();
                } catch (Exception e) {
                        prod_client = null;
                        Utils.info("Logistics estimations can't be fetched as Logistics Service is inaccessible"
                                        + e);
                }
                for(Long entityId: entityIdItemMap.keySet()){
                        List<Item> items = entityIdItemMap.get(entityId);
                        Item firstItem = items.get(0);
                        
                        if(!isMobile(firstItem) && !isTablet(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>");
                        
                        LogisticsInfo logisticsInfo = null;
                        if(prod_client != null){
                                try {
                                        Long itemId = prod_client.getEntityLogisticsEstimation(
                                                        entityId, DEFAULT_PINCODE, DeliveryType.PREPAID)
                                                        .get(0);
                                        logisticsInfo = prod_client.getLogisticsEstimation(itemId,
                                                        DEFAULT_PINCODE, DeliveryType.PREPAID);
                                        irDataXMLSnippets.add(this.xmlIndentation[2] + "<ProductDeliveryEstimate>" + logisticsInfo.getDeliveryTime() + "</ProductDeliveryEstimate>");
                                } catch (Exception e1) {
                                        Utils.info("Unable to get Estimation for Entity: " + entityId + "\n" + e1);
                                }
                        }
                        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);
        }

    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 XML feed for mobile site
     * @throws Exception
     */
    public void generateXMLFeedForMobileSite() throws Exception {
        List<String> productXMLSnippets = new ArrayList<String>();
                productXMLSnippets.add("<Products>");
                List<Long> itemIds = new ArrayList<Long>();
                
                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());
                        }
                }

                List<String> descriptions = new ArrayList<String>();
                descriptions.add("8MP camera, Super AMOLED Plus display, Android Gingerbread");
                descriptions.add("Android OS v2.2 Froyo, 800MHz processor, 3.5\" capacitive display");
                descriptions.add("Dual-SIM, Wi-Fi, Bluetooth, Social networking &amp; IM");
                descriptions.add("Android Gingerbread, Facebook button, 5MP camera");
                descriptions.add("Android Gingerbread, 1GHz processor, 3.7\" Gorilla Glass display");
                descriptions.add("2GB RAM, 500GB HDD, Intel Core 2 Duo T6570 processor, DOS");
                descriptions.add("4GB RAM, 500GB HDD, Intel Core i5 2410M processor, Windows 7 Basic");
                descriptions.add("3.2\" touchscreen, 2MP camera, IM &amp; social networking");
                
                for(Long entityId: entityIdItemMap.keySet()) {
                        List<Item> items = entityIdItemMap.get(entityId);
                        Item firstItem = items.get(0);
                        
                        if(!isMobile(firstItem) && !isLaptop(firstItem)){
                                continue;
                        }

                        String url = getProductURL(entityId, firstItem);
                        String imageUrl = "http://www.saholic.com/images/website" + File.separator + entityId + File.separator + "thumbnail.jpg";
                        String description = descriptions.get((int) (8 * Math.random()));
                        double minPrice = getMinPrice(items);
                        
                        String productType = "";
                        
                        if (firstItem.getCategory() == 10001 || firstItem.getCategory() == 10002 || firstItem.getCategory() == 10003 || firstItem.getCategory() == 10004 || firstItem.getCategory() == 10005)   {
                                productType = "Mobile Phone";
                        
                        } else if (firstItem.getCategory() == 10010)    {
                                productType = "Tablet";
                                
                        } else if (firstItem.getCategory() == 10050)    {
                                productType = "Laptop";
                        }
                        
                        productXMLSnippets.add(this.xmlIndentation[1] + "<Product>");   
                        
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ID>" + entityId + "</ID>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<Type>" + productType + "</Type>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<Brand>" + firstItem.getBrand() + "</Brand>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ModelName>" + firstItem.getModelName() + "</ModelName>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ModelNumber>" + firstItem.getModelNumber() + "</ModelNumber>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<URL>" + url + "</URL>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ImageURL>" + imageUrl + "</ImageURL>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<ShortDesc>" + description + "</ShortDesc>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<MRP>" + firstItem.getMrp() + "</MRP>");
                        productXMLSnippets.add(this.xmlIndentation[2] + "<SellingPrice>" + (int)minPrice  + "</SellingPrice>");
                        
                        productXMLSnippets.add(this.xmlIndentation[1] + "</Product>");
                }
                
                productXMLSnippets.add("</Products>");
                
                String productDataXML = StringUtils.join(productXMLSnippets, "\n");
                
                Utils.info(productDataXML);
                
                // Write it to file
                String productXMLFilename = Utils.EXPORT_PARTNERS_CONTENT_PATH + "msitedata.xml";
                DBUtils.store(productDataXML, productXMLFilename);
    }

        /**
         * 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);
        }
        
        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.generateXMLFeedForMobileSite();
        }
}