Subversion Repositories SmartDukaan

Rev

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