Subversion Repositories SmartDukaan

Rev

Rev 12320 | Rev 18447 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2367 rajveer 1
package in.shop2020.ui.util;
2
 
4805 rajveer 3
import in.shop2020.metamodel.definitions.Catalog;
4802 amit.gupta 4
import in.shop2020.metamodel.definitions.Category;
10168 amit.gupta 5
import in.shop2020.metamodel.util.CreationUtils;
9280 amit.gupta 6
import in.shop2020.metamodel.util.ItemPojo;
11762 amit.gupta 7
import in.shop2020.metamodel.util.PrivateDealPojo;
5945 mandeep.dh 8
import in.shop2020.model.v1.catalog.CatalogService.Client;
9
import in.shop2020.model.v1.catalog.CatalogServiceException;
2367 rajveer 10
import in.shop2020.model.v1.catalog.Item;
11585 amit.gupta 11
import in.shop2020.model.v1.catalog.PrivateDeal;
3560 rajveer 12
import in.shop2020.model.v1.catalog.Source;
13
import in.shop2020.model.v1.catalog.SourceItemPricing;
5227 amit.gupta 14
import in.shop2020.model.v1.catalog.status;
7853 amit.gupta 15
import in.shop2020.model.v1.order.EmiScheme;
3560 rajveer 16
import in.shop2020.thrift.clients.CatalogClient;
7853 amit.gupta 17
import in.shop2020.thrift.clients.TransactionClient;
9218 amit.gupta 18
import in.shop2020.util.PojoCreator;
2367 rajveer 19
import in.shop2020.util.Utils;
20
 
21
import java.io.BufferedWriter;
22
import java.io.File;
23
import java.io.FileOutputStream;
24
import java.io.IOException;
25
import java.io.OutputStreamWriter;
26
import java.util.ArrayList;
27
import java.util.HashMap;
28
import java.util.List;
7853 amit.gupta 29
import java.util.Locale;
2367 rajveer 30
import java.util.Map;
31
import java.util.Properties;
7853 amit.gupta 32
import java.util.TreeMap;
2367 rajveer 33
 
34
import org.apache.commons.io.FileUtils;
3560 rajveer 35
import org.apache.thrift.TException;
2367 rajveer 36
import org.apache.velocity.Template;
37
import org.apache.velocity.VelocityContext;
38
import org.apache.velocity.app.Velocity;
39
import org.apache.velocity.exception.ParseErrorException;
40
import org.apache.velocity.exception.ResourceNotFoundException;
41
 
42
 
43
/**
44
 * utility class to generated all html stuff from java objects
45
 * Driver class to merge Java data objects with VTL script. 
46
 * 
47
 * @author rajveer
48
 *
49
 */
50
public class PriceInsertor {
8952 rajveer 51
    static Map<Long, EmiScheme> EMI_SCHEMES = new TreeMap<Long, EmiScheme>();
10168 amit.gupta 52
    private static Map<Long, Map<Long, Long>> comparisonStats;
8952 rajveer 53
 
54
    static {
55
        try {
10168 amit.gupta 56
        	comparisonStats = CreationUtils.getComparisonStats();
8952 rajveer 57
            TransactionClient transactionClient = new TransactionClient("support_transaction_service_server_host", "transaction_service_server_port");
58
            in.shop2020.model.v1.order.TransactionService.Client trxClient = transactionClient.getClient();
59
            List<EmiScheme> emiSchemes = trxClient.getAvailableEmiSchemes();
60
            System.out.println("EMIs:" + emiSchemes);
61
            for (EmiScheme emiScheme : emiSchemes){
62
                if(!EMI_SCHEMES.containsKey(emiScheme.getMinAmount())) {
63
                    EMI_SCHEMES.put(emiScheme.getMinAmount(), emiScheme);
64
                } else {
65
                    EmiScheme emiSchemeOld = EMI_SCHEMES.get(emiScheme.getMinAmount());
66
                    double interestRateOld = emiSchemeOld.getInterestRate()/12/100;
67
                    double interestRate = emiScheme.getInterestRate()/12/100;
68
                    if(Double.compare(
69
                            interestRateOld*Math.pow((1+interestRateOld), emiSchemeOld.getTenure())/(Math.pow((1+interestRateOld), emiSchemeOld.getTenure())-1),
70
                            interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1)) 
71
                                            > 0){
72
                        EMI_SCHEMES.put(emiScheme.getMinAmount(), emiScheme);
73
                    }
74
                }
75
            }
76
        } catch (Exception e) {
77
            e.printStackTrace();
78
        }
79
    }
3560 rajveer 80
    CatalogClient csc;
81
    Client client;
9283 amit.gupta 82
    PojoCreator creator;
11585 amit.gupta 83
    private Map<Long, PrivateDeal> privateDealsMap;
2367 rajveer 84
 
11585 amit.gupta 85
	public PriceInsertor() throws Exception{
9283 amit.gupta 86
        creator = new PojoCreator();
3560 rajveer 87
        csc = new CatalogClient();
88
        client = csc.getClient();
11833 amit.gupta 89
        privateDealsMap = client.getAllActivePrivateDeals(null,0);
3560 rajveer 90
	}
91
 
4058 rajveer 92
	public void copySolrSchemaFiles() throws IOException{
93
		String source = Utils.EXPORT_PATH + "xml/final/irmetadata_solrschema.xml";
94
		String destination = Utils.EXPORT_PATH + "solr/irmetadata_solrschema.xml";
95
		FileUtils.copyFile(new File(source), new File(destination));
96
 
97
		source = Utils.EXPORT_PATH + "xml/final/irmetadata_catchall.xml";
98
		destination = Utils.EXPORT_PATH + "solr/irmetadata_catchall.xml";
99
		FileUtils.copyFile(new File(source), new File(destination));
100
	}
101
 
6602 amit.gupta 102
	public void insertPriceInSolrData(long catalogId, String priceString, String availabilityString) throws IOException{
2367 rajveer 103
		String irSolrFilename = Utils.EXPORT_PATH + "xml/final/" + catalogId + "_irdata_solr.xml";
104
		String finalFile = Utils.EXPORT_PATH + "solr/" + catalogId + "_irdata_solr.xml";
105
		File f = new File(irSolrFilename);
106
		String s = FileUtils.readFileToString(f);
12101 amit.gupta 107
		if(privateDealsMap.containsKey(catalogId)) {
12105 amit.gupta 108
			priceString += "<field name=\"F_50039\">Show Deals Only</field>";
12101 amit.gupta 109
		}
3560 rajveer 110
		s = s.replaceAll("<field name=\"F_50002\">.*</field>", priceString);
6602 amit.gupta 111
		s = s.replaceAll("<field name=\"F_50028\">.*</field>", availabilityString);
2367 rajveer 112
		File f1 = new File(finalFile);
113
		FileUtils.writeStringToFile(f1, s);
114
	}
115
 
4025 rajveer 116
	/**
117
	 * 
118
	 * 
119
	 * @param items
120
	 * @param catalogId
121
	 * @param domain
122
	 * @param exportPath
123
	 * @param source
124
	 * @return
125
	 */
3560 rajveer 126
	public double insertPriceInHtml(List<Item> items, long catalogId, String domain, String exportPath, Source source){
9280 amit.gupta 127
		ArrayList<Map<String, String>> itemDetails = new ArrayList<Map<String,String>>();
128
		List<ItemPojo> itemPojos = new ArrayList<ItemPojo>();
4025 rajveer 129
		String offerText = null;
6792 vikram.rag 130
		String offerDetailText = null;
131
		String offerDetailLink = null;
5233 amit.gupta 132
		String afterArrival = null;
6241 amit.gupta 133
		String showPrice = "TRUE";
2367 rajveer 134
		Item minPriceItem = null;
11843 amit.gupta 135
		double  minDealPrice = 0d;
11585 amit.gupta 136
		boolean isPrivateDeal = false;
11843 amit.gupta 137
		String privateDealText = null;
11897 amit.gupta 138
		String dealAvailableString = "Available for color ";
139
		int privateDealCounter = 0;
11843 amit.gupta 140
 
2367 rajveer 141
		for(Item item: items){
11843 amit.gupta 142
			String bestDealsText = item.getBestDealText();
2367 rajveer 143
			Map<String, String> itemDetail = new HashMap<String, String>();
9280 amit.gupta 144
			ItemPojo itemPojo = new ItemPojo();
2367 rajveer 145
			boolean showmrp = true;
3560 rajveer 146
			double sellingPrice = item.getSellingPrice();
147
			double mrp = item.getMrp();
148
 
149
			if(source != null){
150
				try {
151
					SourceItemPricing sip = client.getItemPricingBySource(item.getId(), source.getId());
152
					sellingPrice = sip.getSellingPrice();
153
					mrp = sip.getMrp();
154
				} catch (TException e) {
3575 rajveer 155
 
5945 mandeep.dh 156
				} catch (CatalogServiceException e) {
3575 rajveer 157
 
3560 rajveer 158
				}
159
			}
160
 
161
			if (mrp <= sellingPrice) {
2367 rajveer 162
				showmrp = false;
163
			}
164
			if(minPriceItem == null || minPriceItem.getSellingPrice() > item.getSellingPrice()){
165
				minPriceItem = item;
166
			}
3560 rajveer 167
 
2367 rajveer 168
			double saving = Math.round((mrp-sellingPrice)/mrp*100);
9280 amit.gupta 169
			itemDetail.put("ITEM_ID", ((int)item.getId())+"");
3560 rajveer 170
			itemDetail.put("SP", ((int)sellingPrice)+"");
171
			itemDetail.put("MRP", ((int)mrp)+"");
2367 rajveer 172
			itemDetail.put("SAVING", ((int)saving)+"");
173
			itemDetail.put("COLOR", item.getColor());
174
			itemDetail.put("CATALOG_ID", ((int)item.getCatalogItemId())+"");
175
			itemDetail.put("SHOWMRP", showmrp +"");
176
			itemDetail.put("IS_SELECTED", item.isDefaultForEntity() ? "SELECTED" : "");
177
			itemDetails.add(itemDetail);
9280 amit.gupta 178
			itemPojo.setId(item.getId());
179
			itemPojo.setColor(item.getColor());
12024 amit.gupta 180
			itemPojo.setBestDealText(item.getBestDealText());
9283 amit.gupta 181
			itemPojos.add(itemPojo);
4025 rajveer 182
 
5233 amit.gupta 183
			if(item.getItemStatus().equals(status.COMING_SOON)){
184
				afterArrival = "after arrival";
10684 amit.gupta 185
				itemPojo.setStatusDescription(item.getStatus_description());
10673 amit.gupta 186
				itemPojo.setComingSoon(true);
6241 amit.gupta 187
				if(!item.isShowSellingPrice()){
188
					showPrice = "FALSE";
11154 amit.gupta 189
					itemPojo.setShowSellingPrice(false);
6241 amit.gupta 190
				}
10440 amit.gupta 191
			}else {
192
				itemPojo.setSellingPrice(item.getSellingPrice());
11115 amit.gupta 193
				String em = getEMI(item.getSellingPrice());
194
				if(em!=null){
195
					itemPojo.setMinEmi(Double.parseDouble(em));
196
				}
10440 amit.gupta 197
				if(showmrp) {
198
					itemPojo.setMrp(mrp);
199
				}
11935 amit.gupta 200
				if(privateDealsMap.containsKey(item.getId())){
12101 amit.gupta 201
					privateDealsMap.put(item.getCatalogItemId(), null);
11843 amit.gupta 202
					if (items.size()>1){
203
						dealAvailableString += "<b>" +  item.getColor() + "</b>, ";
204
					}
11897 amit.gupta 205
					privateDealCounter += 1;
11585 amit.gupta 206
					PrivateDeal pd = privateDealsMap.get(item.getId());
207
					isPrivateDeal = true;
208
					itemDetail.put("DEAL_PRICE", String.format(Locale.getDefault(),"%.0f",pd.getDealPrice()));
11762 amit.gupta 209
					PrivateDealPojo dealPojo = new PrivateDealPojo();
11955 amit.gupta 210
					dealPojo.setItemId(pd.getItem_id());
11762 amit.gupta 211
					dealPojo.setDealPrice(pd.getDealPrice());
212
					dealPojo.setIsCod(pd.isIsCod());
213
					dealPojo.setDealText(pd.getDealText());
11787 amit.gupta 214
					dealPojo.setDealTextOption(pd.getDealTextOption());
215
					dealPojo.setDealFreebieOption(pd.getDealFreebieOption());
11843 amit.gupta 216
					if(pd.getDealTextOption()==1) {
217
						privateDealText = bestDealsText;
218
					} else if (pd.getDealTextOption()==2) {
219
						privateDealText = pd.getDealText();
220
 
221
					}
11787 amit.gupta 222
					dealPojo.setFreebieItemId(pd.getDealFreebieItemId());
11762 amit.gupta 223
					itemPojo.setDealPojo(dealPojo);
11843 amit.gupta 224
					if(minDealPrice == 0d || minDealPrice > pd.getDealPrice()){
225
						minDealPrice = pd.getDealPrice();
226
					}
11585 amit.gupta 227
				}
5233 amit.gupta 228
			}
5227 amit.gupta 229
			if( bestDealsText != null && bestDealsText.length() > 0 && offerText == null && status.ACTIVE.equals(item.getItemStatus())){
4025 rajveer 230
				offerText = bestDealsText;
6792 vikram.rag 231
				String bestDealsDetailsText = item.getBestDealsDetailsText();
232
				if( bestDealsDetailsText != null && bestDealsDetailsText.length() > 0){
233
					offerDetailText = bestDealsDetailsText;
234
				}
235
				String bestDealsDetailsLink = item.getBestDealsDetailsLink();
236
				if( bestDealsDetailsLink != null && bestDealsDetailsLink.length() > 0){
237
					offerDetailLink = bestDealsDetailsLink;
238
				}
4025 rajveer 239
			}
10168 amit.gupta 240
        	//MostComparedProducts.vm should be generated as part of catalog generation
2367 rajveer 241
		}
3575 rajveer 242
 
243
 
244
 
3576 rajveer 245
 
246
		if(source == null){
247
			exportPath = exportPath + catalogId;
248
		}else{
3575 rajveer 249
			exportPath = exportPath + catalogId + File.separator + source.getId();
3560 rajveer 250
		}
2367 rajveer 251
 
3575 rajveer 252
		File exportDir = new File(exportPath);
253
 
2367 rajveer 254
		if(!exportDir.exists()) {
255
			exportDir.mkdir();
256
		}
257
 
258
		// This URL is used to ensure that images such as icon and thumbnail for
259
		// a particular entity are always downloaded from the same location.
7336 amit.gupta 260
		String staticurl = "http://static" + catalogId%3 + "." + (domain.contains("store") ? "saholic.com":domain);
2367 rajveer 261
 
262
 
263
		VelocityContext context = new VelocityContext();
9280 amit.gupta 264
		String emiString = getEMI(items.get(0).getSellingPrice());
7336 amit.gupta 265
		context.put("domain", domain.contains("store") ? "saholic.com":domain);
2367 rajveer 266
		context.put("itemDetails", itemDetails);
267
		context.put("minPriceItem", minPriceItem);
268
		context.put("staticurl", staticurl);
4025 rajveer 269
		context.put("OFFER_TEXT", offerText);
6792 vikram.rag 270
		context.put("OFFER_DETAIL_TEXT", offerDetailText);
271
		context.put("OFFER_DETAIL_LINK", offerDetailLink);
5233 amit.gupta 272
		context.put("AFTER_ARRIVAL", afterArrival);
7336 amit.gupta 273
		context.put("SHOW_PRICE", domain.contains("store")?"FALSE":showPrice);
7317 amit.gupta 274
		context.put("IS_STORE", domain.contains("store")?"TRUE":"FALSE");
9280 amit.gupta 275
		context.put("EMI", emiString);
11843 amit.gupta 276
		if(isPrivateDeal) {
277
			context.put("PRIVATE_DEAL_TEXT", privateDealText);
278
			context.put("PRIVATE_DEAL_PRICE", String.format(Locale.getDefault(),"%.0f",minDealPrice));
11911 amit.gupta 279
			if(items.size()==privateDealCounter && items.size()>1) {
11897 amit.gupta 280
				context.put("AVAILABLE", "Available for all colors");
11916 amit.gupta 281
			} else if(items.size()>1) context.put("AVAILABLE", dealAvailableString.substring(0, dealAvailableString.length()-2));
11843 amit.gupta 282
		}
2367 rajveer 283
		List<String> filenames = new ArrayList<String>();
7814 amit.gupta 284
		if(!domain.contains("store")){		
285
			filenames.add("WidgetSnippet");
286
			filenames.add("ProductPropertiesSnippet");
287
			filenames.add("MyResearchSnippet");
288
			filenames.add("AfterSales");
289
			filenames.add("SearchSnippet");
290
			filenames.add("CategorySnippet");
291
			filenames.add("HomeSnippet");
292
			filenames.add("ProductDetail");
293
			filenames.add("SlideGuide");
294
		}else {
295
			filenames.add("store/" + catalogId + "/SearchSnippet");
12321 amit.gupta 296
			filenames.add("ProductPropertiesSnippet");
7814 amit.gupta 297
			filenames.add("store/" + catalogId + "/CategorySnippet");
298
			filenames.add("store/" + catalogId + "/HomeSnippet");
299
			filenames.add("store/" + catalogId + "/ProductDetail");
300
			filenames.add("store/" + catalogId + "/SlideGuide");
301
		}
2716 varun.gupt 302
 
4805 rajveer 303
		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(items.get(0).getCategory());
7814 amit.gupta 304
		if(category!=null && !domain.contains("store")){
4802 amit.gupta 305
			Category parentCategory = category.getParentCategory();
306
 
8952 rajveer 307
            if(parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY)    {
308
                filenames.add("PhonesIOwnSnippet");
309
            }
310
            if(parentCategory.isHasAccessories()){
311
                filenames.add("RelatedAccessories");
312
            }
11585 amit.gupta 313
            if(isPrivateDeal){
314
            	filenames.add("DealSnippet");
315
            }
8952 rajveer 316
            filenames.add("CompareProductSnippet");
317
            filenames.add("SlideNamesSnippet");
318
            filenames.add("ComparisonSnippet");
319
            if(category.isComparable()) {
10168 amit.gupta 320
            	//Before adding we should populate 
321
            	try {
322
            		getMostComparedProducts(exportPath,catalogId);
323
            	}catch (Exception e){
324
            		e.printStackTrace();
325
            	}
8952 rajveer 326
                filenames.add("CompareProductSummarySnippet");
327
                filenames.add("MostComparedSnippet");
328
            }
329
        }
330
        getHtmlFromVelocity(filenames,exportPath,context,catalogId);
9218 amit.gupta 331
        //Update catalogInfo to catalog
9313 amit.gupta 332
        creator.updateCatalogInfo(catalogId, offerText, itemPojos);
8952 rajveer 333
        return minPriceItem.getSellingPrice();
334
    }
335
 
336
    private static String getEMI(double sellingPrice) {
337
        String returnString = null;
338
        double finalEmiD = 0d;
339
        for (EmiScheme emiScheme : EMI_SCHEMES.values() ){
340
            double interestRate = emiScheme.getInterestRate()/12/100;
341
            if(emiScheme.getMinAmount() <= sellingPrice) {
342
                double emiD = interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1);
343
                if(finalEmiD == 0d){
344
                    finalEmiD = emiD; 
345
                } else if(Double.compare(finalEmiD, emiD) > 0){
346
                    finalEmiD = emiD;
347
                }
348
            }
349
        }
350
        if(finalEmiD != 0d) {
351
            returnString = String.format(Locale.getDefault(),"%.0f",sellingPrice * finalEmiD);
352
        }
353
        return returnString;
354
    }
7853 amit.gupta 355
 
2367 rajveer 356
	public void getHtmlFromVelocity(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
357
		try {
358
			Properties p = new Properties();
359
			p.setProperty("resource.loader", "file");
360
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
361
			p.setProperty( "file.resource.loader.path", Utils.EXPORT_VELOCITY_PATH);
362
			Velocity.init(p);
363
			for(String filename: filenames){
7814 amit.gupta 364
				if(filename.contains("store/")){
7949 amit.gupta 365
					Template template = Velocity.getTemplate(filename + ".vm", "UTF-8");
7814 amit.gupta 366
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename.split(""+ catalogId +"/")[1] +".html")));
367
					template.merge(context, writer);
368
					writer.flush();
369
					writer.close();
370
 
371
				} else {
7949 amit.gupta 372
					Template template = Velocity.getTemplate(catalogId + File.separator + filename + ".vm", "UTF-8");
7814 amit.gupta 373
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename +".html")));
374
					template.merge(context, writer);
375
					writer.flush();
376
					writer.close();
377
				}
2367 rajveer 378
			}
379
		}catch (ResourceNotFoundException e) {
380
			// TODO Auto-generated catch block
381
			e.printStackTrace();
382
		} catch (IOException e) {
383
			// TODO Auto-generated catch block
384
			e.printStackTrace();
385
		} catch (ParseErrorException e) {
386
			// TODO Auto-generated catch block
387
			e.printStackTrace();
388
		} catch (Exception e) {
389
			// TODO Auto-generated catch block
390
			e.printStackTrace();
391
		}
392
	}
10168 amit.gupta 393
 
394
	/**
395
     * Get most compared phones
396
     *
397
     * @param expEntity
398
     * @param exportPath
399
     * @throws Exception
400
     */
401
    private void getMostComparedProducts(String exportPath, long catalogId) throws Exception {
402
 
403
        Map<Long, Long> comparedPhones = comparisonStats.get(catalogId);
404
 
405
        StringBuffer sb = new StringBuffer();
406
        int maxCount = 10;
407
        int count = 0;
408
        if (comparedPhones != null) {
409
            for (Long entityID : comparedPhones.keySet()) {
410
                if (count > maxCount) {
411
                    break;
412
                }
413
                sb.append(entityID + "\n");
414
                count++;
415
            }
416
        }
10191 amit.gupta 417
        if(count>0){
418
		    String exportFileName = exportPath + File.separator + "MostComparedProducts.html";
419
		    File exportFile = new File(exportFileName);
420
		    exportFile.createNewFile();
421
 
422
		    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
423
		            new FileOutputStream(exportFile)));
424
 
425
		    writer.write(sb.toString());
426
		    writer.flush();
427
		    writer.close();
428
        }
10168 amit.gupta 429
    }
2367 rajveer 430
}
431