Subversion Repositories SmartDukaan

Rev

Rev 9269 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
9269 amit.gupta 1
package in.shop2020.mobileapi.serving.services;
9103 anupam.sin 2
 
3
import in.shop2020.logistics.PickupStore;
4
import in.shop2020.logistics.Provider;
9269 amit.gupta 5
import in.shop2020.mobileapi.serving.utils.Utils;
9103 anupam.sin 6
import in.shop2020.model.v1.order.Order;
7
import in.shop2020.model.v1.order.OrderSource;
8
import in.shop2020.model.v1.order.OrderStatus;
9
import in.shop2020.model.v1.order.OrderStatusGroups;
10
import in.shop2020.model.v1.user.Address;
11
import in.shop2020.model.v1.user.User;
12
import in.shop2020.model.v1.user.UserContextException;
13
import in.shop2020.thrift.clients.LogisticsClient;
14
import in.shop2020.thrift.clients.TransactionClient;
15
import in.shop2020.thrift.clients.UserClient;
16
 
17
import java.io.BufferedReader;
18
import java.io.File;
19
import java.io.FileInputStream;
20
import java.io.FileNotFoundException;
21
import java.io.IOException;
22
import java.io.InputStreamReader;
23
import java.io.StringWriter;
24
import java.text.SimpleDateFormat;
25
import java.util.ArrayList;
26
import java.util.Date;
27
import java.util.HashMap;
28
import java.util.List;
29
import java.util.Map;
30
import java.util.Properties;
31
 
32
import org.apache.log4j.Logger;
33
import org.apache.thrift.TException;
34
import org.apache.velocity.Template;
35
import org.apache.velocity.VelocityContext;
36
import org.apache.velocity.app.Velocity;
37
import org.apache.velocity.exception.MethodInvocationException;
38
import org.apache.velocity.exception.ParseErrorException;
39
import org.apache.velocity.exception.ResourceNotFoundException;
40
 
41
 
42
public class PageLoaderHandler {
43
 
44
    private static Logger logger = Logger.getLogger(PageLoaderHandler.class);
45
 
20825 amit.gupta 46
    static {
47
    	try {
48
	    	Properties p = new Properties();
49
			p.setProperty("resource.loader", "class");
50
			p.setProperty("class.resource.loader.class",
51
			"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
52
			p.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); 
53
			Velocity.init(p);
54
    	} catch(Exception e) {
55
    		e.printStackTrace();
56
    	}
57
    }
58
 
9103 anupam.sin 59
	public String getSlideGuideHtml(long productId) {
60
		StringBuilder htmlString = new StringBuilder();
61
		String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "SlideGuide.html";
62
		File f = new File(filename);
63
 
64
 
65
		FileInputStream fis = null;
66
		try {
67
			fis = new FileInputStream(f);
68
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
69
			String line;
70
			while((line = br.readLine()) != null){
71
				htmlString.append(line+"\n");
72
			}
73
		} catch (FileNotFoundException e) {
74
			logger.error("Unable to find the slide guide for " + productId, e);
75
		} catch (IOException e) {
76
		    logger.error("Unable to read the slide guide for " + productId, e);
77
		}
78
		finally {
79
			if(fis != null) {
80
				try {
81
					fis.close();
82
				} catch (IOException e) {
83
				    logger.warn("Unable to close the slide guide for " + productId, e);
84
				}
85
			}
86
		}
87
 
88
		return htmlString.toString();
89
	}
90
 
91
	public String getProductSummaryHtml(long productId) {
92
		StringBuilder htmlString = new StringBuilder();
93
		String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "ProductDetail.html";
94
		File f = new File(filename);
95
 
96
 
97
		FileInputStream fis = null;
98
		try {
99
			fis = new FileInputStream(f);
100
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
101
			String line;
102
			while((line = br.readLine()) != null){
103
				htmlString.append(line+"\n");
104
			}
105
		} catch (FileNotFoundException e) {
106
			logger.error("Unable to find the product summary file", e);
107
		} catch (IOException e) {
108
			logger.error("Unable to read the product summary file", e);
109
		}
110
		finally {
111
			if(fis != null) {
112
				try {
113
					fis.close();
114
				} catch (IOException e) {
115
					logger.error("Unable to close the product summary file", e);
116
				}
117
			}
118
		}
119
 
120
		return htmlString.toString();
121
	}
122
 
123
	public String getProductPropertiesHtml(long productId) {
124
		StringBuilder htmlString = new StringBuilder();
125
		String filename = Utils.EXPORT_ENTITIES_PATH + productId + File.separator + "ProductPropertiesSnippet.html";
126
		File f = new File(filename);
127
 
128
 
129
		FileInputStream fis = null;
130
		try {
131
			fis = new FileInputStream(f);
132
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
133
			String line;
134
			while((line = br.readLine()) != null){
135
				htmlString.append(line+"\n");
136
			}
137
		} catch (FileNotFoundException e) {
138
		    logger.error("Unable to find the product properties file", e);
139
		} catch (IOException e) {
140
			logger.error("Unable to read the product properties file", e);
141
		} finally {
142
			if(fis != null) {
143
				try {
144
					fis.close();
145
				} catch (IOException e) {
146
					logger.error("Unable to close the product properties file", e);
147
				}
148
			}
149
		}
150
 
151
		return htmlString.toString();
152
	}
153
 
154
	public String getSearchBarHtml(long itemCounts, long categoryId) {
155
		String htmlString = "";
156
		VelocityContext context = new VelocityContext();
157
		String templateFile = "templates/searchbar.vm";
158
 
159
		context.put("itemCount", itemCounts+"");
160
		context.put("categoryId", categoryId+"");
161
 
162
		htmlString = getHtmlFromVelocity(templateFile, context);
163
		return htmlString;
164
	}
165
 
166
	public String getHeaderHtml(boolean isLoggedIn, String email, int totalItems, String url, long catId, boolean displayBestDealsImg)	{
167
		VelocityContext context = new VelocityContext();
168
 
169
		if (isLoggedIn)	{
170
			context.put("LOGGED_IN", "TRUE");
171
			context.put("WELCOME_MESSAGE", "Hi " + email.split("@")[0]);
172
 
173
		} else	{
174
			context.put("WELCOME_MESSAGE", "Hi, Welcome to Saholic");
175
			context.put("REDIRECT_URL", url);
176
		}
177
 
178
		context.put("BEST_DEALS_BADGE", displayBestDealsImg);
179
		context.put("CAT_ID", catId);
180
		context.put("TOTAL_ITEMS", totalItems);
181
		String templateFile = "templates/header.vm";
182
 
183
		return getHtmlFromVelocity(templateFile, context);
184
	}
185
 
186
	public String getThinHeaderHtml(boolean isLoggedIn, String email, int totalItems, String url, long catId, boolean displayBestDealsImg) {
187
        VelocityContext context = new VelocityContext();
188
 
189
        if (isLoggedIn) {
190
            context.put("LOGGED_IN", "TRUE");
191
            context.put("WELCOME_MESSAGE", "Hi " + email.split("@")[0]);
192
 
193
        } else  {
194
            context.put("WELCOME_MESSAGE", "Hi, Welcome to Saholic");
195
            context.put("REDIRECT_URL", url);
196
        }
197
 
198
        context.put("BEST_DEALS_BADGE", displayBestDealsImg);
199
        context.put("CAT_ID", catId);
200
        context.put("TOTAL_ITEMS", totalItems);
201
        String templateFile = "templates/thinheader.vm";
202
 
203
        return getHtmlFromVelocity(templateFile, context);
204
    }
205
 
206
 
207
	public String getOrderDetailsHtml(long orderId, UserSessionInfo userinfo) {
208
		long userId = userinfo.getUserId();
209
		String htmlString = "";
210
		VelocityContext context = new VelocityContext();
211
		String templateFile = "templates/orderdetails.vm";
212
		Order order = null;
213
		Date orderedOn = null, deliveryEstimate = null;
214
		Provider provider = null;
215
        List<Address> addresses = null;
216
        Long defaultAddressId = null;
217
        boolean initiateOrderCancelation = false;
218
        boolean requestOrderCancelation = false;
219
        OrderStatusGroups Groups = new OrderStatusGroups();
220
        List<OrderStatus> codCancellable = Groups.getCodCancellable();
221
        List<OrderStatus> prepaidCancellableBeforeBilled = Groups.getPrepaidCancellableBeforeBilled();
222
        List<OrderStatus> prepaidCancellableAfterBilled = Groups.getPrepaidCancellableAfterBilled();
223
 
224
        try{
225
			TransactionClient transactionServiceClient = new TransactionClient();
226
			in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient.getClient();
227
			order = orderClient.getOrderForCustomer(orderId, userId);
228
			orderedOn = new Date(order.getCreated_timestamp());
229
			deliveryEstimate = new Date(order.getPromised_delivery_time());
230
 
231
			if(order.getSource() == OrderSource.WEBSITE.getValue()){
232
				if(order.isCod()){
233
					if(codCancellable.contains(order.getStatus())){
234
						initiateOrderCancelation = true;
235
					}
236
				}
237
				else {
238
					if(prepaidCancellableBeforeBilled.contains(order.getStatus())){
239
						initiateOrderCancelation = true;
240
					}
241
					else if(prepaidCancellableAfterBilled.contains(order.getStatus())){
242
						requestOrderCancelation = true;
243
					}
244
				}
245
			}
246
 
247
			in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient().getClient();
248
			addresses = userClient.getAllAddressesForUser(userId);
249
			defaultAddressId = userClient.getDefaultAddressId(userId);
250
			logger.info("Found addresses: " + addresses + " for userId: " + userId);
251
 
252
			if(order.getLogistics_provider_id() != 0){
253
				LogisticsClient logisticsServiceClient = new LogisticsClient();
254
				in.shop2020.logistics.LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
255
				provider = logisticsClient.getProvider(order.getLogistics_provider_id());
256
			}
257
 
258
			if (order.getPickupStoreId() != 0) {
259
			    in.shop2020.logistics.LogisticsService.Client logisticsServiceClient = new LogisticsClient().getClient();
260
			    PickupStore store = logisticsServiceClient.getPickupStore(order.getPickupStoreId());
261
			    order.setCustomer_name(store.getName());
262
			    order.setCustomer_address1(store.getLine1());
263
			    order.setCustomer_address2(store.getLine2());
264
			    order.setCustomer_city(store.getCity());
265
			    order.setCustomer_pincode(store.getPin());
266
			    order.setCustomer_state(store.getState());
267
			    order.setCustomer_mobilenumber(store.getPhone());
268
			}
269
		} catch (Exception e){
270
 
271
		}
272
 
273
		SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
274
		SimpleDateFormat dateformat1 = new SimpleDateFormat("dd/MM/yyyy");
275
 
276
		context.put("order", order);
277
		context.put("isShipped", Groups.getShippedOrders().contains(order.getStatus()));
278
		context.put("isDelivered", order.getStatus().equals(OrderStatus.DELIVERY_SUCCESS));
279
		context.put("isOpen", Groups.getShippedOrders().contains(order.getStatus()));
280
		context.put("order", order);
281
		context.put("orderedOn", dateformat.format(orderedOn));
282
		context.put("fdaOn", dateformat1.format(new Date(order.getFirst_attempt_timestamp())));
283
		context.put("promisedDeliveryDate", dateformat1.format(deliveryEstimate));
284
		context.put("deliveredOn", dateformat1.format(new Date(order.getDelivery_timestamp())));
285
		context.put("addresses", addresses);
286
		context.put("defaultAddressId", defaultAddressId);
287
		context.put("userinfo", userinfo);
288
		context.put("initiateOrderCancelation", initiateOrderCancelation);
289
		context.put("requestOrderCancelation", requestOrderCancelation);
290
 
291
		if(provider!=null){
292
			context.put("providerName", provider.getName());
293
		}
294
 
295
		htmlString = getHtmlFromVelocity(templateFile, context);
296
		return htmlString;
297
	}
298
 
299
	public String getMyaccountDetailsHtml(long userId) {
300
		String htmlString = "";
301
		VelocityContext context = new VelocityContext();
302
		String templateFile = "templates/myaccount.vm";
303
		List<Order> orders = null;
304
		Map<Long, String> providerNames = new HashMap<Long, String>();
305
		try{
306
			TransactionClient transactionServiceClient = new TransactionClient();
307
			in.shop2020.model.v1.order.TransactionService.Client orderClient = transactionServiceClient.getClient();
308
			orders = orderClient.getOrdersForCustomer(userId, 0, (new Date()).getTime(), null);
309
 
310
			LogisticsClient logisticsServiceClient = new LogisticsClient();
311
			in.shop2020.logistics.LogisticsService.Client logisticsClient = logisticsServiceClient.getClient();
312
			List<Provider> providers = logisticsClient.getAllProviders();
313
			for(Provider provider: providers)
314
				providerNames.put(provider.getId(), provider.getName());
315
		}catch (Exception e){
316
			logger.error("Unable to get order or provider details", e);
317
		}
318
		List<String> orderDate = new ArrayList<String>();
319
		SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
320
		if(orders!=null && !orders.isEmpty()){
321
			for(Order order: orders){
322
				Date orderedOn = new Date(order.getCreated_timestamp());
323
				orderDate.add(dateformat.format(orderedOn));
324
			}
325
		}
326
		context.put("orders", orders);
327
		context.put("orderDate", orderDate);
328
		context.put("providerNames", providerNames);
329
		htmlString = getHtmlFromVelocity(templateFile, context);
330
		return htmlString;
331
	}
332
 
333
 
334
	public String getLoginDetailsHtml(long userId) {
335
		String htmlString = "";
336
		VelocityContext context = new VelocityContext();
337
		String templateFile = "templates/logindetails.vm";
338
		String email = "";
339
		try{
340
			email = getEmailId(userId);
341
		}catch (Exception e){
342
 
343
		}
344
		context.put("email", email);
345
		htmlString = getHtmlFromVelocity(templateFile, context);
346
		return htmlString;
347
	}
348
 
349
	public String getEmailId(long userId){
350
		String email = " ";
351
 
352
		try {
353
			UserClient userContextServiceClient = new UserClient();
354
			in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
355
			String userEmail = userClient.getUserById(userId).getEmail(); 
356
			if( userEmail != null){
357
				email = userEmail;
358
			}
359
		} catch (UserContextException e) {
360
			logger.error("Unable to get the user for " + userId, e);
361
		} catch (TException e) {
362
		    logger.error("Unable to get the user for " + userId, e);
363
		} catch (Exception e) {
364
		    logger.error("Unable to get the user for " + userId, e);
365
		}
366
		return email; 
367
	}
368
 
369
 
370
	public String getPersonalDetailsHtml(long userId) {
371
		String htmlString = "";
372
		VelocityContext context = new VelocityContext();
373
		String templateFile = "templates/personaldetails.vm";
374
		String email = "";
375
		String name = "";
376
		String dateOfBirth = "";
377
		String sex = "";
378
		String subscribe = "false";
379
		UserClient userContextServiceClient = null;
380
		in.shop2020.model.v1.user.UserContextService.Client userClient = null;
381
		try{
382
			User user = null;
383
			userContextServiceClient = new UserClient();
384
			userClient = userContextServiceClient.getClient();
385
			user = userClient.getUserById(userId);
386
 
387
			email = user.getCommunicationEmail();
388
			name = user.getName();
389
 
390
			dateOfBirth = user.getDateOfBirth();
391
		}catch (Exception e){
392
		    logger.error("Unable to get the user for " + userId, e);
393
		}
394
		context.put("name", name);
395
		context.put("email", email);
396
		context.put("dateOfBirth", dateOfBirth+"");
397
		context.put("subscribe", subscribe);
398
		context.put("sex", sex);
399
		htmlString = getHtmlFromVelocity(templateFile, context);
400
		return htmlString;
401
	}
402
 
403
	public String getMyaccountHeaderHtml() {
404
		String htmlString = "";
405
		VelocityContext context = new VelocityContext();
406
		String templateFile = "templates/myaccountheader.vm";
407
		htmlString = getHtmlFromVelocity(templateFile, context);
408
		return htmlString;
409
	}
410
 
411
	public String getShippingAddressDetailsHtml(long userId, String errorMsg){
412
		String htmlString = "";
413
		VelocityContext context = new VelocityContext();
414
		String templateFile = "templates/shippingaddressdetails.vm";
415
		long defaultAddressId = 0;
416
		List<Address> addresses = null;
417
 
418
		UserClient userContextServiceClient = null;
419
		in.shop2020.model.v1.user.UserContextService.Client userClient = null;
420
		try {
421
			userContextServiceClient = new UserClient();
422
			userClient = userContextServiceClient.getClient();
423
 
424
			addresses = userClient.getAllAddressesForUser(userId);
425
			defaultAddressId = userClient.getDefaultAddressId(userId);
426
		} catch (Exception e) {
427
		    logger.error("Unable to get either the user for " + userId + " or his address", e);
428
		}
429
		context.put("defaultAddressId", defaultAddressId+"");
430
		context.put("addresses", addresses);
431
		context.put("errorMsg", errorMsg);
432
 
433
		htmlString = getHtmlFromVelocity(templateFile, context);
434
		return htmlString;
435
	}
436
 
437
	public String getHtmlFromVelocity(String templateFile, VelocityContext context){
438
        try {
439
            // Velocity.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, value)
440
            Template template = Velocity.getTemplate(templateFile);
441
            if (template != null) {
442
                StringWriter writer = new StringWriter();
443
                template.merge(context, writer);
444
                writer.flush();
445
                writer.close();
446
                return writer.toString();
447
            }
448
 
449
        } catch (ResourceNotFoundException e) {
450
            logger.error("Unable to find the template file " + templateFile, e);
451
        } catch (ParseErrorException e) {
452
            logger.error("Unable to parse the template file " + templateFile, e);
453
        } catch (MethodInvocationException e) {
454
            logger.error("Unable to invoke methods for the velocity template file " + templateFile, e);
455
        } catch (IOException e) {
456
            logger.error("Unable to read the template file " + templateFile, e);
457
        } catch (Exception e) {
458
            logger.error("Unable to generate the HTML from the template file " + templateFile, e);
459
        }
460
 
461
		return null;
462
	}
463
 
464
	public String getCartWidgetSnippet(int totalItems, double totalAmount, long catId) {
465
		String htmlString = "";
466
		VelocityContext context = new VelocityContext();
467
		String templateFile = "templates/cartwidget.vm";
468
		context.put("CAT_ID", catId);
469
		htmlString = getHtmlFromVelocity(templateFile, context);
470
		return htmlString;
471
	}
472
 
473
}