Subversion Repositories SmartDukaan

Rev

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