Subversion Repositories SmartDukaan

Rev

Rev 4956 | 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
 
5945 mandeep.dh 3
import in.shop2020.model.v1.inventory.InventoryServiceException;
4
import in.shop2020.model.v1.inventory.Warehouse;
992 varun.gupt 5
import in.shop2020.model.v1.order.LineItem;
6
import in.shop2020.model.v1.order.Order;
4139 chandransh 7
import in.shop2020.model.v1.order.ReturnOrder;
992 varun.gupt 8
import in.shop2020.model.v1.order.TransactionServiceException;
5945 mandeep.dh 9
import in.shop2020.thrift.clients.InventoryClient;
3125 rajveer 10
import in.shop2020.thrift.clients.TransactionClient;
992 varun.gupt 11
 
5945 mandeep.dh 12
import java.io.ByteArrayOutputStream;
13
import java.io.IOException;
992 varun.gupt 14
import java.text.DateFormat;
5945 mandeep.dh 15
import java.text.ParseException;
992 varun.gupt 16
import java.text.SimpleDateFormat;
17
import java.util.ArrayList;
18
import java.util.Date;
19
import java.util.List;
20
 
2492 ankur.sing 21
import javax.servlet.ServletContext;
992 varun.gupt 22
import javax.servlet.ServletOutputStream;
23
import javax.servlet.http.HttpServletRequest;
24
import javax.servlet.http.HttpServletResponse;
2492 ankur.sing 25
import javax.servlet.http.HttpSession;
992 varun.gupt 26
 
27
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
28
import org.apache.poi.ss.usermodel.Cell;
29
import org.apache.poi.ss.usermodel.CellStyle;
30
import org.apache.poi.ss.usermodel.Font;
31
import org.apache.poi.ss.usermodel.Row;
32
import org.apache.poi.ss.usermodel.Sheet;
33
import org.apache.poi.ss.usermodel.Workbook;
34
import org.apache.poi.ss.util.CellRangeAddress;
2492 ankur.sing 35
import org.apache.struts2.convention.annotation.InterceptorRef;
36
import org.apache.struts2.convention.annotation.InterceptorRefs;
3936 chandransh 37
import org.apache.struts2.convention.annotation.Result;
38
import org.apache.struts2.convention.annotation.Results;
992 varun.gupt 39
import org.apache.struts2.interceptor.ServletRequestAware;
40
import org.apache.struts2.interceptor.ServletResponseAware;
41
import org.apache.struts2.rest.DefaultHttpHeaders;
42
import org.apache.struts2.rest.HttpHeaders;
2492 ankur.sing 43
import org.apache.struts2.util.ServletContextAware;
3213 chandransh 44
import org.apache.thrift.TException;
45
import org.slf4j.Logger;
46
import org.slf4j.LoggerFactory;
992 varun.gupt 47
 
48
/**
49
 * 
50
 * @author Varun Gupta
51
 * @version 1.0
52
 * @description HotspotReconciliationController handles requests to generate a reconciliation
53
 * report in XLS format for all the transactions with HotSpot within a given date range.
54
 * 
55
 */
56
 
4956 varun.gupt 57
@InterceptorRefs({
58
    @InterceptorRef("defaultStack"),
59
    @InterceptorRef("login")
60
})
3936 chandransh 61
@Results({
4956 varun.gupt 62
    @Result(name="authfail", type="redirectAction", params = {"actionName" , "reports"})
3936 chandransh 63
})
2492 ankur.sing 64
public class HotspotReconciliationController implements ServletResponseAware, ServletRequestAware, ServletContextAware {
65
 
3213 chandransh 66
    private static Logger logger = LoggerFactory.getLogger(HotspotReconciliationController.class);
67
 
4139 chandransh 68
	private enum OrderReportColumn {
2360 ankur.sing 69
	    ORDER_ID(0),
70
		BILLING_NUMBER(1),
71
		BILLING_DATE(2),
72
		CUSTOMER_NAME(3),
73
		BRAND(4),
74
		MODEL_NAME(5),
75
		MODEL_NUMBER(6),
76
		COLOR(7),
77
		XFER_PRICE(8),
4600 varun.gupt 78
		SELLING_PRICE(9),
79
		DELIVERY_DATE(10),
80
		STATUS(11);
2008 chandransh 81
 
82
		private int value;
83
 
4139 chandransh 84
		OrderReportColumn(int value) {
2008 chandransh 85
			this.value = value;
86
		}
87
		public int getValue(){
88
			return this.value;
89
		}
90
	}
91
 
4139 chandransh 92
	private enum ReturnOrderReportColumn {
93
		ORDER_ID(0),
94
		WAREHOUSE_ID(1),
95
		INVOICE_NUMBER(2),
96
		PRODUCT_GROUP(3),
97
		BRAND(4),
98
		MODEL_NUMBER(5),
99
		COLOR(6),
100
		CREATED_ON(7),
101
		XFER_PRICE(8);
102
 
103
		private int value;
104
 
105
		ReturnOrderReportColumn(int value) {
106
			this.value = value;
107
		}
108
		public int getValue(){
109
			return this.value;
110
		}
111
	}
112
 
1075 chandransh 113
	//FIXME: Read this configuration from the config server
1884 chandransh 114
	//private String hotspotReconciliationReportPath = "/HotspotReports";
992 varun.gupt 115
 
116
	private HttpServletRequest request;
117
	private HttpServletResponse response;
2492 ankur.sing 118
    private HttpSession session;
119
    private ServletContext context;
992 varun.gupt 120
	private String id;
121
 
4139 chandransh 122
	private final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
123
 
992 varun.gupt 124
	public HotspotReconciliationController(){
125
 
126
	}
127
 
2492 ankur.sing 128
	public String index() {
4295 varun.gupt 129
//	    if(!ReportsUtils.canAccessReport((Long)session.getAttribute(ReportsUtils.ROLE), request.getServletPath())) {
130
//	        return "authfail";
131
//	    }
2492 ankur.sing 132
	    return "report";
992 varun.gupt 133
	}
134
 
135
	// Handles the POST request (Form Submission)
136
	public HttpHeaders create(){
137
		DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
3213 chandransh 138
 
992 varun.gupt 139
		try	{
140
			//Formatting Form input parameters
3213 chandransh 141
		    Date startDate = dateFormat.parse(request.getParameter("start"));
142
		    Date endDate = dateFormat.parse(request.getParameter("end"));
992 varun.gupt 143
 
5945 mandeep.dh 144
			InventoryClient csc = new InventoryClient();
145
			in.shop2020.model.v1.inventory.InventoryService.Client catalogClient = csc.getClient();
992 varun.gupt 146
			List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
147
 
3125 rajveer 148
			TransactionClient transactionServiceClient = new TransactionClient();
992 varun.gupt 149
			in.shop2020.model.v1.order.TransactionService.Client client = transactionServiceClient.getClient();
150
 
4139 chandransh 151
			List<Order> orders = new ArrayList<Order>();
152
			List<ReturnOrder> returnOrders = new ArrayList<ReturnOrder>();
992 varun.gupt 153
 
154
			//Retrieving all the orders across all the warehouses
4139 chandransh 155
			long fromTime = startDate.getTime();
156
			long toTime = endDate.getTime();
992 varun.gupt 157
			for(Warehouse warehouse : warehouses)	{
4139 chandransh 158
				orders.addAll(client.getOrdersByBillingDate(null, fromTime, toTime, warehouse.getId()));
159
				returnOrders.addAll(client.getReturnOrders(warehouse.getId(), fromTime, toTime));
992 varun.gupt 160
			}
3213 chandransh 161
			logger.debug("Total number of Orders: " + orders.size());
992 varun.gupt 162
 
163
			// Preparing XLS file for output
164
			response.setContentType("application/vnd.ms-excel");
165
 
2008 chandransh 166
			DateFormat dateFormatForFile = new SimpleDateFormat("dd.MM.yyyy");
167
			response.setHeader("Content-disposition", "inline; filename=hotspot-reconciliation-from-" + dateFormatForFile.format(startDate) + "-" + dateFormatForFile.format(endDate) + ".xls");
168
 
992 varun.gupt 169
			ServletOutputStream sos;
170
			try {
4139 chandransh 171
				ByteArrayOutputStream baos = getReconciliationReport(orders, returnOrders, startDate, endDate);
992 varun.gupt 172
				sos = response.getOutputStream();
173
				baos.writeTo(sos);
174
				sos.flush();
175
			} catch (IOException e) {
3213 chandransh 176
				logger.error("Error while streaming the hotspot reconciliation report", e);
992 varun.gupt 177
			}
178
 
179
		} catch (ParseException e)	{
3213 chandransh 180
			logger.error("Unable to parse the start or end date", e);
992 varun.gupt 181
		} catch (TransactionServiceException e)	{
3213 chandransh 182
			logger.error("Error while getting order information from the transaction service", e);
183
		} catch (InventoryServiceException e) {
184
		    logger.error("Error while getting the list of warehouses from the catalog service", e);
185
        } catch (TException e) {
186
            logger.error("Unable to get the orders or the warehouses", e);
187
        } catch (Exception e)   {
188
            logger.error("Unexpected exception", e);
189
        }
4600 varun.gupt 190
		return new DefaultHttpHeaders("report1");
992 varun.gupt 191
	}
192
 
193
	// Prepares the XLS worksheet object and fills in the data with proper formatting
4139 chandransh 194
	private ByteArrayOutputStream getReconciliationReport(List<Order> orders, List<ReturnOrder> returnOrders, Date startDate, Date endDate)	{
992 varun.gupt 195
		ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
196
 
4139 chandransh 197
	    Workbook wb = new HSSFWorkbook();	    
992 varun.gupt 198
 
4139 chandransh 199
	    //Create the style for the title row
992 varun.gupt 200
	    Font font = wb.createFont();
201
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
4139 chandransh 202
	    CellStyle boldStyle = wb.createCellStyle();
203
	    boldStyle.setFont(font);
992 varun.gupt 204
 
4139 chandransh 205
	    CellStyle rightAlignStyle = wb.createCellStyle();
206
	    rightAlignStyle.setAlignment(CellStyle.ALIGN_RIGHT);
207
 
208
		Sheet orderSheet = wb.createSheet("Orders");
209
		Sheet returnSheet = wb.createSheet("Returns");
210
 
211
	    populateOrderSheet(orders, startDate, endDate, orderSheet, boldStyle, rightAlignStyle);
212
	    populateReturnOrderSheet(returnOrders, startDate, endDate, returnSheet, boldStyle, rightAlignStyle);
213
 
214
		// Write the workbook to the output stream
215
		try {
216
			wb.write(baosXLS);
217
			baosXLS.close();
218
		} catch (IOException e) {
219
			logger.error("Unable to write the hotspot reconciliation report to the byte array", e);
220
		}		
221
		return baosXLS;
222
	}
223
 
224
	private void populateOrderSheet(List<Order> orders, Date startDate, Date endDate, Sheet sheet, CellStyle style, CellStyle rightAlignStyle) {
225
	    short serialNo = 0;
226
 
227
	    // Create the title row and put all the titles in it. Rows are 0 based.
992 varun.gupt 228
	    Row titleRow = sheet.createRow(serialNo ++);
229
	    Cell titleCell = titleRow.createCell(0);
4139 chandransh 230
	    titleCell.setCellValue("Order Reconciliation Report (" + DATE_FORMAT.format(startDate) + " - " + DATE_FORMAT.format(endDate) + ")");
992 varun.gupt 231
	    titleCell.setCellStyle(style);
232
 
233
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
234
 
235
	    sheet.createRow(serialNo ++);
236
 
237
	    Row headerRow = sheet.createRow(serialNo ++);
4139 chandransh 238
	    headerRow.createCell(OrderReportColumn.ORDER_ID.getValue()).setCellValue("Order Id");
239
	    headerRow.createCell(OrderReportColumn.BILLING_NUMBER.getValue()).setCellValue("Billing Number");
240
	    headerRow.createCell(OrderReportColumn.BILLING_DATE.getValue()).setCellValue("Billing Date");
241
	    headerRow.createCell(OrderReportColumn.CUSTOMER_NAME.getValue()).setCellValue("Customer Name");
242
	    headerRow.createCell(OrderReportColumn.BRAND.getValue()).setCellValue("Brand");
243
	    headerRow.createCell(OrderReportColumn.MODEL_NAME.getValue()).setCellValue("Model Name");
244
	    headerRow.createCell(OrderReportColumn.MODEL_NUMBER.getValue()).setCellValue("Model Number");
245
	    headerRow.createCell(OrderReportColumn.COLOR.getValue()).setCellValue("Color");
246
	    headerRow.createCell(OrderReportColumn.XFER_PRICE.getValue()).setCellValue("Transfer Price");
247
	    headerRow.createCell(OrderReportColumn.SELLING_PRICE.getValue()).setCellValue("Selling Price");
4600 varun.gupt 248
	    headerRow.createCell(OrderReportColumn.DELIVERY_DATE.getValue()).setCellValue("Delivery Date");
249
	    headerRow.createCell(OrderReportColumn.STATUS.getValue()).setCellValue("Current Status");
992 varun.gupt 250
 
2014 rajveer 251
	    sheet.createRow(serialNo ++);
992 varun.gupt 252
	    double totalTransferPrice = 0.0;
2011 rajveer 253
	    double totalSellingPrice = 0.0;
992 varun.gupt 254
 
4139 chandransh 255
	    for(Order order : orders)	{
2014 rajveer 256
	    	Row contentRow = sheet.createRow(serialNo++);
992 varun.gupt 257
 
258
		    LineItem lineItem = order.getLineitems().get(0);
259
		    double transferPrice = lineItem.getTransfer_price();
260
		    totalTransferPrice += transferPrice;
261
 
2014 rajveer 262
            double sellingPrice = lineItem.getTotal_price();
263
            totalSellingPrice += sellingPrice;
2011 rajveer 264
 
4139 chandransh 265
            contentRow.createCell(OrderReportColumn.ORDER_ID.getValue()).setCellValue(order.getId());
266
		    contentRow.createCell(OrderReportColumn.BILLING_NUMBER.getValue()).setCellValue(order.getInvoice_number());
267
		    contentRow.createCell(OrderReportColumn.BILLING_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getBilling_timestamp())));
268
		    contentRow.createCell(OrderReportColumn.CUSTOMER_NAME.getValue()).setCellValue(order.getCustomer_name());
269
		    contentRow.createCell(OrderReportColumn.BRAND.getValue()).setCellValue(getValueForEmptyString(lineItem.getBrand()));
270
		    contentRow.createCell(OrderReportColumn.MODEL_NAME.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_name()));
271
		    contentRow.createCell(OrderReportColumn.MODEL_NUMBER.getValue()).setCellValue(getValueForEmptyString(lineItem.getModel_number()));
272
		    contentRow.createCell(OrderReportColumn.COLOR.getValue()).setCellValue(getValueForEmptyString(lineItem.getColor()));
273
		    contentRow.createCell(OrderReportColumn.XFER_PRICE.getValue()).setCellValue(transferPrice);
274
		    contentRow.createCell(OrderReportColumn.SELLING_PRICE.getValue()).setCellValue(sellingPrice);
4600 varun.gupt 275
 
276
		    if(order.getDelivery_timestamp() > 0)	{
277
		    	contentRow.createCell(OrderReportColumn.DELIVERY_DATE.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getDelivery_timestamp())));
278
		    } else	{
279
		    	contentRow.createCell(OrderReportColumn.DELIVERY_DATE.getValue()).setCellValue("-");
280
		    }
281
		    contentRow.createCell(OrderReportColumn.STATUS.getValue()).setCellValue(order.getStatus().name());
992 varun.gupt 282
	    }
283
	    sheet.createRow(serialNo ++);
284
    	Row contentRow = sheet.createRow(serialNo);
285
    	contentRow.createCell(0).setCellValue("Total Transfer Price");
4139 chandransh 286
    	contentRow.createCell(OrderReportColumn.XFER_PRICE.getValue()).setCellValue(totalTransferPrice);
287
    	contentRow.createCell(OrderReportColumn.SELLING_PRICE.getValue()).setCellValue(totalSellingPrice);
992 varun.gupt 288
    	sheet.addMergedRegion(new CellRangeAddress(serialNo, serialNo, 0, 5));
4139 chandransh 289
	}
290
 
291
	private void populateReturnOrderSheet(List<ReturnOrder> returnOrders, Date startDate, Date endDate, Sheet sheet, CellStyle titleStyle, CellStyle rightAlignStyle) {
292
	    short serialNo = 0;
293
 
294
	    // Create the title row and put all the titles in it. Rows are 0 based.
295
	    Row titleRow = sheet.createRow(serialNo ++);
296
	    Cell titleCell = titleRow.createCell(0);
297
	    titleCell.setCellValue("Return Orders Reconciliation Report (" + DATE_FORMAT.format(startDate) + " - " + DATE_FORMAT.format(endDate) + ")");
298
	    titleCell.setCellStyle(titleStyle);
299
	    sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
300
 
301
	    // Create the header row
302
	    sheet.createRow(serialNo ++);	    
303
	    Row headerRow = sheet.createRow(serialNo ++);
304
	    headerRow.createCell(ReturnOrderReportColumn.ORDER_ID.getValue()).setCellValue("Order Id");
305
	    headerRow.createCell(ReturnOrderReportColumn.WAREHOUSE_ID.getValue()).setCellValue("Warehouse Id");
306
	    headerRow.createCell(ReturnOrderReportColumn.INVOICE_NUMBER.getValue()).setCellValue("Invoice Number");
307
	    headerRow.createCell(ReturnOrderReportColumn.PRODUCT_GROUP.getValue()).setCellValue("Product Group");
308
	    headerRow.createCell(ReturnOrderReportColumn.BRAND.getValue()).setCellValue("Brand");
309
	    headerRow.createCell(ReturnOrderReportColumn.MODEL_NUMBER.getValue()).setCellValue("Model Number");
310
	    headerRow.createCell(ReturnOrderReportColumn.COLOR.getValue()).setCellValue("Color");
311
	    headerRow.createCell(ReturnOrderReportColumn.CREATED_ON.getValue()).setCellValue("Created On");
312
	    headerRow.createCell(ReturnOrderReportColumn.XFER_PRICE.getValue()).setCellValue("Transfer Price");
313
 
314
 
315
	    // Create an empty row
316
	    sheet.createRow(serialNo ++);
317
 
318
	    double totalTransferPrice = 0.0;
319
	    for(ReturnOrder order : returnOrders)	{
320
	    	Row contentRow = sheet.createRow(serialNo++);
321
		    double transferPrice = order.getTransferPrice();
322
		    totalTransferPrice += transferPrice;
323
 
324
    	    contentRow.createCell(ReturnOrderReportColumn.ORDER_ID.getValue()).setCellValue(order.getOrderId());
325
    	    contentRow.createCell(ReturnOrderReportColumn.WAREHOUSE_ID.getValue()).setCellValue(order.getWarehouseId());
326
    	    contentRow.createCell(ReturnOrderReportColumn.INVOICE_NUMBER.getValue()).setCellValue(order.getInvoiceNumber());
327
    	    contentRow.createCell(ReturnOrderReportColumn.PRODUCT_GROUP.getValue()).setCellValue(order.getProductGroup());
328
    	    contentRow.createCell(ReturnOrderReportColumn.BRAND.getValue()).setCellValue(order.getBrand());
329
    	    contentRow.createCell(ReturnOrderReportColumn.MODEL_NUMBER.getValue()).setCellValue(order.getModelNumber());
330
    	    contentRow.createCell(ReturnOrderReportColumn.COLOR.getValue()).setCellValue(order.getColor());
331
    	    contentRow.createCell(ReturnOrderReportColumn.CREATED_ON.getValue()).setCellValue(DATE_FORMAT.format(new Date(order.getCreatedAt())));
332
    	    contentRow.createCell(ReturnOrderReportColumn.XFER_PRICE.getValue()).setCellValue(transferPrice);
333
	    }
334
	    sheet.createRow(serialNo ++);
335
    	Row contentRow = sheet.createRow(serialNo);
336
    	Cell totalCell = contentRow.createCell(0);
337
    	totalCell.setCellValue("Total Transfer Price");
338
    	totalCell.setCellStyle(rightAlignStyle);
992 varun.gupt 339
 
4139 chandransh 340
    	contentRow.createCell(ReturnOrderReportColumn.XFER_PRICE.getValue()).setCellValue(totalTransferPrice);
341
    	sheet.addMergedRegion(new CellRangeAddress(serialNo, serialNo, 0, ReturnOrderReportColumn.CREATED_ON.getValue()));
992 varun.gupt 342
	}
343
 
344
	public String getId(){
345
		return id;
346
	}
347
 
348
	public void setId(String id){
349
		this.id = id;
350
	}
351
 
352
	@Override
353
	public void setServletRequest(HttpServletRequest request) {
354
		this.request = request;
2492 ankur.sing 355
		this.session = request.getSession();    
992 varun.gupt 356
	}
357
 
358
	@Override
359
	public void setServletResponse(HttpServletResponse response) {
360
		this.response  = response;
361
	}
362
 
363
	private String getValueForEmptyString(String s){
364
		if(s==null || s.equals(""))
365
			return "-";
366
		else
367
			return s; 
368
	}
2492 ankur.sing 369
	@Override
370
    public void setServletContext(ServletContext context) {
371
        this.context = context;
372
    }
373
 
374
    public String getServletContextPath() {
375
        return context.getContextPath();
376
    }
2011 rajveer 377
}