Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
992 varun.gupt 1
package in.shop2020.support.controllers;
2
 
3213 chandransh 3
import in.shop2020.model.v1.catalog.InventoryServiceException;
992 varun.gupt 4
import in.shop2020.model.v1.catalog.Warehouse;
5
import in.shop2020.model.v1.order.LineItem;
6
import in.shop2020.model.v1.order.Order;
7
import in.shop2020.model.v1.order.TransactionServiceException;
2492 ankur.sing 8
import in.shop2020.support.utils.ReportsUtils;
3125 rajveer 9
import in.shop2020.thrift.clients.CatalogClient;
10
import in.shop2020.thrift.clients.TransactionClient;
992 varun.gupt 11
 
12
import java.text.DateFormat;
13
import java.text.SimpleDateFormat;
14
import java.text.ParseException;
15
 
16
import java.io.ByteArrayOutputStream;
17
import java.io.IOException;
18
import java.util.ArrayList;
19
import java.util.Date;
20
import java.util.List;
21
 
2492 ankur.sing 22
import javax.servlet.ServletContext;
992 varun.gupt 23
import javax.servlet.ServletOutputStream;
24
import javax.servlet.http.HttpServletRequest;
25
import javax.servlet.http.HttpServletResponse;
2492 ankur.sing 26
import javax.servlet.http.HttpSession;
992 varun.gupt 27
 
28
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
29
import org.apache.poi.ss.usermodel.Cell;
30
import org.apache.poi.ss.usermodel.CellStyle;
31
import org.apache.poi.ss.usermodel.Font;
32
import org.apache.poi.ss.usermodel.Row;
33
import org.apache.poi.ss.usermodel.Sheet;
34
import org.apache.poi.ss.usermodel.Workbook;
35
import org.apache.poi.ss.util.CellRangeAddress;
2492 ankur.sing 36
import org.apache.struts2.convention.annotation.InterceptorRef;
37
import org.apache.struts2.convention.annotation.InterceptorRefs;
992 varun.gupt 38
import org.apache.struts2.interceptor.ServletRequestAware;
39
import org.apache.struts2.interceptor.ServletResponseAware;
40
import org.apache.struts2.rest.DefaultHttpHeaders;
41
import org.apache.struts2.rest.HttpHeaders;
2492 ankur.sing 42
import org.apache.struts2.util.ServletContextAware;
3213 chandransh 43
import org.apache.thrift.TException;
44
import org.slf4j.Logger;
45
import org.slf4j.LoggerFactory;
992 varun.gupt 46
 
47
/**
48
 * 
49
 * @author Varun Gupta
50
 * @version 1.0
51
 * @description HotspotReconciliationController handles requests to generate a reconciliation
52
 * report in XLS format for all the transactions with HotSpot within a given date range.
53
 * 
54
 */
55
 
2492 ankur.sing 56
@InterceptorRefs({
57
    @InterceptorRef("defaultStack"),
58
    @InterceptorRef("login")
59
})
60
public class HotspotReconciliationController implements ServletResponseAware, ServletRequestAware, ServletContextAware {
61
 
3213 chandransh 62
    private static Logger logger = LoggerFactory.getLogger(HotspotReconciliationController.class);
63
 
2008 chandransh 64
	private enum ReportColumn{
2360 ankur.sing 65
	    ORDER_ID(0),
66
		BILLING_NUMBER(1),
67
		BILLING_DATE(2),
68
		CUSTOMER_NAME(3),
69
		BRAND(4),
70
		MODEL_NAME(5),
71
		MODEL_NUMBER(6),
72
		COLOR(7),
73
		XFER_PRICE(8),
74
		SELLING_PRICE(9);
2008 chandransh 75
 
76
		private int value;
77
 
78
		ReportColumn(int value) {
79
			this.value = value;
80
		}
81
		public int getValue(){
82
			return this.value;
83
		}
84
	}
85
 
1075 chandransh 86
	//FIXME: Read this configuration from the config server
1884 chandransh 87
	//private String hotspotReconciliationReportPath = "/HotspotReports";
992 varun.gupt 88
 
89
	private HttpServletRequest request;
90
	private HttpServletResponse response;
2492 ankur.sing 91
    private HttpSession session;
92
    private ServletContext context;
992 varun.gupt 93
	private String id;
94
 
95
	public HotspotReconciliationController(){
96
 
97
	}
98
 
2492 ankur.sing 99
	public String index() {
100
	    if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath())) {
101
	        return "exception";
102
	    }
103
	    return "report";
992 varun.gupt 104
	}
105
 
106
	// Handles the POST request (Form Submission)
107
	public HttpHeaders create(){
108
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
3213 chandransh 109
 
992 varun.gupt 110
		try	{
111
			//Formatting Form input parameters
3213 chandransh 112
		    Date startDate = dateFormat.parse(request.getParameter("start"));
113
		    Date endDate = dateFormat.parse(request.getParameter("end"));
992 varun.gupt 114
 
3125 rajveer 115
			CatalogClient csc = new CatalogClient();
992 varun.gupt 116
			in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
117
			List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
118
 
3125 rajveer 119
			TransactionClient transactionServiceClient = new TransactionClient();
992 varun.gupt 120
			in.shop2020.model.v1.order.TransactionService.Client client = transactionServiceClient.getClient();
121
 
122
			List <Order> orders = new ArrayList<Order>();
123
 
124
			//Retrieving all the orders across all the warehouses
125
			for(Warehouse warehouse : warehouses)	{
2008 chandransh 126
				orders.addAll(client.getOrdersByBillingDate(null, startDate.getTime(), endDate.getTime(), warehouse.getId()));
992 varun.gupt 127
			}
3213 chandransh 128
			logger.debug("Total number of Orders: " + orders.size());
992 varun.gupt 129
 
130
			// Preparing XLS file for output
131
			response.setContentType("application/vnd.ms-excel");
132
 
133
 
2008 chandransh 134
			DateFormat dateFormatForFile = new SimpleDateFormat("dd.MM.yyyy");
135
			response.setHeader("Content-disposition", "inline; filename=hotspot-reconciliation-from-" + dateFormatForFile.format(startDate) + "-" + dateFormatForFile.format(endDate) + ".xls");
136
 
992 varun.gupt 137
			ServletOutputStream sos;
138
			try {
139
				ByteArrayOutputStream baos = getSpreadSheetData(orders, startDate, endDate);
140
				sos = response.getOutputStream();
141
				baos.writeTo(sos);
142
				sos.flush();
143
			} catch (IOException e) {
3213 chandransh 144
				logger.error("Error while streaming the hotspot reconciliation report", e);
992 varun.gupt 145
			}
146
 
147
		} catch (ParseException e)	{
3213 chandransh 148
			logger.error("Unable to parse the start or end date", e);
992 varun.gupt 149
		} catch (TransactionServiceException e)	{
3213 chandransh 150
			logger.error("Error while getting order information from the transaction service", e);
151
		} catch (InventoryServiceException e) {
152
		    logger.error("Error while getting the list of warehouses from the catalog service", e);
153
        } catch (TException e) {
154
            logger.error("Unable to get the orders or the warehouses", e);
155
        } catch (Exception e)   {
156
            logger.error("Unexpected exception", e);
157
        }
992 varun.gupt 158
		return new DefaultHttpHeaders("report");
159
	}
160
 
161
	// Prepares the XLS worksheet object and fills in the data with proper formatting
162
	private ByteArrayOutputStream getSpreadSheetData(List <Order> orders, Date startDate, Date endDate)	{
163
		ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
164
 
165
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
166
 
167
	    Workbook wb = new HSSFWorkbook();
168
	    Sheet sheet = wb.createSheet("new sheet");
169
	    short serialNo = 0;
170
 
171
	    // Create the header row and put all the titles in it. Rows are 0 based.
172
	    Font font = wb.createFont();
173
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
174
	    CellStyle style = wb.createCellStyle();
175
	    style.setFont(font);
176
 
177
	    Row titleRow = sheet.createRow(serialNo ++);
178
	    Cell titleCell = titleRow.createCell(0);
179
	    titleCell.setCellValue("HotSpot Reconciliation Report (" + dateFormat.format(startDate) + " - " + dateFormat.format(endDate) + ")");
180
	    titleCell.setCellStyle(style);
181
 
182
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
183
 
184
	    sheet.createRow(serialNo ++);
185
 
186
	    Row headerRow = sheet.createRow(serialNo ++);
2360 ankur.sing 187
	    headerRow.createCell(ReportColumn.ORDER_ID.getValue()).setCellValue("Order Id");
2008 chandransh 188
	    headerRow.createCell(ReportColumn.BILLING_NUMBER.getValue()).setCellValue("Billing Number");
189
	    headerRow.createCell(ReportColumn.BILLING_DATE.getValue()).setCellValue("Billing Date");
190
	    headerRow.createCell(ReportColumn.CUSTOMER_NAME.getValue()).setCellValue("Customer Name");
191
	    headerRow.createCell(ReportColumn.BRAND.getValue()).setCellValue("Brand");
192
	    headerRow.createCell(ReportColumn.MODEL_NAME.getValue()).setCellValue("Model Name");
193
	    headerRow.createCell(ReportColumn.MODEL_NUMBER.getValue()).setCellValue("Model Number");
194
	    headerRow.createCell(ReportColumn.COLOR.getValue()).setCellValue("Color");
195
	    headerRow.createCell(ReportColumn.XFER_PRICE.getValue()).setCellValue("Transfer Price");
2011 rajveer 196
	    headerRow.createCell(ReportColumn.SELLING_PRICE.getValue()).setCellValue("Selling Price");
992 varun.gupt 197
 
2014 rajveer 198
	    sheet.createRow(serialNo ++);
992 varun.gupt 199
	    double totalTransferPrice = 0.0;
2011 rajveer 200
	    double totalSellingPrice = 0.0;
992 varun.gupt 201
 
202
	    for(int i = 0; i < orders.size(); i ++)	{
203
	    	Order order = orders.get(i);
2014 rajveer 204
 
205
	    	Row contentRow = sheet.createRow(serialNo++);
992 varun.gupt 206
 
207
		    LineItem lineItem = order.getLineitems().get(0);
208
		    double transferPrice = lineItem.getTransfer_price();
209
		    totalTransferPrice += transferPrice;
210
 
2014 rajveer 211
            double sellingPrice = lineItem.getTotal_price();
212
            totalSellingPrice += sellingPrice;
2011 rajveer 213
 
2360 ankur.sing 214
            contentRow.createCell(ReportColumn.ORDER_ID.getValue()).setCellValue(order.getId());
2008 chandransh 215
		    contentRow.createCell(ReportColumn.BILLING_NUMBER.getValue()).setCellValue(order.getInvoice_number());
216
		    contentRow.createCell(ReportColumn.BILLING_DATE.getValue()).setCellValue(dateFormat.format(new Date(order.getBilling_timestamp())));
217
		    contentRow.createCell(ReportColumn.CUSTOMER_NAME.getValue()).setCellValue(order.getCustomer_name());
218
		    contentRow.createCell(ReportColumn.BRAND.getValue()).setCellValue(getValueForEmptyString(lineItem.getBrand()));
219
		    contentRow.createCell(ReportColumn.MODEL_NAME.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_name()));
220
		    contentRow.createCell(ReportColumn.MODEL_NUMBER.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_number()));
221
		    contentRow.createCell(ReportColumn.COLOR.getValue()).setCellValue(getValueForEmptyString(lineItem.getColor()));
222
		    contentRow.createCell(ReportColumn.XFER_PRICE.getValue()).setCellValue(transferPrice);
2011 rajveer 223
		    contentRow.createCell(ReportColumn.SELLING_PRICE.getValue()).setCellValue(sellingPrice);
992 varun.gupt 224
	    }
225
	    sheet.createRow(serialNo ++);
226
    	Row contentRow = sheet.createRow(serialNo);
227
    	contentRow.createCell(0).setCellValue("Total Transfer Price");
2008 chandransh 228
    	contentRow.createCell(ReportColumn.XFER_PRICE.getValue()).setCellValue(totalTransferPrice);
2011 rajveer 229
    	contentRow.createCell(ReportColumn.SELLING_PRICE.getValue()).setCellValue(totalSellingPrice);
992 varun.gupt 230
    	sheet.addMergedRegion(new CellRangeAddress(serialNo, serialNo, 0, 5));
231
 
232
		// Write the workbook to the output stream
233
		try {
234
			wb.write(baosXLS);
235
			baosXLS.close();
236
		} catch (IOException e) {
3213 chandransh 237
			logger.error("Unable to write the hotspot reconciliation report to the byte array", e);
992 varun.gupt 238
		}		
239
		return baosXLS;
240
	}
241
 
242
	public String getId(){
243
		return id;
244
	}
245
 
246
	public void setId(String id){
247
		this.id = id;
248
	}
249
 
250
	@Override
251
	public void setServletRequest(HttpServletRequest request) {
252
		this.request = request;
2492 ankur.sing 253
		this.session = request.getSession();    
992 varun.gupt 254
	}
255
 
256
	@Override
257
	public void setServletResponse(HttpServletResponse response) {
258
		this.response  = response;
259
	}
260
 
261
	private String getValueForEmptyString(String s){
262
		if(s==null || s.equals(""))
263
			return "-";
264
		else
265
			return s; 
266
	}
2492 ankur.sing 267
	@Override
268
    public void setServletContext(ServletContext context) {
269
        this.context = context;
270
    }
271
 
272
    public String getServletContextPath() {
273
        return context.getContextPath();
274
    }
2011 rajveer 275
}