Subversion Repositories SmartDukaan

Rev

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