Rev 18447 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.ui.util;import in.shop2020.metamodel.definitions.Catalog;import in.shop2020.metamodel.definitions.Category;import in.shop2020.metamodel.util.CreationUtils;import in.shop2020.metamodel.util.ItemPojo;import in.shop2020.metamodel.util.PrivateDealPojo;import in.shop2020.metamodel.util.QtyPricePojo;import in.shop2020.model.v1.catalog.CatalogService.Client;import in.shop2020.model.v1.catalog.BulkItemPricing;import in.shop2020.model.v1.catalog.CatalogServiceException;import in.shop2020.model.v1.catalog.Item;import in.shop2020.model.v1.catalog.PrivateDeal;import in.shop2020.model.v1.catalog.Source;import in.shop2020.model.v1.catalog.SourceItemPricing;import in.shop2020.model.v1.catalog.status;import in.shop2020.model.v1.order.EmiScheme;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.util.PojoCreator;import in.shop2020.util.Utils;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;import java.util.Properties;import java.util.TreeMap;import org.apache.commons.io.FileUtils;import org.apache.thrift.TException;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.Velocity;import org.apache.velocity.exception.ParseErrorException;import org.apache.velocity.exception.ResourceNotFoundException;/*** utility class to generated all html stuff from java objects* Driver class to merge Java data objects with VTL script.** @author rajveer**/public class PriceInsertor {static Map<Long, EmiScheme> EMI_SCHEMES = new TreeMap<Long, EmiScheme>();private static Map<Long, Map<Long, Long>> comparisonStats;static {try {comparisonStats = CreationUtils.getComparisonStats();TransactionClient transactionClient = new TransactionClient("support_transaction_service_server_host", "transaction_service_server_port");in.shop2020.model.v1.order.TransactionService.Client trxClient = transactionClient.getClient();List<EmiScheme> emiSchemes = trxClient.getAvailableEmiSchemes();System.out.println("EMIs:" + emiSchemes);for (EmiScheme emiScheme : emiSchemes){if(!EMI_SCHEMES.containsKey(emiScheme.getMinAmount())) {EMI_SCHEMES.put(emiScheme.getMinAmount(), emiScheme);} else {EmiScheme emiSchemeOld = EMI_SCHEMES.get(emiScheme.getMinAmount());double interestRateOld = emiSchemeOld.getInterestRate()/12/100;double interestRate = emiScheme.getInterestRate()/12/100;if(Double.compare(interestRateOld*Math.pow((1+interestRateOld), emiSchemeOld.getTenure())/(Math.pow((1+interestRateOld), emiSchemeOld.getTenure())-1),interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1))> 0){EMI_SCHEMES.put(emiScheme.getMinAmount(), emiScheme);}}}} catch (Exception e) {e.printStackTrace();}}CatalogClient csc;Client client;PojoCreator creator;private Map<Long, PrivateDeal> privateDealsMap;private Map<Long, List<BulkItemPricing>> bulkItemPricingMap;public PriceInsertor() throws Exception{creator = new PojoCreator();csc = new CatalogClient();client = csc.getClient();privateDealsMap = client.getAllActivePrivateDeals(null,0);bulkItemPricingMap = client.getBulkPricingForItems(new ArrayList<Long>());}public void copySolrSchemaFiles() throws IOException{String source = Utils.EXPORT_PATH + "xml/final/irmetadata_solrschema.xml";String destination = Utils.EXPORT_PATH + "solr/irmetadata_solrschema.xml";FileUtils.copyFile(new File(source), new File(destination));source = Utils.EXPORT_PATH + "xml/final/irmetadata_catchall.xml";destination = Utils.EXPORT_PATH + "solr/irmetadata_catchall.xml";FileUtils.copyFile(new File(source), new File(destination));}public void insertPriceInSolrData(long catalogId, String priceString, String availabilityString) throws IOException{String irSolrFilename = Utils.EXPORT_PATH + "xml/final/" + catalogId + "_irdata_solr.xml";String finalFile = Utils.EXPORT_PATH + "solr/" + catalogId + "_irdata_solr.xml";File f = new File(irSolrFilename);String s = FileUtils.readFileToString(f);if(privateDealsMap.containsKey(catalogId)) {priceString += "<field name=\"F_50039\">Show Deals Only</field>";}s = s.replaceAll("<field name=\"F_50002\">.*</field>", priceString);s = s.replaceAll("<field name=\"F_50028\">.*</field>", availabilityString);File f1 = new File(finalFile);FileUtils.writeStringToFile(f1, s);}/***** @param items* @param catalogId* @param domain* @param exportPath* @param source* @return*/public double insertPriceInHtml(List<Item> items, long catalogId, String domain, String exportPath, Source source){ArrayList<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>();List<ItemPojo> itemPojos = new ArrayList<ItemPojo>();String offerText = null;String offerDetailText = null;String offerDetailLink = null;String afterArrival = null;String showPrice = "TRUE";Item minPriceItem = null;double minDealPrice = 0d;boolean isPrivateDeal = false;String privateDealText = null;String dealAvailableString = "Available for color ";int privateDealCounter = 0;for(Item item: items){String bestDealsText = item.getBestDealText();Map<String, String> itemDetail = new HashMap<String, String>();ItemPojo itemPojo = new ItemPojo();boolean showmrp = true;double sellingPrice = item.getSellingPrice();double mrp = item.getMrp();if(source != null){try {SourceItemPricing sip = client.getItemPricingBySource(item.getId(), source.getId());sellingPrice = sip.getSellingPrice();mrp = sip.getMrp();} catch (TException e) {} catch (CatalogServiceException e) {}}if (mrp <= sellingPrice) {showmrp = false;}if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){minPriceItem = item;}double saving = Math.round((mrp-sellingPrice)/mrp*100);itemDetail.put("ITEM_ID", ((int)item.getId())+"");itemDetail.put("SP", ((int)sellingPrice)+"");itemDetail.put("MRP", ((int)mrp)+"");itemDetail.put("SAVING", ((int)saving)+"");itemDetail.put("COLOR", item.getColor());itemDetail.put("CATALOG_ID", ((int)item.getCatalogItemId())+"");itemDetail.put("SHOWMRP", showmrp +"");itemDetail.put("IS_SELECTED", item.isDefaultForEntity() ? "SELECTED" : "");itemDetails.add(itemDetail);itemPojo.setId(item.getId());itemPojo.setColor(item.getColor());itemPojo.setBestDealText(item.getBestDealText());itemPojos.add(itemPojo);if(item.getItemStatus().equals(status.COMING_SOON)){afterArrival = "after arrival";itemPojo.setStatusDescription(item.getStatus_description());itemPojo.setComingSoon(true);if(!item.isShowSellingPrice()){showPrice = "FALSE";itemPojo.setShowSellingPrice(false);}}else {itemPojo.setSellingPrice(item.getSellingPrice());String em = getEMI(item.getSellingPrice());if(em!=null){itemPojo.setMinEmi(Double.parseDouble(em));}if(showmrp) {itemPojo.setMrp(mrp);}if(privateDealsMap.containsKey(item.getId())){privateDealsMap.put(item.getCatalogItemId(), null);if (items.size()>1){dealAvailableString += "<b>" + item.getColor() + "</b>, ";}privateDealCounter += 1;PrivateDeal pd = privateDealsMap.get(item.getId());isPrivateDeal = true;itemDetail.put("DEAL_PRICE", String.format(Locale.getDefault(),"%.0f",pd.getDealPrice()));PrivateDealPojo dealPojo = new PrivateDealPojo();dealPojo.setItemId(pd.getItem_id());dealPojo.setDealPrice(pd.getDealPrice());dealPojo.setIsCod(pd.isIsCod());dealPojo.setDealText(pd.getDealText());dealPojo.setDealTextOption(pd.getDealTextOption());dealPojo.setDealFreebieOption(pd.getDealFreebieOption());if(pd.getDealTextOption()==1) {privateDealText = bestDealsText;} else if (pd.getDealTextOption()==2) {privateDealText = pd.getDealText();}dealPojo.setFreebieItemId(pd.getDealFreebieItemId());itemPojo.setDealPojo(dealPojo);if(minDealPrice == 0d || minDealPrice > pd.getDealPrice()){minDealPrice = pd.getDealPrice();}}if(bulkItemPricingMap.containsKey(item.getId())){List<QtyPricePojo> qpl = new ArrayList<QtyPricePojo>();for(BulkItemPricing bip : bulkItemPricingMap.get(item.getId())) {QtyPricePojo qp = new QtyPricePojo();qp.setQuantity(bip.getQuantity());qp.setPrice(bip.getPrice());qpl.add(qp);}//Insert 1 qtyQtyPricePojo oneQty = new QtyPricePojo();if(!qpl.contains(oneQty)){if (privateDealsMap.containsKey(item.getId())){oneQty.setPrice(privateDealsMap.get(item.getId()).getDealPrice());}else {oneQty.setPrice(item.getSellingPrice());}qpl.add(0, oneQty);}}}if( bestDealsText != null && bestDealsText.length() > 0 && offerText == null && status.ACTIVE.equals(item.getItemStatus())){offerText = bestDealsText;String bestDealsDetailsText = item.getBestDealsDetailsText();if( bestDealsDetailsText != null && bestDealsDetailsText.length() > 0){offerDetailText = bestDealsDetailsText;}String bestDealsDetailsLink = item.getBestDealsDetailsLink();if( bestDealsDetailsLink != null && bestDealsDetailsLink.length() > 0){offerDetailLink = bestDealsDetailsLink;}}//MostComparedProducts.vm should be generated as part of catalog generation}if(source == null){exportPath = exportPath + catalogId;}else{exportPath = exportPath + catalogId + File.separator + source.getId();}File exportDir = new File(exportPath);if(!exportDir.exists()) {exportDir.mkdir();}// This URL is used to ensure that images such as icon and thumbnail for// a particular entity are always downloaded from the same location.String staticurl = "http://static" + catalogId%3 + "." + (domain.contains("store") ? "saholic.com":domain);VelocityContext context = new VelocityContext();String emiString = getEMI(items.get(0).getSellingPrice());context.put("domain", domain.contains("store") ? "saholic.com":domain);context.put("itemDetails", itemDetails);context.put("minPriceItem", minPriceItem);context.put("staticurl", staticurl);context.put("OFFER_TEXT", offerText);context.put("OFFER_DETAIL_TEXT", offerDetailText);context.put("OFFER_DETAIL_LINK", offerDetailLink);context.put("AFTER_ARRIVAL", afterArrival);context.put("SHOW_PRICE", domain.contains("store")?"FALSE":showPrice);context.put("IS_STORE", domain.contains("store")?"TRUE":"FALSE");context.put("EMI", emiString);if(isPrivateDeal) {context.put("PRIVATE_DEAL_TEXT", privateDealText);context.put("PRIVATE_DEAL_PRICE", String.format(Locale.getDefault(),"%.0f",minDealPrice));if(items.size()==privateDealCounter && items.size()>1) {context.put("AVAILABLE", "Available for all colors");} else if(items.size()>1) context.put("AVAILABLE", dealAvailableString.substring(0, dealAvailableString.length()-2));}List<String> filenames = new ArrayList<String>();if(!domain.contains("store")){filenames.add("WidgetSnippet");filenames.add("ProductPropertiesSnippet");filenames.add("MyResearchSnippet");filenames.add("AfterSales");filenames.add("SearchSnippet");filenames.add("CategorySnippet");filenames.add("HomeSnippet");filenames.add("ProductDetail");filenames.add("SlideGuide");}else {filenames.add("store/" + catalogId + "/SearchSnippet");filenames.add("ProductPropertiesSnippet");filenames.add("store/" + catalogId + "/CategorySnippet");filenames.add("store/" + catalogId + "/HomeSnippet");filenames.add("store/" + catalogId + "/ProductDetail");filenames.add("store/" + catalogId + "/SlideGuide");}Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(items.get(0).getCategory());if(category!=null && !domain.contains("store")){Category parentCategory = category.getParentCategory();if(parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY) {filenames.add("PhonesIOwnSnippet");}if(parentCategory.isHasAccessories()){filenames.add("RelatedAccessories");}if(isPrivateDeal){filenames.add("DealSnippet");}filenames.add("CompareProductSnippet");filenames.add("SlideNamesSnippet");filenames.add("ComparisonSnippet");if(category.isComparable()) {//Before adding we should populatetry {getMostComparedProducts(exportPath,catalogId);}catch (Exception e){e.printStackTrace();}filenames.add("CompareProductSummarySnippet");filenames.add("MostComparedSnippet");}}getHtmlFromVelocity(filenames,exportPath,context,catalogId);//Update catalogInfo to catalogcreator.updateCatalogInfo(catalogId, offerText, itemPojos);return minPriceItem.getSellingPrice();}private static String getEMI(double sellingPrice) {String returnString = null;double finalEmiD = 0d;for (EmiScheme emiScheme : EMI_SCHEMES.values() ){double interestRate = emiScheme.getInterestRate()/12/100;if(emiScheme.getMinAmount() <= sellingPrice) {double emiD = interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1);if(finalEmiD == 0d){finalEmiD = emiD;} else if(Double.compare(finalEmiD, emiD) > 0){finalEmiD = emiD;}}}if(finalEmiD != 0d) {returnString = String.format(Locale.getDefault(),"%.0f",sellingPrice * finalEmiD);}return returnString;}public void getHtmlFromVelocity(List<String> filenames, String exportPath, VelocityContext context, long catalogId){try {Properties p = new Properties();p.setProperty("resource.loader", "file");p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");p.setProperty( "file.resource.loader.path", Utils.EXPORT_VELOCITY_PATH);Velocity.init(p);for(String filename: filenames){if(filename.contains("store/")){Template template = Velocity.getTemplate(filename + ".vm", "UTF-8");BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename.split(""+ catalogId +"/")[1] +".html")));template.merge(context, writer);writer.flush();writer.close();} else {Template template = Velocity.getTemplate(catalogId + File.separator + filename + ".vm", "UTF-8");BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename +".html")));template.merge(context, writer);writer.flush();writer.close();}}}catch (ResourceNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ParseErrorException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** Get most compared phones** @param expEntity* @param exportPath* @throws Exception*/private void getMostComparedProducts(String exportPath, long catalogId) throws Exception {Map<Long, Long> comparedPhones = comparisonStats.get(catalogId);StringBuffer sb = new StringBuffer();int maxCount = 10;int count = 0;if (comparedPhones != null) {for (Long entityID : comparedPhones.keySet()) {if (count > maxCount) {break;}sb.append(entityID + "\n");count++;}}if(count>0){String exportFileName = exportPath + File.separator + "MostComparedProducts.html";File exportFile = new File(exportFileName);exportFile.createNewFile();BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportFile)));writer.write(sb.toString());writer.flush();writer.close();}}}