Subversion Repositories SmartDukaan

Rev

Rev 6960 | Rev 7065 | 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;
6985 anupam.sin 84
    private String               line1;
85
    private String               line2;
86
    private String               city;
87
    private String               state;
88
    private String               pin;
2674 vikas 89
 
3578 mandeep.dh 90
    public UserOrderInfoController() {
2674 vikas 91
        super();
4689 anupam.sin 92
        setOfcancellableStates = new HashSet<OrderStatus>();
93
        setOfcancellableStates.add(OrderStatus.SUBMITTED_FOR_PROCESSING);
94
        setOfcancellableStates.add(OrderStatus.INVENTORY_LOW);
95
        setOfcancellableStates.add(OrderStatus.LOW_INV_PO_RAISED);
96
        setOfcancellableStates.add(OrderStatus.LOW_INV_REVERSAL_IN_PROCESS);
97
        setOfcancellableStates.add(OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT);
98
        setOfcancellableStates.add(OrderStatus.ACCEPTED);
99
        setOfcancellableStates.add(OrderStatus.BILLED);
2674 vikas 100
    }
101
 
4689 anupam.sin 102
    public String index() {
103
        try {
104
            PaymentClient paymentServiceClient = new PaymentClient();
105
            TransactionClient transactionServiceClient = new TransactionClient();
3090 mandeep.dh 106
 
3499 mandeep.dh 107
            order = transactionServiceClient.getClient().getOrder(orderId);
2674 vikas 108
 
4689 anupam.sin 109
            payments = paymentServiceClient.getClient()
110
            .getPaymentForTxnId(order.getTransactionId());
3090 mandeep.dh 111
 
3578 mandeep.dh 112
 
4689 anupam.sin 113
 
114
            // Spawning a thread to capture shipment updates from Bluedart
115
            // This is done to ensure that response from Crm web app is sent
116
            // within given time limits. Also, we wont be affected in the cases 
117
            // where bluedart site is down or slow
118
            Executors.newSingleThreadExecutor().invokeAll(Collections.singletonList(new Callable<Boolean>() {
119
                public Boolean call() throws Exception {
4710 anupam.sin 120
                    if (order.getLogistics_provider_id() == 1)
121
                        shipmentUpdates = blueDartTrackingService.getUpdates(order.getAirwaybill_no());
122
                    else if (order.getLogistics_provider_id() == 2) {
123
                        shipmentUpdates = aramexTrackingService.getUpdates(order.getAirwaybill_no());
124
                    }
5303 phani.kuma 125
                    else if (order.getLogistics_provider_id() == 3) {
126
                        shipmentUpdates = delhiveryTrackingService.getUpdates(order.getAirwaybill_no());
127
                    }
4710 anupam.sin 128
                    else {
5845 mandeep.dh 129
                        shipmentUpdates = new ArrayList<ShipmentUpdate>();
4710 anupam.sin 130
                        log.error("Error : providerId = " + order.getLogistics_provider_id() + "for orderId : " + order.getId());
131
                    }
4689 anupam.sin 132
                    return true;
133
                }
134
            }), 5, TimeUnit.SECONDS);
135
 
136
            if (order.isCod() && OrderStatus.COD_VERIFICATION_PENDING.equals(order.getStatus())) {
137
                populateCODTicketId(order.getCustomer_id());
4416 mandeep.dh 138
            }
139
 
4689 anupam.sin 140
            if (canEditOrderAddress()) {
141
                userContextServiceClient = new UserClient().getClient();
142
                addresses = userContextServiceClient.getAllAddressesForUser(order.getCustomer_id());
143
            }
3578 mandeep.dh 144
 
4689 anupam.sin 145
        } catch (TTransportException e) {
146
            log.error("Unable to create thrift Client", e);
147
        } catch (TransactionServiceException e) {
148
            addActionError("Invalid order id or no order selected.");
149
        } catch (TException e) {
150
            log.error("Unable to get thrift Client", e);
151
        } catch (PaymentException e) {
152
            log.error("Unable to get payments for transctionId : " + order.getTransactionId(), e);
153
        } catch (InterruptedException e) {
154
            log.error("Thread was interrupted", e);
155
        } catch (UserContextException e) {
156
            log.error("Unable to get addresses for user : " + order.getCustomer_id(), e);
4142 mandeep.dh 157
        }
158
        return INDEX;
2674 vikas 159
    }
160
 
4142 mandeep.dh 161
    private boolean canEditOrderAddress() {
162
        return false;
163
    }
164
 
3578 mandeep.dh 165
    private void populateCODTicketId(long customerId) {
166
        try {
167
            SearchFilter searchFilter = new SearchFilter();
168
            searchFilter.setTicketCategory(TicketCategory.COD_VERIFICATION);
169
            searchFilter.setTicketStatuses(new ArrayList<TicketStatus>());
170
            searchFilter.getTicketStatuses().add(TicketStatus.OPEN);
171
            searchFilter.getTicketStatuses().add(TicketStatus.REOPEN);
172
            searchFilter.setCustomerId(customerId);
173
            crmServiceClient = new CRMClient().getClient();
174
            List<Ticket> tickets = crmServiceClient.getTickets(searchFilter);
175
            if (tickets != null && !tickets.isEmpty()) {
176
                codTicketId = tickets.get(0).getId();
177
            }
178
        } catch (TException e) {
179
            log.error("Error fetching tickets for customerId: " + customerId, e);
180
        }
181
    }
182
 
4689 anupam.sin 183
    public String markOrderForCancellation() {
184
        try{
185
            TransactionClient transactionServiceClient = new TransactionClient();
186
            log.info("URL = " + request.getRequestURI());
187
            log.info("Initiator = " + request.getParameter("cancellationInitiator"));
188
            log.info("orderId = " + request.getParameter("orderId"));
189
            if (cancellationInitiator.equals("CUSTOMER")) {
190
                order = transactionServiceClient.getClient().getOrder(orderId);
191
                transactionServiceClient.getClient().markOrderCancellationRequestReceived(orderId);
192
                long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();
193
                Ticket ticket = new Ticket();
194
                String plainTextbody = "";
195
                if(body!=null && !body.isEmpty()){
196
                    plainTextbody = new Source(body).getTextExtractor().toString();
197
                }
198
                ticket.setDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);
199
                ticket.setCreatorId(creatorId);
200
                ticket.setStatus(TicketStatus.OPEN);
201
                ticket.setPriority(TicketPriority.HIGH);
202
                ticket.setCategory(TicketCategory.ORDER_CANCELLATION);
203
                ticket.setOrderId(orderId);
204
 
205
                Activity activity = new Activity();
206
                activity.setDescription("Creating Ticket");
207
                activity.setType(ActivityType.OTHER);
208
                activity.setTicketPriority(TicketPriority.HIGH);
209
                activity.setTicketStatus(TicketStatus.OPEN);
210
                activity.setCreatorId(creatorId);
211
                activity.setTicketDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);
212
                activity.setTicketCategory(TicketCategory.ORDER_CANCELLATION);
213
 
214
                ticket.setCustomerId(order.getCustomer_id());
215
                activity.setCustomerId(order.getCustomer_id());
216
                ticket.setCustomerName(order.getCustomer_name());
217
                activity.setCustomerName(order.getCustomer_name());
218
                ticket.setCustomerEmailId(order.getCustomer_email());
219
                activity.setCustomerEmailId(order.getCustomer_email());
220
                ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());
221
                activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());
222
 
223
                crmServiceClient = new CRMClient().getClient();
224
                crmServiceClient.insertTicket(ticket, activity);
225
            } 
226
            else if (cancellationInitiator.equals("INTERNAL")) {
227
                String plainTextbody = "";
228
                if(body!=null && !body.isEmpty()){
229
                    plainTextbody = new Source(body).getTextExtractor().toString();
230
                }
231
                transactionServiceClient.getClient().refundOrder(orderId, currentAgentEmailId, cancelReason + " : " + plainTextbody);
232
                long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();
233
                Ticket ticket = new Ticket();
234
                ticket.setDescription("Creating ticket for Order Cancellation due to Low inventory");
235
                ticket.setCreatorId(creatorId);
236
                ticket.setStatus(TicketStatus.CLOSED);
237
                ticket.setPriority(TicketPriority.MEDIUM);
238
                ticket.setCategory(TicketCategory.ORDER_CANCELLATION);
239
                ticket.setOrderId(orderId);
240
 
241
                Activity activity = new Activity();
242
                activity.setDescription("Creating Ticket");
243
                activity.setType(ActivityType.OTHER);
244
                activity.setTicketPriority(TicketPriority.MEDIUM);
245
                activity.setTicketStatus(TicketStatus.CLOSED);
246
                activity.setCreatorId(creatorId);
247
                activity.setTicketCategory(TicketCategory.ORDER_CANCELLATION);
248
                activity.setTicketDescription("Creating ticket for Order Cancellation due to Low inventory");
249
 
250
                ticket.setCustomerId(order.getCustomer_id());
251
                activity.setCustomerId(order.getCustomer_id());
252
                ticket.setCustomerName(order.getCustomer_name());
253
                activity.setCustomerName(order.getCustomer_name());
254
                ticket.setCustomerEmailId(order.getCustomer_email());
255
                activity.setCustomerEmailId(order.getCustomer_email());
256
                ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());
257
                activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());
258
 
259
                crmServiceClient = new CRMClient().getClient();
260
                crmServiceClient.insertTicket(ticket, activity);
261
            }
262
        } catch(Exception e) {
263
            log.error("Could not mark order for Cancellation, OrderId : " + orderId, e);
264
        }
265
        return index();
266
    }
267
 
6322 amar.kumar 268
    public void getOrderConfirmationMail() throws IOException, TException {
269
    	HelperClient helperClient = new HelperClient();
270
    	String mail = helperClient.getClient().getOrderConfirmationMail(orderId);
271
    	File file = new File("temp");
272
    	FileWriter writer = new FileWriter(file);
273
    	writer.append(mail);
274
    	writer.close();
275
 
276
    	byte[] buffer = new byte[(int)file.length()];
277
        InputStream input = null;
278
    	try {
279
            int totalBytesRead = 0;
280
            input = new BufferedInputStream(new FileInputStream(file));
281
            while(totalBytesRead < buffer.length){
282
                int bytesRemaining = buffer.length - totalBytesRead;
283
                int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining); 
284
                if (bytesRead > 0){
285
                    totalBytesRead = totalBytesRead + bytesRead;
286
                }
287
            }
288
        }
289
        finally {
290
            input.close();
291
            file.delete();
292
        }
293
 
294
 
295
    	response.setHeader("Content-disposition", "inline; filename=" + "OrderDetail_"+orderId );
296
 
297
        ServletOutputStream sos;
298
        try {
299
            sos = response.getOutputStream();
300
            sos.write(buffer);
301
            sos.flush();
302
        } catch (IOException e) {
303
            System.out.println("Unable to stream the manifest file");
304
        }   
305
    }
306
 
4689 anupam.sin 307
    public boolean canOrderBeCancelled() {
308
        if (setOfcancellableStates.contains(order.getStatus())) {
309
            return true;
310
        }
311
        return false;
312
    }
313
 
4142 mandeep.dh 314
    public String getPaymentGateway(Payment payment) {
315
        String gatewayName = "";
3578 mandeep.dh 316
 
4142 mandeep.dh 317
        try {
318
            Client paymentServiceClient = new PaymentClient().getClient();
319
            gatewayName = paymentServiceClient.getPaymentGateway(payment.getGatewayId()).getName();
320
        } catch (TTransportException e) {
321
        } catch (PaymentException e) {
322
        } catch (TException e) {
2674 vikas 323
        }
4142 mandeep.dh 324
 
325
        return gatewayName;
2674 vikas 326
    }
327
 
4142 mandeep.dh 328
    public String getProductName(LineItem lineItem) {
329
        String name = ModelUtils.extractProductNameFromLineItem(lineItem);
330
 
4146 mandeep.dh 331
        if (lineItem.getColor() != null && !lineItem.getColor().isEmpty()) {
4142 mandeep.dh 332
            name += "(" + lineItem.getColor() + ")";
2674 vikas 333
        }
4142 mandeep.dh 334
 
335
        return name;
2674 vikas 336
    }
337
 
4142 mandeep.dh 338
    public int convertDouble(double value) {
339
        return (int)value;
2674 vikas 340
    }
6912 anupam.sin 341
 
342
    public String getInsuranceExpiryDate(long DeliveryDate) {
343
        if (DeliveryDate == 0) {
344
            return "N/A";
345
        }
346
        Calendar cal = Calendar.getInstance();
347
        cal.setTimeInMillis(DeliveryDate);
348
        cal.add(Calendar.YEAR, 1);
6960 anupam.sin 349
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");
350
        return sdf.format(cal.getTime());
6912 anupam.sin 351
    }
3578 mandeep.dh 352
 
5845 mandeep.dh 353
    public String getShippingAddressOfStore(long storeId) {
354
        try {
355
            in.shop2020.logistics.LogisticsService.Client client = new LogisticsClient().getClient();
356
            PickupStore store = client.getPickupStore(storeId);
357
            return StringUtils.join(new String[] {
358
                    store.getName(),
359
                    store.getLine1(),
360
                    store.getLine2(),
361
                    store.getPin(),
362
                    store.getCity(),
363
                    store.getState(),
364
                    store.getPhone()}, ",");
365
        } catch (Exception e) {
366
            return "";
367
        }
368
    }
369
 
4142 mandeep.dh 370
    public String getAddress(Order order) {
371
        return ModelUtils.extractAddressFromOrder(order);
372
    }
6985 anupam.sin 373
 
374
    public String changeShippingAddress() {
375
        try {
376
            TransactionClient transactionServiceClient = new TransactionClient();
377
            transactionServiceClient.getClient().changeShippingAddress(orderId, line1, line2, city, state, pin);
378
        } catch(Exception e) {
379
            log.error("Unable to update address for orderId : " + orderId + "and address : " + 
380
                    line1 + ", " + line2+ ", " + city + ", " + state + ", " + pin, e);
381
        }
382
        return null;
383
    }
384
 
385
    public Address getShippingAddress(Order order) {
386
        Address address = new Address();
387
        address.setLine1(order.getCustomer_address1());
388
        address.setLine2(order.getCustomer_address2());
389
        address.setCity(order.getCustomer_city());
390
        address.setState(order.getCustomer_state());
391
        address.setPin(order.getCustomer_pincode());
392
        return address;
393
    }
4142 mandeep.dh 394
 
2728 vikas 395
    public String getPaymentMethod(List<Attribute> paymentAttributes) {
396
        String paymentMethod = null;
3578 mandeep.dh 397
        if (paymentAttributes == null || paymentAttributes.isEmpty()) {
2728 vikas 398
            return "N/A";
399
        }
3578 mandeep.dh 400
        for (Attribute a : paymentAttributes) {
401
            if ("payMethod".equals(a.getName())) {
2728 vikas 402
                paymentMethod = Constants.PAYMENT_METHOD.get(a.getValue());
403
                break;
404
            }
405
        }
406
        return paymentMethod != null ? paymentMethod : "N/A";
407
    }
2674 vikas 408
 
409
    public void setOrderId(String orderId) {
410
        try {
411
            this.orderId = Long.parseLong(orderId);
3578 mandeep.dh 412
        } catch (NumberFormatException e) {
2674 vikas 413
            log.error(e);
414
        }
415
    }
416
 
4142 mandeep.dh 417
    public List<Payment> getPayments() {
418
        return payments;
2674 vikas 419
    }
420
 
3090 mandeep.dh 421
    public List<ShipmentUpdate> getShipmentUpdates() {
422
        return shipmentUpdates;
423
    }
424
 
425
    public void setShipmentUpdates(List<ShipmentUpdate> shipmentUpdates) {
426
        this.shipmentUpdates = shipmentUpdates;
427
    }
3499 mandeep.dh 428
 
429
    public Order getOrder() {
430
        return order;
431
    }
432
 
433
    public void setOrder(Order order) {
434
        this.order = order;
435
    }
3578 mandeep.dh 436
 
437
    public Long getCodTicketId() {
438
        return codTicketId;
439
    }
440
 
441
    public void setCodTicketId(Long codTicketId) {
442
        this.codTicketId = codTicketId;
443
    }
4142 mandeep.dh 444
 
445
    public List<Address> getAddresses() {
446
        return addresses;
447
    }
448
 
449
    public void setAddresses(List<Address> addresses) {
450
        this.addresses = addresses;
451
    }
4241 anupam.sin 452
 
453
    public String getOrderStatusDescription(Order order) {
454
        String status = order.getStatus().getDescription();
455
 
456
        if (order.getStatus() == OrderStatus.DELIVERY_SUCCESS) {
457
            status = "Completed";
458
        }
459
 
460
        return status;
461
    }
4689 anupam.sin 462
 
463
    public String getCancellationInitiator() {
464
        return cancellationInitiator;
465
    }
466
 
467
    public void setCancellationInitiator(String cancellationInitiator) {
468
        this.cancellationInitiator = cancellationInitiator;
469
    }
470
 
471
    public String getCancelReason() {
472
        return cancelReason;
473
    }
474
 
475
    public void setCancelReason(String cancelReason) {
476
        this.cancelReason = cancelReason;
477
    }
478
 
479
    public String getBody() {
480
        return body;
481
    }
482
 
483
    public void setBody(String body) {
484
        this.body = body;
485
    }
6985 anupam.sin 486
 
487
    public String getLine1() {
488
        return line1;
489
    }
490
 
491
    public void setLine1(String line1) {
492
        this.line1 = line1;
493
    }
494
 
495
    public String getLine2() {
496
        return line2;
497
    }
498
 
499
    public void setLine2(String line2) {
500
        this.line2 = line2;
501
    }
502
 
503
    public String getCity() {
504
        return city;
505
    }
506
 
507
    public void setCity(String city) {
508
        this.city = city;
509
    }
510
 
511
    public String getState() {
512
        return state;
513
    }
514
 
515
    public void setState(String state) {
516
        this.state = state;
517
    }
518
 
519
    public String getPin() {
520
        return pin;
521
    }
522
 
523
    public void setPin(String pin) {
524
        this.pin = pin;
525
    }
2674 vikas 526
}