Rev 5814 | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.support.controllers;import in.shop2020.logistics.LogisticsServiceException;import in.shop2020.logistics.PickupStore;import in.shop2020.logistics.Provider;import in.shop2020.model.v1.order.Attribute;import in.shop2020.model.v1.order.LineItem;import in.shop2020.model.v1.order.Order;import in.shop2020.model.v1.order.TransactionService.Client;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.support.utils.ReportsUtils;import in.shop2020.thrift.clients.LogisticsClient;import in.shop2020.thrift.clients.TransactionClient;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.HashMap;import java.util.List;import javax.servlet.ServletContext;import javax.servlet.ServletOutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.DataFormat;import org.apache.poi.ss.usermodel.Font;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.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;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;@Results({@Result(name = "redirect", location = "${redirectUrl}", type = "redirect")})public class PickupStoreController implements ServletResponseAware, ServletRequestAware, ServletContextAware {private static Logger logger = LoggerFactory.getLogger(PickupStoreController.class);private HttpServletRequest request;private HttpServletResponse response;private ServletContext context;private String storeIdString;private long storeId;private String id;private String error = "";private Client client;private String redirectUrl;public PickupStoreController() throws TTransportException{client = (new TransactionClient()).getClient();}@Overridepublic void setServletRequest(HttpServletRequest req) {this.request = req;}public HttpServletRequest getServletRequest() {return request;}@Overridepublic void setServletResponse(HttpServletResponse res) {this.response = res;}public HttpServletResponse getServletResponse() {return response;}@Overridepublic void setServletContext(ServletContext context) {this.context = context;}public String getServletContextPath() {return context.getContextPath();}public String index() throws TTransportException, TException{storeIdString = (String) request.getSession().getAttribute("STORE_ID");if(storeIdString == null){storeIdString = request.getParameter("storeid");if(storeIdString == null){return "authfail";}else{try {storeIdString = Long.toString((new LogisticsClient()).getClient().getPickupStoreByHotspotId(storeIdString).getId());} catch (TTransportException e) {e.printStackTrace();return "authfail";} catch (TException e) {e.printStackTrace();return "authfail";}request.getSession().setAttribute("STORE_ID", storeIdString);}}storeId = Long.parseLong(storeIdString);if(request.getQueryString() != null){redirectUrl = request.getRequestURL().toString();return "redirect";}return "index";}public String show(){if(id.equalsIgnoreCase("admin")){if(!ReportsUtils.canAccessReport((Long)request.getSession().getAttribute(ReportsUtils.ROLE), request.getServletPath())) {return "authfail";}return "admin";}storeIdString = (String) request.getSession().getAttribute("STORE_ID");if(storeIdString == null){storeIdString = request.getParameter("storeid");if(storeIdString == null){return "authfail";}else{try {storeIdString = Long.toString((new LogisticsClient()).getClient().getPickupStoreByHotspotId(storeIdString).getId());} catch (TTransportException e) {e.printStackTrace();return "authfail";} catch (TException e) {e.printStackTrace();return "authfail";}request.getSession().setAttribute("STORE_ID", storeIdString);}}storeId = Long.parseLong(storeIdString);return "show";}// Handles the POST request (Form Submission)public String create() {storeIdString = (String) request.getSession().getAttribute("STORE_ID");if(storeIdString == null){return "authfail";}storeId = Long.parseLong(storeIdString);String orderIdString = request.getParameter("orderid");String action = request.getParameter("action");try {Client client = (new TransactionClient()).getClient();if(action.equals("markreceived")){long orderId = Long.parseLong(orderIdString);client.markOrderAsReceivedAtStore(orderId, Calendar.getInstance().getTimeInMillis());if(!error.equalsIgnoreCase("")){setId("receive");return show();}}else if(action.equals("markrejected")){long orderId = Long.parseLong(orderIdString);Order order = client.getOrder(orderId);String reason = request.getParameter("reason");if(reason == null || reason.isEmpty()){reason = request.getParameter("selectreason");}DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String returnReason = formatter.format(Calendar.getInstance().getTime()) + "|" + reason;HashMap<String, String> orderMap = new HashMap<String, String>();orderMap.put(order.getAirwaybill_no(), returnReason);client.markAsRTOrders(order.getLogistics_provider_id(), orderMap);setId("receive");return show();}else if(action.equals("markdelivered")){long orderId = Long.parseLong(orderIdString);String receiver = request.getParameter("receiver");String secretCode = request.getParameter("secretcode");Order order = client.getOrder(orderId);List<Attribute> attributes = client.getAllAttributesForOrderId(orderId);for(Attribute attribute: attributes){if(attribute.getName().equals("SECRET_CODE")){if(!attribute.getValue().equalsIgnoreCase(secretCode)){error = "Secret code does not match";}}}List<Attribute> newAttributes = new ArrayList<Attribute>();if(order.isCod()){double amount = Double.parseDouble(request.getParameter("amount"));if(order.getTotal_amount()-order.getGvAmount() != amount){error = "<br>Amount does not match";}}if(!error.equalsIgnoreCase("")){setId("deliver");return show();}else{if(order.isCod()){String paymentType = request.getParameter("paymenttype");newAttributes.add(new Attribute("PAYMENT_MODE", paymentType));client.setOrderAttributes(orderId, newAttributes);}}client.markOrderAsDelivered(Long.parseLong(orderIdString), Calendar.getInstance().getTimeInMillis(), receiver);}else if(action.equals("markreturned")){String orderIdsString = request.getParameter("orderIds");long providerId = Long.parseLong(request.getParameter("providerID"));List<Long> orderIds = new ArrayList<Long>();for(String orderIdString1: orderIdsString.split(":")){orderIds.add(Long.parseLong(orderIdString1));}List<String> awbs = new ArrayList<String>();for(String awb: request.getParameter("awbs").split(":")){awbs.add(awb);}client.markOrdersAsReturnedFromStore(providerId, orderIds, awbs);}else if(action.equals("getreport")){String startDateStr = request.getParameter("startDate");String endDateStr = request.getParameter("endDate");DateFormat df = new SimpleDateFormat("dd/MM/yyyy");Date startDate = null, endDate = null;try {startDate = df.parse(startDateStr);endDate = df.parse(endDateStr);Calendar cal = Calendar.getInstance();cal.setTime(endDate);cal.add(Calendar.DATE, 1);endDate.setTime(cal.getTimeInMillis());} catch (ParseException pe) {error = "Please enter start and end dates in format MM/dd/yyyy";}if(!error.equalsIgnoreCase("")){setId("report");return show();}ByteArrayOutputStream baos = generateCollectionReport(startDate, endDate, storeId);if (baos == null) {error = "No output for given date range";} else {error = "Generating report...";}response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "inline; filename=collection-report.xls");ServletOutputStream sos;try {sos = response.getOutputStream();baos.writeTo(sos);sos.flush();error = "Report generated";} catch (IOException e) {error = "Failed to write to response.";logger.error("Unable to stream the colection report", e);}if(!error.equalsIgnoreCase("")){setId("report");return show();}}return "index";} catch (TTransportException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NumberFormatException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TransactionServiceException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (TException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "index";}private ByteArrayOutputStream generateCollectionReport(Date startDate, Date endDate, long storeId) throws TException {List<Order> orders = client.getOrdersCollectionAtStore(storeId, startDate.getTime(), endDate.getTime(), false);ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();Workbook wb = new HSSFWorkbook();DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");Font font = wb.createFont();font.setBoldweight(Font.BOLDWEIGHT_BOLD);CellStyle style = wb.createCellStyle();style.setFont(font);DataFormat format = wb.createDataFormat();CellStyle styleAmount = wb.createCellStyle();styleAmount.setDataFormat(format.getFormat("#,##0.00"));Sheet collectionSheet = wb.createSheet("Collection");short collectionSerialNo = 0;Row headerRow = collectionSheet.createRow(collectionSerialNo++);headerRow.createCell(0).setCellValue("S.No");headerRow.createCell(1).setCellValue("Order Id");headerRow.createCell(2).setCellValue("Product");headerRow.createCell(3).setCellValue("Order Type");headerRow.createCell(4).setCellValue("Collection Date");headerRow.createCell(5).setCellValue("Order Amount");headerRow.createCell(6).setCellValue("Collected Amount");headerRow.createCell(7).setCellValue("Store Margin");for(Order order: orders){Row contentRow = collectionSheet.createRow(collectionSerialNo++);LineItem line = order.getLineitems().get(0);String productName = line.getBrand() + " " + line.getModel_name() + " " + line.getModel_number() + " " + line.getColor();productName = productName.replaceAll("null", "").replaceAll(" ", " ");contentRow.createCell(0).setCellValue(collectionSerialNo-1);contentRow.createCell(1).setCellValue(order.getId());contentRow.createCell(2).setCellValue(productName);contentRow.createCell(3).setCellValue(order.isCod() ? "COD" : "Prepaid");contentRow.createCell(4).setCellValue(formatter.format(order.getDelivery_timestamp()));contentRow.createCell(5).setCellValue(order.getTotal_amount()-order.getGvAmount());contentRow.createCell(6).setCellValue(order.isCod() ? order.getTotal_amount() : 0.0);contentRow.createCell(7).setCellValue(order.isCod() ? .01 * order.getTotal_amount() : .005 * order.getTotal_amount());}try {wb.write(baosXLS);baosXLS.close();} catch (IOException e) {logger.error("Error while streaming payment details report", e);}return baosXLS;}public List<Order> getReceivePendingOrders() throws TException{Client client = (new TransactionClient()).getClient();return client.getReceivePendingOrders(storeId);}public List<Order> getReceivedAtStoreOrders() throws TException{Client client = (new TransactionClient()).getClient();return client.getReceivedAtStoreOrders(storeId);}public String getSecretCode(long orderId) throws TException{List<Attribute> attributes = client.getAllAttributesForOrderId(orderId);String secretCode = "";for(Attribute attribute: attributes){if(attribute.getName().equals("SECRET_CODE") ){secretCode = attribute.getValue();}}return secretCode;}public void setId(String id) {this.id = id;}public String getId() {return id;}public void setError(String error) {this.error = error;}public String getError() {return error;}public long getStoreId(){return storeId;}public String getRedirectUrl(){return redirectUrl;}public List<Provider> getAllProviders() throws TTransportException, LogisticsServiceException, TException{return (new LogisticsClient()).getClient().getAllProviders();}public List<PickupStore> getAllStores() throws TTransportException, TException{return (new LogisticsClient()).getClient().getAllPickupStores();}}