Subversion Repositories SmartDukaan

Rev

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