Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1895 vikas 1
package in.shop2020.support.controllers;
2
 
3
import in.shop2020.model.v1.catalog.Item;
4
import in.shop2020.model.v1.order.Transaction;
5
import in.shop2020.model.v1.order.TransactionServiceException;
6
import in.shop2020.model.v1.order.TransactionStatus;
7
import in.shop2020.model.v1.user.Address;
8
import in.shop2020.model.v1.user.Cart;
9
import in.shop2020.model.v1.user.Line;
3213 chandransh 10
import in.shop2020.model.v1.user.ShoppingCartException;
1895 vikas 11
import in.shop2020.model.v1.user.User;
12
import in.shop2020.model.v1.user.UserContextService.Client;
3125 rajveer 13
import in.shop2020.thrift.clients.CatalogClient;
14
import in.shop2020.thrift.clients.TransactionClient;
15
import in.shop2020.thrift.clients.UserClient;
1895 vikas 16
 
17
import java.io.ByteArrayOutputStream;
18
import java.io.IOException;
19
import java.text.ParseException;
20
import java.util.Calendar;
21
import java.util.Date;
22
import java.util.HashMap;
23
import java.util.Iterator;
24
import java.util.LinkedList;
25
import java.util.List;
26
import java.util.Map;
27
 
28
import javax.servlet.ServletOutputStream;
29
import javax.servlet.http.HttpServletResponse;
30
 
31
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
32
import org.apache.poi.ss.usermodel.Cell;
33
import org.apache.poi.ss.usermodel.CellStyle;
34
import org.apache.poi.ss.usermodel.CreationHelper;
35
import org.apache.poi.ss.usermodel.Font;
36
import org.apache.poi.ss.usermodel.Row;
37
import org.apache.poi.ss.usermodel.Sheet;
38
import org.apache.poi.ss.usermodel.Workbook;
39
import org.apache.poi.ss.util.CellRangeAddress;
40
import org.apache.struts2.interceptor.ServletResponseAware;
3213 chandransh 41
import org.apache.thrift.TException;
42
import org.slf4j.Logger;
43
import org.slf4j.LoggerFactory;
1895 vikas 44
 
2904 chandransh 45
/**
46
 * Provides reports about carts created in last 15 days. Also provides data
47
 * about transactions created for a cart.
48
 * 
49
 * @author Ankur Singhal
50
 * 
51
 */
1895 vikas 52
public class CartReportController implements ServletResponseAware{
53
 
3213 chandransh 54
    private static Logger logger = LoggerFactory.getLogger(CartReportController.class);
55
 
1895 vikas 56
	private HttpServletResponse response;
57
 
58
	private String errorMsg = "";
59
 
60
	@Override
61
	public void setServletResponse(HttpServletResponse res) {
62
		this.response = res;
63
	}
64
 
65
	public void index(){
66
		try	{
3125 rajveer 67
			TransactionClient transactionServiceClient = new TransactionClient();
1895 vikas 68
			in.shop2020.model.v1.order.TransactionService.Client transactionClient = transactionServiceClient.getClient();
69
 
3125 rajveer 70
			UserClient userContextServiceClient = new UserClient();
1895 vikas 71
			Client userClient = userContextServiceClient.getClient();
72
 
73
			// get carts created in last 15 days.
74
			Date now = new Date();
75
			Date from = new Date();
76
			Calendar c = Calendar.getInstance();
77
		    c.setTime(from);
78
		    c.add(Calendar.DATE, -15);
79
		    from.setTime(c.getTime().getTime());
80
 
81
		    List<Cart> carts = userClient.getCartsByTime(from.getTime(), now.getTime(), null);
82
		    System.out.println("Total carts : " + carts.size());
83
		    Map<Long, Transaction> cartToTransactionMap = new HashMap<Long, Transaction>();
84
            for (Iterator<Cart> itr = carts.iterator(); itr.hasNext();) {
85
			    Cart cart = itr.next();
86
			    if (cart.getCheckedOutOn() == 0) {
87
			        itr.remove();
88
			    }
89
			    else {
90
			        List<Transaction> cartTransactions = transactionClient.getTransactionsForShoppingCartId(cart.getId());
91
			        long cartTime = cart.getCheckedOutOn();
92
			        for (Transaction t : cartTransactions) {
93
			            long tTime = t.getCreatedOn();
94
			            if (tTime > cartTime && ((tTime - cartTime)/(60 * 1000) < 30)) { // transaction with in 30 min of checkout
95
			                if (t.getTransactionStatus() == TransactionStatus.IN_PROCESS || t.getTransactionStatus() == TransactionStatus.FAILED) {
96
			                    itr.remove();
97
			                }
98
			                else {
99
			                    if (cartToTransactionMap.containsKey(cart.getId())) {
100
                                    if (cartToTransactionMap.get(cart.getId()).getCreatedOn() > t.getCreatedOn()) 
101
                                    {
102
                                        cartToTransactionMap.put(cart.getId(),t);
103
                                    }
104
			                    }
105
			                    else {
106
			                        cartToTransactionMap.put(cart.getId(),t);
107
			                    }
108
			                }
109
			            }
110
			        }
111
			    }
112
			}
113
            System.out.println("Checked out carts with unsuccessful payment : " + carts.size());
114
 
115
			// Preparing XLS file for output
116
			response.setContentType("application/vnd.ms-excel");
117
 
118
			response.setHeader("Content-disposition", "inline; filename=cart-report" + ".xls");
119
 
120
			ServletOutputStream sos;
121
			try {
122
				ByteArrayOutputStream baos = getSpreadSheetData(carts, cartToTransactionMap, userClient);
123
				sos = response.getOutputStream();
124
				baos.writeTo(sos);
125
				sos.flush();
126
			} catch (IOException e) {
127
				errorMsg = "Failed to write to response.";
3213 chandransh 128
				logger.error("Unable to stream the cart report", e);
1895 vikas 129
			}
130
 
131
		} catch (ParseException e)	{
3213 chandransh 132
		    logger.error("Unable to parse the start or end date", e);
133
		    errorMsg = e.getMessage();
1895 vikas 134
		} catch (TransactionServiceException e)	{
3213 chandransh 135
		    logger.error("Error while getting transaction info", e);
1895 vikas 136
			errorMsg = e.getMessage();
3213 chandransh 137
		} catch (ShoppingCartException e) {
138
		    logger.error("Error while getting cart date", e);
139
            errorMsg = e.getMessage();
140
        } catch (TException e) {
141
            logger.error("Unable to get order or cart data", e);
142
            errorMsg = e.getMessage();
143
        } catch (Exception e)   {
144
            logger.error("Unexpected exception", e);
145
            errorMsg = e.getMessage();
146
        }
1895 vikas 147
	}
148
 
149
	// Prepares the XLS worksheet object and fills in the data with proper formatting
150
    private ByteArrayOutputStream getSpreadSheetData(List<Cart> carts,
151
            Map<Long, Transaction> cartToTransactionMap, Client userClient)
152
            throws Exception 
153
	{
154
	    ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
155
 
156
		Workbook wb = new HSSFWorkbook();
157
 
158
	    Font font = wb.createFont();
159
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
160
	    CellStyle style = wb.createCellStyle();
161
	    style.setFont(font);
162
 
163
	    CreationHelper createHelper = wb.getCreationHelper();
164
	    CellStyle dateCellStyle = wb.createCellStyle();
165
	    dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("DD/MM/YYYY HH:MM"));
166
 
167
	    createCartSheet(carts, cartToTransactionMap, userClient, wb, style, dateCellStyle);
168
 
169
		// Write the workbook to the output stream
170
		try {
171
			wb.write(baosXLS);
172
			baosXLS.close();
173
		} catch (IOException e) {
3213 chandransh 174
			logger.error("Unable to convert the cart report to byte array", e);
1895 vikas 175
		}		
176
		return baosXLS;
177
	}
178
 
179
    private void createCartSheet(List<Cart> carts,
180
            Map<Long, Transaction> cartToTransactionMap, Client userClient,
181
            Workbook wb, CellStyle style, CellStyle dateCellStyle)
182
            throws Exception 
183
    {
184
        CellStyle styleWT = wb.createCellStyle();
185
        styleWT.setWrapText(true);
3125 rajveer 186
	    CatalogClient catalogServiceClient = new CatalogClient();
1895 vikas 187
        in.shop2020.model.v1.catalog.InventoryService.Client catalogClient = catalogServiceClient.getClient();
188
 
189
		// CART SHEET
190
	    Sheet cartSheet = wb.createSheet("Cart");
191
	    short cartSerialNo = 0;
192
 
193
	    List<Cart> noAddressCarts = new LinkedList<Cart>();
194
	    List<Cart> noPaymentCarts = new LinkedList<Cart>();
195
	    List<Cart> otherCarts = new LinkedList<Cart>();
196
	    for (Cart cart : carts) {
197
	        if (cart.getAddressId() == 0) {
198
	            noAddressCarts.add(cart);
199
	        }
200
	        else if (!cartToTransactionMap.containsKey(cart.getId())) {
201
	            noPaymentCarts.add(cart);
202
	        }
203
	        else {
204
	            otherCarts.add(cart);
205
	        }
206
	    }
207
	    List<Cart> orderedCarts = new LinkedList<Cart>();
208
	    orderedCarts.addAll(noAddressCarts);
209
	    orderedCarts.addAll(noPaymentCarts);
210
	    orderedCarts.addAll(otherCarts);
211
 
212
	    Row cartTitleRow = cartSheet.createRow(cartSerialNo ++);
213
	    Cell cartTitleCell = cartTitleRow.createCell(0);
214
	    cartTitleCell.setCellValue("User Cart Conversions");
215
	    cartTitleCell.setCellStyle(style);
216
 
217
	    cartSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
218
 
219
	    cartSheet.createRow(cartSerialNo ++);
220
 
221
	    Row cartHeaderRow = cartSheet.createRow(cartSerialNo ++);
222
	    cartHeaderRow.createCell(0).setCellValue("Cart Id");
223
	    cartHeaderRow.createCell(1).setCellValue("Cart Address");
224
	    cartHeaderRow.getCell(1).setCellStyle(styleWT);
225
	    cartHeaderRow.createCell(2).setCellValue("Checked out date");
226
	    cartHeaderRow.createCell(3).setCellValue("Transaction Date");
227
        cartHeaderRow.createCell(4).setCellValue("Transaction Status");
228
	    cartHeaderRow.createCell(5).setCellValue("Created On");
229
	    cartHeaderRow.createCell(6).setCellValue("Item size");
230
	    cartHeaderRow.createCell(7).setCellValue("Updated On");
231
	    cartHeaderRow.createCell(8).setCellValue("Cart Status");
232
	    cartHeaderRow.createCell(9).setCellValue("Cart Items");
233
	    cartHeaderRow.createCell(10).setCellValue("User Id");
234
	    cartHeaderRow.createCell(11).setCellValue("Comm Email");
235
	    cartHeaderRow.createCell(12).setCellValue("Date Of Birth");
236
	    cartHeaderRow.createCell(13).setCellValue("Mobile");
237
	    cartHeaderRow.createCell(14).setCellValue("Name");
238
 
239
	    for (int i=0; i<15 ;i++) {
240
            cartHeaderRow.getCell(i).setCellStyle(style);
241
        }
242
 
243
	    int addrColWidth = 35;
244
        cartSheet.setColumnWidth(1, 256 * addrColWidth); // set width of address column to 35 characters
245
	    for(Cart cart : orderedCarts)	{
246
	        cartSerialNo ++;
247
	        Row contentRow = cartSheet.createRow(cartSerialNo);
248
	        Transaction transaction = cartToTransactionMap.get(cart.getId());
249
	        User user = userClient.getUserById(cart.getUserId());
250
	        List<Line> cartLines = cart.getLines();
251
	        String cartItems = "";
252
	        for (Line line : cartLines) {
253
	            Item item = catalogClient.getItem(line.getItemId());
254
	            if (!cartItems.isEmpty()) {
255
	                cartItems += ", ";
256
	            }
257
	            cartItems += item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + "(" + line.getQuantity()+ ")";
258
	        }
259
 
260
	        String cartAddress = "-";
261
	        if (cart.getAddressId() != 0) {
262
	            Address address = userClient.getAddressById(cart.getAddressId());
263
	            cartAddress = address.getName() + ", " + address.getLine1() + ", " + address.getLine2() + ", " + address.getCity() 
264
	                + ", " + address.getState() + "-" + address.getPin() + ", " + address.getPhone();
265
	        }
266
 
267
	        contentRow.createCell(0).setCellValue(cart.getId());
268
	        contentRow.createCell(1).setCellValue(cartAddress);
269
	        contentRow.getCell(1).setCellStyle(styleWT);
270
 
271
	        float rowHeight = cartSheet.getDefaultRowHeightInPoints();
272
	        int maxLength = Math.max(cartAddress.length(), cartSheet.getDefaultColumnWidth());
273
            contentRow.setHeightInPoints((maxLength / addrColWidth + 1) * rowHeight); // Setting Row Height
274
 
275
            contentRow.createCell(2).setCellValue(new Date(cart.getCheckedOutOn()));
276
            contentRow.getCell(2).setCellStyle(dateCellStyle);
277
            if (transaction != null) {
278
                contentRow.createCell(3).setCellValue(new Date(transaction.getCreatedOn()));
279
                contentRow.getCell(3).setCellStyle(dateCellStyle);
280
                contentRow.createCell(4).setCellValue(transaction.getStatusDescription());
281
            }
282
	        contentRow.createCell(5).setCellValue(new Date(cart.getCreatedOn()));
283
	        contentRow.getCell(5).setCellStyle(dateCellStyle);
284
	        contentRow.createCell(6).setCellValue(cart.getLinesSize());
285
	        contentRow.createCell(7).setCellValue(new Date(cart.getUpdatedOn()));
286
	        contentRow.getCell(7).setCellStyle(dateCellStyle);
287
	        contentRow.createCell(8).setCellValue(cart.getStatus().name());
288
	        contentRow.createCell(9).setCellValue(cartItems);
289
 
290
	        contentRow.createCell(10).setCellValue(user.getEmail());
291
	        contentRow.createCell(11).setCellValue(user.getCommunicationEmail());
292
	        contentRow.createCell(12).setCellValue(user.getDateOfBirth());
293
	        contentRow.createCell(13).setCellValue(user.getMobileNumber());
294
	        contentRow.createCell(14).setCellValue(user.getName());
295
	    }
296
	    for (int i = 0; i <= 14; i++) {
297
            if (i != 1) {
298
                cartSheet.autoSizeColumn(i);
299
            }
300
        }
301
	}
302
 
303
	public String getErrorMsg() {
304
		return errorMsg;
305
	}
306
}
307