Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
679 chandransh 1
package in.shop2020.support.controllers;
2
 
4386 anupam.sin 3
import in.shop2020.logistics.Awb;
4
import in.shop2020.logistics.DeliveryType;
5
import in.shop2020.logistics.LogisticsServiceException;
6
import in.shop2020.logistics.Provider;
7
import in.shop2020.model.v1.catalog.InventoryServiceException;
754 chandransh 8
import in.shop2020.model.v1.catalog.Warehouse;
4386 anupam.sin 9
import in.shop2020.model.v1.order.LineItem;
10
import in.shop2020.model.v1.order.Order;
11
import in.shop2020.model.v1.order.OrderStatus;
12
import in.shop2020.model.v1.order.TransactionServiceException;
3364 chandransh 13
import in.shop2020.support.utils.FileUtils;
3125 rajveer 14
import in.shop2020.thrift.clients.CatalogClient;
15
import in.shop2020.thrift.clients.HelperClient;
4386 anupam.sin 16
import in.shop2020.thrift.clients.LogisticsClient;
17
import in.shop2020.thrift.clients.TransactionClient;
749 chandransh 18
import in.shop2020.utils.LogisticsUser;
4386 anupam.sin 19
import in.shop2020.support.models.AwbDetails;
679 chandransh 20
 
21
import java.io.ByteArrayOutputStream;
756 chandransh 22
import java.io.File;
679 chandransh 23
import java.io.IOException;
4386 anupam.sin 24
import java.io.PrintStream;
25
import java.util.ArrayList;
679 chandransh 26
import java.util.Calendar;
4386 anupam.sin 27
import java.util.Collection;
28
import java.util.Date;
679 chandransh 29
import java.util.GregorianCalendar;
754 chandransh 30
import java.util.HashMap;
4386 anupam.sin 31
import java.util.Iterator;
754 chandransh 32
import java.util.List;
4386 anupam.sin 33
import java.util.ListIterator;
754 chandransh 34
import java.util.Map;
679 chandransh 35
 
1075 chandransh 36
import javax.servlet.ServletContext;
679 chandransh 37
import javax.servlet.ServletOutputStream;
38
import javax.servlet.http.HttpServletRequest;
39
import javax.servlet.http.HttpServletResponse;
749 chandransh 40
import javax.servlet.http.HttpSession;
679 chandransh 41
 
4386 anupam.sin 42
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
43
import org.apache.poi.ss.usermodel.Cell;
44
import org.apache.poi.ss.usermodel.CellStyle;
45
import org.apache.poi.ss.usermodel.CreationHelper;
46
import org.apache.poi.ss.usermodel.Row;
47
import org.apache.poi.ss.usermodel.Sheet;
48
import org.apache.poi.ss.usermodel.Workbook;
679 chandransh 49
import org.apache.struts2.interceptor.ServletRequestAware;
50
import org.apache.struts2.interceptor.ServletResponseAware;
1075 chandransh 51
import org.apache.struts2.util.ServletContextAware;
4386 anupam.sin 52
import org.apache.thrift.TException;
53
import org.apache.thrift.transport.TTransportException;
3062 chandransh 54
import org.slf4j.Logger;
55
import org.slf4j.LoggerFactory;
679 chandransh 56
 
2904 chandransh 57
/**
58
 * Allows executives of courier companies to login and download courier details
59
 * report which they then use to upload into their database.
60
 * 
61
 * @author Chandranshu
62
 * 
63
 */
679 chandransh 64
public class CourierDetailsController implements ServletResponseAware,
1075 chandransh 65
		ServletRequestAware, ServletContextAware {
3062 chandransh 66
 
67
    private static Logger logger = LoggerFactory.getLogger(CourierDetailsController.class);
68
 
749 chandransh 69
	private String id;
1075 chandransh 70
	private int daysToSubtract;
756 chandransh 71
 
72
	//FIXME: Read this configuration from the config client
73
	private String courierDetailsPath = "/CourierDetailReports";
74
 
1075 chandransh 75
	private ServletContext context;
679 chandransh 76
	private HttpServletRequest request;
77
	private HttpServletResponse response;
749 chandransh 78
	private HttpSession session;
679 chandransh 79
 
4386 anupam.sin 80
    private String awbNumbers;
81
    private List<AwbDetails> detailedAWBs;
82
 
83
    private String errorMsg = "";
84
 
749 chandransh 85
	public String index(){
86
		if(getSessionUserName()==null)
87
			return "authfail";
88
		else
89
			return "authsuccess";
90
	}
91
 
92
	// Handler for POST /courier-details
93
	public String create(){
94
		String username = request.getParameter("username");
95
		String password = request.getParameter("password");
96
		try{
3125 rajveer 97
			HelperClient helperServiceClient = new HelperClient();
749 chandransh 98
			in.shop2020.utils.HelperService.Client client = helperServiceClient.getClient();
99
			LogisticsUser user = client.authenticateLogisticsUser(username, password);
100
			session.setAttribute("username", user.getUsername());
101
			session.setAttribute("providerId", Long.valueOf(user.getProviderId()));
102
		}catch(Exception e){
3105 chandransh 103
			logger.error("Error authenticating the user " + username, e);
749 chandransh 104
			return "authfail";
105
		}
106
		return "authsuccess";
679 chandransh 107
	}
108
 
749 chandransh 109
	// Handler for GET /courier-details/<warehouseId>
110
	public String show(){
111
		try {
112
			long warehouseId = Long.parseLong(getId());
4209 rajveer 113
			if(warehouseId == 1){
114
				warehouseId = 0;
115
			}
749 chandransh 116
			long providerId = ((Long)session.getAttribute("providerId")).longValue();
3062 chandransh 117
			boolean isCod;
118
			try {
119
	            isCod = Boolean.parseBoolean(request.getParameter("isCod"));
120
	        } catch (Exception e) {
121
	            isCod = false;
122
	        }
3105 chandransh 123
			logger.info("Download request for " + (isCod ? "COD" : "Prepaid") + " Courier Details report of warehouse Id: " + warehouseId + " and provider Id:" + providerId);
749 chandransh 124
 
3062 chandransh 125
			String deliveryType = "prepaid";
126
			if(isCod)
127
			    deliveryType = "cod";
128
 
749 chandransh 129
			response.setContentType("application/vnd.ms-excel");
130
 
131
			Calendar date = new GregorianCalendar();
1075 chandransh 132
			date.add(Calendar.DAY_OF_MONTH, daysToSubtract);
749 chandransh 133
			int year = date.get(Calendar.YEAR);
134
			int month = date.get(Calendar.MONTH) +1;
135
			int day = date.get(Calendar.DAY_OF_MONTH);
3062 chandransh 136
			String fileName = courierDetailsPath + "/courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-" + month + "-" + day +".xls";
137
			response.setHeader("Content-disposition", "inline; filename=courier-details-" + deliveryType + "-" + warehouseId + "-" + providerId + "-" + year + "-"+ month + "-" + day +".xls" );
749 chandransh 138
 
139
			ServletOutputStream sos;
140
			try {
756 chandransh 141
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
3364 chandransh 142
				baos.write(FileUtils.getBytesFromFile(new File(fileName)));
749 chandransh 143
				sos = response.getOutputStream();
144
				baos.writeTo(sos);
145
				sos.flush();
146
			} catch (IOException e) {
3062 chandransh 147
				logger.error("Unable to stream the courier details report", e);
749 chandransh 148
			}	
149
			return "authsuccess";
150
		}catch(NumberFormatException nfe){
3062 chandransh 151
			logger.error("Unable to parse the warehouse id", nfe);
749 chandransh 152
		}
153
		return "authfail";
154
	}
4386 anupam.sin 155
 
156
	public static void main(String[] args) {
157
	    CourierDetailsController cdc = new CourierDetailsController();
158
	    cdc.setAwbNumbers("4340987735");
159
	    String msg = cdc.getAwbDetails();
160
	    System.out.println(msg);
161
	    //58539182004
162
	    //43726980393
163
    }
164
 
165
	/**
166
	 * Use this method to get details of a given awb number
167
	 */
168
	public String getAwbDetails() {
169
	    Order order = null;
170
	    if(awbNumbers.isEmpty()) {
171
	        setErrorMsg("Field cannot be empty");
172
	        return "info";
173
	    }
174
	    List<AwbDetails> tempList = new ArrayList<AwbDetails>() ;
175
	    String [] awbArray = awbNumbers.split(",");
176
	    for(String awbNumber : awbArray) {
177
	        try {
178
	            LogisticsClient lsc = new LogisticsClient();
179
	            TransactionClient tsc = new TransactionClient();
180
	            CatalogClient csc = new CatalogClient();
181
	            in.shop2020.model.v1.catalog.InventoryService.Client inventoryClient = csc.getClient();
182
	            in.shop2020.model.v1.order.TransactionService.Client txnClient = tsc.getClient();
183
	            in.shop2020.logistics.LogisticsService.Client logisticsClient = lsc.getClient();
184
 
185
	            /*
186
	             * Get required stuff
187
	             * FIXME: Reduce service calls 
188
	             */
4391 anupam.sin 189
	            Provider provider = logisticsClient.getProvider(((Long)session.getAttribute("providerId")).longValue());
4386 anupam.sin 190
	            order = txnClient.getOrderForAwb(awbNumber);
191
	            Warehouse warehouse = inventoryClient.getWarehouse(order.getWarehouse_id());
192
 
193
	            String accountNo;
194
	            if(order.isCod())
195
	                 accountNo = provider.getDetails().get(DeliveryType.COD).getAccountNo();
196
	            else
197
	                accountNo = provider.getDetails().get(DeliveryType.PREPAID).getAccountNo();
198
 
199
	            AwbDetails detailedAwb = new AwbDetails();
200
 
201
	            detailedAwb.setAwbNumber(awbNumber);
202
	            detailedAwb.setAccountCode(accountNo);
203
	            detailedAwb.setAddress1(order.getCustomer_address1());
204
	            detailedAwb.setAddress2(order.getCustomer_address2());
205
	            detailedAwb.setAmountToCollect("" + order.getTotal_amount());
206
	            Date date = new Date(order.getPickup_timestamp());
207
	            detailedAwb.setAwbDate(date.toString());
208
	            detailedAwb.setCity(order.getCustomer_city());
209
	            detailedAwb.setCustomerName(order.getCustomer_name());
210
	            detailedAwb.setItemId("" + order.getLineitems().get(0).getId());
211
	            detailedAwb.setOrderId("" + order.getId());
212
	            detailedAwb.setPacketWeight("" + order.getTotal_weight());
213
	            if (order.isCod()) {
214
	                detailedAwb.setPaymentMode("COD");
215
	            } else {
216
	                detailedAwb.setPaymentMode("Prepaid");
217
	            }
218
 
219
	            detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());
220
	            detailedAwb.setPickupLocation(warehouse.getLocation());
221
	            detailedAwb.setPinCode(order.getCustomer_pincode());
222
	            LineItem lineitem = order.getLineitems().get(0);
223
	            detailedAwb.setProductName(lineitem.getBrand() + " " + lineitem.getModel_name() + " " 
224
	                                         + lineitem.getItem_number() + " " + lineitem.getColor());
225
	            detailedAwb.setShipmentValue("" + order.getTotal_amount());
226
	            detailedAwb.setState(order.getCustomer_state());
227
 
228
	            tempList.add(detailedAwb);
3105 chandransh 229
 
4386 anupam.sin 230
	        } catch (TTransportException e) {
231
	            setErrorMsg("Your request cannot be processed due to technical error. Please try later.");
232
	        } catch (TException e) {
233
	            setErrorMsg(e.getMessage());
234
	        } catch (TransactionServiceException e) {
235
	            setErrorMsg(e.getMessage());
236
	        } catch (LogisticsServiceException e) {
237
	            setErrorMsg(e.getMessage());
238
            } catch (InventoryServiceException e) {
239
                setErrorMsg(e.getMessage());
240
            }
241
        setDetailedAWBs(tempList);
242
	    }
243
	    return "info";
244
	}
245
 
3105 chandransh 246
    /**
4386 anupam.sin 247
	 * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
248
	 * Should be used to view day before yesterday's courier details report.
249
	 * 
3105 chandransh 250
     * @return the same string tokens as show
251
     */
1075 chandransh 252
	public String dayBefore(){
253
		daysToSubtract = -2;
254
		return show();
255
	}
3105 chandransh 256
 
257
    /**
258
     * Sets the daysToSubtract to -1 and then invokes the standard show()
259
     * handler. Should be used to view yesterday's courier details report.
260
     * 
261
     * @return the same string tokens as show
262
     */
1075 chandransh 263
	public String yesterday(){
264
		daysToSubtract = -1;
265
		return show();
266
	}
3105 chandransh 267
 
268
    /**
269
     * Sets the daysToSubtract to 0 and then invokes the standard show()
270
     * handler. Should be used to view today's courier details report.
271
     * 
272
     * @return the same string tokens as show
273
     */
1075 chandransh 274
	public String today(){
275
		daysToSubtract = 0;
276
		return show();
277
	}
3364 chandransh 278
 
679 chandransh 279
	@Override
1075 chandransh 280
	public void setServletContext(ServletContext context) {
281
		this.context = context;
282
	}
283
 
284
	@Override
679 chandransh 285
	public void setServletResponse(HttpServletResponse response) {
286
		this.response  = response;
287
	}
288
 
289
	@Override
290
	public void setServletRequest(HttpServletRequest request) {
291
		this.request = request;
749 chandransh 292
		this.session = request.getSession();
679 chandransh 293
	}
294
 
749 chandransh 295
	public String getId(){
296
		return id;
297
	}
298
 
299
	public void setId(String id){
300
		this.id = id;
301
	}
302
 
303
	public String getSessionUserName(){
304
		return (String) session.getAttribute("username");
305
	}
3105 chandransh 306
 
307
    /**
308
     * Gets the list of all warehouses and maps the warehouse ids to their
309
     * display name.
310
     * 
311
     * @return the mapping of warehouse if to its display namee
312
     */
754 chandransh 313
	public Map<Long, String> getWarehouses(){
314
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
315
		try{
3125 rajveer 316
			CatalogClient csc = new CatalogClient();
754 chandransh 317
			in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
318
			List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
319
			for(Warehouse warehouse : warehouses){
4209 rajveer 320
				// FIXME Remove the hardcoding
321
				if(warehouse.getId() == 2 || warehouse.getId() == 5){
322
					continue;
323
				}
754 chandransh 324
				warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
325
			}
326
		}catch(Exception e){
3105 chandransh 327
			logger.error("Error getting the list of warehouses", e);
754 chandransh 328
		}
329
		return warehouseMap;
330
	}
749 chandransh 331
 
1075 chandransh 332
	public String getServletContextPath(){
333
		return context.getContextPath();
334
	}
4386 anupam.sin 335
 
336
    public String getAwbNumbers() {
337
        return awbNumbers;
338
    }
339
 
340
    public void setAwbNumbers(String awbNumbers) {
341
        this.awbNumbers = awbNumbers;
342
    }
343
 
344
    public List<AwbDetails> getDetailedAWBs() {
345
        return detailedAWBs;
346
    }
347
 
348
    public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {
349
        this.detailedAWBs = detailedAWBs;
350
    }
351
 
352
    public String getErrorMsg() {
353
        return errorMsg;
354
    }
355
 
356
    public void setErrorMsg(String errorMsg) {
357
        this.errorMsg = errorMsg;
358
    }
679 chandransh 359
}