Subversion Repositories SmartDukaan

Rev

Rev 3343 | Rev 3936 | 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;
1901 vikas 6
import in.shop2020.model.v1.user.Affiliate;
7
import in.shop2020.model.v1.user.MasterAffiliate;
8
import in.shop2020.model.v1.user.TrackLog;
3378 vikas 9
import in.shop2020.model.v1.user.TrackLogType;
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;
3293 vikas 13
import in.shop2020.support.utils.ReportsUtils;
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;
3293 vikas 20
import java.text.DateFormat;
21
import java.text.ParseException;
22
import java.text.SimpleDateFormat;
2501 vikas 23
import java.util.ArrayList;
3293 vikas 24
import java.util.Calendar;
1901 vikas 25
import java.util.Date;
26
import java.util.HashMap;
2393 vikas 27
import java.util.HashSet;
1901 vikas 28
import java.util.List;
29
import java.util.Map;
3315 vikas 30
import java.util.Map.Entry;
2393 vikas 31
import java.util.Set;
3315 vikas 32
import java.util.SortedSet;
33
import java.util.TimeZone;
34
import java.util.TreeSet;
1901 vikas 35
 
36
import javax.servlet.ServletOutputStream;
37
import javax.servlet.http.HttpServletRequest;
38
import javax.servlet.http.HttpServletResponse;
3293 vikas 39
import javax.servlet.http.HttpSession;
1901 vikas 40
 
41
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
42
import org.apache.poi.ss.usermodel.Cell;
43
import org.apache.poi.ss.usermodel.CellStyle;
44
import org.apache.poi.ss.usermodel.CreationHelper;
45
import org.apache.poi.ss.usermodel.Font;
46
import org.apache.poi.ss.usermodel.Row;
47
import org.apache.poi.ss.usermodel.Sheet;
48
import org.apache.poi.ss.usermodel.Workbook;
49
import org.apache.poi.ss.util.CellRangeAddress;
3293 vikas 50
import org.apache.struts2.convention.annotation.InterceptorRef;
51
import org.apache.struts2.convention.annotation.InterceptorRefs;
1901 vikas 52
import org.apache.struts2.interceptor.ServletRequestAware;
53
import org.apache.struts2.interceptor.ServletResponseAware;
3213 chandransh 54
import org.apache.thrift.TException;
55
import org.slf4j.Logger;
56
import org.slf4j.LoggerFactory;
1901 vikas 57
 
2904 chandransh 58
/**
59
 * Provides reports about successful registrations and orders place through an
60
 * affiliate.
61
 * 
62
 * @author Vikas Malik
63
 * 
64
 */
3293 vikas 65
@InterceptorRefs({
66
    @InterceptorRef("defaultStack"),
67
    @InterceptorRef("login")
68
})
69
public class AffiliateController implements ServletRequestAware, ServletResponseAware{
1901 vikas 70
 
3293 vikas 71
    private static Logger log = LoggerFactory.getLogger(AffiliateController.class);
3213 chandransh 72
 
1901 vikas 73
	private HttpServletResponse response;
74
	private HttpServletRequest request;
3293 vikas 75
	private HttpSession session;
76
 
1901 vikas 77
	private String errorMsg = "";
78
	private List<MasterAffiliate> masterAffiliates;
3315 vikas 79
	private Date startDate = null;
80
	private Date endDate = null;
1901 vikas 81
 
82
	@Override
83
	public void setServletResponse(HttpServletResponse res) {
84
		this.response = res;
85
	}
86
 
87
	@Override
88
    public void setServletRequest(HttpServletRequest req) {
89
	    this.request = req;
3293 vikas 90
        this.session = req.getSession();
1901 vikas 91
    }
92
 
93
	public String index()  {
3293 vikas 94
	    log.info(request.getServletPath());
95
        if (!ReportsUtils.canAccessReport(
96
                (Long) session.getAttribute(ReportsUtils.ROLE),
97
                request.getServletPath())) 
98
        {
99
            return "exception";
100
        }
1901 vikas 101
        try {
3125 rajveer 102
        	UserClient userContextServiceClient = new UserClient();
1901 vikas 103
            Client userClient = userContextServiceClient.getClient();
104
            masterAffiliates = userClient.getAllMasterAffiliates();
105
        } catch (Exception e) {
3293 vikas 106
            log.error("Error while getting all affiliates", e);
1901 vikas 107
        }
108
        return "report";
109
    }
110
 
111
	public String create()	{
112
	    try   {
113
	        long mAfId = Long.parseLong(request.getParameter("masterAffiliate"));
3315 vikas 114
	        String mAffName;
3293 vikas 115
	        String startDateStr = request.getParameter("startDate");
116
	        String endDateStr = request.getParameter("endDate");
117
 
118
	        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
3315 vikas 119
	        df.setTimeZone(TimeZone.getTimeZone("IST"));
3293 vikas 120
	        try {
121
	            startDate = df.parse(startDateStr);
122
	            endDate = df.parse(endDateStr);
123
	            Calendar cal = Calendar.getInstance();
124
	            cal.setTime(endDate);
125
	            endDate.setTime(cal.getTimeInMillis());
126
	        } catch (ParseException pe) {
127
	            errorMsg = "Please enter start and end dates in format MM/dd/yyyy";
128
	            return "report";
129
	        }
130
 
3125 rajveer 131
	        UserClient userContextServiceClient = new UserClient();
132
            PaymentClient paymentServiceClient = new PaymentClient();
133
            TransactionClient transactionServiceClient = new TransactionClient();
2340 vikas 134
 
1901 vikas 135
            Client userClient = userContextServiceClient.getClient();
2340 vikas 136
            in.shop2020.payments.PaymentService.Client paymentClient = paymentServiceClient.getClient();
137
 
2501 vikas 138
            List<Affiliate> affiliates;
139
            if (mAfId == -1) {
3315 vikas 140
                mAffName = "All";
2501 vikas 141
                affiliates = new ArrayList<Affiliate>();
142
                for(MasterAffiliate mAffiliate : userClient.getAllMasterAffiliates()) {
143
                    affiliates.addAll(userClient.getAffiliatesByMasterAffiliate(mAffiliate.getId()));
144
                }
145
            }
146
            else {
147
                affiliates = userClient.getAffiliatesByMasterAffiliate(mAfId);
3315 vikas 148
                mAffName = userClient.getMasterAffiliateById(mAfId).getName();
2501 vikas 149
            }
2980 vikas 150
 
3315 vikas 151
            SortedSet<Date> dates = new TreeSet<Date>();
152
            Map<Date, Long> registerCountMap = new HashMap<Date, Long>();
153
            Map<Date, Double> saleQuantityMap = new HashMap<Date, Double>();
154
            Map<Date, Double> saleAmountMap = new HashMap<Date, Double>();
155
 
156
            Map<Date, Map<String, Double>> productQuantityMap = new HashMap<Date, Map<String, Double>>();
157
            Map<Date, Map<String, Double>> productAmountMap = new HashMap<Date, Map<String,Double>>();
158
 
2501 vikas 159
            for (Affiliate aff : affiliates) {
3315 vikas 160
                Set<Long> Payments = new HashSet<Long>(); // To deal with multiple refreshes on pay-success page.
3293 vikas 161
                for (TrackLog tracklog : userClient.getTrackLogsByAffiliate(aff.getId(), startDate.getTime(), endDate.getTime())) {
3315 vikas 162
                    Date date = df.parse(df.format(new Date(tracklog.getAddedOn())));
163
                    dates.add(date);
3378 vikas 164
                    if (tracklog.getEventType() == TrackLogType.NEW_REGISTRATION) {
3315 vikas 165
                        if (registerCountMap.containsKey(date)) {
166
                            Long count = registerCountMap.get(date);
167
                            registerCountMap.put(date, ++count);
168
                        }
169
                        else {
170
                            registerCountMap.put(date, 1l);
171
                        }
172
                    }
3378 vikas 173
                    else if (tracklog.getEventType() == TrackLogType.PAYMENT_SUCCESS) {
3343 vikas 174
                        long paymentId = Long.parseLong(tracklog.getData().replaceAll("\\(.*\\)", ""));
3315 vikas 175
                        if (Payments.contains(paymentId)) {
176
                            continue;
177
                        }
178
                        Payments.add(paymentId);
179
                        Payment payment = paymentClient.getPayment(paymentId);
180
                        List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(
181
                                        payment.getMerchantTxnId(),
182
                                        payment.getUserId());
183
                        for (Order order : orders) {
3341 vikas 184
                            if (order.getStatus() == OrderStatus.DELIVERY_SUCCESS) {
3315 vikas 185
                                List<LineItem> items = order.getLineitems();
186
                                if (saleAmountMap.containsKey(date)) {
187
                                    Double amount = saleAmountMap.get(date);
188
                                    amount += order.getTotal_amount();
189
                                    saleAmountMap.put(date, amount);
2980 vikas 190
                                }
3315 vikas 191
                                else {
192
                                    saleAmountMap.put(date, order.getTotal_amount());
193
                                }
2340 vikas 194
                                for (LineItem item : items) {
3315 vikas 195
                                    if (saleQuantityMap.containsKey(date)) {
196
                                        Double quantity = saleQuantityMap.get(date);
197
                                        quantity += item.getQuantity();
198
                                        saleQuantityMap.put(date, quantity);
199
                                    }
200
                                    else {
201
                                        saleQuantityMap.put(date, item.getQuantity());
202
                                    }
203
 
204
                                    String productName = item.getBrand() + " "
2340 vikas 205
                                            + item.getModel_name() + " "
3315 vikas 206
                                            + item.getModel_number();
207
                                    productName = productName.replace("null", "").replaceAll("  ", " ").trim();
208
                                    if (productQuantityMap.containsKey(date)) {
209
                                        Map<String, Double> pQuantityMap = productQuantityMap.get(date);
210
                                        if (pQuantityMap.containsKey(productName)) {
211
                                            Double quantity = pQuantityMap.get(productName);
212
                                            quantity += item.getQuantity();
213
                                            pQuantityMap.put(productName, quantity);
214
                                        }
215
                                        else {
216
                                            pQuantityMap.put(productName, item.getQuantity());
217
                                        }
218
                                    }
219
                                    else {
220
                                        Map<String, Double> pQuantityMap = new HashMap<String, Double>();
221
                                        pQuantityMap.put(productName, item.getQuantity());
222
                                        productQuantityMap.put(date, pQuantityMap);
223
                                    }
224
 
225
                                    if (productAmountMap.containsKey(date)) {
226
                                        Map<String, Double> pAmountMap = productAmountMap.get(date);
227
                                        if (pAmountMap.containsKey(productName)) {
228
                                            Double amount = pAmountMap.get(productName);
229
                                            amount += item.getTotal_price();
230
                                            pAmountMap.put(productName, amount);
231
                                        }
232
                                        else {
233
                                            pAmountMap.put(productName, item.getTotal_price());
234
                                        }
235
                                    }
236
                                    else {
237
                                        Map<String, Double> pAmountMap = new HashMap<String, Double>();
238
                                        pAmountMap.put(productName, item.getTotal_price());
239
                                        productAmountMap.put(date, pAmountMap);
240
                                    }
2340 vikas 241
                                }
242
                            }
243
                        }
244
                    }
1901 vikas 245
                }
246
            }
3315 vikas 247
 
1901 vikas 248
            // Preparing XLS file for output
249
            response.setContentType("application/vnd.ms-excel");
250
 
3315 vikas 251
            response.setHeader("Content-disposition", "inline; filename=" + mAffName + "-affiliate-report" + ".xls");
1901 vikas 252
 
253
            ServletOutputStream sos;
254
            try {
3315 vikas 255
                ByteArrayOutputStream baos = getSpreadSheetData(mAffName, dates, registerCountMap, saleQuantityMap, saleAmountMap, productQuantityMap, productAmountMap);
1901 vikas 256
                sos = response.getOutputStream();
257
                baos.writeTo(sos);
258
                sos.flush();
259
            } catch (IOException e) {
3293 vikas 260
                log.error("Unable to stream the affiliates report", e);
1901 vikas 261
                errorMsg = "Failed to write to response.";
262
            }
3213 chandransh 263
        } catch (UserAffiliateException e) {
3293 vikas 264
            log.error("Error while getting affiliated users", e);
1901 vikas 265
            errorMsg = e.getMessage();
3213 chandransh 266
        } catch (TException e) {
3293 vikas 267
            log.error("Unable to get affiliated users", e);
3213 chandransh 268
            errorMsg = e.getMessage();
269
        } catch (Exception e) {
3293 vikas 270
            log.error("Unexpected exception", e);
3213 chandransh 271
            errorMsg = e.getMessage();
1901 vikas 272
        }
273
        return null;
274
	}
275
 
3315 vikas 276
    // Prepares the XLS worksheet object and fills in the data with proper formatting
277
	private ByteArrayOutputStream getSpreadSheetData(String mAffName, 
278
	        SortedSet<Date> dates,
279
            Map<Date, Long> registerCountMap,
280
            Map<Date, Double> saleQuantityMap,
281
            Map<Date, Double> saleAmountMap, 
282
            Map<Date, Map<String, Double>> productQuantityMap,
283
            Map<Date, Map<String, Double>> productAmountMap)
1901 vikas 284
	{
285
	    ByteArrayOutputStream baosXLS = new ByteArrayOutputStream();
286
 
287
		Workbook wb = new HSSFWorkbook();
288
 
289
	    Font font = wb.createFont();
290
	    font.setBoldweight(Font.BOLDWEIGHT_BOLD);
291
	    CellStyle style = wb.createCellStyle();
292
	    style.setFont(font);
293
 
294
	    CreationHelper createHelper = wb.getCreationHelper();
295
	    CellStyle dateCellStyle = wb.createCellStyle();
3315 vikas 296
	    dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("DD/MM/YYYY"));
1901 vikas 297
 
3315 vikas 298
	    createSummarySheet(mAffName, dates, registerCountMap, saleQuantityMap, saleAmountMap, wb, style, dateCellStyle);
299
	    createSaleDetailSheet(mAffName, dates, productQuantityMap, productAmountMap, wb, style, dateCellStyle);
1901 vikas 300
 
301
		// Write the workbook to the output stream
302
		try {
303
			wb.write(baosXLS);
304
			baosXLS.close();
305
		} catch (IOException e) {
3293 vikas 306
			log.error("Unable to get the byte array for the affiliate report", e);
1901 vikas 307
		}		
308
		return baosXLS;
309
	}
310
 
3315 vikas 311
    private void createSaleDetailSheet(String mAffName, SortedSet<Date> dates,
312
            Map<Date, Map<String, Double>> productQuantityMap,
313
            Map<Date, Map<String, Double>> productAmountMap, Workbook wb,
314
            CellStyle style, CellStyle dateCellStyle) {
315
        // Product Sales SHEET
316
        Sheet affSheet = wb.createSheet("Product Sales Report");
317
        short affSerialNo = 0;
318
 
319
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
320
 
321
        Row affTitleRow = affSheet.createRow(affSerialNo ++);
322
        Cell affTitleCell = affTitleRow.createCell(0);
323
        affTitleCell.setCellValue("Modelwise Sales Report");
324
        affTitleCell.setCellStyle(style);
325
        affSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
326
 
327
        affSheet.createRow(affSerialNo ++);
328
        Row affNameRow = affSheet.createRow(affSerialNo ++);
329
        Cell affNameCell = affNameRow.createCell(0);
330
        affNameCell.setCellValue("Affiliate : " + mAffName);
331
        affNameCell.setCellStyle(style);
332
        affSheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 6));
333
 
334
        Row affDateRangeRow = affSheet.createRow(affSerialNo ++);
335
        Cell affDateRangeCell = affDateRangeRow.createCell(0);
336
        affDateRangeCell.setCellValue("Date Range : " + df.format(startDate) + " - " + df.format(endDate));
337
        affDateRangeCell.setCellStyle(style);
338
        affSheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 6));
339
 
340
        affSheet.createRow(affSerialNo ++);affSheet.createRow(affSerialNo ++);
341
 
342
        Row affHeaderRow = affSheet.createRow(affSerialNo++);
343
        affHeaderRow.createCell(0).setCellValue("Date");
344
        affHeaderRow.createCell(1).setCellValue("ProductName");
345
        affHeaderRow.createCell(2).setCellValue("Sales Count");
346
        affHeaderRow.createCell(3).setCellValue("Amount");
347
        for (int i=0; i<4 ;i++) {
348
            affHeaderRow.getCell(i).setCellStyle(style);
349
        }
350
 
3343 vikas 351
        Double totalQuantity = 0d;
352
        Double totalAmount = 0d;
3315 vikas 353
        for(Date date : dates) {
354
            if (!productQuantityMap.containsKey(date)) {
355
                continue;
356
            }
357
            for (Entry<String, Double> quantityEntry : productQuantityMap.get(date).entrySet()) {
358
                affSerialNo++;
359
                String prodName = quantityEntry.getKey();
360
                Double quantity = quantityEntry.getValue();
361
                Double amount = productAmountMap.get(date).get(prodName);
3343 vikas 362
                totalQuantity += quantity;
363
                totalAmount += amount;
3315 vikas 364
                Row commContentRow = affSheet.createRow(affSerialNo);
365
                commContentRow.createCell(0).setCellValue(date);
366
                commContentRow.getCell(0).setCellStyle(dateCellStyle);
367
                commContentRow.createCell(1).setCellValue(prodName);
368
                commContentRow.createCell(2).setCellValue(quantity);
369
                commContentRow.createCell(3).setCellValue(amount);
370
 
371
            }
372
        }
3343 vikas 373
        affSerialNo+=2;
374
        Row commContentRow = affSheet.createRow(affSerialNo);
375
        commContentRow.createCell(0).setCellValue("Total");
376
        commContentRow.createCell(1).setCellValue("");
377
        commContentRow.createCell(2).setCellValue(totalQuantity);
378
        commContentRow.createCell(3).setCellValue(totalAmount);
379
 
380
        for (int i = 0; i<4; i++) {
381
            affSheet.autoSizeColumn(i);
382
        }
3315 vikas 383
    }
384
 
385
    private void createSummarySheet(String mAffName, 
386
            SortedSet<Date> dates,
387
            Map<Date, Long> registerCountMap,
388
            Map<Date, Double> saleQuantityMap,
389
            Map<Date, Double> saleAmountMap, 
390
            Workbook wb, 
391
            CellStyle style,
392
            CellStyle dateCellStyle) 
393
    {
394
		// Summary SHEET
395
	    Sheet affSheet = wb.createSheet("Summary Report");
1901 vikas 396
	    short affSerialNo = 0;
3315 vikas 397
 
398
	    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
1901 vikas 399
 
400
	    Row affTitleRow = affSheet.createRow(affSerialNo ++);
401
	    Cell affTitleCell = affTitleRow.createCell(0);
3315 vikas 402
	    affTitleCell.setCellValue("Daily Stats Report");
1901 vikas 403
	    affTitleCell.setCellStyle(style);
404
	    affSheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
405
 
406
	    affSheet.createRow(affSerialNo ++);
3315 vikas 407
	    Row affNameRow = affSheet.createRow(affSerialNo ++);
408
        Cell affNameCell = affNameRow.createCell(0);
409
        affNameCell.setCellValue("Affiliate : " + mAffName);
410
        affNameCell.setCellStyle(style);
411
        affSheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 6));
412
 
413
        Row affDateRangeRow = affSheet.createRow(affSerialNo ++);
414
        Cell affDateRangeCell = affDateRangeRow.createCell(0);
415
        affDateRangeCell.setCellValue("Date Range : " + df.format(startDate) + " - " + df.format(endDate));
416
        affDateRangeCell.setCellStyle(style);
417
        affSheet.addMergedRegion(new CellRangeAddress(3, 3, 0, 6));
418
 
419
	    affSheet.createRow(affSerialNo ++);affSheet.createRow(affSerialNo ++);
1901 vikas 420
 
421
	    Row affHeaderRow = affSheet.createRow(affSerialNo++);
3315 vikas 422
	    affHeaderRow.createCell(0).setCellValue("Date");
423
	    affHeaderRow.createCell(1).setCellValue("New Registrations");
424
	    affHeaderRow.createCell(2).setCellValue("Sales Count");
425
	    affHeaderRow.createCell(3).setCellValue("Amount");
426
	    for (int i=0; i<4 ;i++) {
1901 vikas 427
	        affHeaderRow.getCell(i).setCellStyle(style);
428
	    }
429
 
3343 vikas 430
	    Double totalregisterCount = 0d;
431
        Double totalQuantity = 0d;
432
	    Double totalAmount = 0d;
433
        for(Date date : dates) {
3315 vikas 434
		    affSerialNo++;
1901 vikas 435
			Row commContentRow = affSheet.createRow(affSerialNo);
3315 vikas 436
			Long registerCount = registerCountMap.get(date);
437
			Double saleQuantity = saleQuantityMap.get(date);
438
			Double saleAmount = saleAmountMap.get(date);
439
			if (registerCount == null) {
440
			    registerCount = 0l;
2340 vikas 441
			}
3315 vikas 442
			if (saleQuantity == null) {
443
                saleQuantity = 0d;
444
            }
445
			if (saleAmount == null) {
446
                saleAmount = 0d;
447
            }
3343 vikas 448
			totalregisterCount += registerCount;
449
            totalQuantity += saleQuantity;
450
			totalAmount += saleAmount;
451
            commContentRow.createCell(0).setCellValue(date);
3315 vikas 452
			commContentRow.getCell(0).setCellStyle(dateCellStyle);
453
            commContentRow.createCell(1).setCellValue(registerCount);
454
			commContentRow.createCell(2).setCellValue(saleQuantity);
455
			commContentRow.createCell(3).setCellValue(saleAmount);
1901 vikas 456
		}
3343 vikas 457
        affSerialNo+=2;
458
        Row commContentRow = affSheet.createRow(affSerialNo);
459
        commContentRow.createCell(0).setCellValue("Total");
460
        commContentRow.createCell(1).setCellValue(totalregisterCount);
461
        commContentRow.createCell(2).setCellValue(totalQuantity);
462
        commContentRow.createCell(3).setCellValue(totalAmount);
463
 
3315 vikas 464
        for (int i = 0; i<4; i++) {
1901 vikas 465
            affSheet.autoSizeColumn(i);
466
        }
467
	}
468
 
469
	public String getErrorMsg() {
470
		return errorMsg;
471
	}
472
 
473
	public List<MasterAffiliate> getMasterAffiliates() {
474
        return masterAffiliates;
475
    }
2340 vikas 476
}