Subversion Repositories SmartDukaan

Rev

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