Subversion Repositories SmartDukaan

Rev

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