Subversion Repositories SmartDukaan

Rev

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