Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
1901 vikas 1
package in.shop2020.support.controllers;
2
 
2340 vikas 3
import in.shop2020.model.v1.order.LineItem;
4
import in.shop2020.model.v1.order.Order;
2980 vikas 5
import in.shop2020.model.v1.order.OrderStatus;
3213 chandransh 6
import in.shop2020.model.v1.order.TransactionServiceException;
1901 vikas 7
import in.shop2020.model.v1.user.Affiliate;
8
import in.shop2020.model.v1.user.MasterAffiliate;
9
import in.shop2020.model.v1.user.TrackLog;
3213 chandransh 10
import in.shop2020.model.v1.user.UserAffiliateException;
1901 vikas 11
import in.shop2020.model.v1.user.UserContextService.Client;
2340 vikas 12
import in.shop2020.payments.Payment;
3213 chandransh 13
import in.shop2020.payments.PaymentException;
3125 rajveer 14
import in.shop2020.thrift.clients.PaymentClient;
15
import in.shop2020.thrift.clients.TransactionClient;
16
import in.shop2020.thrift.clients.UserClient;
1901 vikas 17
 
18
import java.io.ByteArrayOutputStream;
19
import java.io.IOException;
2501 vikas 20
import java.util.ArrayList;
1901 vikas 21
import java.util.Date;
22
import java.util.HashMap;
2393 vikas 23
import java.util.HashSet;
1901 vikas 24
import java.util.LinkedList;
25
import java.util.List;
26
import java.util.Map;
2393 vikas 27
import java.util.Set;
1901 vikas 28
 
29
import javax.servlet.ServletOutputStream;
30
import javax.servlet.http.HttpServletRequest;
31
import javax.servlet.http.HttpServletResponse;
32
 
33
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
34
import org.apache.poi.ss.usermodel.Cell;
35
import org.apache.poi.ss.usermodel.CellStyle;
36
import org.apache.poi.ss.usermodel.CreationHelper;
37
import org.apache.poi.ss.usermodel.Font;
38
import org.apache.poi.ss.usermodel.Row;
39
import org.apache.poi.ss.usermodel.Sheet;
40
import org.apache.poi.ss.usermodel.Workbook;
41
import org.apache.poi.ss.util.CellRangeAddress;
42
import org.apache.struts2.interceptor.ServletRequestAware;
43
import org.apache.struts2.interceptor.ServletResponseAware;
3213 chandransh 44
import org.apache.thrift.TException;
45
import org.slf4j.Logger;
46
import org.slf4j.LoggerFactory;
1901 vikas 47
 
2904 chandransh 48
/**
49
 * Provides reports about successful registrations and orders place through an
50
 * affiliate.
51
 * 
52
 * @author Vikas Malik
53
 * 
54
 */
1901 vikas 55
public class AffiliateController implements ServletResponseAware, ServletRequestAware{
56
 
3213 chandransh 57
    private static Logger logger = LoggerFactory.getLogger(AffiliateController.class);
58
 
1901 vikas 59
	private HttpServletResponse response;
60
	private HttpServletRequest request;
61
 
62
	private String errorMsg = "";
63
	private List<MasterAffiliate> masterAffiliates;
64
 
65
	@Override
66
	public void setServletResponse(HttpServletResponse res) {
67
		this.response = res;
68
	}
69
 
70
	@Override
71
    public void setServletRequest(HttpServletRequest req) {
72
	    this.request = req;
73
    }
74
 
75
	public String index()  {
76
 
77
        try {
3125 rajveer 78
        	UserClient userContextServiceClient = new UserClient();
1901 vikas 79
            Client userClient = userContextServiceClient.getClient();
80
            masterAffiliates = userClient.getAllMasterAffiliates();
81
        } catch (Exception e) {
3213 chandransh 82
            logger.error("Error while getting all affiliates", e);
1901 vikas 83
        }
84
        return "report";
85
    }
86
 
87
	public String create()	{
88
	    try   {
89
	        long mAfId = Long.parseLong(request.getParameter("masterAffiliate"));
3125 rajveer 90
	        UserClient userContextServiceClient = new UserClient();
91
            PaymentClient paymentServiceClient = new PaymentClient();
92
            TransactionClient transactionServiceClient = new TransactionClient();
2340 vikas 93
 
1901 vikas 94
            Client userClient = userContextServiceClient.getClient();
2340 vikas 95
            in.shop2020.payments.PaymentService.Client paymentClient = paymentServiceClient.getClient();
96
 
2393 vikas 97
            Set<Long> Payments = new HashSet<Long>();
2501 vikas 98
            List<Map<String, String>> contentRows = new LinkedList<Map<String,String>>();
99
            List<Affiliate> affiliates;
100
            if (mAfId == -1) {
101
                affiliates = new ArrayList<Affiliate>();
102
                for(MasterAffiliate mAffiliate : userClient.getAllMasterAffiliates()) {
103
                    affiliates.addAll(userClient.getAffiliatesByMasterAffiliate(mAffiliate.getId()));
104
                }
105
            }
106
            else {
107
                affiliates = userClient.getAffiliatesByMasterAffiliate(mAfId);
108
            }
2980 vikas 109
 
2501 vikas 110
            for (Affiliate aff : affiliates) {
111
                MasterAffiliate mAffiliate = userClient.getMasterAffiliateById(aff.getMasterAffiliateId());
2000 vikas 112
                for (TrackLog tracklog : userClient.getTrackLogsByAffiliate(aff.getId())) {
2980 vikas 113
                    boolean orderCompleted = false;
2000 vikas 114
                    Map<String, String> contentRow = new HashMap<String, String>();
115
                    contentRow.put("mAffiliate", mAffiliate.getName());
116
                    contentRow.put("affiliate", aff.getName());
117
                    contentRow.put("affiliateUrl", aff.getUrl());
118
                    contentRow.put("date",String.valueOf(tracklog.getAddedOn()));
119
                    contentRow.put("event", tracklog.getEvent());
120
                    contentRow.put("url", tracklog.getUrl());
2345 vikas 121
                    if (tracklog.getEvent().equals("payment success")) {
2340 vikas 122
                        try {
2345 vikas 123
                            long paymentId = Long.parseLong(tracklog.getData().replaceAll("\\(*\\)", ""));
2393 vikas 124
                            if (Payments.contains(paymentId)) {
125
                                continue;
126
                            }
127
                            Payments.add(paymentId);
3213 chandransh 128
                            Payment payment = paymentClient.getPayment(paymentId);
129
                            List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(
2340 vikas 130
                                            payment.getMerchantTxnId(),
131
                                            payment.getUserId());
3213 chandransh 132
                            contentRow.put("amount", Double.toString(payment.getAmount()));
2345 vikas 133
                            String itemString = "";
2340 vikas 134
                            for (Order order : orders) {
2980 vikas 135
                                if (order.getStatus() == OrderStatus.DELIVERY_SUCCESS) {
136
                                    orderCompleted = true;
137
                                }
2340 vikas 138
                                List<LineItem> items = order.getLineitems();
139
                                for (LineItem item : items) {
140
                                    itemString += item.getBrand() + " "
141
                                            + item.getModel_name() + " "
142
                                            + item.getModel_number() + "("
143
                                            + item.getQuantity() + ", "
144
                                            + item.getTotal_price() + "), ";
145
                                }
2345 vikas 146
                                contentRow.put("items", itemString.replaceAll("null", ""));
2340 vikas 147
                            }
3213 chandransh 148
                        } catch (PaymentException e) {
149
                            logger.error("Error while getting payment info", e);
150
                        } catch (TransactionServiceException e) {
151
                            logger.error("Error while getting order info", e);
152
                        } catch (TException e) {
153
                            logger.error("Unable to get order or payment info", e);
154
                        } catch (NullPointerException e) {
155
                            logger.error("Unexpected exception", e);
2340 vikas 156
                        }
157
                    }
2000 vikas 158
                    contentRow.put("data", tracklog.getData());
2980 vikas 159
                    if (orderCompleted) {
160
                        contentRows.add(contentRow);
161
                    }
1901 vikas 162
                }
163
            }
164
 
165
            // Preparing XLS file for output
166
            response.setContentType("application/vnd.ms-excel");
167
 
2058 vikas 168
            response.setHeader("Content-disposition", "inline; filename=affiliate-report" + ".xls");
1901 vikas 169
 
170
            ServletOutputStream sos;
171
            try {
2501 vikas 172
                ByteArrayOutputStream baos = getSpreadSheetData(contentRows);
1901 vikas 173
                sos = response.getOutputStream();
174
                baos.writeTo(sos);
175
                sos.flush();
176
            } catch (IOException e) {
3213 chandransh 177
                logger.error("Unable to stream the affiliates report", e);
1901 vikas 178
                errorMsg = "Failed to write to response.";
179
            }
3213 chandransh 180
        } catch (UserAffiliateException e) {
181
            logger.error("Error while getting affiliated users", e);
1901 vikas 182
            errorMsg = e.getMessage();
3213 chandransh 183
        } catch (TException e) {
184
            logger.error("Unable to get affiliated users", e);
185
            errorMsg = e.getMessage();
186
        } catch (Exception e) {
187
            logger.error("Unexpected exception", e);
188
            errorMsg = e.getMessage();
1901 vikas 189
        }
190
        return null;
191
	}
192
 
193
	// Prepares the XLS worksheet object and fills in the data with proper formatting
2501 vikas 194
	private ByteArrayOutputStream getSpreadSheetData(List<Map<String, String>> contentRows)
1901 vikas 195
	{
196
	    ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
197
 
198
		Workbook wb = new HSSFWorkbook();
199
 
200
	    Font font = wb.createFont();
201
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
202
	    CellStyle style = wb.createCellStyle();
203
	    style.setFont(font);
204
 
205
	    CreationHelper createHelper = wb.getCreationHelper();
206
	    CellStyle dateCellStyle = wb.createCellStyle();
207
	    dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("DD/MM/YYYY HH:MM"));
208
 
2501 vikas 209
	    createAffiliateSheet(contentRows, wb, style, dateCellStyle);
1901 vikas 210
 
211
		// Write the workbook to the output stream
212
		try {
213
			wb.write(baosXLS);
214
			baosXLS.close();
215
		} catch (IOException e) {
3213 chandransh 216
			logger.error("Unable to get the byte array for the affiliate report", e);
1901 vikas 217
		}		
218
		return baosXLS;
219
	}
220
 
2501 vikas 221
	private void createAffiliateSheet(List<Map<String, String>> contentRows, Workbook wb, CellStyle style, CellStyle dateCellStyle) 
1901 vikas 222
	{
223
		// Affiliate SHEET
224
	    Sheet affSheet = wb.createSheet("Affiliates Report");
225
	    short affSerialNo = 0;
226
 
227
	    Row affTitleRow = affSheet.createRow(affSerialNo ++);
228
	    Cell affTitleCell = affTitleRow.createCell(0);
2501 vikas 229
	    affTitleCell.setCellValue("Affiliates Report");
1901 vikas 230
	    affTitleCell.setCellStyle(style);
231
 
232
	    affSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
233
 
234
	    affSheet.createRow(affSerialNo ++);
235
 
236
	    Row affHeaderRow = affSheet.createRow(affSerialNo++);
237
	    affHeaderRow.createCell(0).setCellValue("Affiliate");
238
	    affHeaderRow.createCell(1).setCellValue("Affiliate Url");
239
	    affHeaderRow.createCell(2).setCellValue("Date");
240
	    affHeaderRow.createCell(3).setCellValue("Event");
241
	    affHeaderRow.createCell(4).setCellValue("Url");
242
	    affHeaderRow.createCell(5).setCellValue("Data");
2340 vikas 243
	    affHeaderRow.createCell(6).setCellValue("Items");
244
	    affHeaderRow.createCell(7).setCellValue("Amount");
245
	    for (int i=0; i<8 ;i++) {
1901 vikas 246
	        affHeaderRow.getCell(i).setCellStyle(style);
247
	    }
248
 
249
		for( Map<String, String> contentRow : contentRows) {
250
			affSerialNo++;
251
			Row commContentRow = affSheet.createRow(affSerialNo);
252
 
253
			commContentRow.createCell(0).setCellValue(contentRow.get("affiliate"));
254
			commContentRow.createCell(1).setCellValue(contentRow.get("affiliateUrl"));
255
			commContentRow.createCell(2).setCellValue(new Date(Long.parseLong(contentRow.get("date"))));
256
			commContentRow.getCell(2).setCellStyle(dateCellStyle);
257
            commContentRow.createCell(3).setCellValue(contentRow.get("event"));
258
			commContentRow.createCell(4).setCellValue(contentRow.get("url"));
259
			commContentRow.createCell(5).setCellValue(contentRow.get("data"));
2340 vikas 260
			if (contentRow.containsKey("items")) {
261
			    commContentRow.createCell(6).setCellValue(contentRow.get("items"));
262
			}
263
			if (contentRow.containsKey("amount")) {
264
	            commContentRow.createCell(7).setCellValue(contentRow.get("amount"));
265
			}
1901 vikas 266
		}
2340 vikas 267
        for (int i = 0; i<8; i++) {
1901 vikas 268
            affSheet.autoSizeColumn(i);
269
        }
270
	}
271
 
272
	public String getErrorMsg() {
273
		return errorMsg;
274
	}
275
 
276
	public List<MasterAffiliate> getMasterAffiliates() {
277
        return masterAffiliates;
278
    }
2340 vikas 279
}