Subversion Repositories SmartDukaan

Rev

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