Subversion Repositories SmartDukaan

Rev

Rev 12321 | 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;
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
					}
240
					itemPojo.setBulkItemPricing(qpl);
241
				}
5233 amit.gupta 242
			}
5227 amit.gupta 243
			if( bestDealsText != null && bestDealsText.length() > 0 && offerText == null && status.ACTIVE.equals(item.getItemStatus())){
4025 rajveer 244
				offerText = bestDealsText;
6792 vikram.rag 245
				String bestDealsDetailsText = item.getBestDealsDetailsText();
246
				if( bestDealsDetailsText != null && bestDealsDetailsText.length() > 0){
247
					offerDetailText = bestDealsDetailsText;
248
				}
249
				String bestDealsDetailsLink = item.getBestDealsDetailsLink();
250
				if( bestDealsDetailsLink != null && bestDealsDetailsLink.length() > 0){
251
					offerDetailLink = bestDealsDetailsLink;
252
				}
4025 rajveer 253
			}
10168 amit.gupta 254
        	//MostComparedProducts.vm should be generated as part of catalog generation
2367 rajveer 255
		}
3575 rajveer 256
 
257
 
258
 
3576 rajveer 259
 
260
		if(source == null){
261
			exportPath = exportPath + catalogId;
262
		}else{
3575 rajveer 263
			exportPath = exportPath + catalogId + File.separator + source.getId();
3560 rajveer 264
		}
2367 rajveer 265
 
3575 rajveer 266
		File exportDir = new File(exportPath);
267
 
2367 rajveer 268
		if(!exportDir.exists()) {
269
			exportDir.mkdir();
270
		}
271
 
272
		// This URL is used to ensure that images such as icon and thumbnail for
273
		// a particular entity are always downloaded from the same location.
7336 amit.gupta 274
		String staticurl = "http://static" + catalogId%3 + "." + (domain.contains("store") ? "saholic.com":domain);
2367 rajveer 275
 
276
 
277
		VelocityContext context = new VelocityContext();
9280 amit.gupta 278
		String emiString = getEMI(items.get(0).getSellingPrice());
7336 amit.gupta 279
		context.put("domain", domain.contains("store") ? "saholic.com":domain);
2367 rajveer 280
		context.put("itemDetails", itemDetails);
281
		context.put("minPriceItem", minPriceItem);
282
		context.put("staticurl", staticurl);
4025 rajveer 283
		context.put("OFFER_TEXT", offerText);
6792 vikram.rag 284
		context.put("OFFER_DETAIL_TEXT", offerDetailText);
285
		context.put("OFFER_DETAIL_LINK", offerDetailLink);
5233 amit.gupta 286
		context.put("AFTER_ARRIVAL", afterArrival);
7336 amit.gupta 287
		context.put("SHOW_PRICE", domain.contains("store")?"FALSE":showPrice);
7317 amit.gupta 288
		context.put("IS_STORE", domain.contains("store")?"TRUE":"FALSE");
9280 amit.gupta 289
		context.put("EMI", emiString);
11843 amit.gupta 290
		if(isPrivateDeal) {
291
			context.put("PRIVATE_DEAL_TEXT", privateDealText);
292
			context.put("PRIVATE_DEAL_PRICE", String.format(Locale.getDefault(),"%.0f",minDealPrice));
11911 amit.gupta 293
			if(items.size()==privateDealCounter && items.size()>1) {
11897 amit.gupta 294
				context.put("AVAILABLE", "Available for all colors");
11916 amit.gupta 295
			} else if(items.size()>1) context.put("AVAILABLE", dealAvailableString.substring(0, dealAvailableString.length()-2));
11843 amit.gupta 296
		}
2367 rajveer 297
		List<String> filenames = new ArrayList<String>();
7814 amit.gupta 298
		if(!domain.contains("store")){		
299
			filenames.add("WidgetSnippet");
300
			filenames.add("ProductPropertiesSnippet");
301
			filenames.add("MyResearchSnippet");
302
			filenames.add("AfterSales");
303
			filenames.add("SearchSnippet");
304
			filenames.add("CategorySnippet");
305
			filenames.add("HomeSnippet");
306
			filenames.add("ProductDetail");
307
			filenames.add("SlideGuide");
308
		}else {
309
			filenames.add("store/" + catalogId + "/SearchSnippet");
12321 amit.gupta 310
			filenames.add("ProductPropertiesSnippet");
7814 amit.gupta 311
			filenames.add("store/" + catalogId + "/CategorySnippet");
312
			filenames.add("store/" + catalogId + "/HomeSnippet");
313
			filenames.add("store/" + catalogId + "/ProductDetail");
314
			filenames.add("store/" + catalogId + "/SlideGuide");
315
		}
2716 varun.gupt 316
 
4805 rajveer 317
		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(items.get(0).getCategory());
7814 amit.gupta 318
		if(category!=null && !domain.contains("store")){
4802 amit.gupta 319
			Category parentCategory = category.getParentCategory();
320
 
8952 rajveer 321
            if(parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY)    {
322
                filenames.add("PhonesIOwnSnippet");
323
            }
324
            if(parentCategory.isHasAccessories()){
325
                filenames.add("RelatedAccessories");
326
            }
11585 amit.gupta 327
            if(isPrivateDeal){
328
            	filenames.add("DealSnippet");
329
            }
8952 rajveer 330
            filenames.add("CompareProductSnippet");
331
            filenames.add("SlideNamesSnippet");
332
            filenames.add("ComparisonSnippet");
333
            if(category.isComparable()) {
10168 amit.gupta 334
            	//Before adding we should populate 
335
            	try {
336
            		getMostComparedProducts(exportPath,catalogId);
337
            	}catch (Exception e){
338
            		e.printStackTrace();
339
            	}
8952 rajveer 340
                filenames.add("CompareProductSummarySnippet");
341
                filenames.add("MostComparedSnippet");
342
            }
343
        }
344
        getHtmlFromVelocity(filenames,exportPath,context,catalogId);
9218 amit.gupta 345
        //Update catalogInfo to catalog
9313 amit.gupta 346
        creator.updateCatalogInfo(catalogId, offerText, itemPojos);
8952 rajveer 347
        return minPriceItem.getSellingPrice();
348
    }
349
 
350
    private static String getEMI(double sellingPrice) {
351
        String returnString = null;
352
        double finalEmiD = 0d;
353
        for (EmiScheme emiScheme : EMI_SCHEMES.values() ){
354
            double interestRate = emiScheme.getInterestRate()/12/100;
355
            if(emiScheme.getMinAmount() <= sellingPrice) {
356
                double emiD = interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1);
357
                if(finalEmiD == 0d){
358
                    finalEmiD = emiD; 
359
                } else if(Double.compare(finalEmiD, emiD) > 0){
360
                    finalEmiD = emiD;
361
                }
362
            }
363
        }
364
        if(finalEmiD != 0d) {
365
            returnString = String.format(Locale.getDefault(),"%.0f",sellingPrice * finalEmiD);
366
        }
367
        return returnString;
368
    }
7853 amit.gupta 369
 
2367 rajveer 370
	public void getHtmlFromVelocity(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
371
		try {
372
			Properties p = new Properties();
373
			p.setProperty("resource.loader", "file");
374
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
375
			p.setProperty( "file.resource.loader.path", Utils.EXPORT_VELOCITY_PATH);
376
			Velocity.init(p);
377
			for(String filename: filenames){
7814 amit.gupta 378
				if(filename.contains("store/")){
7949 amit.gupta 379
					Template template = Velocity.getTemplate(filename + ".vm", "UTF-8");
7814 amit.gupta 380
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename.split(""+ catalogId +"/")[1] +".html")));
381
					template.merge(context, writer);
382
					writer.flush();
383
					writer.close();
384
 
385
				} else {
7949 amit.gupta 386
					Template template = Velocity.getTemplate(catalogId + File.separator + filename + ".vm", "UTF-8");
7814 amit.gupta 387
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename +".html")));
388
					template.merge(context, writer);
389
					writer.flush();
390
					writer.close();
391
				}
2367 rajveer 392
			}
393
		}catch (ResourceNotFoundException e) {
394
			// TODO Auto-generated catch block
395
			e.printStackTrace();
396
		} catch (IOException e) {
397
			// TODO Auto-generated catch block
398
			e.printStackTrace();
399
		} catch (ParseErrorException e) {
400
			// TODO Auto-generated catch block
401
			e.printStackTrace();
402
		} catch (Exception e) {
403
			// TODO Auto-generated catch block
404
			e.printStackTrace();
405
		}
406
	}
10168 amit.gupta 407
 
408
	/**
409
     * Get most compared phones
410
     *
411
     * @param expEntity
412
     * @param exportPath
413
     * @throws Exception
414
     */
415
    private void getMostComparedProducts(String exportPath, long catalogId) throws Exception {
416
 
417
        Map<Long, Long> comparedPhones = comparisonStats.get(catalogId);
418
 
419
        StringBuffer sb = new StringBuffer();
420
        int maxCount = 10;
421
        int count = 0;
422
        if (comparedPhones != null) {
423
            for (Long entityID : comparedPhones.keySet()) {
424
                if (count > maxCount) {
425
                    break;
426
                }
427
                sb.append(entityID + "\n");
428
                count++;
429
            }
430
        }
10191 amit.gupta 431
        if(count>0){
432
		    String exportFileName = exportPath + File.separator + "MostComparedProducts.html";
433
		    File exportFile = new File(exportFileName);
434
		    exportFile.createNewFile();
435
 
436
		    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
437
		            new FileOutputStream(exportFile)));
438
 
439
		    writer.write(sb.toString());
440
		    writer.flush();
441
		    writer.close();
442
        }
10168 amit.gupta 443
    }
2367 rajveer 444
}
445