Subversion Repositories SmartDukaan

Rev

Rev 20257 | 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;
20175 amit.gupta 27
import java.text.DecimalFormat;
7792 anupam.sin 28
import java.text.ParseException;
29
import java.text.SimpleDateFormat;
4386 anupam.sin 30
import java.util.ArrayList;
679 chandransh 31
import java.util.Calendar;
4386 anupam.sin 32
import java.util.Date;
679 chandransh 33
import java.util.GregorianCalendar;
754 chandransh 34
import java.util.HashMap;
35
import java.util.List;
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.CellStyle;
47
import org.apache.poi.ss.usermodel.CreationHelper;
48
import org.apache.poi.ss.usermodel.Row;
49
import org.apache.poi.ss.usermodel.Sheet;
50
import org.apache.poi.ss.usermodel.Workbook;
679 chandransh 51
import org.apache.struts2.interceptor.ServletRequestAware;
52
import org.apache.struts2.interceptor.ServletResponseAware;
1075 chandransh 53
import org.apache.struts2.util.ServletContextAware;
4386 anupam.sin 54
import org.apache.thrift.TException;
55
import org.apache.thrift.transport.TTransportException;
3062 chandransh 56
import org.slf4j.Logger;
57
import org.slf4j.LoggerFactory;
679 chandransh 58
 
2904 chandransh 59
/**
60
 * Allows executives of courier companies to login and download courier details
61
 * report which they then use to upload into their database.
62
 * 
63
 * @author Chandranshu
64
 * 
65
 */
679 chandransh 66
public class CourierDetailsController implements ServletResponseAware,
1075 chandransh 67
		ServletRequestAware, ServletContextAware {
3062 chandransh 68
 
69
    private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);
70
 
7792 anupam.sin 71
    private static final String EMPTY_STRING = "-";
72
 
749 chandransh 73
	private String id;
1075 chandransh 74
	private int daysToSubtract;
756 chandransh 75
 
76
	//FIXME: Read this configuration from the config client
77
	private String courierDetailsPath = "/CourierDetailReports";
78
 
1075 chandransh 79
	private ServletContext context;
679 chandransh 80
	private HttpServletRequest request;
81
	private HttpServletResponse response;
749 chandransh 82
	private HttpSession session;
679 chandransh 83
 
4386 anupam.sin 84
    private String awbNumbers;
85
    private List<AwbDetails> detailedAWBs;
86
 
87
    private String errorMsg = "";
7792 anupam.sin 88
 
89
    private File awbFile;
90
    private String awbFileContentType;
91
    private String awbFileFileName;
4386 anupam.sin 92
 
749 chandransh 93
	public String index(){
94
		if(getSessionUserName()==null)
95
			return "authfail";
96
		else
97
			return "authsuccess";
98
	}
99
 
100
	// Handler for POST /courier-details
101
	public String create(){
102
		String username = request.getParameter("username");
103
		String password = request.getParameter("password");
104
		try{
3125 rajveer 105
			HelperClient helperServiceClient = new HelperClient();
749 chandransh 106
			in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
107
			LogisticsUser user = client.authenticateLogisticsUser(username, password);
108
			session.setAttribute("username", user.getUsername());
109
			session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
110
		}catch(Exception e){
3105 chandransh 111
			logger.error("Error authenticating the user " + username, e);
749 chandransh 112
			return "authfail";
113
		}
114
		return "authsuccess";
679 chandransh 115
	}
116
 
749 chandransh 117
	// Handler for GET /courier-details/<warehouseId>
118
	public String show(){
119
		try {
120
			long warehouseId = Long.parseLong(getId());
4209 rajveer 121
			if(warehouseId == 1){
122
				warehouseId = 0;
123
			}
749 chandransh 124
			long providerId = ((Long)session.getAttribute("providerId")).longValue();
3062 chandransh 125
			boolean isCod;
126
			try {
127
	            isCod = Boolean.parseBoolean(request.getParameter("isCod"));
128
	        } catch (Exception e) {
129
	            isCod = false;
130
	        }
3105 chandransh 131
			logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);
749 chandransh 132
 
3062 chandransh 133
			String deliveryType = "prepaid";
134
			if(isCod)
135
			    deliveryType = "cod";
136
 
749 chandransh 137
			response.setContentType("application/vnd.ms-excel");
138
 
139
			Calendar date = new GregorianCalendar();
1075 chandransh 140
			date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
749 chandransh 141
			int year = date.get(Calendar.YEAR);
7792 anupam.sin 142
			int month = date.get(Calendar.MONTH) + 1;
749 chandransh 143
			int day = date.get(Calendar.DAY_OF_MONTH);
3062 chandransh 144
			String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";
145
			response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );
749 chandransh 146
 
147
			ServletOutputStream sos;
148
			try {
756 chandransh 149
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
3364 chandransh 150
				baos.write(FileUtils.getBytesFromFile(new File(fileName)));
749 chandransh 151
				sos = response.getOutputStream();
152
				baos.writeTo(sos);
153
				sos.flush();
154
			} catch (IOException e) {
3062 chandransh 155
				logger.error("Unable to stream the courier details report", e);
749 chandransh 156
			}	
157
			return "authsuccess";
158
		}catch(NumberFormatException nfe){
3062 chandransh 159
			logger.error("Unable to parse the warehouse id", nfe);
749 chandransh 160
		}
161
		return "authfail";
162
	}
4386 anupam.sin 163
 
164
	/**
7792 anupam.sin 165
	 * Use this method to view details of a given awb number
4386 anupam.sin 166
	 */
7792 anupam.sin 167
	public String viewAwbDetails() {
13361 manish.sha 168
		if(awbNumbers.isEmpty()) {
169
			setErrorMsg("Field cannot be empty");
170
			return "info";
171
		}
172
		String [] awbArray = awbNumbers.split(",");
173
		createAwbDetailList(awbArray);
174
		return "info";
7792 anupam.sin 175
	}
176
 
177
	/**
13361 manish.sha 178
	 * Use this method to download details of given comma separated list of awb numbers
179
	 */
180
 
7792 anupam.sin 181
	public String getAwbDetails() {
13361 manish.sha 182
		if(awbNumbers.isEmpty()) {
183
			setErrorMsg("Field cannot be empty");
184
			return "info";
185
		}
186
		String [] awbArray = awbNumbers.split(",");
187
		createAwbDetailList(awbArray);
188
		ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
189
		response.setContentType("application/vnd.ms-excel");
190
		response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
191
		ServletOutputStream sos;
192
		try {
193
			sos = response.getOutputStream();
194
			baos.writeTo(sos);
195
			sos.flush();
196
		} catch (IOException e) {
197
			logger.error("Encountered error while sending invoice response: ", e);
198
		}
199
		return "info";
200
	}
201
 
7792 anupam.sin 202
	/**
13361 manish.sha 203
	 * Use this method to download details of given list of awb numbers uploaded in a text file
204
	 */
205
 
7792 anupam.sin 206
	public String getAwbDetailsByFile() {
13361 manish.sha 207
		if(awbFile == null) {
208
			return null;
209
		}
7792 anupam.sin 210
 
13361 manish.sha 211
		List<String> awbList = new ArrayList<String>();
7792 anupam.sin 212
 
13361 manish.sha 213
		try {
214
			BufferedReader in = new BufferedReader(new FileReader(awbFile));
215
			String line;
216
			while((line = in.readLine()) != null) {
217
				awbList.add(line.trim());
218
			}
219
		} catch (FileNotFoundException e1) {
220
			logger.error("File not found", e1);
221
			return null;
222
		} catch (IOException e) {
223
			logger.error("Unable to read file", e);
224
			return null;
225
		}
7792 anupam.sin 226
 
13361 manish.sha 227
		String[] awbArray  = awbList.toArray(new String [awbList.size()]);
228
		createAwbDetailList(awbArray);
229
 
230
		ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);
231
		response.setContentType("application/vnd.ms-excel");
232
		response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");
233
		ServletOutputStream sos;
234
		try {
235
			sos = response.getOutputStream();
236
			baos.writeTo(sos);
237
			sos.flush();
238
		} catch (IOException e) {
239
			logger.error("Encountered error while sending invoice response: ", e);
240
		}
241
		return "info";
7792 anupam.sin 242
	}
16284 manish.sha 243
 
244
	private String getItemDisplayName(LineItem lineitem, boolean appendIMEI){
245
		StringBuffer itemName = new StringBuffer();
246
		if(lineitem.getBrand()!= null)
247
			itemName.append(lineitem.getBrand() + " ");
248
		if(lineitem.getModel_name() != null)
249
			itemName.append(lineitem.getModel_name() + " ");
250
		if(lineitem.getModel_number() != null )
251
			itemName.append(lineitem.getModel_number() + " ");
252
		if(lineitem.getColor() != null && !lineitem.getColor().trim().equals("NA"))
253
			itemName.append("("+lineitem.getColor()+")");
254
		if(appendIMEI && lineitem.isSetSerial_number()){
255
			itemName.append("\nIMEI No. " + lineitem.getSerial_number());
256
		}
7792 anupam.sin 257
 
16284 manish.sha 258
		return itemName.toString();
259
	}
260
 
13361 manish.sha 261
	private void createAwbDetailList(String[] awbArray) {
20175 amit.gupta 262
		DecimalFormat df = new DecimalFormat("#.##");
13361 manish.sha 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){
17470 manish.sha 349
			    		totalAmount = totalAmount + (o.getTotal_amount()+o.getShippingCost()+o.getCodCharges()-o.getGvAmount());
16284 manish.sha 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());
20175 amit.gupta 410
					detailedAwb.setPacketWeight(df.format(Math.max(totalWeight, 0.01d)));
16284 manish.sha 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);
20258 amit.gupta 600
		int i = 0;
20257 amit.gupta 601
		headerRow.createCell(i++).setCellValue("Airwaybill");
602
		headerRow.createCell(i++).setCellValue("Type"); //Values : "COD" / "NONCOD"
603
		headerRow.createCell(i++).setCellValue("Reference Number"); //OrderId
604
		headerRow.createCell(i++).setCellValue("Sender / Store name"); //"Spice Online retail pvt ltd"
605
		headerRow.createCell(i++).setCellValue("attention"); //Customer name
606
		headerRow.createCell(i++).setCellValue("address1"); //Line 1
607
		headerRow.createCell(i++).setCellValue("address2"); //Line 2
608
		headerRow.createCell(i++).setCellValue("address3"); //city + state
609
		headerRow.createCell(i++).setCellValue("pincode");
610
		headerRow.createCell(i++).setCellValue("tel number"); //Empty
611
		headerRow.createCell(i++).setCellValue("mobile number"); //Empty
612
		headerRow.createCell(i++).setCellValue("Prod/SKU code");  //ItemId
613
		headerRow.createCell(i++).setCellValue("contents"); //Product name
614
		headerRow.createCell(i++).setCellValue("weight");  //In Kgs
615
		headerRow.createCell(i++).setCellValue("Declared Value");  
616
		headerRow.createCell(i++).setCellValue("Collectable Value");
617
		headerRow.createCell(i++).setCellValue("Vendor Code");
618
		headerRow.createCell(i++).setCellValue("Shipper Name");  
619
		headerRow.createCell(i++).setCellValue("Return Address1");
620
		headerRow.createCell(i++).setCellValue("Return Address2");
621
		headerRow.createCell(i++).setCellValue("Return Address3");
622
		headerRow.createCell(i++).setCellValue("Return Pin");
623
		headerRow.createCell(i++).setCellValue("Length ( Cms )");
624
		headerRow.createCell(i++).setCellValue("Bredth ( Cms )");
625
		headerRow.createCell(i++).setCellValue("Height ( Cms )");
626
		headerRow.createCell(i++).setCellValue("Pieces");       
627
		headerRow.createCell(i++).setCellValue("Area_customer_code");
628
		headerRow.createCell(i++).setCellValue("Handover Date ( DD/MM/YYYY )");
629
		headerRow.createCell(i++).setCellValue("Handover Time ( 24 hrs format )");
13361 manish.sha 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);
20258 amit.gupta 643
			i=0;
20257 amit.gupta 644
			contentRow.createCell(i++).setCellValue(awbDetail.getAwbNumber());
645
			contentRow.createCell(i++).setCellValue(awbDetail.getPaymentMode().equals("COD") ? "COD" : "NONCOD");
646
			contentRow.createCell(i++).setCellValue(awbDetail.getMasterOrderId());
647
			contentRow.createCell(i++).setCellValue("Hotspot Sales & Solutions Pvt Ltd");
648
			contentRow.createCell(i++).setCellValue(awbDetail.getCustomerName());
649
			contentRow.createCell(i++).setCellValue(awbDetail.getAddress1());
650
			contentRow.createCell(i++).setCellValue(awbDetail.getAddress2());
651
			contentRow.createCell(i++).setCellValue(awbDetail.getCity() + ", " + awbDetail.getState());
652
			contentRow.createCell(i++).setCellValue(awbDetail.getPinCode());
653
			contentRow.createCell(i++).setCellValue(awbDetail.getPhoneNumber());
654
			contentRow.createCell(i++).setCellValue(awbDetail.getPhoneNumber());
655
			contentRow.createCell(i++).setCellValue(awbDetail.getItemId());
656
			contentRow.createCell(i++).setCellValue(awbDetail.getProductName());
657
			contentRow.createCell(i++).setCellValue(awbDetail.getPacketWeight());
658
			contentRow.createCell(i++).setCellValue(awbDetail.getShipmentValue());
659
			contentRow.createCell(i++).setCellValue(awbDetail.getAmountToCollect());
660
			contentRow.createCell(i++).setCellValue(awbDetail.getVendorCode());
661
			contentRow.createCell(i++).setCellValue("Hotspot Sales & Solutions Pvt Ltd"); 
662
			contentRow.createCell(i++).setCellValue(awbDetail.getReturnAddress1());
663
			contentRow.createCell(i++).setCellValue(awbDetail.getReturnAddress2());
664
			contentRow.createCell(i++).setCellValue(awbDetail.getReturnAddress3());
665
			contentRow.createCell(i++).setCellValue(awbDetail.getReturnPin());
666
			contentRow.createCell(i++).setCellValue(CourierDetailsController.EMPTY_STRING);
667
			contentRow.createCell(i++).setCellValue(CourierDetailsController.EMPTY_STRING);
668
			contentRow.createCell(i++).setCellValue(CourierDetailsController.EMPTY_STRING);
669
			contentRow.createCell(i++).setCellValue("1");
670
			contentRow.createCell(i++).setCellValue(awbDetail.getAccountCode());
13361 manish.sha 671
 
672
			Date date = null;
673
			SimpleDateFormat sdf4Date = new SimpleDateFormat("dd/MM/yyyy");                
674
			SimpleDateFormat sdf4Time = new SimpleDateFormat("HHmm");
675
 
676
			if(!awbDetail.getAwbDate().equals("N/A")) {
677
				try {
678
					date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(awbDetail.getAwbDate());
679
				} catch (ParseException e) {
680
					// TODO Auto-generated catch block
681
					e.printStackTrace();
682
				}
683
				contentRow.createCell(28).setCellValue(sdf4Date.format(date));
684
				contentRow.createCell(29).setCellValue(sdf4Time.format(date));
685
			} else {
686
				contentRow.createCell(28).setCellValue("N/A");
687
				contentRow.createCell(29).setCellValue("N/A");
688
			}
689
 
690
 
691
 
692
			/**
693
			 * According to javadoc of Date, Date.toString() converts a Date object to a String of the form:
694
			 * 
7792 anupam.sin 695
                 dow mon dd hh:mm:ss zzz yyyy
696
 
697
            where:
698
 
13361 manish.sha 699
			 * dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
700
			 * mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
701
			 * dd is the day of the month (01 through 31), as two decimal digits.
702
			 * hh is the hour of the day (00 through 23), as two decimal digits.
703
			 * mm is the minute within the hour (00 through 59), as two decimal digits.
704
			 * ss is the second within the minute (00 through 61, as two decimal digits.
705
			 * 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.
706
			 * yyyy is the year, as four decimal digits. 
707
			 * 
708
			 * And we need to send this in format DD/MM/YYYY and time in HHMM
709
			 */
710
		}
711
 
712
		try {
713
			wb.write(baos);
714
			baos.close();
715
		} catch (IOException e) {
716
			// TODO Auto-generated catch block
717
			e.printStackTrace();
718
		}
719
		return baos;
4386 anupam.sin 720
	}
721
 
13361 manish.sha 722
 
723
	/**
4386 anupam.sin 724
	 * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
725
	 * Should be used to view day before yesterday's courier details report.
726
	 * 
13361 manish.sha 727
	 * @return the same string tokens as show
728
	 */
1075 chandransh 729
	public String dayBefore(){
730
		daysToSubtract = -2;
731
		return show();
732
	}
3105 chandransh 733
 
13361 manish.sha 734
	/**
735
	 * Sets the daysToSubtract to -1 and then invokes the standard show()
736
	 * handler. Should be used to view yesterday's courier details report.
737
	 * 
738
	 * @return the same string tokens as show
739
	 */
1075 chandransh 740
	public String yesterday(){
741
		daysToSubtract = -1;
742
		return show();
743
	}
3105 chandransh 744
 
13361 manish.sha 745
	/**
746
	 * Sets the daysToSubtract to 0 and then invokes the standard show()
747
	 * handler. Should be used to view today's courier details report.
748
	 * 
749
	 * @return the same string tokens as show
750
	 */
1075 chandransh 751
	public String today(){
752
		daysToSubtract = 0;
753
		return show();
754
	}
13361 manish.sha 755
 
679 chandransh 756
	@Override
1075 chandransh 757
	public void setServletContext(ServletContext context) {
758
		this.context = context;
759
	}
13361 manish.sha 760
 
1075 chandransh 761
	@Override
679 chandransh 762
	public void setServletResponse(HttpServletResponse response) {
763
		this.response  = response;
764
	}
765
 
766
	@Override
767
	public void setServletRequest(HttpServletRequest request) {
768
		this.request = request;
749 chandransh 769
		this.session = request.getSession();
679 chandransh 770
	}
771
 
749 chandransh 772
	public String getId(){
773
		return id;
774
	}
13361 manish.sha 775
 
749 chandransh 776
	public void setId(String id){
777
		this.id = id;
778
	}
13361 manish.sha 779
 
749 chandransh 780
	public String getSessionUserName(){
781
		return (String) session.getAttribute("username");
782
	}
3105 chandransh 783
 
13361 manish.sha 784
	/**
785
	 * Gets the list of all warehouses and maps the warehouse ids to their
786
	 * display name.
787
	 * 
788
	 * @return the mapping of warehouse if to its display namee
789
	 */
754 chandransh 790
	public Map<Long, String> getWarehouses(){
791
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
792
		try{
5945 mandeep.dh 793
			InventoryClient isc = new InventoryClient();
794
			in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient= isc.getClient();
795
			List<Warehouse> warehouses = inventoryClient.getShippingLocations();
754 chandransh 796
			for(Warehouse warehouse : warehouses){
797
				warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
798
			}
799
		}catch(Exception e){
3105 chandransh 800
			logger.error("Error getting the list of warehouses", e);
754 chandransh 801
		}
802
		return warehouseMap;
803
	}
749 chandransh 804
 
1075 chandransh 805
	public String getServletContextPath(){
806
		return context.getContextPath();
807
	}
4386 anupam.sin 808
 
13361 manish.sha 809
	public String getAwbNumbers() {
810
		return awbNumbers;
811
	}
4386 anupam.sin 812
 
13361 manish.sha 813
	public void setAwbNumbers(String awbNumbers) {
814
		this.awbNumbers = awbNumbers;
815
	}
4386 anupam.sin 816
 
13361 manish.sha 817
	public List<AwbDetails> getDetailedAWBs() {
818
		return detailedAWBs;
819
	}
4386 anupam.sin 820
 
13361 manish.sha 821
	public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {
822
		this.detailedAWBs = detailedAWBs;
823
	}
4386 anupam.sin 824
 
13361 manish.sha 825
	public String getErrorMsg() {
826
		return errorMsg;
827
	}
4386 anupam.sin 828
 
13361 manish.sha 829
	public void setErrorMsg(String errorMsg) {
830
		this.errorMsg = errorMsg;
831
	}
7792 anupam.sin 832
 
13361 manish.sha 833
	public File getAwbFile() {
834
		return awbFile;
835
	}
7792 anupam.sin 836
 
13361 manish.sha 837
	public void setAwbFile(File awbFile) {
838
		this.awbFile = awbFile;
839
	}
7792 anupam.sin 840
 
13361 manish.sha 841
	public String getAwbFileContentType() {
842
		return awbFileContentType;
843
	}
7792 anupam.sin 844
 
13361 manish.sha 845
	public void setAwbFileContentType(String awbFileContentType) {
846
		this.awbFileContentType = awbFileContentType;
847
	}
7792 anupam.sin 848
 
13361 manish.sha 849
	public String getAwbFileFileName() {
850
		return awbFileFileName;
851
	}
7792 anupam.sin 852
 
13361 manish.sha 853
	public void setAwbFileFileName(String awbFileFileName) {
854
		this.awbFileFileName = awbFileFileName;
855
	}
856
 
857
	public static void main(String[] args) {
858
		//        CourierDetailsController cdc = new CourierDetailsController();
859
		//        cdc.setAwbNumbers("4340987735");
860
		//        String msg = cdc.getAwbDetails();
861
		//        System.out.println(msg);
862
		//        //58539182004
863
		//        //43726980393
864
 
865
		//        String string = "January 2, 2010";
866
		//        Date date = null;
867
		//        Calendar cal = Calendar.getInstance();
868
		//        //cal.set(2014, 0, 20);
869
		//        
870
		//        try {
871
		//            date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(cal.getTime().toString());
872
		//        } catch (ParseException e) {
873
		//            // TODO Auto-generated catch block
874
		//            e.printStackTrace();
875
		//        }
876
		//        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
877
		//        System.out.println(sdf.format(date));
878
 
879
		String[] addresses = "fjdaks\n,24/1,hello".split(",+");
880
		System.out.println(addresses[0].trim());
881
		System.out.println(addresses[1]);
882
		System.out.println(addresses[2]);
883
	}
679 chandransh 884
}