Subversion Repositories SmartDukaan

Rev

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