Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

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