Subversion Repositories SmartDukaan

Rev

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