Rev 8128 | Rev 13361 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.support.controllers;import in.shop2020.logistics.DeliveryType;import in.shop2020.logistics.LogisticsServiceException;import in.shop2020.logistics.PickupStore;import in.shop2020.logistics.Provider;import in.shop2020.logistics.ProviderDetails;import in.shop2020.model.v1.inventory.InventoryServiceException;import in.shop2020.model.v1.inventory.Warehouse;import in.shop2020.model.v1.order.LineItem;import in.shop2020.model.v1.order.Order;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.support.models.AwbDetails;import in.shop2020.support.utils.FileUtils;import in.shop2020.thrift.clients.HelperClient;import in.shop2020.thrift.clients.InventoryClient;import in.shop2020.thrift.clients.LogisticsClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.utils.LogisticsUser;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;import javax.servlet.ServletContext;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.commons.lang.StringUtils;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.struts2.interceptor.ServletRequestAware;import org.apache.struts2.interceptor.ServletResponseAware;import org.apache.struts2.util.ServletContextAware;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/*** Allows executives of courier companies to login and download courier details* report which they then use to upload into their database.** @author Chandranshu**/public class CourierDetailsController implements ServletResponseAware,ServletRequestAware, ServletContextAware {private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);private static final String EMPTY_STRING = "-";private String id;private int daysToSubtract;//FIXME: Read this configuration from the config clientprivate String courierDetailsPath = "/CourierDetailReports";private ServletContext context;private HttpServletRequest request;private HttpServletResponse response;private HttpSession session;private String awbNumbers;private List<AwbDetails> detailedAWBs;private String errorMsg = "";private File awbFile;private String awbFileContentType;private String awbFileFileName;public String index(){if(getSessionUserName()==null)return "authfail";elsereturn "authsuccess";}// Handler for POST /courier-detailspublic String create(){String username = request.getParameter("username");String password = request.getParameter("password");try{HelperClient helperServiceClient = new HelperClient();in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();LogisticsUser user = client.authenticateLogisticsUser(username, password);session.setAttribute("username", user.getUsername());session.setAttribute("providerId", Long.valueOf(user.getProviderId()));}catch(Exception e){logger.error("Error authenticating the user " + username, e);return "authfail";}return "authsuccess";}// Handler for GET /courier-details/<warehouseId>public String show(){try {long warehouseId = Long.parseLong(getId());if(warehouseId == 1){warehouseId = 0;}long providerId = ((Long)session.getAttribute("providerId")).longValue();boolean isCod;try {isCod = Boolean.parseBoolean(request.getParameter("isCod"));} catch (Exception e) {isCod = false;}logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);String deliveryType = "prepaid";if(isCod)deliveryType = "cod";response.setContentType("application/vnd.ms-excel");Calendar date = new GregorianCalendar();date.add(Calendar.DAY_OF_MONTH, daysToSubtract);int year = date.get(Calendar.YEAR);int month = date.get(Calendar.MONTH) + 1;int day = date.get(Calendar.DAY_OF_MONTH);String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );ServletOutputStream sos;try {ByteArrayOutputStream baos = new ByteArrayOutputStream();baos.write(FileUtils.getBytesFromFile(new File(fileName)));sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {logger.error("Unable to stream the courier details report", e);}return "authsuccess";}catch(NumberFormatException nfe){logger.error("Unable to parse the warehouse id", nfe);}return "authfail";}/*** Use this method to view details of a given awb number*/public String viewAwbDetails() {if(awbNumbers.isEmpty()) {setErrorMsg("Field cannot be empty");return "info";}String [] awbArray = awbNumbers.split(",");createAwbDetailList(awbArray);return "info";}/*** Use this method to download details of given comma separated list of awb numbers*/public String getAwbDetails() {if(awbNumbers.isEmpty()) {setErrorMsg("Field cannot be empty");return "info";}String [] awbArray = awbNumbers.split(",");createAwbDetailList(awbArray);ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");ServletOutputStream sos;try {sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {logger.error("Encountered error while sending invoice response: ", e);}return "info";}/*** Use this method to download details of given list of awb numbers uploaded in a text file*/public String getAwbDetailsByFile() {if(awbFile == null) {return null;}List<String> awbList = new ArrayList<String>();try {BufferedReader in = new BufferedReader(new FileReader(awbFile));String line;while((line = in.readLine()) != null) {awbList.add(line.trim());}} catch (FileNotFoundException e1) {logger.error("File not found", e1);return null;} catch (IOException e) {logger.error("Unable to read file", e);return null;}String[] awbArray = awbList.toArray(new String [awbList.size()]);createAwbDetailList(awbArray);ByteArrayOutputStream baos = generateAwbDetailsSheet(this.detailedAWBs);response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "inline; filename=awbDetails-" + Calendar.getInstance().getTime().toString() + ".xls");ServletOutputStream sos;try {sos = response.getOutputStream();baos.writeTo(sos);sos.flush();} catch (IOException e) {logger.error("Encountered error while sending invoice response: ", e);}return "info";}private void createAwbDetailList(String[] awbArray) {Order order = null;List<AwbDetails> tempList = new ArrayList<AwbDetails>() ;for(String awbNumber : awbArray) {try {LogisticsClient lsc = new LogisticsClient();TransactionClient tsc = new TransactionClient();InventoryClient isc = new InventoryClient();in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient = isc.getClient();in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();/** Get required stuff* FIXME: Reduce service calls*/logger.info("Session : " + session);logger.info("provider Id : " + ((Long)session.getAttribute("providerId")).longValue());Provider provider = logisticsClient.getProvider(((Long)session.getAttribute("providerId")).longValue());order = txnClient.getOrderForAwb(awbNumber);Warehouse warehouse = inventoryClient.getWarehouse(order.getWarehouse_id());String accountNo = "";DeliveryType dt = DeliveryType.PREPAID;if (order.isLogisticsCod()) {dt = DeliveryType.COD;}for (ProviderDetails detail : provider.getDetails()) {if(in.shop2020.model.v1.inventory.WarehouseLocation.findByValue((int) detail.getLogisticLocation()) == warehouse.getLogisticsLocation() && detail.getDeliveryType() == dt) {accountNo = detail.getAccountNo();}}AwbDetails detailedAwb = new AwbDetails();String[] addresses = warehouse.getLocation().split(",+");detailedAwb.setReturnAddress1((addresses[0].trim() + ", " + addresses[1].trim()).replace("\n", ", "));detailedAwb.setReturnAddress2((addresses[2].trim() + (addresses.length > 3 ? ", " + addresses[3].trim() : "")).replace("\n", ", "));String line3 = "";if(addresses.length > 4) {for(int i = 4; i<addresses.length; i++) {line3 += addresses[i] + ", ";}}if(StringUtils.isNotEmpty(line3)) {detailedAwb.setReturnAddress3(line3.trim().replace("\n", ", "));} else {detailedAwb.setReturnAddress3(EMPTY_STRING);}detailedAwb.setReturnPin(warehouse.getPincode());detailedAwb.setAwbNumber(awbNumber);detailedAwb.setAccountCode(accountNo);detailedAwb.setVendorCode((int) order.getWarehouse_id());if(order.isLogisticsCod()){detailedAwb.setAmountToCollect("" + (order.getTotal_amount()-order.getGvAmount()-order.getAdvanceAmount()));} else {detailedAwb.setAmountToCollect("" + 0 );}if(order.getShipping_timestamp() > 0) {Date date = new Date(order.getShipping_timestamp());detailedAwb.setAwbDate(date.toString());} else {detailedAwb.setAwbDate("N/A");}if(order.getPickupStoreId() > 0) {PickupStore store = lsc.getClient().getPickupStore(order.getPickupStoreId());detailedAwb.setAddress1(store.getLine1());detailedAwb.setAddress2(store.getLine2());detailedAwb.setCity(store.getCity());detailedAwb.setCustomerName("Spice Hotspot");detailedAwb.setPhoneNumber("" + store.getPhone());detailedAwb.setPinCode(store.getPin());detailedAwb.setState(store.getState());} else {detailedAwb.setAddress1(order.getCustomer_address1());detailedAwb.setAddress2(order.getCustomer_address2());detailedAwb.setCity(order.getCustomer_city());detailedAwb.setCustomerName(order.getCustomer_name());detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());detailedAwb.setPinCode(order.getCustomer_pincode());detailedAwb.setState(order.getCustomer_state());}detailedAwb.setItemId("" + order.getLineitems().get(0).getItem_id());detailedAwb.setOrderId("" + order.getId());detailedAwb.setPacketWeight("" + order.getTotal_weight());if(order.isLogisticsCod()){detailedAwb.setPaymentMode("COD");} else {detailedAwb.setPaymentMode("Prepaid");}detailedAwb.setPickupLocation(warehouse.getLocation());LineItem lineitem = order.getLineitems().get(0);detailedAwb.setProductName(lineitem.getBrand() + " "+ (lineitem.getModel_name() == null ? "" : lineitem.getModel_name()) + " "+ (lineitem.getModel_number() == null ? "" : lineitem.getModel_number()) + " "+ (lineitem.getColor() == null ? "" : lineitem.getColor()));if (order.getFreebieItemId() > 0) {//If order has a freebie order attached with itdetailedAwb.setShipmentValue("" + (order.getTotal_amount()));} else {//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//so we set the transfer price as shipment valueif (lineitem.getExtra_info() != null && lineitem.getExtra_info().contains("Freebie Order for Order ID")) {detailedAwb.setShipmentValue("" + (lineitem.getTransfer_price()));} else {//Else set total amountdetailedAwb.setShipmentValue("" + (order.getTotal_amount()));}}tempList.add(detailedAwb);} catch (TTransportException e) {setErrorMsg("Your request cannot be processed due to technical error. Please try later.");} catch (TException e) {setErrorMsg(e.getMessage());} catch (TransactionServiceException e) {setErrorMsg(e.getMessage());} catch (LogisticsServiceException e) {setErrorMsg(e.getMessage());} catch (InventoryServiceException e) {setErrorMsg(e.getMessage());}}setDetailedAWBs(tempList);}public ByteArrayOutputStream generateAwbDetailsSheet(List<AwbDetails> awbDetailList) {ByteArrayOutputStream baos = new ByteArrayOutputStream();;Workbook wb = new HSSFWorkbook();CreationHelper createHelper = wb.getCreationHelper();Sheet sheet = wb.createSheet("Saholic - Data");CellStyle dateCellStyle = wb.createCellStyle();dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yyyy"));CellStyle weightStyle = wb.createCellStyle();weightStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.000"));Row headerRow = sheet.createRow((short)0);headerRow.createCell(0).setCellValue("Airwaybill");headerRow.createCell(1).setCellValue("Type"); //Values : "COD" / "NONCOD"headerRow.createCell(2).setCellValue("Reference Number"); //OrderIdheaderRow.createCell(3).setCellValue("Sender / Store name"); //"Spice Online retail pvt ltd"headerRow.createCell(4).setCellValue("attention"); //Customer nameheaderRow.createCell(5).setCellValue("address1"); //Line 1headerRow.createCell(6).setCellValue("address2"); //Line 2headerRow.createCell(7).setCellValue("address3"); //city + stateheaderRow.createCell(8).setCellValue("pincode");headerRow.createCell(9).setCellValue("tel number"); //EmptyheaderRow.createCell(10).setCellValue("mobile number"); //EmptyheaderRow.createCell(11).setCellValue("Prod/SKU code"); //ItemIdheaderRow.createCell(12).setCellValue("contents"); //Product nameheaderRow.createCell(13).setCellValue("weight"); //In KgsheaderRow.createCell(14).setCellValue("Declared Value");headerRow.createCell(15).setCellValue("Collectable Value");headerRow.createCell(16).setCellValue("Vendor Code");headerRow.createCell(17).setCellValue("Shipper Name");headerRow.createCell(18).setCellValue("Return Address1");headerRow.createCell(19).setCellValue("Return Address2");headerRow.createCell(20).setCellValue("Return Address3");headerRow.createCell(21).setCellValue("Return Pin");headerRow.createCell(22).setCellValue("Length ( Cms )");headerRow.createCell(23).setCellValue("Bredth ( Cms )");headerRow.createCell(24).setCellValue("Height ( Cms )");headerRow.createCell(25).setCellValue("Pieces");headerRow.createCell(26).setCellValue("Area_customer_code");headerRow.createCell(27).setCellValue("Handover Date ( DD/MM/YYYY )");headerRow.createCell(28).setCellValue("Handover Time ( 24 hrs format )");int serialNo = 0;for(AwbDetails awbDetail : awbDetailList) {// 0 Airwaybill 1 Type 2 Reference Number 3 Sender / Store name 4 attention 5 address1 6 address2 7 address3// 8 pincode 9 tel number 10 mobile number 11 Prod/SKU code 12 contents 13 weight// 14 Declared Value 15 Collectable Value// 16 Vendor Code 17 Shipper Name 18 Return Address1 19 Return Address2 20 Return Address3 21 Return Pin// 22 Length ( Cms ) 23 Breadth ( Cms ) 24 Height ( Cms )// 25 Pieces 26 Area_customer_code 27 Handover Date ( DD/MM/YYYY ) 28 Handover Time ( 24 hrs format )serialNo++;Row contentRow = sheet.createRow((short)serialNo);contentRow.createCell(0).setCellValue(awbDetail.getAwbNumber());contentRow.createCell(1).setCellValue(awbDetail.getPaymentMode().equals("COD") ? "COD" : "NONCOD");contentRow.createCell(2).setCellValue(awbDetail.getOrderId());contentRow.createCell(3).setCellValue("Spice Online Retail Pvt Ltd");contentRow.createCell(4).setCellValue(awbDetail.getCustomerName());contentRow.createCell(5).setCellValue(awbDetail.getAddress1());contentRow.createCell(6).setCellValue(awbDetail.getAddress2());contentRow.createCell(7).setCellValue(awbDetail.getCity() + ", " + awbDetail.getState());contentRow.createCell(8).setCellValue(awbDetail.getPinCode());contentRow.createCell(9).setCellValue(awbDetail.getPhoneNumber());contentRow.createCell(10).setCellValue(awbDetail.getPhoneNumber());contentRow.createCell(11).setCellValue(awbDetail.getItemId());contentRow.createCell(12).setCellValue(awbDetail.getProductName());contentRow.createCell(13).setCellValue(awbDetail.getPacketWeight());contentRow.createCell(14).setCellValue(awbDetail.getShipmentValue());contentRow.createCell(15).setCellValue(awbDetail.getAmountToCollect());contentRow.createCell(16).setCellValue(awbDetail.getVendorCode());contentRow.createCell(17).setCellValue("Spice Online Retail Pvt Ltd");contentRow.createCell(18).setCellValue(awbDetail.getReturnAddress1());contentRow.createCell(19).setCellValue(awbDetail.getReturnAddress2());contentRow.createCell(20).setCellValue(awbDetail.getReturnAddress3());contentRow.createCell(21).setCellValue(awbDetail.getReturnPin());contentRow.createCell(22).setCellValue(CourierDetailsController.EMPTY_STRING);contentRow.createCell(23).setCellValue(CourierDetailsController.EMPTY_STRING);contentRow.createCell(24).setCellValue(CourierDetailsController.EMPTY_STRING);contentRow.createCell(25).setCellValue("1");contentRow.createCell(26).setCellValue(awbDetail.getAccountCode());Date date = null;SimpleDateFormat sdf4Date = new SimpleDateFormat("dd/MM/yyyy");SimpleDateFormat sdf4Time = new SimpleDateFormat("HHmm");if(!awbDetail.getAwbDate().equals("N/A")) {try {date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(awbDetail.getAwbDate());} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}contentRow.createCell(27).setCellValue(sdf4Date.format(date));contentRow.createCell(28).setCellValue(sdf4Time.format(date));} else {contentRow.createCell(27).setCellValue("N/A");contentRow.createCell(28).setCellValue("N/A");}/*** According to javadoc of Date, Date.toString() converts a Date object to a String of the form:*dow mon dd hh:mm:ss zzz yyyywhere:* dow is the day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).* mon is the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).* dd is the day of the month (01 through 31), as two decimal digits.* hh is the hour of the day (00 through 23), as two decimal digits.* mm is the minute within the hour (00 through 59), as two decimal digits.* ss is the second within the minute (00 through 61, as two decimal digits.* 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.* yyyy is the year, as four decimal digits.** And we need to send this in format DD/MM/YYYY and time in HHMM*/}try {wb.write(baos);baos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return baos;}/*** Sets the daysToSubtract to -2 and then invokes the standard show() handler.* Should be used to view day before yesterday's courier details report.** @return the same string tokens as show*/public String dayBefore(){daysToSubtract = -2;return show();}/*** Sets the daysToSubtract to -1 and then invokes the standard show()* handler. Should be used to view yesterday's courier details report.** @return the same string tokens as show*/public String yesterday(){daysToSubtract = -1;return show();}/*** Sets the daysToSubtract to 0 and then invokes the standard show()* handler. Should be used to view today's courier details report.** @return the same string tokens as show*/public String today(){daysToSubtract = 0;return show();}@Overridepublic void setServletContext(ServletContext context) {this.context = context;}@Overridepublic void setServletResponse(HttpServletResponse response) {this.response = response;}@Overridepublic void setServletRequest(HttpServletRequest request) {this.request = request;this.session = request.getSession();}public String getId(){return id;}public void setId(String id){this.id = id;}public String getSessionUserName(){return (String) session.getAttribute("username");}/*** Gets the list of all warehouses and maps the warehouse ids to their* display name.** @return the mapping of warehouse if to its display namee*/public Map<Long, String> getWarehouses(){Map<Long, String> warehouseMap = new HashMap<Long, String>();try{InventoryClient isc = new InventoryClient();in.shop2020.model.v1.inventory.InventoryService.Client inventoryClient= isc.getClient();List<Warehouse> warehouses = inventoryClient.getShippingLocations();for(Warehouse warehouse : warehouses){warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());}}catch(Exception e){logger.error("Error getting the list of warehouses", e);}return warehouseMap;}public String getServletContextPath(){return context.getContextPath();}public String getAwbNumbers() {return awbNumbers;}public void setAwbNumbers(String awbNumbers) {this.awbNumbers = awbNumbers;}public List<AwbDetails> getDetailedAWBs() {return detailedAWBs;}public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {this.detailedAWBs = detailedAWBs;}public String getErrorMsg() {return errorMsg;}public void setErrorMsg(String errorMsg) {this.errorMsg = errorMsg;}public File getAwbFile() {return awbFile;}public void setAwbFile(File awbFile) {this.awbFile = awbFile;}public String getAwbFileContentType() {return awbFileContentType;}public void setAwbFileContentType(String awbFileContentType) {this.awbFileContentType = awbFileContentType;}public String getAwbFileFileName() {return awbFileFileName;}public void setAwbFileFileName(String awbFileFileName) {this.awbFileFileName = awbFileFileName;}public static void main(String[] args) {// CourierDetailsController cdc = new CourierDetailsController();// cdc.setAwbNumbers("4340987735");// String msg = cdc.getAwbDetails();// System.out.println(msg);// //58539182004// //43726980393// String string = "January 2, 2010";// Date date = null;// Calendar cal = Calendar.getInstance();// //cal.set(2014, 0, 20);//// try {// date = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse(cal.getTime().toString());// } catch (ParseException e) {// // TODO Auto-generated catch block// e.printStackTrace();// }// SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");// System.out.println(sdf.format(date));String[] addresses = "fjdaks\n,24/1,hello".split(",+");System.out.println(addresses[0].trim());System.out.println(addresses[1]);System.out.println(addresses[2]);}}