Subversion Repositories SmartDukaan

Rev

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