Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
2674 vikas 1
package in.shop2020.serving.controllers;
2
 
4689 anupam.sin 3
import in.shop2020.crm.Activity;
4
import in.shop2020.crm.ActivityType;
3578 mandeep.dh 5
import in.shop2020.crm.SearchFilter;
6
import in.shop2020.crm.Ticket;
7
import in.shop2020.crm.TicketCategory;
4689 anupam.sin 8
import in.shop2020.crm.TicketPriority;
3578 mandeep.dh 9
import in.shop2020.crm.TicketStatus;
5845 mandeep.dh 10
import in.shop2020.logistics.PickupStore;
2674 vikas 11
import in.shop2020.model.v1.order.LineItem;
12
import in.shop2020.model.v1.order.Order;
3578 mandeep.dh 13
import in.shop2020.model.v1.order.OrderStatus;
4689 anupam.sin 14
import in.shop2020.model.v1.order.TransactionServiceException;
4142 mandeep.dh 15
import in.shop2020.model.v1.user.Address;
4689 anupam.sin 16
import in.shop2020.model.v1.user.UserContextException;
2728 vikas 17
import in.shop2020.payments.Attribute;
18
import in.shop2020.payments.Constants;
2674 vikas 19
import in.shop2020.payments.Payment;
2728 vikas 20
import in.shop2020.payments.PaymentException;
4142 mandeep.dh 21
import in.shop2020.payments.PaymentService.Client;
4689 anupam.sin 22
import in.shop2020.serving.auth.CRMAuthorizingRealm;
3090 mandeep.dh 23
import in.shop2020.serving.model.ShipmentUpdate;
5845 mandeep.dh 24
import in.shop2020.serving.services.AramexTrackingService;
3090 mandeep.dh 25
import in.shop2020.serving.services.BlueDartTrackingService;
5303 phani.kuma 26
import in.shop2020.serving.services.DelhiveryTrackingService;
3578 mandeep.dh 27
import in.shop2020.thrift.clients.CRMClient;
6322 amar.kumar 28
import in.shop2020.thrift.clients.HelperClient;
5845 mandeep.dh 29
import in.shop2020.thrift.clients.LogisticsClient;
3128 rajveer 30
import in.shop2020.thrift.clients.PaymentClient;
31
import in.shop2020.thrift.clients.TransactionClient;
4142 mandeep.dh 32
import in.shop2020.thrift.clients.UserClient;
3546 mandeep.dh 33
import in.shop2020.utils.ModelUtils;
6322 amar.kumar 34
import in.shop2020.warehouse.WarehouseService;
2674 vikas 35
 
6322 amar.kumar 36
import java.io.BufferedInputStream;
37
import java.io.File;
38
import java.io.FileInputStream;
39
import java.io.FileWriter;
40
import java.io.IOException;
41
import java.io.InputStream;
6912 anupam.sin 42
import java.text.SimpleDateFormat;
2674 vikas 43
import java.util.ArrayList;
6912 anupam.sin 44
import java.util.Calendar;
4416 mandeep.dh 45
import java.util.Collections;
6912 anupam.sin 46
import java.util.Date;
4689 anupam.sin 47
import java.util.HashSet;
2674 vikas 48
import java.util.List;
4689 anupam.sin 49
import java.util.Set;
4416 mandeep.dh 50
import java.util.concurrent.Callable;
51
import java.util.concurrent.Executors;
52
import java.util.concurrent.TimeUnit;
2674 vikas 53
 
6322 amar.kumar 54
import javax.servlet.ServletOutputStream;
55
 
4689 anupam.sin 56
import net.htmlparser.jericho.Source;
57
 
5845 mandeep.dh 58
import org.apache.commons.lang.StringUtils;
2674 vikas 59
import org.apache.log4j.Logger;
2728 vikas 60
import org.apache.thrift.TException;
4142 mandeep.dh 61
import org.apache.thrift.transport.TTransportException;
2674 vikas 62
 
63
/**
64
 * @author vikas
3578 mandeep.dh 65
 * 
2674 vikas 66
 */
67
@SuppressWarnings("serial")
68
public class UserOrderInfoController extends BaseController {
3578 mandeep.dh 69
    private static Logger                  log                     = Logger.getLogger(Class.class);
3090 mandeep.dh 70
    private static BlueDartTrackingService blueDartTrackingService = new BlueDartTrackingService();
4710 anupam.sin 71
    private static AramexTrackingService aramexTrackingService     = new AramexTrackingService();
5303 phani.kuma 72
    private static DelhiveryTrackingService delhiveryTrackingService     = new DelhiveryTrackingService();
3090 mandeep.dh 73
 
4142 mandeep.dh 74
    private long                 orderId;
75
    private Order                order;
76
    private List<Payment>        payments;
4416 mandeep.dh 77
    private List<ShipmentUpdate> shipmentUpdates = new ArrayList<ShipmentUpdate>();
4142 mandeep.dh 78
    private Long                 codTicketId;
79
    private List<Address>        addresses;
4689 anupam.sin 80
    private Set<OrderStatus>     setOfcancellableStates;
81
    private String               cancellationInitiator;
82
    private String               cancelReason;
83
    private String               body;
2674 vikas 84
 
3578 mandeep.dh 85
    public UserOrderInfoController() {
2674 vikas 86
        super();
4689 anupam.sin 87
        setOfcancellableStates = new HashSet<OrderStatus>();
88
        setOfcancellableStates.add(OrderStatus.SUBMITTED_FOR_PROCESSING);
89
        setOfcancellableStates.add(OrderStatus.INVENTORY_LOW);
90
        setOfcancellableStates.add(OrderStatus.LOW_INV_PO_RAISED);
91
        setOfcancellableStates.add(OrderStatus.LOW_INV_REVERSAL_IN_PROCESS);
92
        setOfcancellableStates.add(OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT);
93
        setOfcancellableStates.add(OrderStatus.ACCEPTED);
94
        setOfcancellableStates.add(OrderStatus.BILLED);
2674 vikas 95
    }
96
 
4689 anupam.sin 97
    public String index() {
98
        try {
99
            PaymentClient paymentServiceClient = new PaymentClient();
100
            TransactionClient transactionServiceClient = new TransactionClient();
3090 mandeep.dh 101
 
3499 mandeep.dh 102
            order = transactionServiceClient.getClient().getOrder(orderId);
2674 vikas 103
 
4689 anupam.sin 104
            payments = paymentServiceClient.getClient()
105
            .getPaymentForTxnId(order.getTransactionId());
3090 mandeep.dh 106
 
3578 mandeep.dh 107
 
4689 anupam.sin 108
 
109
            // Spawning a thread to capture shipment updates from Bluedart
110
            // This is done to ensure that response from Crm web app is sent
111
            // within given time limits. Also, we wont be affected in the cases 
112
            // where bluedart site is down or slow
113
            Executors.newSingleThreadExecutor().invokeAll(Collections.singletonList(new Callable<Boolean>() {
114
                public Boolean call() throws Exception {
4710 anupam.sin 115
                    if (order.getLogistics_provider_id() == 1)
116
                        shipmentUpdates = blueDartTrackingService.getUpdates(order.getAirwaybill_no());
117
                    else if (order.getLogistics_provider_id() == 2) {
118
                        shipmentUpdates = aramexTrackingService.getUpdates(order.getAirwaybill_no());
119
                    }
5303 phani.kuma 120
                    else if (order.getLogistics_provider_id() == 3) {
121
                        shipmentUpdates = delhiveryTrackingService.getUpdates(order.getAirwaybill_no());
122
                    }
4710 anupam.sin 123
                    else {
5845 mandeep.dh 124
                        shipmentUpdates = new ArrayList<ShipmentUpdate>();
4710 anupam.sin 125
                        log.error("Error : providerId = " + order.getLogistics_provider_id() + "for orderId : " + order.getId());
126
                    }
4689 anupam.sin 127
                    return true;
128
                }
129
            }), 5, TimeUnit.SECONDS);
130
 
131
            if (order.isCod() && OrderStatus.COD_VERIFICATION_PENDING.equals(order.getStatus())) {
132
                populateCODTicketId(order.getCustomer_id());
4416 mandeep.dh 133
            }
134
 
4689 anupam.sin 135
            if (canEditOrderAddress()) {
136
                userContextServiceClient = new UserClient().getClient();
137
                addresses = userContextServiceClient.getAllAddressesForUser(order.getCustomer_id());
138
            }
3578 mandeep.dh 139
 
4689 anupam.sin 140
        } catch (TTransportException e) {
141
            log.error("Unable to create thrift Client", e);
142
        } catch (TransactionServiceException e) {
143
            addActionError("Invalid order id or no order selected.");
144
        } catch (TException e) {
145
            log.error("Unable to get thrift Client", e);
146
        } catch (PaymentException e) {
147
            log.error("Unable to get payments for transctionId : " + order.getTransactionId(), e);
148
        } catch (InterruptedException e) {
149
            log.error("Thread was interrupted", e);
150
        } catch (UserContextException e) {
151
            log.error("Unable to get addresses for user : " + order.getCustomer_id(), e);
4142 mandeep.dh 152
        }
153
        return INDEX;
2674 vikas 154
    }
155
 
4142 mandeep.dh 156
    private boolean canEditOrderAddress() {
157
        return false;
158
    }
159
 
3578 mandeep.dh 160
    private void populateCODTicketId(long customerId) {
161
        try {
162
            SearchFilter searchFilter = new SearchFilter();
163
            searchFilter.setTicketCategory(TicketCategory.COD_VERIFICATION);
164
            searchFilter.setTicketStatuses(new ArrayList<TicketStatus>());
165
            searchFilter.getTicketStatuses().add(TicketStatus.OPEN);
166
            searchFilter.getTicketStatuses().add(TicketStatus.REOPEN);
167
            searchFilter.setCustomerId(customerId);
168
            crmServiceClient = new CRMClient().getClient();
169
            List<Ticket> tickets = crmServiceClient.getTickets(searchFilter);
170
            if (tickets != null && !tickets.isEmpty()) {
171
                codTicketId = tickets.get(0).getId();
172
            }
173
        } catch (TException e) {
174
            log.error("Error fetching tickets for customerId: " + customerId, e);
175
        }
176
    }
177
 
4689 anupam.sin 178
    public String markOrderForCancellation() {
179
        try{
180
            TransactionClient transactionServiceClient = new TransactionClient();
181
            log.info("URL = " + request.getRequestURI());
182
            log.info("Initiator = " + request.getParameter("cancellationInitiator"));
183
            log.info("orderId = " + request.getParameter("orderId"));
184
            if (cancellationInitiator.equals("CUSTOMER")) {
185
                order = transactionServiceClient.getClient().getOrder(orderId);
186
                transactionServiceClient.getClient().markOrderCancellationRequestReceived(orderId);
187
                long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();
188
                Ticket ticket = new Ticket();
189
                String plainTextbody = "";
190
                if(body!=null && !body.isEmpty()){
191
                    plainTextbody = new Source(body).getTextExtractor().toString();
192
                }
193
                ticket.setDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);
194
                ticket.setCreatorId(creatorId);
195
                ticket.setStatus(TicketStatus.OPEN);
196
                ticket.setPriority(TicketPriority.HIGH);
197
                ticket.setCategory(TicketCategory.ORDER_CANCELLATION);
198
                ticket.setOrderId(orderId);
199
 
200
                Activity activity = new Activity();
201
                activity.setDescription("Creating Ticket");
202
                activity.setType(ActivityType.OTHER);
203
                activity.setTicketPriority(TicketPriority.HIGH);
204
                activity.setTicketStatus(TicketStatus.OPEN);
205
                activity.setCreatorId(creatorId);
206
                activity.setTicketDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);
207
                activity.setTicketCategory(TicketCategory.ORDER_CANCELLATION);
208
 
209
                ticket.setCustomerId(order.getCustomer_id());
210
                activity.setCustomerId(order.getCustomer_id());
211
                ticket.setCustomerName(order.getCustomer_name());
212
                activity.setCustomerName(order.getCustomer_name());
213
                ticket.setCustomerEmailId(order.getCustomer_email());
214
                activity.setCustomerEmailId(order.getCustomer_email());
215
                ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());
216
                activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());
217
 
218
                crmServiceClient = new CRMClient().getClient();
219
                crmServiceClient.insertTicket(ticket, activity);
220
            } 
221
            else if (cancellationInitiator.equals("INTERNAL")) {
222
                String plainTextbody = "";
223
                if(body!=null && !body.isEmpty()){
224
                    plainTextbody = new Source(body).getTextExtractor().toString();
225
                }
226
                transactionServiceClient.getClient().refundOrder(orderId, currentAgentEmailId, cancelReason + " : " + plainTextbody);
227
                long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();
228
                Ticket ticket = new Ticket();
229
                ticket.setDescription("Creating ticket for Order Cancellation due to Low inventory");
230
                ticket.setCreatorId(creatorId);
231
                ticket.setStatus(TicketStatus.CLOSED);
232
                ticket.setPriority(TicketPriority.MEDIUM);
233
                ticket.setCategory(TicketCategory.ORDER_CANCELLATION);
234
                ticket.setOrderId(orderId);
235
 
236
                Activity activity = new Activity();
237
                activity.setDescription("Creating Ticket");
238
                activity.setType(ActivityType.OTHER);
239
                activity.setTicketPriority(TicketPriority.MEDIUM);
240
                activity.setTicketStatus(TicketStatus.CLOSED);
241
                activity.setCreatorId(creatorId);
242
                activity.setTicketCategory(TicketCategory.ORDER_CANCELLATION);
243
                activity.setTicketDescription("Creating ticket for Order Cancellation due to Low inventory");
244
 
245
                ticket.setCustomerId(order.getCustomer_id());
246
                activity.setCustomerId(order.getCustomer_id());
247
                ticket.setCustomerName(order.getCustomer_name());
248
                activity.setCustomerName(order.getCustomer_name());
249
                ticket.setCustomerEmailId(order.getCustomer_email());
250
                activity.setCustomerEmailId(order.getCustomer_email());
251
                ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());
252
                activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());
253
 
254
                crmServiceClient = new CRMClient().getClient();
255
                crmServiceClient.insertTicket(ticket, activity);
256
            }
257
        } catch(Exception e) {
258
            log.error("Could not mark order for Cancellation, OrderId : " + orderId, e);
259
        }
260
        return index();
261
    }
262
 
6322 amar.kumar 263
    public void getOrderConfirmationMail() throws IOException, TException {
264
    	HelperClient helperClient = new HelperClient();
265
    	String mail = helperClient.getClient().getOrderConfirmationMail(orderId);
266
    	File file = new File("temp");
267
    	FileWriter writer = new FileWriter(file);
268
    	writer.append(mail);
269
    	writer.close();
270
 
271
    	byte[] buffer = new byte[(int)file.length()];
272
        InputStream input = null;
273
    	try {
274
            int totalBytesRead = 0;
275
            input = new BufferedInputStream(new FileInputStream(file));
276
            while(totalBytesRead < buffer.length){
277
                int bytesRemaining = buffer.length - totalBytesRead;
278
                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
279
                if (bytesRead > 0){
280
                    totalBytesRead = totalBytesRead + bytesRead;
281
                }
282
            }
283
        }
284
        finally {
285
            input.close();
286
            file.delete();
287
        }
288
 
289
 
290
    	response.setHeader("Content-disposition", "inline; filename=" + "OrderDetail_"+orderId );
291
 
292
        ServletOutputStream sos;
293
        try {
294
            sos = response.getOutputStream();
295
            sos.write(buffer);
296
            sos.flush();
297
        } catch (IOException e) {
298
            System.out.println("Unable to stream the manifest file");
299
        }   
300
    }
301
 
4689 anupam.sin 302
    public boolean canOrderBeCancelled() {
303
        if (setOfcancellableStates.contains(order.getStatus())) {
304
            return true;
305
        }
306
        return false;
307
    }
308
 
4142 mandeep.dh 309
    public String getPaymentGateway(Payment payment) {
310
        String gatewayName = "";
3578 mandeep.dh 311
 
4142 mandeep.dh 312
        try {
313
            Client paymentServiceClient = new PaymentClient().getClient();
314
            gatewayName = paymentServiceClient.getPaymentGateway(payment.getGatewayId()).getName();
315
        } catch (TTransportException e) {
316
        } catch (PaymentException e) {
317
        } catch (TException e) {
2674 vikas 318
        }
4142 mandeep.dh 319
 
320
        return gatewayName;
2674 vikas 321
    }
322
 
4142 mandeep.dh 323
    public String getProductName(LineItem lineItem) {
324
        String name = ModelUtils.extractProductNameFromLineItem(lineItem);
325
 
4146 mandeep.dh 326
        if (lineItem.getColor() != null && !lineItem.getColor().isEmpty()) {
4142 mandeep.dh 327
            name += "(" + lineItem.getColor() + ")";
2674 vikas 328
        }
4142 mandeep.dh 329
 
330
        return name;
2674 vikas 331
    }
332
 
4142 mandeep.dh 333
    public int convertDouble(double value) {
334
        return (int)value;
2674 vikas 335
    }
6912 anupam.sin 336
 
337
    public String getInsuranceExpiryDate(long DeliveryDate) {
338
        if (DeliveryDate == 0) {
339
            return "N/A";
340
        }
341
        Calendar cal = Calendar.getInstance();
342
        cal.setTimeInMillis(DeliveryDate);
343
        cal.add(Calendar.YEAR, 1);
6960 anupam.sin 344
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
345
        return sdf.format(cal.getTime());
6912 anupam.sin 346
    }
3578 mandeep.dh 347
 
5845 mandeep.dh 348
    public String getShippingAddressOfStore(long storeId) {
349
        try {
350
            in.shop2020.logistics.LogisticsService.Client client = new LogisticsClient().getClient();
351
            PickupStore store = client.getPickupStore(storeId);
352
            return StringUtils.join(new String[] {
353
                    store.getName(),
354
                    store.getLine1(),
355
                    store.getLine2(),
356
                    store.getPin(),
357
                    store.getCity(),
358
                    store.getState(),
359
                    store.getPhone()}, ",");
360
        } catch (Exception e) {
361
            return "";
362
        }
363
    }
364
 
4142 mandeep.dh 365
    public String getAddress(Order order) {
366
        return ModelUtils.extractAddressFromOrder(order);
367
    }
368
 
2728 vikas 369
    public String getPaymentMethod(List<Attribute> paymentAttributes) {
370
        String paymentMethod = null;
3578 mandeep.dh 371
        if (paymentAttributes == null || paymentAttributes.isEmpty()) {
2728 vikas 372
            return "N/A";
373
        }
3578 mandeep.dh 374
        for (Attribute a : paymentAttributes) {
375
            if ("payMethod".equals(a.getName())) {
2728 vikas 376
                paymentMethod = Constants.PAYMENT_METHOD.get(a.getValue());
377
                break;
378
            }
379
        }
380
        return paymentMethod != null ? paymentMethod : "N/A";
381
    }
2674 vikas 382
 
383
    public void setOrderId(String orderId) {
384
        try {
385
            this.orderId = Long.parseLong(orderId);
3578 mandeep.dh 386
        } catch (NumberFormatException e) {
2674 vikas 387
            log.error(e);
388
        }
389
    }
390
 
4142 mandeep.dh 391
    public List<Payment> getPayments() {
392
        return payments;
2674 vikas 393
    }
394
 
3090 mandeep.dh 395
    public List<ShipmentUpdate> getShipmentUpdates() {
396
        return shipmentUpdates;
397
    }
398
 
399
    public void setShipmentUpdates(List<ShipmentUpdate> shipmentUpdates) {
400
        this.shipmentUpdates = shipmentUpdates;
401
    }
3499 mandeep.dh 402
 
403
    public Order getOrder() {
404
        return order;
405
    }
406
 
407
    public void setOrder(Order order) {
408
        this.order = order;
409
    }
3578 mandeep.dh 410
 
411
    public Long getCodTicketId() {
412
        return codTicketId;
413
    }
414
 
415
    public void setCodTicketId(Long codTicketId) {
416
        this.codTicketId = codTicketId;
417
    }
4142 mandeep.dh 418
 
419
    public List<Address> getAddresses() {
420
        return addresses;
421
    }
422
 
423
    public void setAddresses(List<Address> addresses) {
424
        this.addresses = addresses;
425
    }
4241 anupam.sin 426
 
427
    public String getOrderStatusDescription(Order order) {
428
        String status = order.getStatus().getDescription();
429
 
430
        if (order.getStatus() == OrderStatus.DELIVERY_SUCCESS) {
431
            status = "Completed";
432
        }
433
 
434
        return status;
435
    }
4689 anupam.sin 436
 
437
    public String getCancellationInitiator() {
438
        return cancellationInitiator;
439
    }
440
 
441
    public void setCancellationInitiator(String cancellationInitiator) {
442
        this.cancellationInitiator = cancellationInitiator;
443
    }
444
 
445
    public String getCancelReason() {
446
        return cancelReason;
447
    }
448
 
449
    public void setCancelReason(String cancelReason) {
450
        this.cancelReason = cancelReason;
451
    }
452
 
453
    public String getBody() {
454
        return body;
455
    }
456
 
457
    public void setBody(String body) {
458
        this.body = body;
459
    }
2674 vikas 460
}