Subversion Repositories SmartDukaan

Rev

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