Subversion Repositories SmartDukaan

Rev

Rev 4209 | Rev 4391 | 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
	             */
189
	            Awb awb = logisticsClient.getAwbForNumber(awbNumber);
190
	            Provider provider = logisticsClient.getProvider(awb.getProviderId());
191
	            order = txnClient.getOrderForAwb(awbNumber);
192
	            Warehouse warehouse = inventoryClient.getWarehouse(order.getWarehouse_id());
193
 
194
	            String accountNo;
195
	            if(order.isCod())
196
	                 accountNo = provider.getDetails().get(DeliveryType.COD).getAccountNo();
197
	            else
198
	                accountNo = provider.getDetails().get(DeliveryType.PREPAID).getAccountNo();
199
 
200
	            AwbDetails detailedAwb = new AwbDetails();
201
 
202
	            detailedAwb.setAwbNumber(awbNumber);
203
	            detailedAwb.setAccountCode(accountNo);
204
	            detailedAwb.setAddress1(order.getCustomer_address1());
205
	            detailedAwb.setAddress2(order.getCustomer_address2());
206
	            detailedAwb.setAmountToCollect("" + order.getTotal_amount());
207
	            Date date = new Date(order.getPickup_timestamp());
208
	            detailedAwb.setAwbDate(date.toString());
209
	            detailedAwb.setCity(order.getCustomer_city());
210
	            detailedAwb.setCustomerName(order.getCustomer_name());
211
	            detailedAwb.setItemId("" + order.getLineitems().get(0).getId());
212
	            detailedAwb.setOrderId("" + order.getId());
213
	            detailedAwb.setPacketWeight("" + order.getTotal_weight());
214
	            if (order.isCod()) {
215
	                detailedAwb.setPaymentMode("COD");
216
	            } else {
217
	                detailedAwb.setPaymentMode("Prepaid");
218
	            }
219
 
220
	            detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());
221
	            detailedAwb.setPickupLocation(warehouse.getLocation());
222
	            detailedAwb.setPinCode(order.getCustomer_pincode());
223
	            LineItem lineitem = order.getLineitems().get(0);
224
	            detailedAwb.setProductName(lineitem.getBrand() + " " + lineitem.getModel_name() + " " 
225
	                                         + lineitem.getItem_number() + " " + lineitem.getColor());
226
	            detailedAwb.setShipmentValue("" + order.getTotal_amount());
227
	            detailedAwb.setState(order.getCustomer_state());
228
 
229
	            tempList.add(detailedAwb);
3105 chandransh 230
 
4386 anupam.sin 231
	        } catch (TTransportException e) {
232
	            setErrorMsg("Your request cannot be processed due to technical error. Please try later.");
233
	        } catch (TException e) {
234
	            setErrorMsg(e.getMessage());
235
	        } catch (TransactionServiceException e) {
236
	            setErrorMsg(e.getMessage());
237
	        } catch (LogisticsServiceException e) {
238
	            setErrorMsg(e.getMessage());
239
            } catch (InventoryServiceException e) {
240
                setErrorMsg(e.getMessage());
241
            }
242
        setDetailedAWBs(tempList);
243
	    }
244
	    return "info";
245
	}
246
 
3105 chandransh 247
    /**
4386 anupam.sin 248
	 * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
249
	 * Should be used to view day before yesterday's courier details report.
250
	 * 
3105 chandransh 251
     * @return the same string tokens as show
252
     */
1075 chandransh 253
	public String dayBefore(){
254
		daysToSubtract = -2;
255
		return show();
256
	}
3105 chandransh 257
 
258
    /**
259
     * Sets the daysToSubtract to -1 and then invokes the standard show()
260
     * handler. Should be used to view yesterday's courier details report.
261
     * 
262
     * @return the same string tokens as show
263
     */
1075 chandransh 264
	public String yesterday(){
265
		daysToSubtract = -1;
266
		return show();
267
	}
3105 chandransh 268
 
269
    /**
270
     * Sets the daysToSubtract to 0 and then invokes the standard show()
271
     * handler. Should be used to view today's courier details report.
272
     * 
273
     * @return the same string tokens as show
274
     */
1075 chandransh 275
	public String today(){
276
		daysToSubtract = 0;
277
		return show();
278
	}
3364 chandransh 279
 
679 chandransh 280
	@Override
1075 chandransh 281
	public void setServletContext(ServletContext context) {
282
		this.context = context;
283
	}
284
 
285
	@Override
679 chandransh 286
	public void setServletResponse(HttpServletResponse response) {
287
		this.response  = response;
288
	}
289
 
290
	@Override
291
	public void setServletRequest(HttpServletRequest request) {
292
		this.request = request;
749 chandransh 293
		this.session = request.getSession();
679 chandransh 294
	}
295
 
749 chandransh 296
	public String getId(){
297
		return id;
298
	}
299
 
300
	public void setId(String id){
301
		this.id = id;
302
	}
303
 
304
	public String getSessionUserName(){
305
		return (String) session.getAttribute("username");
306
	}
3105 chandransh 307
 
308
    /**
309
     * Gets the list of all warehouses and maps the warehouse ids to their
310
     * display name.
311
     * 
312
     * @return the mapping of warehouse if to its display namee
313
     */
754 chandransh 314
	public Map<Long, String> getWarehouses(){
315
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
316
		try{
3125 rajveer 317
			CatalogClient csc = new CatalogClient();
754 chandransh 318
			in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
319
			List<Warehouse> warehouses = catalogClient.getAllWarehouses(true);
320
			for(Warehouse warehouse : warehouses){
4209 rajveer 321
				// FIXME Remove the hardcoding
322
				if(warehouse.getId() == 2 || warehouse.getId() == 5){
323
					continue;
324
				}
754 chandransh 325
				warehouseMap.put(warehouse.getId(), warehouse.getDisplayName());
326
			}
327
		}catch(Exception e){
3105 chandransh 328
			logger.error("Error getting the list of warehouses", e);
754 chandransh 329
		}
330
		return warehouseMap;
331
	}
749 chandransh 332
 
1075 chandransh 333
	public String getServletContextPath(){
334
		return context.getContextPath();
335
	}
4386 anupam.sin 336
 
337
    public String getAwbNumbers() {
338
        return awbNumbers;
339
    }
340
 
341
    public void setAwbNumbers(String awbNumbers) {
342
        this.awbNumbers = awbNumbers;
343
    }
344
 
345
    public List<AwbDetails> getDetailedAWBs() {
346
        return detailedAWBs;
347
    }
348
 
349
    public void setDetailedAWBs(List<AwbDetails> detailedAWBs) {
350
        this.detailedAWBs = detailedAWBs;
351
    }
352
 
353
    public String getErrorMsg() {
354
        return errorMsg;
355
    }
356
 
357
    public void setErrorMsg(String errorMsg) {
358
        this.errorMsg = errorMsg;
359
    }
679 chandransh 360
}