Subversion Repositories SmartDukaan

Rev

Rev 11676 | Rev 11970 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
317 ashish 1
/**
2
 * 
3
 */
4
package in.shop2020.serving.controllers;
5
 
650 rajveer 6
 
2306 vikas 7
import in.shop2020.datalogger.EventType;
4934 amit.gupta 8
import in.shop2020.logistics.DeliveryType;
9840 amit.gupta 9
import in.shop2020.logistics.ItemText;
11672 anikendra 10
import in.shop2020.logistics.LogisticsInfo;
4934 amit.gupta 11
import in.shop2020.logistics.LogisticsService;
11672 anikendra 12
import in.shop2020.logistics.LogisticsServiceException;
2306 vikas 13
import in.shop2020.model.v1.catalog.Item;
14
import in.shop2020.model.v1.user.UserContextService.Client;
3242 vikas 15
import in.shop2020.serving.cache.EhcacheWrapper;
3561 rajveer 16
import in.shop2020.serving.services.ContentServingService;
17
import in.shop2020.serving.utils.SnippetType;
3126 rajveer 18
import in.shop2020.thrift.clients.CatalogClient;
4934 amit.gupta 19
import in.shop2020.thrift.clients.LogisticsClient;
3126 rajveer 20
import in.shop2020.thrift.clients.UserClient;
2511 vikas 21
import in.shop2020.utils.DataLogger;
375 ashish 22
 
317 ashish 23
import java.io.IOException;
11672 anikendra 24
import java.text.SimpleDateFormat;
9840 amit.gupta 25
import java.util.ArrayList;
11672 anikendra 26
import java.util.Calendar;
27
import java.util.GregorianCalendar;
3225 vikas 28
import java.util.HashMap;
4934 amit.gupta 29
import java.util.List;
375 ashish 30
import java.util.Map;
317 ashish 31
 
3225 vikas 32
import net.sf.ehcache.CacheManager;
33
 
5026 varun.gupt 34
import org.apache.commons.lang.StringUtils;
832 rajveer 35
import org.apache.log4j.Logger;
507 rajveer 36
import org.apache.struts2.convention.annotation.Action;
37
import org.apache.struts2.convention.annotation.Actions;
974 vikas 38
import org.apache.struts2.convention.annotation.Result;
2306 vikas 39
import org.apache.struts2.convention.annotation.Results;
11672 anikendra 40
import org.apache.thrift.TException;
2306 vikas 41
import org.json.JSONException;
42
import org.json.JSONObject;
317 ashish 43
 
4934 amit.gupta 44
import com.google.gson.Gson;
45
 
317 ashish 46
/**
47
 * 
650 rajveer 48
 * @author rajveer
317 ashish 49
 *
50
 */
650 rajveer 51
 
2306 vikas 52
@Results({
53
    @Result(name = "show", location = "entity-show.vm"),
5266 rajveer 54
    @Result(name = "redirect", location = "${redirectUrl}", type = "redirect", params={"statusCode", "301"})
2306 vikas 55
})
650 rajveer 56
public class EntityController extends BaseController {
57
 
58
	private static final long serialVersionUID = 1L;
1957 vikas 59
	private static Logger log = Logger.getLogger(Class.class);
11672 anikendra 60
	private Long firstItem =  0l;
3225 vikas 61
	private static final String PRODUCT_PROERTIES_SNIPPET_KEY = "PRODUCT_PROPERTIES";
62
	private static final String PRODUCT_SUMMARY_SNIPPET_KEY = "PRODUCT_SUMMARY";
63
	private static final String PRODUCT_SLIDEGUIDE_KEY = "SLIDEGUIDE";
11964 amit.gupta 64
	private static final String ENTITY_DETAIL_KEY = "ENTITY_DETAIL";
11672 anikendra 65
    private String entityLogisticsEstimation = "[]";
5037 rajveer 66
	private static final String DEFAULT_PINCODE = "110001";
317 ashish 67
	private String id;
2306 vikas 68
	private String redirectUrl;
620 rajveer 69
	private long productId;
2867 rajveer 70
	private boolean isMobile = false;
71
 
6084 rajveer 72
	private Map<String, Double> discounts = new HashMap<String, Double>();
3225 vikas 73
	private Map<String, String> snippets;
5094 phani.kuma 74
	private static Map<Long, String> label = new HashMap<Long, String>();
11672 anikendra 75
 
76
	public static Map<Integer, String> businessDayToActualDateMap = new HashMap<Integer, String>();
77
	private Map<String, String> deliveryEstimate = new HashMap<String, String>();
78
 
5094 phani.kuma 79
	static{
80
		setRetargettingLabel();
81
	}
3225 vikas 82
 
375 ashish 83
	public EntityController(){
84
		super();
85
	}
507 rajveer 86
 
974 vikas 87
	// GET /*/1000001
507 rajveer 88
	@Actions({
974 vikas 89
		@Action("/mobile-phones"),
5873 amit.gupta 90
		@Action("/cameras"),
1005 vikas 91
		@Action("/mobile-accessories"),
2460 rajveer 92
		@Action("/tablets"),
3715 rajveer 93
		@Action("/laptops"),
5182 varun.gupt 94
		@Action("/laptop-accessories"),
6593 amit.gupta 95
		@Action("/entity"),
8315 amit.gupta 96
		@Action("/music-players"),
97
		@Action("/smart-watches")
507 rajveer 98
	})
2306 vikas 99
    public String show() throws SecurityException, IOException, JSONException {
317 ashish 100
    	log.info("id=" + id);
637 rajveer 101
 
2306 vikas 102
    	String entityUrl = "";
103
    	String metaDescription = "";
104
    	String pageTitle = "";
2434 rajveer 105
    	String productName = "";
3830 chandransh 106
    	String categoryName = "";
107
    	String categoryUrl = "";
2652 rajveer 108
    	String displayAccessories = "FALSE";
3830 chandransh 109
    	String breadCrumb = "";
5347 amit.gupta 110
    	String parentCategory = "";
5930 amit.gupta 111
    	String compareCategory = "";
10190 amit.gupta 112
    	String isComparable = "false";
2306 vikas 113
    	try {
3225 vikas 114
    	    setSnippets();
115
            htmlSnippets.put("PRODUCT_PROPERTIES", snippets.get(PRODUCT_PROERTIES_SNIPPET_KEY));
116
    	    JSONObject productPropertiesInJson = new JSONObject(htmlSnippets.get("PRODUCT_PROPERTIES"));
2306 vikas 117
    	    entityUrl = productPropertiesInJson.getString("entityUrl");
118
    	    metaDescription = productPropertiesInJson.getString("metaDescription");
119
    	    pageTitle = productPropertiesInJson.getString("title");
2434 rajveer 120
    	    productName = productPropertiesInJson.getString("name");
3830 chandransh 121
    	    categoryName = productPropertiesInJson.getString("categoryName");
122
    	    categoryUrl = productPropertiesInJson.getString("categoryUrl");
2652 rajveer 123
    	    displayAccessories = productPropertiesInJson.getString("displayAccessories");
3830 chandransh 124
    	    breadCrumb = productPropertiesInJson.getString("breadCrumb");
5347 amit.gupta 125
    	    parentCategory = productPropertiesInJson.getString("parentCategory");
5930 amit.gupta 126
    	    compareCategory = productPropertiesInJson.getString("compareCategory");
10190 amit.gupta 127
    	    isComparable = productPropertiesInJson.getString("isComparable");
2306 vikas 128
    	}
129
    	catch (JSONException e) {
4965 rajveer 130
            log.warn("Unable to parse product properties JSON", e);
2306 vikas 131
            try {
3126 rajveer 132
                CatalogClient catalogClientService = new CatalogClient();
5945 mandeep.dh 133
                in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();
2306 vikas 134
 
135
                Item item = client.getItemsByCatalogId(productId).get(0);
2307 vikas 136
                redirectUrl = "/" + item.getBrand().toLowerCase().replace(" ", "-");
2306 vikas 137
            } catch (Exception e1) {
4965 rajveer 138
                log.warn("Unable to get items by catalog id", e1);
2306 vikas 139
                redirectUrl = "/";
140
            }
141
            log.info(redirectUrl);
142
            return "redirect";
143
       }
144
    	String currentUrl = request.getRequestURL().toString();
1197 varun.gupt 145
 
2306 vikas 146
    	if (!currentUrl.contains(entityUrl)) {
147
    	    redirectUrl = entityUrl;
148
    	    return "redirect";
149
    	}
150
 
2434 rajveer 151
    	//Extracting base url
1689 rajveer 152
    	String rootUrl = currentUrl.split("/")[2];
2194 varun.gupt 153
 
3225 vikas 154
    	htmlSnippets.put("PRODUCT_SUMMARY", snippets.get(PRODUCT_SUMMARY_SNIPPET_KEY));
1258 varun.gupt 155
    	htmlSnippets.put("PRODUCT_ID", productId + "");
156
    	htmlSnippets.put("PRODUCT_NAME", productName);
3830 chandransh 157
    	htmlSnippets.put("CATEGORY_NAME", categoryName);
158
    	htmlSnippets.put("CATEGORY_URL", categoryUrl);
1689 rajveer 159
    	htmlSnippets.put("PRODUCT_URL", currentUrl);
2194 varun.gupt 160
    	htmlSnippets.put("ROOT_URL", "http://" + rootUrl);
3225 vikas 161
		htmlSnippets.put("SLIDE_GUIDE", snippets.get(PRODUCT_SLIDEGUIDE_KEY));
1269 varun.gupt 162
		htmlSnippets.put("PAGE_TITLE", pageTitle.trim());
2306 vikas 163
		htmlSnippets.put("PAGE_METADESC", metaDescription);
3830 chandransh 164
		htmlSnippets.put("BREADCRUMB", breadCrumb);
5347 amit.gupta 165
		htmlSnippets.put("PARENT_CATEGORY", parentCategory);
5930 amit.gupta 166
		htmlSnippets.put("COMPARE_CATEGORY", compareCategory);
10190 amit.gupta 167
		htmlSnippets.put("IS_COMPARABLE", isComparable);
3830 chandransh 168
 
2652 rajveer 169
		if(displayAccessories.equals("TRUE")){
2867 rajveer 170
			setMobile(true);
2652 rajveer 171
		}
172
 
650 rajveer 173
		try {
5188 rajveer 174
			if(userinfo.getUserId() != -1){
175
				long itemId = Long.parseLong(id);
176
				UserClient userServiceClient = new UserClient();
177
				Client client = userServiceClient.getClient();
178
				client.updateBrowseHistory(userinfo.getUserId(), itemId);
1511 rajveer 179
			}
650 rajveer 180
 
449 rajveer 181
		} catch (Exception e) {
2949 chandransh 182
			log.warn("Unable to update the browsing history because of: ", e);
449 rajveer 183
		}
4494 varun.gupt 184
 
11672 anikendra 185
		DataLogger.logData(EventType.PRODUCT_VIEW, getSessionId(), userinfo.getUserId(), userinfo.getEmail(), userinfo.getPincode(), 
186
                productName, Long.toString(productId), StringUtils.substring(request.getHeader("referer"), 0, 500));			       
187
 
188
        try {
189
            CatalogClient catalogClientService = new CatalogClient();
190
            in.shop2020.model.v1.catalog.CatalogService.Client client = catalogClientService.getClient();
191
 
11676 amit.gupta 192
            setEntityLogisticsEstimation();
11672 anikendra 193
            getDeliveryEstimate( firstItem, userinfo.getPincode());
194
        } catch (Exception e1) {
195
            log.warn("Unable to get delivery estimates for "+ id);
196
        }
2149 vikas 197
		return "show";
317 ashish 198
    }
11672 anikendra 199
 
200
	/**
201
	 * 
202
	 * @return
203
	 */
204
	public void getDeliveryEstimate(Long itemId, String pincode){
205
		LogisticsClient logisticsServiceClient = null;
206
		String days = "-1";
207
		long businessDays = -1;
208
		boolean isCODAvailable=false;
209
		boolean isOTGAvailable=false;
210
		String codDays = "-1";
211
    	try {
212
			logisticsServiceClient = new LogisticsClient();
213
			LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
214
			LogisticsInfo logistincInfo = logisticsClient.getLogisticsEstimation(itemId, pincode, DeliveryType.PREPAID);
215
 
216
			if(logistincInfo.getDeliveryTime()!=-1L){
217
				days = getDeliveryDateString((int)logistincInfo.getDeliveryTime(), DeliveryType.PREPAID);
218
				if(logistincInfo.isCodAllowed()){
219
					codDays = getDeliveryDateString((int)(logistincInfo.getDeliveryTime()), DeliveryType.COD);
220
				}
221
			}
222
			businessDays = logistincInfo.getDeliveryTime();
223
			isCODAvailable = logistincInfo.isCodAllowed();
224
			isOTGAvailable = logistincInfo.isOtgAvailable();
225
 
226
			log.info("busines days = " + businessDays + "is COD avaialbale " + isCODAvailable + "is OTG available " + isOTGAvailable + " days "+days+" cod days "+codDays);
227
    	} catch (LogisticsServiceException e)	{
228
    		log.error("Unable to get estimate/COD availability for " + itemId, e);
229
		} catch(TException e)	{
230
 
231
		} catch (Exception e)	{
232
 
233
		}
234
		deliveryEstimate.put("delivery_estimate", days);
235
		deliveryEstimate.put("cod_delivery_estimate", codDays);
236
		deliveryEstimate.put("is_cod_available_for_location", Boolean.toString(isCODAvailable));
237
		deliveryEstimate.put("on_time_guarantee", Boolean.toString(isOTGAvailable));
238
		deliveryEstimate.put("business_days", businessDays + "");        	
239
	}
240
 
241
	private  static String getDeliveryDateString(int days, DeliveryType type) throws TException {
242
    	Calendar now = new GregorianCalendar();
243
    	int hour = now.get(Calendar.HOUR_OF_DAY);
244
    	if(type == DeliveryType.COD && hour < 15){
245
			days = days + 1;
246
		}
247
    	if(businessDayToActualDateMap.containsKey(days)){
248
    		if(hour != 0){	
249
    			return businessDayToActualDateMap.get(days);
250
    		}
251
    		businessDayToActualDateMap.clear();
252
		}
253
 
254
    	now.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
255
 
256
    	LogisticsClient logisticsServiceClient = null;
257
		logisticsServiceClient = new LogisticsClient();
258
		LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
259
 
260
    	int newdays = (int) logisticsClient.adjustDeliveryDays(now.getTimeInMillis(), days);
261
    	now.add(Calendar.DAY_OF_MONTH, newdays);
262
 
263
    	SimpleDateFormat dateformat = new SimpleDateFormat("EEE dd-MMM-yy");
264
    	if(newdays == 1){
265
    		businessDayToActualDateMap.put(days, "Tomorrow, " + dateformat.format(now.getTime()));
266
    	}else{
267
    		businessDayToActualDateMap.put(days, dateformat.format(now.getTime()));
268
    	}
269
    	return businessDayToActualDateMap.get(days);
270
	}
3225 vikas 271
 
317 ashish 272
    /**
273
     * 
274
     * @param id
275
     */
276
    public void setId(String id) {
4831 varun.gupt 277
    	String[] tokens = id.split("-");
278
    	this.id = tokens[tokens.length - 1];
974 vikas 279
    	this.productId = Long.parseLong(this.id);
317 ashish 280
    }
281
 
387 rajveer 282
	public Map<String,String> getHtmlSnippets(){
388 rajveer 283
		System.out.println(" getHtmlSnippets  is called");
387 rajveer 284
		return htmlSnippets;
375 ashish 285
	}
388 rajveer 286
 
449 rajveer 287
	public String getSlideGuideSnippet(){
388 rajveer 288
		return htmlSnippets.get("SLIDE_GUIDE");
289
	}
290
 
2306 vikas 291
	public String getRedirectUrl(){
5493 rajveer 292
		String query = request.getQueryString();
293
		if(query!=null){
294
			return redirectUrl + "?" + query;
295
		}
296
		return redirectUrl;
2306 vikas 297
    }
298
 
449 rajveer 299
	public String getProductSummarySnippet(){
300
		return htmlSnippets.get("PRODUCT_SUMMARY");
301
	}
302
 
974 vikas 303
	public String getPageTitleSnippet(){
304
		return htmlSnippets.get("PAGE_TITLE");
305
	}
306
 
307
	public String getPageMetaDescSnippet(){
308
		return htmlSnippets.get("PAGE_METADESC");
309
	}
310
 
311
 
1197 varun.gupt 312
	public String getProductName()	{
313
		return htmlSnippets.get("PRODUCT_NAME");
314
	}
5347 amit.gupta 315
 
5930 amit.gupta 316
	public String getCompareCategory(){
317
		return htmlSnippets.get("COMPARE_CATEGORY");
5347 amit.gupta 318
	}
319
 
5930 amit.gupta 320
	public String getCompareCategoryLowerCase(){
321
		String compareCategory = htmlSnippets.get("COMPARE_CATEGORY");
322
		return compareCategory.toLowerCase();
5347 amit.gupta 323
	}
1258 varun.gupt 324
 
3830 chandransh 325
	public String getCategoryName()	{
326
		return htmlSnippets.get("CATEGORY_NAME");
327
	}
328
 
329
	public String getCategoryUrl()	{
330
		return htmlSnippets.get("CATEGORY_URL");
331
	}
332
 
1258 varun.gupt 333
	public String getProductId()	{
334
		return htmlSnippets.get("PRODUCT_ID");
335
	}
336
 
337
	public String getProductUrl()	{
338
		return htmlSnippets.get("PRODUCT_URL");
339
	}
1364 varun.gupt 340
 
341
	public String getRootUrl()	{
342
		return htmlSnippets.get("ROOT_URL");
343
	}
2867 rajveer 344
 
3830 chandransh 345
	public String getBreadCrumb(){
346
		return htmlSnippets.get("BREADCRUMB");
347
	}
10190 amit.gupta 348
 
349
	public String isComparable(){
350
		return htmlSnippets.get("IS_COMPARABLE");
351
	}
3830 chandransh 352
 
2867 rajveer 353
	/**
354
	 * @param isMobile the isMobile to set
355
	 */
356
	public void setMobile(boolean isMobile) {
357
		this.isMobile = isMobile;
2652 rajveer 358
	}
2867 rajveer 359
 
360
	/**
361
	 * @return the isMobile
362
	 */
363
	public boolean isMobile() {
364
		return isMobile;
365
	}
3225 vikas 366
 
367
    private void setSnippets() {
368
        EhcacheWrapper<Long, Map<String, String>> productSnippetsCache = new EhcacheWrapper<Long, Map<String, String>>(
369
                EhcacheWrapper.PRODUCT_PAGE_SNIPPET_CACHE_NAME, CacheManager.create());
3561 rajveer 370
        if(sourceId == -1){
371
        	snippets = productSnippetsCache.get(productId);
372
        }
3225 vikas 373
        if (snippets == null) {
374
            log.info("Getting product snippet for :" + productId);
375
            snippets = new HashMap<String, String>();
3561 rajveer 376
            snippets.put(PRODUCT_PROERTIES_SNIPPET_KEY, ContentServingService.getSnippet(SnippetType.PRODUCT_PROPERTIES_SNIPPET, productId+"", sourceId));
377
            snippets.put(PRODUCT_SUMMARY_SNIPPET_KEY, ContentServingService.getSnippet(SnippetType.PRODUCT_DETAIL_SNIPPET, productId+"", sourceId));
378
            snippets.put(PRODUCT_SLIDEGUIDE_KEY, ContentServingService.getSnippet(SnippetType.SLIDE_GUIDE_SNIPPET, productId+"", sourceId));
11964 amit.gupta 379
        	snippets.put(ENTITY_DETAIL_KEY, ContentServingService.getJSON(productId + ""));
3561 rajveer 380
            if(sourceId == -1){
381
            	productSnippetsCache.put(productId, snippets);
382
            }
3225 vikas 383
            return;
384
        }
385
        log.info("Loaded from cache product snippet for :" + productId);
386
    }
4494 varun.gupt 387
 
388
    public Map<String, Double> getDiscounts()	{
389
    	return discounts;
390
    }
4934 amit.gupta 391
 
11672 anikendra 392
    public void setEntityLogisticsEstimation(){
9840 amit.gupta 393
    	List<ItemText> itemTexts = null; 
4934 amit.gupta 394
    	try {
395
    		LogisticsClient cl = new LogisticsClient();
396
            LogisticsService.Client client = cl.getClient();
9840 amit.gupta 397
            itemTexts = client.getEntityLogisticsEstimation(productId, DEFAULT_PINCODE, DeliveryType.PREPAID );
10195 amit.gupta 398
            if(itemTexts!=null){
399
            	List<Long> items = new ArrayList<Long>();
400
            	for(ItemText itemText : itemTexts) {
401
            		items.add(itemText.getItemId());
402
            	}
11672 anikendra 403
            	firstItem = items.get(0);
404
            	entityLogisticsEstimation = new Gson().toJson(items);
405
            	return;
10195 amit.gupta 406
            }
4934 amit.gupta 407
        } catch (Exception e1) {
10190 amit.gupta 408
            log.error("Unable to get items for productId: "+  productId, e1);
4934 amit.gupta 409
        }
11672 anikendra 410
        entityLogisticsEstimation = "[]";
10195 amit.gupta 411
 
4934 amit.gupta 412
    }
5094 phani.kuma 413
 
11672 anikendra 414
    public String getEntityLogisticsEstimation() {
415
    	return entityLogisticsEstimation;
416
    }
417
 
5094 phani.kuma 418
    private static void setRetargettingLabel() {
419
    	label.put((long) 1002160, "6EIBCKjf1wMQ6Pua0wM"); //Samsung Galaxy Y S5360
420
    	label.put((long) 1002106, "JFGVCKCt8gMQ6Pua0wM"); //Sony Ericsson Xperia Neo V MT11i
421
    	label.put((long) 1003230, "ArAYCJiu8gMQ6Pua0wM"); //Micromax Funbook Tab P300
422
    	label.put((long) 1002151, "j0c_CJCv8gMQ6Pua0wM"); //HTC Explorer (Pico) A310e
423
    	label.put((long) 1000607, "7H3QCKDh8wMQ6Pua0wM"); //SanDisk MicroSD 8GB
424
    	label.put((long) 1003213, "QtGQCJji8wMQ6Pua0wM"); //Micromax SUPERFONE Gossip A78
425
    	label.put((long) 1002530, "0YNbCJDj8wMQ6Pua0wM"); //Samsung Champ Deluxe Duos C3312
426
    	label.put((long) 1003039, "pQUaCIjk8wMQ6Pua0wM"); //Samsung Star 3 Duos S5222
427
    	label.put((long) 1002575, "zcYTCIDl8wMQ6Pua0wM"); //Samsung Galaxy Y Duos S6102
428
    }
429
 
430
    public String getRetargettingLabel() {
431
    	return label.get(this.productId);
432
    }
7853 amit.gupta 433
 
434
 
435
    public String getEmiObject(){
436
    	return ProceedToPayController.getEmiSchemesInJSON();
437
    }
5491 rajveer 438
 
11672 anikendra 439
    public String getDeliveryEstimate() {
440
    	return new Gson().toJson(this.deliveryEstimate);
441
    }
11964 amit.gupta 442
 
443
    public String getProductJSON(){
444
    	if(userinfo.isPrivateDealUser()){
445
			return snippets.get(ENTITY_DETAIL_KEY);
446
		} else {
447
			return null;
448
		}
449
    }
1197 varun.gupt 450
}