Subversion Repositories SmartDukaan

Rev

Rev 10168 | Rev 10440 | 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.setSellingPrice(item.getSellingPrice());
168
			itemPojo.setMrp(mrp);
169
			itemPojo.setColor(item.getColor());
9283 amit.gupta 170
			String em = getEMI(item.getSellingPrice());
171
			if(em!=null){
172
				itemPojo.setMinEmi(Double.parseDouble(em));
173
			}
174
			itemPojos.add(itemPojo);
4025 rajveer 175
 
5233 amit.gupta 176
			if(item.getItemStatus().equals(status.COMING_SOON)){
177
				afterArrival = "after arrival";
6241 amit.gupta 178
				if(!item.isShowSellingPrice()){
179
					showPrice = "FALSE";
180
				}
5233 amit.gupta 181
			}
4025 rajveer 182
			String bestDealsText = item.getBestDealText();
5227 amit.gupta 183
			if( bestDealsText != null && bestDealsText.length() > 0 && offerText == null && status.ACTIVE.equals(item.getItemStatus())){
4025 rajveer 184
				offerText = bestDealsText;
6792 vikram.rag 185
				String bestDealsDetailsText = item.getBestDealsDetailsText();
186
				if( bestDealsDetailsText != null && bestDealsDetailsText.length() > 0){
187
					offerDetailText = bestDealsDetailsText;
188
				}
189
				String bestDealsDetailsLink = item.getBestDealsDetailsLink();
190
				if( bestDealsDetailsLink != null && bestDealsDetailsLink.length() > 0){
191
					offerDetailLink = bestDealsDetailsLink;
192
				}
4025 rajveer 193
			}
10168 amit.gupta 194
        	//MostComparedProducts.vm should be generated as part of catalog generation
2367 rajveer 195
		}
3575 rajveer 196
 
197
 
198
 
3576 rajveer 199
 
200
		if(source == null){
201
			exportPath = exportPath + catalogId;
202
		}else{
3575 rajveer 203
			exportPath = exportPath + catalogId + File.separator + source.getId();
3560 rajveer 204
		}
2367 rajveer 205
 
3575 rajveer 206
		File exportDir = new File(exportPath);
207
 
2367 rajveer 208
		if(!exportDir.exists()) {
209
			exportDir.mkdir();
210
		}
211
 
212
		// This URL is used to ensure that images such as icon and thumbnail for
213
		// a particular entity are always downloaded from the same location.
7336 amit.gupta 214
		String staticurl = "http://static" + catalogId%3 + "." + (domain.contains("store") ? "saholic.com":domain);
2367 rajveer 215
 
216
 
217
		VelocityContext context = new VelocityContext();
9280 amit.gupta 218
		String emiString = getEMI(items.get(0).getSellingPrice());
7336 amit.gupta 219
		context.put("domain", domain.contains("store") ? "saholic.com":domain);
2367 rajveer 220
		context.put("itemDetails", itemDetails);
221
		context.put("minPriceItem", minPriceItem);
222
		context.put("staticurl", staticurl);
4025 rajveer 223
		context.put("OFFER_TEXT", offerText);
6792 vikram.rag 224
		context.put("OFFER_DETAIL_TEXT", offerDetailText);
225
		context.put("OFFER_DETAIL_LINK", offerDetailLink);
5233 amit.gupta 226
		context.put("AFTER_ARRIVAL", afterArrival);
7336 amit.gupta 227
		context.put("SHOW_PRICE", domain.contains("store")?"FALSE":showPrice);
7317 amit.gupta 228
		context.put("IS_STORE", domain.contains("store")?"TRUE":"FALSE");
9280 amit.gupta 229
		context.put("EMI", emiString);
2367 rajveer 230
		List<String> filenames = new ArrayList<String>();
7814 amit.gupta 231
		if(!domain.contains("store")){		
232
			filenames.add("WidgetSnippet");
233
			filenames.add("ProductPropertiesSnippet");
234
			filenames.add("MyResearchSnippet");
235
			filenames.add("AfterSales");
236
			filenames.add("SearchSnippet");
237
			filenames.add("CategorySnippet");
238
			filenames.add("HomeSnippet");
239
			filenames.add("ProductDetail");
240
			filenames.add("SlideGuide");
241
		}else {
242
			filenames.add("store/" + catalogId + "/SearchSnippet");
243
			filenames.add("store/" + catalogId + "/CategorySnippet");
244
			filenames.add("store/" + catalogId + "/HomeSnippet");
245
			filenames.add("store/" + catalogId + "/ProductDetail");
246
			filenames.add("store/" + catalogId + "/SlideGuide");
247
		}
2716 varun.gupt 248
 
4805 rajveer 249
		Category category = Catalog.getInstance().getDefinitionsContainer().getCategory(items.get(0).getCategory());
7814 amit.gupta 250
		if(category!=null && !domain.contains("store")){
4802 amit.gupta 251
			Category parentCategory = category.getParentCategory();
252
 
8952 rajveer 253
            if(parentCategory.getID() == Utils.MOBILE_PHONES_CATAGORY)    {
254
                filenames.add("PhonesIOwnSnippet");
255
            }
256
            if(parentCategory.isHasAccessories()){
257
                filenames.add("RelatedAccessories");
258
            }
259
            filenames.add("CompareProductSnippet");
260
            filenames.add("SlideNamesSnippet");
261
            filenames.add("ComparisonSnippet");
262
            if(category.isComparable()) {
10168 amit.gupta 263
            	//Before adding we should populate 
264
            	try {
265
            		getMostComparedProducts(exportPath,catalogId);
266
            	}catch (Exception e){
267
            		e.printStackTrace();
268
            	}
8952 rajveer 269
                filenames.add("CompareProductSummarySnippet");
270
                filenames.add("MostComparedSnippet");
271
            }
272
        }
273
        getHtmlFromVelocity(filenames,exportPath,context,catalogId);
9218 amit.gupta 274
        //Update catalogInfo to catalog
9313 amit.gupta 275
        creator.updateCatalogInfo(catalogId, offerText, itemPojos);
8952 rajveer 276
        return minPriceItem.getSellingPrice();
277
    }
278
 
279
    private static String getEMI(double sellingPrice) {
280
        String returnString = null;
281
        double finalEmiD = 0d;
282
        for (EmiScheme emiScheme : EMI_SCHEMES.values() ){
283
            double interestRate = emiScheme.getInterestRate()/12/100;
284
            if(emiScheme.getMinAmount() <= sellingPrice) {
285
                double emiD = interestRate*Math.pow((1+interestRate), emiScheme.getTenure())/(Math.pow((1+interestRate), emiScheme.getTenure())-1);
286
                if(finalEmiD == 0d){
287
                    finalEmiD = emiD; 
288
                } else if(Double.compare(finalEmiD, emiD) > 0){
289
                    finalEmiD = emiD;
290
                }
291
            }
292
        }
293
        if(finalEmiD != 0d) {
294
            returnString = String.format(Locale.getDefault(),"%.0f",sellingPrice * finalEmiD);
295
        }
296
        return returnString;
297
    }
7853 amit.gupta 298
 
2367 rajveer 299
	public void getHtmlFromVelocity(List<String> filenames, String exportPath, VelocityContext context, long catalogId){
300
		try {
301
			Properties p = new Properties();
302
			p.setProperty("resource.loader", "file");
303
			p.setProperty("file.resource.loader.class","org.apache.velocity.runtime.resource.loader.FileResourceLoader");
304
			p.setProperty( "file.resource.loader.path", Utils.EXPORT_VELOCITY_PATH);
305
			Velocity.init(p);
306
			for(String filename: filenames){
7814 amit.gupta 307
				if(filename.contains("store/")){
7949 amit.gupta 308
					Template template = Velocity.getTemplate(filename + ".vm", "UTF-8");
7814 amit.gupta 309
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename.split(""+ catalogId +"/")[1] +".html")));
310
					template.merge(context, writer);
311
					writer.flush();
312
					writer.close();
313
 
314
				} else {
7949 amit.gupta 315
					Template template = Velocity.getTemplate(catalogId + File.separator + filename + ".vm", "UTF-8");
7814 amit.gupta 316
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(exportPath + File.separator + filename +".html")));
317
					template.merge(context, writer);
318
					writer.flush();
319
					writer.close();
320
				}
2367 rajveer 321
			}
322
		}catch (ResourceNotFoundException e) {
323
			// TODO Auto-generated catch block
324
			e.printStackTrace();
325
		} catch (IOException e) {
326
			// TODO Auto-generated catch block
327
			e.printStackTrace();
328
		} catch (ParseErrorException e) {
329
			// TODO Auto-generated catch block
330
			e.printStackTrace();
331
		} catch (Exception e) {
332
			// TODO Auto-generated catch block
333
			e.printStackTrace();
334
		}
335
	}
10168 amit.gupta 336
 
337
	/**
338
     * Get most compared phones
339
     *
340
     * @param expEntity
341
     * @param exportPath
342
     * @throws Exception
343
     */
344
    private void getMostComparedProducts(String exportPath, long catalogId) throws Exception {
345
 
346
        Map<Long, Long> comparedPhones = comparisonStats.get(catalogId);
347
 
348
        StringBuffer sb = new StringBuffer();
349
        int maxCount = 10;
350
        int count = 0;
351
        if (comparedPhones != null) {
352
            for (Long entityID : comparedPhones.keySet()) {
353
                if (count > maxCount) {
354
                    break;
355
                }
356
                sb.append(entityID + "\n");
357
                count++;
358
            }
359
        }
10191 amit.gupta 360
        if(count>0){
361
		    String exportFileName = exportPath + File.separator + "MostComparedProducts.html";
362
		    File exportFile = new File(exportFileName);
363
		    exportFile.createNewFile();
364
 
365
		    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
366
		            new FileOutputStream(exportFile)));
367
 
368
		    writer.write(sb.toString());
369
		    writer.flush();
370
		    writer.close();
371
        }
10168 amit.gupta 372
    }
2367 rajveer 373
}
374