Subversion Repositories SmartDukaan

Rev

Rev 10191 | Rev 10673 | 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
			String em = getEMI(item.getSellingPrice());
169
			if(em!=null){
170
				itemPojo.setMinEmi(Double.parseDouble(em));
171
			}
172
			itemPojos.add(itemPojo);
4025 rajveer 173
 
5233 amit.gupta 174
			if(item.getItemStatus().equals(status.COMING_SOON)){
175
				afterArrival = "after arrival";
6241 amit.gupta 176
				if(!item.isShowSellingPrice()){
177
					showPrice = "FALSE";
10440 amit.gupta 178
				}else {
179
					itemPojo.setSellingPrice(item.getSellingPrice());
6241 amit.gupta 180
				}
10440 amit.gupta 181
			}else {
182
				itemPojo.setSellingPrice(item.getSellingPrice());
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