Subversion Repositories SmartDukaan

Rev

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