Subversion Repositories SmartDukaan

Rev

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