Subversion Repositories SmartDukaan

Rev

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