Subversion Repositories SmartDukaan

Rev

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