Subversion Repositories SmartDukaan

Rev

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