Subversion Repositories SmartDukaan

Rev

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