Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
679 chandransh 1
package in.shop2020.support.controllers;
2
 
4386 anupam.sin 3
import in.shop2020.logistics.DeliveryType;
4
import in.shop2020.logistics.LogisticsServiceException;
7792 anupam.sin 5
import in.shop2020.logistics.PickupStore;
4386 anupam.sin 6
import in.shop2020.logistics.Provider;
7792 anupam.sin 7
import in.shop2020.logistics.ProviderDetails;
5945 mandeep.dh 8
import in.shop2020.model.v1.inventory.InventoryServiceException;
9
import in.shop2020.model.v1.inventory.Warehouse;
4386 anupam.sin 10
import in.shop2020.model.v1.order.LineItem;
11
import in.shop2020.model.v1.order.Order;
12
import in.shop2020.model.v1.order.TransactionServiceException;
5945 mandeep.dh 13
import in.shop2020.support.models.AwbDetails;
3364 chandransh 14
import in.shop2020.support.utils.FileUtils;
3125 rajveer 15
import in.shop2020.thrift.clients.HelperClient;
5945 mandeep.dh 16
import in.shop2020.thrift.clients.InventoryClient;
4386 anupam.sin 17
import in.shop2020.thrift.clients.LogisticsClient;
18
import in.shop2020.thrift.clients.TransactionClient;
749 chandransh 19
import in.shop2020.utils.LogisticsUser;
679 chandransh 20
 
7792 anupam.sin 21
import java.io.BufferedReader;
679 chandransh 22
import java.io.ByteArrayOutputStream;
756 chandransh 23
import java.io.File;
7792 anupam.sin 24
import java.io.FileNotFoundException;
25
import java.io.FileReader;
679 chandransh 26
import java.io.IOException;
7792 anupam.sin 27
import java.text.ParseException;
28
import java.text.SimpleDateFormat;
4386 anupam.sin 29
import java.util.ArrayList;
679 chandransh 30
import java.util.Calendar;
4386 anupam.sin 31
import java.util.Date;
679 chandransh 32
import java.util.GregorianCalendar;
754 chandransh 33
import java.util.HashMap;
34
import java.util.List;
7792 anupam.sin 35
import java.util.Locale;
754 chandransh 36
import java.util.Map;
679 chandransh 37
 
1075 chandransh 38
import javax.servlet.ServletContext;
679 chandransh 39
import javax.servlet.ServletOutputStream;
40
import javax.servlet.http.HttpServletRequest;
41
import javax.servlet.http.HttpServletResponse;
749 chandransh 42
import javax.servlet.http.HttpSession;
679 chandransh 43
 
7811 anupam.sin 44
import org.apache.commons.lang.StringUtils;
7792 anupam.sin 45
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
46
import org.apache.poi.ss.usermodel.Cell;
47
import org.apache.poi.ss.usermodel.CellStyle;
48
import org.apache.poi.ss.usermodel.CreationHelper;
49
import org.apache.poi.ss.usermodel.Row;
50
import org.apache.poi.ss.usermodel.Sheet;
51
import org.apache.poi.ss.usermodel.Workbook;
679 chandransh 52
import org.apache.struts2.interceptor.ServletRequestAware;
53
import org.apache.struts2.interceptor.ServletResponseAware;
1075 chandransh 54
import org.apache.struts2.util.ServletContextAware;
4386 anupam.sin 55
import org.apache.thrift.TException;
56
import org.apache.thrift.transport.TTransportException;
3062 chandransh 57
import org.slf4j.Logger;
58
import org.slf4j.LoggerFactory;
679 chandransh 59
 
2904 chandransh 60
/**
61
 * Allows executives of courier companies to login and download courier details
62
 * report which they then use to upload into their database.
63
 * 
64
 * @author Chandranshu
65
 * 
66
 */
679 chandransh 67
public class CourierDetailsController implements ServletResponseAware,
1075 chandransh 68
		ServletRequestAware, ServletContextAware {
3062 chandransh 69
 
70
    private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);
71
 
7792 anupam.sin 72
    private static final String EMPTY_STRING = "-";
73
 
749 chandransh 74
	private String id;
1075 chandransh 75
	private int daysToSubtract;
756 chandransh 76
 
77
	//FIXME: Read this configuration from the config client
78
	private String courierDetailsPath = "/CourierDetailReports";
79
 
1075 chandransh 80
	private ServletContext context;
679 chandransh 81
	private HttpServletRequest request;
82
	private HttpServletResponse response;
749 chandransh 83
	private HttpSession session;
679 chandransh 84
 
4386 anupam.sin 85
    private String awbNumbers;
86
    private List<AwbDetails> detailedAWBs;
87
 
88
    private String errorMsg = "";
7792 anupam.sin 89
 
90
    private File awbFile;
91
    private String awbFileContentType;
92
    private String awbFileFileName;
4386 anupam.sin 93
 
749 chandransh 94
	public String index(){
95
		if(getSessionUserName()==null)
96
			return "authfail";
97
		else
98
			return "authsuccess";
99
	}
100
 
101
	// Handler for POST /courier-details
102
	public String create(){
103
		String username = request.getParameter("username");
104
		String password = request.getParameter("password");
105
		try{
3125 rajveer 106
			HelperClient helperServiceClient = new HelperClient();
749 chandransh 107
			in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
108
			LogisticsUser user = client.authenticateLogisticsUser(username, password);
109
			session.setAttribute("username", user.getUsername());
110
			session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
111
		}catch(Exception e){
3105 chandransh 112
			logger.error("Error authenticating the user " + username, e);
749 chandransh 113
			return "authfail";
114
		}
115
		return "authsuccess";
679 chandransh 116
	}
117
 
749 chandransh 118
	// Handler for GET /courier-details/<warehouseId>
119
	public String show(){
120
		try {
121
			long warehouseId = Long.parseLong(getId());
4209 rajveer 122
			if(warehouseId == 1){
123
				warehouseId = 0;
124
			}
749 chandransh 125
			long providerId = ((Long)session.getAttribute("providerId")).longValue();
3062 chandransh 126
			boolean isCod;
127
			try {
128
	            isCod = Boolean.parseBoolean(request.getParameter("isCod"));
129
	        } catch (Exception e) {
130
	            isCod = false;
131
	        }
3105 chandransh 132
			logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);
749 chandransh 133
 
3062 chandransh 134
			String deliveryType = "prepaid";
135
			if(isCod)
136
			    deliveryType = "cod";
137
 
749 chandransh 138
			response.setContentType("application/vnd.ms-excel");
139
 
140
			Calendar date = new GregorianCalendar();
1075 chandransh 141
			date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
749 chandransh 142
			int year = date.get(Calendar.YEAR);
7792 anupam.sin 143
			int month = date.get(Calendar.MONTH) + 1;
749 chandransh 144
			int day = date.get(Calendar.DAY_OF_MONTH);
3062 chandransh 145
			String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";
146
			response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );
749 chandransh 147
 
148
			ServletOutputStream sos;
149
			try {
756 chandransh 150
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
3364 chandransh 151
				baos.write(FileUtils.getBytesFromFile(new File(fileName)));
749 chandransh 152
				sos = response.getOutputStream();
153
				baos.writeTo(sos);
154
				sos.flush();
155
			} catch (IOException e) {
3062 chandransh 156
				logger.error("Unable to stream the courier details report", e);
749 chandransh 157
			}	
158
			return "authsuccess";
159
		}catch(NumberFormatException nfe){
3062 chandransh 160
			logger.error("Unable to parse the warehouse id", nfe);
749 chandransh 161
		}
162
		return "authfail";
163
	}
4386 anupam.sin 164
 
165
	/**
7792 anupam.sin 166
	 * Use this method to view details of a given awb number
4386 anupam.sin 167
	 */
7792 anupam.sin 168
	public String viewAwbDetails() {
13361 manish.sha 169
		if(awbNumbers.isEmpty()) {
170
			setErrorMsg("Field cannot be empty");
171
			return "info";
172
		}
173
		String [] awbArray = awbNumbers.split(",");
174
		createAwbDetailList(awbArray);
175
		return "info";
7792 anupam.sin 176
	}
177
 
178
	/**
13361 manish.sha 179
	 * Use this method to download details of given comma separated list of awb numbers
180
	 */
181
 
7792 anupam.sin 182
	public String getAwbDetails() {
13361 manish.sha 183
		if(awbNumbers.isEmpty()) {
184
			setErrorMsg("Field cannot be empty");
185
			return "info";
186
		}
187
		String [] awbArray = awbNumbers.split(",");
188
		createAwbDetailList(awbArray);
189
		ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
190
		response.setContentType("application/vnd.ms-excel");
191
		response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
192
		ServletOutputStream sos;
193
		try {
194
			sos = response.getOutputStream();
195
			baos.writeTo(sos);
196
			sos.flush();
197
		} catch (IOException e) {
198
			logger.error("Encountered error while sending invoice response: ", e);
199
		}
200
		return "info";
201
	}
202
 
7792 anupam.sin 203
	/**
13361 manish.sha 204
	 * Use this method to download details of given list of awb numbers uploaded in a text file
205
	 */
206
 
7792 anupam.sin 207
	public String getAwbDetailsByFile() {
13361 manish.sha 208
		if(awbFile == null) {
209
			return null;
210
		}
7792 anupam.sin 211
 
13361 manish.sha 212
		List<String> awbList = new ArrayList<String>();
7792 anupam.sin 213
 
13361 manish.sha 214
		try {
215
			BufferedReader in = new BufferedReader(new FileReader(awbFile));
216
			String line;
217
			while((line = in.readLine()) != null) {
218
				awbList.add(line.trim());
219
			}
220
		} catch (FileNotFoundException e1) {
221
			logger.error("File not found", e1);
222
			return null;
223
		} catch (IOException e) {
224
			logger.error("Unable to read file", e);
225
			return null;
226
		}
7792 anupam.sin 227
 
13361 manish.sha 228
		String[] awbArray  = awbList.toArray(new String [awbList.size()]);
229
		createAwbDetailList(awbArray);
230
 
231
		ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
232
		response.setContentType("application/vnd.ms-excel");
233
		response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
234
		ServletOutputStream sos;
235
		try {
236
			sos = response.getOutputStream();
237
			baos.writeTo(sos);
238
			sos.flush();
239
		} catch (IOException e) {
240
			logger.error("Encountered error while sending invoice response: ", e);
241
		}
242
		return "info";
7792 anupam.sin 243
	}
16284 manish.sha 244
 
245
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
246
		StringBuffer itemName = new StringBuffer();
247
		if(lineitem.getBrand()!= null)
248
			itemName.append(lineitem.getBrand() + " ");
249
		if(lineitem.getModel_name() != null)
250
			itemName.append(lineitem.getModel_name() + " ");
251
		if(lineitem.getModel_number() != null )
252
			itemName.append(lineitem.getModel_number() + " ");
253
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
254
			itemName.append("("+lineitem.getColor()+")");
255
		if(appendIMEI && lineitem.isSetSerial_number()){
256
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
257
		}
7792 anupam.sin 258
 
16284 manish.sha 259
		return itemName.toString();
260
	}
261
 
13361 manish.sha 262
	private void createAwbDetailList(String[] awbArray) {
263
		List<Order> orderList;
264
		List<AwbDetails> tempList = new ArrayList<AwbDetails>() ;
265
		for(String awbNumber : awbArray) {
266
			try {
267
				LogisticsClient lsc = new LogisticsClient();
268
				TransactionClient tsc = new TransactionClient();
269
				InventoryClient isc = new InventoryClient();
270
				in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = isc.getClient();
271
				in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
272
				in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
3105 chandransh 273
 
13361 manish.sha 274
				/*
275
				 * Get required stuff
276
				 * FIXME: Reduce service calls 
277
				 */
278
				logger.info("Session : " + session);
279
				logger.info("provider Id : " + ((Long)session.getAttribute("providerId")).longValue());
280
				Provider provider = logisticsClient.getProvider(((Long)session.getAttribute("providerId")).longValue());
281
				orderList = txnClient.getOrderForAwb(awbNumber);
16284 manish.sha 282
 
283
				Map<String, List<Order>> logisticsTxnIdOrdersMap = new HashMap<String, List<Order>>(); 
284
			    Map<Long, String> itemNamesMap = new HashMap<Long, String>();
285
			    Map<String, Map<Long, Double>> logisticsTxnIdOrderQuantityMap = new HashMap<String, Map<Long, Double>>();
286
 
287
			    for(Order order:orderList){
288
					if(order.getLogistics_provider_id()!=provider.getId())
289
						continue;
290
					LineItem lineItem = order.getLineitems().get(0);
291
					if(order.isSetLogisticsTransactionId()){
292
						if(logisticsTxnIdOrdersMap.containsKey(order.getLogisticsTransactionId())){
293
							List<Order> ordersList = logisticsTxnIdOrdersMap.get(order.getLogisticsTransactionId());
294
							ordersList.add(order);
295
							logisticsTxnIdOrdersMap.put(order.getLogisticsTransactionId(), ordersList);
296
						} else{
297
							List<Order> ordersList = new ArrayList<Order>();
298
							ordersList.add(order);
299
							logisticsTxnIdOrdersMap.put(order.getLogisticsTransactionId(), ordersList);
300
						}
301
						if(logisticsTxnIdOrderQuantityMap.containsKey(order.getLogisticsTransactionId())){
302
							Map<Long, Double> orderItemQuantityMap = logisticsTxnIdOrderQuantityMap.get(order.getLogisticsTransactionId());
303
							if(orderItemQuantityMap.containsKey(lineItem.getItem_id())){
304
								double orderQuantity = orderItemQuantityMap.get(lineItem.getItem_id())+ lineItem.getQuantity();
305
								orderItemQuantityMap.put(lineItem.getItem_id(),orderQuantity);
306
								logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
307
							}else{
308
								double orderQuantity = lineItem.getQuantity();
309
								orderItemQuantityMap.put(lineItem.getItem_id(),orderQuantity);
310
								logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
311
							}
312
						}else{
313
							Map<Long, Double> orderItemQuantityMap = new HashMap<Long, Double>();
314
							orderItemQuantityMap.put(lineItem.getItem_id(), lineItem.getQuantity());
315
							logisticsTxnIdOrderQuantityMap.put(order.getLogisticsTransactionId(), orderItemQuantityMap);
316
						}
317
					}else{
318
						List<Order> ordersList = new ArrayList<Order>();
319
						ordersList.add(order);
320
						logisticsTxnIdOrdersMap.put(order.getId()+"", ordersList);
321
						Map<Long, Double> orderItemQuantityMap = new HashMap<Long, Double>();
322
						orderItemQuantityMap.put(lineItem.getItem_id(), lineItem.getQuantity());
323
						logisticsTxnIdOrderQuantityMap.put(order.getId()+"", orderItemQuantityMap);
324
					}
325
					if(!itemNamesMap.containsKey(lineItem.getItem_id())){
326
						itemNamesMap.put(lineItem.getItem_id(), getItemDisplayName(lineItem, false));
327
					}
328
			    }
329
 
330
			    for(String logisticsTxnId : logisticsTxnIdOrdersMap.keySet()){
331
			    	List<Order> ordersList = logisticsTxnIdOrdersMap.get(logisticsTxnId);
332
			    	Warehouse warehouse = inventoryClient.getWarehouse(ordersList.get(0).getWarehouse_id());
333
			    	String accountNo = "";
334
 
335
					DeliveryType dt =  DeliveryType.PREPAID;
336
					if (ordersList.get(0).isLogisticsCod()) {
337
						dt = DeliveryType.COD;
338
					}
339
 
340
					for (ProviderDetails detail : provider.getDetails()) {
341
						if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
342
							accountNo = detail.getAccountNo();
343
						}
344
					}
345
 
346
					double totalAmount = 0.0;
347
			    	double totalWeight = 0.0;
348
			    	for(Order o:ordersList){
349
			    		totalAmount = totalAmount + (o.getTotal_amount()-o.getGvAmount());
350
			    		totalWeight = totalWeight + o.getTotal_weight();
351
			    	}
352
 
353
					AwbDetails detailedAwb = new AwbDetails();
354
 
355
					String[] addresses = warehouse.getLocation().split(",+");
356
 
357
					detailedAwb.setReturnAddress1((addresses[0].trim() + ", " + addresses[1].trim()).replace("\n", ", "));
358
					detailedAwb.setReturnAddress2((addresses[2].trim() + (addresses.length > 3 ? ", " + addresses[3].trim() : "")).replace("\n", ", "));
359
 
360
					String line3 = "";
361
					if(addresses.length > 4) {
362
						for(int i = 4; i<addresses.length; i++) {
363
							line3 += addresses[i] + ", ";
364
						}
365
					}
366
 
367
					if(StringUtils.isNotEmpty(line3)) {
368
						detailedAwb.setReturnAddress3(line3.trim().replace("\n", ", "));
369
					} else {
370
						detailedAwb.setReturnAddress3(EMPTY_STRING);
371
					}
372
					detailedAwb.setReturnPin(warehouse.getPincode());
373
					detailedAwb.setAwbNumber(awbNumber);
374
					detailedAwb.setAccountCode(accountNo);
375
					detailedAwb.setVendorCode((int) ordersList.get(0).getWarehouse_id());
376
					if(ordersList.get(0).isLogisticsCod()){
377
						detailedAwb.setAmountToCollect("" + totalAmount);
378
					} else {
379
						detailedAwb.setAmountToCollect("" + 0 );
380
					}
381
 
382
					if(ordersList.get(0).getShipping_timestamp() > 0) {
383
						Date date = new Date(ordersList.get(0).getShipping_timestamp());
384
						detailedAwb.setAwbDate(date.toString());
385
					} else {
386
						detailedAwb.setAwbDate("N/A");
387
					}
388
 
389
					if(ordersList.get(0).getPickupStoreId() > 0) {
390
						PickupStore store = lsc.getClient().getPickupStore(ordersList.get(0).getPickupStoreId());
391
						detailedAwb.setAddress1(store.getLine1());
392
						detailedAwb.setAddress2(store.getLine2());
393
						detailedAwb.setCity(store.getCity());
394
						detailedAwb.setCustomerName("Spice Hotspot");
395
						detailedAwb.setPhoneNumber("" + store.getPhone());
396
						detailedAwb.setPinCode(store.getPin());
397
						detailedAwb.setState(store.getState());
398
					} else {
399
						detailedAwb.setAddress1(ordersList.get(0).getCustomer_address1());
400
						detailedAwb.setAddress2(ordersList.get(0).getCustomer_address2());
401
						detailedAwb.setCity(ordersList.get(0).getCustomer_city());
402
						detailedAwb.setCustomerName(ordersList.get(0).getCustomer_name());
403
						detailedAwb.setPhoneNumber("" + ordersList.get(0).getCustomer_mobilenumber());
404
						detailedAwb.setPinCode(ordersList.get(0).getCustomer_pincode());
405
						detailedAwb.setState(ordersList.get(0).getCustomer_state());
406
					}
407
 
408
					detailedAwb.setItemId("" + ordersList.get(0).getLineitems().get(0).getItem_id());
409
					detailedAwb.setOrderId("" + ordersList.get(0).getId());
410
					detailedAwb.setPacketWeight("" + totalWeight);
411
					if(ordersList.get(0).isLogisticsCod()){
412
						detailedAwb.setPaymentMode("COD");
413
					} else {
414
						detailedAwb.setPaymentMode("Prepaid");
415
					}
416
 
417
 
418
					detailedAwb.setPickupLocation(warehouse.getLocation());
419
 
420
					StringBuffer productNameBuffer = new StringBuffer();
421
				    int skuSizeTxn = logisticsTxnIdOrderQuantityMap.get(logisticsTxnId).keySet().size();
422
				    int count = 1;
423
				    for(Long itemId : logisticsTxnIdOrderQuantityMap.get(logisticsTxnId).keySet()){
424
				    	Map<Long, Double> quantityMap = logisticsTxnIdOrderQuantityMap.get(logisticsTxnId);
425
				    	double quantity = quantityMap.get(itemId);
426
				    	productNameBuffer.append(itemNamesMap.get(itemId)+"("+quantity+")");
427
				    	if(count<skuSizeTxn){
428
				    		productNameBuffer.append(",");
429
				    	}
430
				    	count++;
431
				    }
432
 
433
				    detailedAwb.setProductName(productNameBuffer.toString());
434
				    LineItem lineitem = ordersList.get(0).getLineitems().get(0);
435
					if (ordersList.get(0).getFreebieItemId() > 0) {
436
						//If order has a freebie order attached with it
437
						detailedAwb.setShipmentValue("" + (ordersList.get(0).getTotal_amount()));
438
					} else {
439
						//else if the order is itself a split freebie order then we don't know how much was the selling price at the time of order
440
						//so we set the transfer price as shipment value
441
						if (lineitem.getExtra_info() != null && lineitem.getExtra_info().contains("Freebie Order for Order ID")) {
442
							detailedAwb.setShipmentValue("" + (totalAmount));
443
						} else {
444
							//Else set total amount
445
							detailedAwb.setShipmentValue("" +totalAmount);
446
						}
447
					}
448
 
449
					if(ordersList.get(0).isSetLogisticsTransactionId()){
450
						detailedAwb.setMasterOrderId(ordersList.get(0).getLogisticsTransactionId());
451
					}else{
452
						detailedAwb.setMasterOrderId("-");
453
					}
454
 
455
					tempList.add(detailedAwb);
456
			    }
457
 
458
				/*for(Order order : orderList){
13361 manish.sha 459
					Warehouse warehouse = inventoryClient.getWarehouse(order.getWarehouse_id());
460
 
461
					String accountNo = "";
462
 
463
					DeliveryType dt =  DeliveryType.PREPAID;
464
					if (order.isLogisticsCod()) {
465
						dt = DeliveryType.COD;
466
					}
467
 
468
					for (ProviderDetails detail : provider.getDetails()) {
469
						if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {
470
							accountNo = detail.getAccountNo();
471
						}
472
					}
473
 
474
					AwbDetails detailedAwb = new AwbDetails();
475
 
476
					String[] addresses = warehouse.getLocation().split(",+");
477
 
478
					detailedAwb.setReturnAddress1((addresses[0].trim() + ", " + addresses[1].trim()).replace("\n", ", "));
479
					detailedAwb.setReturnAddress2((addresses[2].trim() + (addresses.length > 3 ? ", " + addresses[3].trim() : "")).replace("\n", ", "));
480
 
481
					String line3 = "";
482
					if(addresses.length > 4) {
483
						for(int i = 4; i<addresses.length; i++) {
484
							line3 += addresses[i] + ", ";
485
						}
486
					}
487
 
488
					if(StringUtils.isNotEmpty(line3)) {
489
						detailedAwb.setReturnAddress3(line3.trim().replace("\n", ", "));
490
					} else {
491
						detailedAwb.setReturnAddress3(EMPTY_STRING);
492
					}
493
					detailedAwb.setReturnPin(warehouse.getPincode());
494
					detailedAwb.setAwbNumber(awbNumber);
495
					detailedAwb.setAccountCode(accountNo);
496
					detailedAwb.setVendorCode((int) order.getWarehouse_id());
497
					if(order.isLogisticsCod()){
498
						detailedAwb.setAmountToCollect("" + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));
499
					} else {
500
						detailedAwb.setAmountToCollect("" + 0 );
501
					}
502
 
503
					if(order.getShipping_timestamp() > 0) {
504
						Date date = new Date(order.getShipping_timestamp());
505
						detailedAwb.setAwbDate(date.toString());
506
					} else {
507
						detailedAwb.setAwbDate("N/A");
508
					}
509
 
510
					if(order.getPickupStoreId() > 0) {
511
						PickupStore store = lsc.getClient().getPickupStore(order.getPickupStoreId());
512
						detailedAwb.setAddress1(store.getLine1());
513
						detailedAwb.setAddress2(store.getLine2());
514
						detailedAwb.setCity(store.getCity());
515
						detailedAwb.setCustomerName("Spice Hotspot");
516
						detailedAwb.setPhoneNumber("" + store.getPhone());
517
						detailedAwb.setPinCode(store.getPin());
518
						detailedAwb.setState(store.getState());
519
					} else {
520
						detailedAwb.setAddress1(order.getCustomer_address1());
521
						detailedAwb.setAddress2(order.getCustomer_address2());
522
						detailedAwb.setCity(order.getCustomer_city());
523
						detailedAwb.setCustomerName(order.getCustomer_name());
524
						detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());
525
						detailedAwb.setPinCode(order.getCustomer_pincode());
526
						detailedAwb.setState(order.getCustomer_state());
527
					}
528
 
529
					detailedAwb.setItemId("" + order.getLineitems().get(0).getItem_id());
530
					detailedAwb.setOrderId("" + order.getId());
531
					detailedAwb.setPacketWeight("" + order.getTotal_weight());
532
					if(order.isLogisticsCod()){
533
						detailedAwb.setPaymentMode("COD");
534
					} else {
535
						detailedAwb.setPaymentMode("Prepaid");
536
					}
537
 
538
 
539
					detailedAwb.setPickupLocation(warehouse.getLocation());
540
 
541
					LineItem lineitem = order.getLineitems().get(0);
542
					detailedAwb.setProductName(lineitem.getBrand() + " " 
543
							+ (lineitem.getModel_name() == null ? "" : lineitem.getModel_name()) + " " 
544
							+ (lineitem.getModel_number() == null ? "" : lineitem.getModel_number()) + " " 
545
							+ (lineitem.getColor() == null ? "" : lineitem.getColor()));
546
					if (order.getFreebieItemId() > 0) {
547
						//If order has a freebie order attached with it
548
						detailedAwb.setShipmentValue("" + (order.getTotal_amount()));
549
					} else {
550
						//else if the order is itself a split freebie order then we don't know how much was the selling price at the time of order
551
						//so we set the transfer price as shipment value
552
						if (lineitem.getExtra_info() != null && lineitem.getExtra_info().contains("Freebie Order for Order ID")) {
553
							detailedAwb.setShipmentValue("" + (lineitem.getTransfer_price()));
554
						} else {
555
							//Else set total amount
556
							detailedAwb.setShipmentValue("" + (order.getTotal_amount()));
557
						}
558
					}
559
 
560
					if(order.isSetLogisticsTransactionId()){
561
						detailedAwb.setMasterOrderId(order.getLogisticsTransactionId());
562
					}else{
563
						detailedAwb.setMasterOrderId("-");
564
					}
565
 
566
					tempList.add(detailedAwb);
16284 manish.sha 567
				}*/
13361 manish.sha 568
 
569
			} catch (TTransportException e) {
570
				setErrorMsg("Your request cannot be processed due to technical error. Please try later.");
571
			} catch (TException e) {
572
				setErrorMsg(e.getMessage());
573
			} catch (TransactionServiceException e) {
574
				setErrorMsg(e.getMessage());
575
			} catch (LogisticsServiceException e) {
576
				setErrorMsg(e.getMessage());
577
			} catch (InventoryServiceException e) {
578
				setErrorMsg(e.getMessage());
579
			}
580
		}
581
		setDetailedAWBs(tempList);
582
	}
583
 
584
 
7792 anupam.sin 585
	public ByteArrayOutputStream generateAwbDetailsSheet(List<AwbDetails> awbDetailList) {
13361 manish.sha 586
		ByteArrayOutputStream baos = new ByteArrayOutputStream();;
587
		Workbook wb = new HSSFWorkbook();
588
		CreationHelper createHelper = wb.getCreationHelper();
589
		Sheet sheet = wb.createSheet("Saholic - Data");
7792 anupam.sin 590
 
13361 manish.sha 591
		CellStyle dateCellStyle = wb.createCellStyle();
592
		dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yyyy"));
7792 anupam.sin 593
 
13361 manish.sha 594
		CellStyle weightStyle = wb.createCellStyle();
595
		weightStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.000"));
16284 manish.sha 596
 
597
 
7792 anupam.sin 598
 
13361 manish.sha 599
		Row headerRow = sheet.createRow((short)0);
600
		headerRow.createCell(0).setCellValue("Airwaybill");
601
		headerRow.createCell(1).setCellValue("Type"); //Values : "COD" / "NONCOD"
16284 manish.sha 602
		headerRow.createCell(2).setCellValue("Master Order Id");
13361 manish.sha 603
		headerRow.createCell(3).setCellValue("Reference Number"); //OrderId
604
		headerRow.createCell(4).setCellValue("Sender / Store name"); //"Spice Online retail pvt ltd"
605
		headerRow.createCell(5).setCellValue("attention"); //Customer name
606
		headerRow.createCell(6).setCellValue("address1"); //Line 1
607
		headerRow.createCell(7).setCellValue("address2"); //Line 2
608
		headerRow.createCell(8).setCellValue("address3"); //city + state
609
		headerRow.createCell(9).setCellValue("pincode");
610
		headerRow.createCell(10).setCellValue("tel number"); //Empty
611
		headerRow.createCell(11).setCellValue("mobile number"); //Empty
612
		headerRow.createCell(12).setCellValue("Prod/SKU code");  //ItemId
613
		headerRow.createCell(13).setCellValue("contents"); //Product name
614
		headerRow.createCell(14).setCellValue("weight");  //In Kgs
615
		headerRow.createCell(15).setCellValue("Declared Value");  
616
		headerRow.createCell(16).setCellValue("Collectable Value");
617
		headerRow.createCell(17).setCellValue("Vendor Code");
618
		headerRow.createCell(18).setCellValue("Shipper Name");  
619
		headerRow.createCell(19).setCellValue("Return Address1");
620
		headerRow.createCell(20).setCellValue("Return Address2");
621
		headerRow.createCell(21).setCellValue("Return Address3");
622
		headerRow.createCell(22).setCellValue("Return Pin");
623
		headerRow.createCell(23).setCellValue("Length ( Cms )");
624
		headerRow.createCell(24).setCellValue("Bredth ( Cms )");
625
		headerRow.createCell(25).setCellValue("Height ( Cms )");
626
		headerRow.createCell(26).setCellValue("Pieces");       
627
		headerRow.createCell(27).setCellValue("Area_customer_code");
628
		headerRow.createCell(28).setCellValue("Handover Date ( DD/MM/YYYY )");
629
		headerRow.createCell(29).setCellValue("Handover Time ( 24 hrs format )");
630
 
631
		int serialNo = 0;
632
 
633
		for(AwbDetails awbDetail : awbDetailList) {
634
			//          0  Airwaybill   1 Type    2 Reference Number  3 Sender / Store name 4 attention   5 address1    6 address2    7 address3    
635
			//          8 pincode    9 tel number     10 mobile number   11 Prod/SKU code    12 contents    13 weight  
636
			//          14 Declared Value   15 Collectable Value   
637
			//          16 Vendor Code    17 Shipper Name    18 Return Address1    19 Return Address2    20 Return Address3     21 Return Pin  
638
			//          22 Length ( Cms )   23 Breadth ( Cms )      24 Height ( Cms )  
639
			//          25 Pieces  26 Area_customer_code  27 Handover Date ( DD/MM/YYYY )   28 Handover Time ( 24 hrs format )  
640
 
641
			serialNo++;
642
			Row contentRow = sheet.createRow((short)serialNo);
643
 
644
			contentRow.createCell(0).setCellValue(awbDetail.getAwbNumber());
645
			contentRow.createCell(1).setCellValue(awbDetail.getPaymentMode().equals("COD") ? "COD" : "NONCOD");
646
			contentRow.createCell(2).setCellValue(awbDetail.getMasterOrderId());
647
			contentRow.createCell(3).setCellValue(awbDetail.getOrderId());
648
			contentRow.createCell(4).setCellValue("Spice Online Retail Pvt Ltd");
649
			contentRow.createCell(5).setCellValue(awbDetail.getCustomerName());
650
			contentRow.createCell(6).setCellValue(awbDetail.getAddress1());
651
			contentRow.createCell(7).setCellValue(awbDetail.getAddress2());
652
			contentRow.createCell(8).setCellValue(awbDetail.getCity() + ", " + awbDetail.getState());
653
			contentRow.createCell(9).setCellValue(awbDetail.getPinCode());
654
			contentRow.createCell(10).setCellValue(awbDetail.getPhoneNumber());
655
			contentRow.createCell(11).setCellValue(awbDetail.getPhoneNumber());
656
			contentRow.createCell(12).setCellValue(awbDetail.getItemId());
657
			contentRow.createCell(13).setCellValue(awbDetail.getProductName());
658
			contentRow.createCell(14).setCellValue(awbDetail.getPacketWeight());
659
			contentRow.createCell(15).setCellValue(awbDetail.getShipmentValue());
660
			contentRow.createCell(16).setCellValue(awbDetail.getAmountToCollect());
661
			contentRow.createCell(17).setCellValue(awbDetail.getVendorCode());
662
			contentRow.createCell(18).setCellValue("Spice Online Retail Pvt Ltd");
663
			contentRow.createCell(19).setCellValue(awbDetail.getReturnAddress1());
664
			contentRow.createCell(20).setCellValue(awbDetail.getReturnAddress2());
665
			contentRow.createCell(21).setCellValue(awbDetail.getReturnAddress3());
666
			contentRow.createCell(22).setCellValue(awbDetail.getReturnPin());
667
			contentRow.createCell(23).setCellValue(CourierDetailsController.EMPTY_STRING);
668
			contentRow.createCell(24).setCellValue(CourierDetailsController.EMPTY_STRING);
669
			contentRow.createCell(25).setCellValue(CourierDetailsController.EMPTY_STRING);
670
			contentRow.createCell(26).setCellValue("1");
671
			contentRow.createCell(27).setCellValue(awbDetail.getAccountCode());
672
 
673
			Date date = null;
674
			SimpleDateFormat sdf4Date = new SimpleDateFormat("dd/MM/yyyy");                
675
			SimpleDateFormat sdf4Time = new SimpleDateFormat("HHmm");
676
 
677
			if(!awbDetail.getAwbDate().equals("N/A")) {
678
				try {
679
					date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(awbDetail.getAwbDate());
680
				} catch (ParseException e) {
681
					// TODO Auto-generated catch block
682
					e.printStackTrace();
683
				}
684
				contentRow.createCell(28).setCellValue(sdf4Date.format(date));
685
				contentRow.createCell(29).setCellValue(sdf4Time.format(date));
686
			} else {
687
				contentRow.createCell(28).setCellValue("N/A");
688
				contentRow.createCell(29).setCellValue("N/A");
689
			}
690
 
691
 
692
 
693
			/**
694
			 * According to javadoc of Date, Date.toString() converts a Date object to a String of the form:
695
			 * 
7792 anupam.sin 696
                 dow mon dd hh:mm:ss zzz yyyy
697
 
698
            where:
699
 
13361 manish.sha 700
			 * dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
701
			 * mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
702
			 * dd is the day of the month (01 through 31), as two decimal digits.
703
			 * hh is the hour of the day (00 through 23), as two decimal digits.
704
			 * mm is the minute within the hour (00 through 59), as two decimal digits.
705
			 * ss is the second within the minute (00 through 61, as two decimal digits.
706
			 * zzz is the time zone (and may reflect daylight saving time). Standard time zone abbreviations include those recognized by the method parse. If time zone information is not available, then zzz is empty - that is, it consists of no characters at all.
707
			 * yyyy is the year, as four decimal digits. 
708
			 * 
709
			 * And we need to send this in format DD/MM/YYYY and time in HHMM
710
			 */
711
		}
712
 
713
		try {
714
			wb.write(baos);
715
			baos.close();
716
		} catch (IOException e) {
717
			// TODO Auto-generated catch block
718
			e.printStackTrace();
719
		}
720
		return baos;
4386 anupam.sin 721
	}
722
 
13361 manish.sha 723
 
724
	/**
4386 anupam.sin 725
	 * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
726
	 * Should be used to view day before yesterday's courier details report.
727
	 * 
13361 manish.sha 728
	 * @return the same string tokens as show
729
	 */
1075 chandransh 730
	public String dayBefore(){
731
		daysToSubtract = -2;
732
		return show();
733
	}
3105 chandransh 734
 
13361 manish.sha 735
	/**
736
	 * Sets the daysToSubtract to -1 and then invokes the standard show()
737
	 * handler. Should be used to view yesterday's courier details report.
738
	 * 
739
	 * @return the same string tokens as show
740
	 */
1075 chandransh 741
	public String yesterday(){
742
		daysToSubtract = -1;
743
		return show();
744
	}
3105 chandransh 745
 
13361 manish.sha 746
	/**
747
	 * Sets the daysToSubtract to 0 and then invokes the standard show()
748
	 * handler. Should be used to view today's courier details report.
749
	 * 
750
	 * @return the same string tokens as show
751
	 */
1075 chandransh 752
	public String today(){
753
		daysToSubtract = 0;
754
		return show();
755
	}
13361 manish.sha 756
 
679 chandransh 757
	@Override
1075 chandransh 758
	public void setServletContext(ServletContext context) {
759
		this.context = context;
760
	}
13361 manish.sha 761
 
1075 chandransh 762
	@Override
679 chandransh 763
	public void setServletResponse(HttpServletResponse response) {
764
		this.response  = response;
765
	}
766
 
767
	@Override
768
	public void setServletRequest(HttpServletRequest request) {
769
		this.request = request;
749 chandransh 770
		this.session = request.getSession();
679 chandransh 771
	}
772
 
749 chandransh 773
	public String getId(){
774
		return id;
775
	}
13361 manish.sha 776
 
749 chandransh 777
	public void setId(String id){
778
		this.id = id;
779
	}
13361 manish.sha 780
 
749 chandransh 781
	public String getSessionUserName(){
782
		return (String) session.getAttribute("username");
783
	}
3105 chandransh 784
 
13361 manish.sha 785
	/**
786
	 * Gets the list of all warehouses and maps the warehouse ids to their
787
	 * display name.
788
	 * 
789
	 * @return the mapping of warehouse if to its display namee
790
	 */
754 chandransh 791
	public Map<Long, String> getWarehouses(){
792
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
793
		try{
5945 mandeep.dh 794
			InventoryClient isc = new InventoryClient();
795
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient= isc.getClient();
796
			List<Warehouse> warehouses = inventoryClient.getShippingLocations();
754 chandransh 797
			for(Warehouse warehouse : warehouses){
798
				warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
799
			}
800
		}catch(Exception e){
3105 chandransh 801
			logger.error("Error getting the list of warehouses", e);
754 chandransh 802
		}
803
		return warehouseMap;
804
	}
749 chandransh 805
 
1075 chandransh 806
	public String getServletContextPath(){
807
		return context.getContextPath();
808
	}
4386 anupam.sin 809
 
13361 manish.sha 810
	public String getAwbNumbers() {
811
		return awbNumbers;
812
	}
4386 anupam.sin 813
 
13361 manish.sha 814
	public void setAwbNumbers(String awbNumbers) {
815
		this.awbNumbers = awbNumbers;
816
	}
4386 anupam.sin 817
 
13361 manish.sha 818
	public List<AwbDetails> getDetailedAWBs() {
819
		return detailedAWBs;
820
	}
4386 anupam.sin 821
 
13361 manish.sha 822
	public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {
823
		this.detailedAWBs = detailedAWBs;
824
	}
4386 anupam.sin 825
 
13361 manish.sha 826
	public String getErrorMsg() {
827
		return errorMsg;
828
	}
4386 anupam.sin 829
 
13361 manish.sha 830
	public void setErrorMsg(String errorMsg) {
831
		this.errorMsg = errorMsg;
832
	}
7792 anupam.sin 833
 
13361 manish.sha 834
	public File getAwbFile() {
835
		return awbFile;
836
	}
7792 anupam.sin 837
 
13361 manish.sha 838
	public void setAwbFile(File awbFile) {
839
		this.awbFile = awbFile;
840
	}
7792 anupam.sin 841
 
13361 manish.sha 842
	public String getAwbFileContentType() {
843
		return awbFileContentType;
844
	}
7792 anupam.sin 845
 
13361 manish.sha 846
	public void setAwbFileContentType(String awbFileContentType) {
847
		this.awbFileContentType = awbFileContentType;
848
	}
7792 anupam.sin 849
 
13361 manish.sha 850
	public String getAwbFileFileName() {
851
		return awbFileFileName;
852
	}
7792 anupam.sin 853
 
13361 manish.sha 854
	public void setAwbFileFileName(String awbFileFileName) {
855
		this.awbFileFileName = awbFileFileName;
856
	}
857
 
858
	public static void main(String[] args) {
859
		//        CourierDetailsController cdc = new CourierDetailsController();
860
		//        cdc.setAwbNumbers("4340987735");
861
		//        String msg = cdc.getAwbDetails();
862
		//        System.out.println(msg);
863
		//        //58539182004
864
		//        //43726980393
865
 
866
		//        String string = "January 2, 2010";
867
		//        Date date = null;
868
		//        Calendar cal = Calendar.getInstance();
869
		//        //cal.set(2014, 0, 20);
870
		//        
871
		//        try {
872
		//            date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(cal.getTime().toString());
873
		//        } catch (ParseException e) {
874
		//            // TODO Auto-generated catch block
875
		//            e.printStackTrace();
876
		//        }
877
		//        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
878
		//        System.out.println(sdf.format(date));
879
 
880
		String[] addresses = "fjdaks\n,24/1,hello".split(",+");
881
		System.out.println(addresses[0].trim());
882
		System.out.println(addresses[1]);
883
		System.out.println(addresses[2]);
884
	}
679 chandransh 885
}