Subversion Repositories SmartDukaan

Rev

Rev 4788 | Rev 5554 | 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());
4604 anupam.sin 205
	            if (order.isCod()) {
206
	                detailedAwb.setAmountToCollect("" + order.getTotal_amount());
207
	            } else {
208
	                detailedAwb.setAmountToCollect("" + 0 );
209
	            }
4386 anupam.sin 210
	            Date date = new Date(order.getPickup_timestamp());
211
	            detailedAwb.setAwbDate(date.toString());
212
	            detailedAwb.setCity(order.getCustomer_city());
213
	            detailedAwb.setCustomerName(order.getCustomer_name());
214
	            detailedAwb.setItemId("" + order.getLineitems().get(0).getId());
215
	            detailedAwb.setOrderId("" + order.getId());
216
	            detailedAwb.setPacketWeight("" + order.getTotal_weight());
217
	            if (order.isCod()) {
218
	                detailedAwb.setPaymentMode("COD");
219
	            } else {
220
	                detailedAwb.setPaymentMode("Prepaid");
221
	            }
222
 
223
	            detailedAwb.setPhoneNumber("" + order.getCustomer_mobilenumber());
224
	            detailedAwb.setPickupLocation(warehouse.getLocation());
225
	            detailedAwb.setPinCode(order.getCustomer_pincode());
226
	            LineItem lineitem = order.getLineitems().get(0);
227
	            detailedAwb.setProductName(lineitem.getBrand() + " " + lineitem.getModel_name() + " " 
228
	                                         + lineitem.getItem_number() + " " + lineitem.getColor());
229
	            detailedAwb.setShipmentValue("" + order.getTotal_amount());
230
	            detailedAwb.setState(order.getCustomer_state());
231
 
232
	            tempList.add(detailedAwb);
3105 chandransh 233
 
4386 anupam.sin 234
	        } catch (TTransportException e) {
235
	            setErrorMsg("Your request cannot be processed due to technical error. Please try later.");
236
	        } catch (TException e) {
237
	            setErrorMsg(e.getMessage());
238
	        } catch (TransactionServiceException e) {
239
	            setErrorMsg(e.getMessage());
240
	        } catch (LogisticsServiceException e) {
241
	            setErrorMsg(e.getMessage());
242
            } catch (InventoryServiceException e) {
243
                setErrorMsg(e.getMessage());
244
            }
245
        setDetailedAWBs(tempList);
246
	    }
247
	    return "info";
248
	}
249
 
3105 chandransh 250
    /**
4386 anupam.sin 251
	 * Sets the daysToSubtract to -2 and then invokes the standard show() handler.
252
	 * Should be used to view day before yesterday's courier details report.
253
	 * 
3105 chandransh 254
     * @return the same string tokens as show
255
     */
1075 chandransh 256
	public String dayBefore(){
257
		daysToSubtract = -2;
258
		return show();
259
	}
3105 chandransh 260
 
261
    /**
262
     * Sets the daysToSubtract to -1 and then invokes the standard show()
263
     * handler. Should be used to view yesterday's courier details report.
264
     * 
265
     * @return the same string tokens as show
266
     */
1075 chandransh 267
	public String yesterday(){
268
		daysToSubtract = -1;
269
		return show();
270
	}
3105 chandransh 271
 
272
    /**
273
     * Sets the daysToSubtract to 0 and then invokes the standard show()
274
     * handler. Should be used to view today's courier details report.
275
     * 
276
     * @return the same string tokens as show
277
     */
1075 chandransh 278
	public String today(){
279
		daysToSubtract = 0;
280
		return show();
281
	}
3364 chandransh 282
 
679 chandransh 283
	@Override
1075 chandransh 284
	public void setServletContext(ServletContext context) {
285
		this.context = context;
286
	}
287
 
288
	@Override
679 chandransh 289
	public void setServletResponse(HttpServletResponse response) {
290
		this.response  = response;
291
	}
292
 
293
	@Override
294
	public void setServletRequest(HttpServletRequest request) {
295
		this.request = request;
749 chandransh 296
		this.session = request.getSession();
679 chandransh 297
	}
298
 
749 chandransh 299
	public String getId(){
300
		return id;
301
	}
302
 
303
	public void setId(String id){
304
		this.id = id;
305
	}
306
 
307
	public String getSessionUserName(){
308
		return (String) session.getAttribute("username");
309
	}
3105 chandransh 310
 
311
    /**
312
     * Gets the list of all warehouses and maps the warehouse ids to their
313
     * display name.
314
     * 
315
     * @return the mapping of warehouse if to its display namee
316
     */
754 chandransh 317
	public Map<Long, String> getWarehouses(){
318
		Map<Long, String> warehouseMap = new HashMap<Long, String>();
319
		try{
3125 rajveer 320
			CatalogClient csc = new CatalogClient();
754 chandransh 321
			in.shop2020.model.v1.catalog.InventoryService.Client catalogClient= csc.getClient();
5185 mandeep.dh 322
			List<Warehouse> warehouses = catalogClient.getShippingLocations();
754 chandransh 323
			for(Warehouse warehouse : warehouses){
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
}