Rev 7399 | Rev 7612 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.serving.controllers;import in.shop2020.config.ConfigException;import in.shop2020.crm.Activity;import in.shop2020.crm.ActivityType;import in.shop2020.crm.SearchFilter;import in.shop2020.crm.Ticket;import in.shop2020.crm.TicketCategory;import in.shop2020.crm.TicketPriority;import in.shop2020.crm.TicketStatus;import in.shop2020.logistics.PickupStore;import in.shop2020.model.v1.catalog.CatalogService;import in.shop2020.model.v1.catalog.CatalogServiceException;import in.shop2020.model.v1.catalog.Item;import in.shop2020.model.v1.order.HotspotStore;import in.shop2020.model.v1.order.LineItem;import in.shop2020.model.v1.order.Order;import in.shop2020.model.v1.order.OrderStatus;import in.shop2020.model.v1.order.StoreOrderDetail;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.user.Address;import in.shop2020.model.v1.user.UserContextException;import in.shop2020.payments.Attribute;import in.shop2020.payments.Constants;import in.shop2020.payments.Payment;import in.shop2020.payments.PaymentException;import in.shop2020.payments.PaymentService.Client;import in.shop2020.serving.auth.CRMAuthorizingRealm;import in.shop2020.serving.model.ShipmentUpdate;import in.shop2020.serving.services.AramexTrackingService;import in.shop2020.serving.services.BlueDartTrackingService;import in.shop2020.serving.services.DelhiveryTrackingService;import in.shop2020.serving.services.RedExpressTrackingService;import in.shop2020.thrift.clients.CRMClient;import in.shop2020.thrift.clients.CatalogClient;import in.shop2020.thrift.clients.HelperClient;import in.shop2020.thrift.clients.LogisticsClient;import in.shop2020.thrift.clients.PaymentClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.thrift.clients.UserClient;import in.shop2020.thrift.clients.config.ConfigClient;import in.shop2020.utils.ModelUtils;import in.shop2020.warehouse.WarehouseService;import java.io.BufferedInputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Collections;import java.util.Date;import java.util.HashSet;import java.util.List;import java.util.Set;import java.util.concurrent.Callable;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import javax.servlet.ServletOutputStream;import net.htmlparser.jericho.Source;import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;/*** @author vikas**/@SuppressWarnings("serial")public class UserOrderInfoController extends BaseController {private static Logger log = Logger.getLogger(Class.class);private static BlueDartTrackingService blueDartTrackingService = new BlueDartTrackingService();private static AramexTrackingService aramexTrackingService = new AramexTrackingService();private static DelhiveryTrackingService delhiveryTrackingService = new DelhiveryTrackingService();private static RedExpressTrackingService redexpressTrackingService = new RedExpressTrackingService();private long orderId;private Order order;private List<Payment> payments;private List<ShipmentUpdate> shipmentUpdates = new ArrayList<ShipmentUpdate>();private Long codTicketId;private List<Address> addresses;private Set<OrderStatus> setOfcancellableStates;private String cancellationInitiator;private String cancelReason;private String body;private String line1;private String line2;private String city;private String state;private String pin;private String freebieItem;private String dealText;private String parentOrderIdForFreebieOrder;private String freebieOrderId;private double cashAmount;private double cardAmount;private StoreOrderDetail storeOrderDetail;public UserOrderInfoController() {super();setOfcancellableStates = new HashSet<OrderStatus>();setOfcancellableStates.add(OrderStatus.SUBMITTED_FOR_PROCESSING);setOfcancellableStates.add(OrderStatus.INVENTORY_LOW);setOfcancellableStates.add(OrderStatus.LOW_INV_PO_RAISED);setOfcancellableStates.add(OrderStatus.LOW_INV_REVERSAL_IN_PROCESS);setOfcancellableStates.add(OrderStatus.LOW_INV_NOT_AVAILABLE_AT_HOTSPOT);setOfcancellableStates.add(OrderStatus.ACCEPTED);setOfcancellableStates.add(OrderStatus.BILLED);}public String index() {try {PaymentClient paymentServiceClient = new PaymentClient();TransactionClient transactionServiceClient = new TransactionClient();order = transactionServiceClient.getClient().getOrder(orderId);if(order.getSource() == 2) {storeOrderDetail = transactionServiceClient.getClient().getStoreOrderDetail(order.getId(),order.getStoreId());if(order.getStatus().getValue() == 15 || order.getStatus().getValue() == 34) {setCashAmount(storeOrderDetail.getCashRefundAmount());setCardAmount(storeOrderDetail.getCardRefundAmount());} else {setCashAmount(storeOrderDetail.getCashAmount());setCardAmount(storeOrderDetail.getCardAmount());}}if(order.getFreebieItemId()>0) {CatalogService.Client catalogClient = new CatalogClient().getClient();Item item = catalogClient.getItem(order.getFreebieItemId());freebieItem = item.getBrand() + " " + item.getModelName() + " " + item.getModelNumber() + " " + item.getColor();}if(order.getLineitems().get(0).getDealText()!=null && !order.getLineitems().get(0).getDealText().isEmpty()) {dealText = order.getLineitems().get(0).getDealText();}List<in.shop2020.model.v1.order.Attribute> attributes =transactionServiceClient.getClient().getAllAttributesForOrderId(orderId);for(in.shop2020.model.v1.order.Attribute attribute: attributes){if(attribute.getName().equals("parentOrderIdForFreebie")){parentOrderIdForFreebieOrder = attribute.getValue();} else if (attribute.getName().equals("freebieOrderId")){freebieOrderId = attribute.getValue();}}payments = paymentServiceClient.getClient().getPaymentForTxnId(order.getTransactionId());// Spawning a thread to capture shipment updates from Bluedart// This is done to ensure that response from Crm web app is sent// within given time limits. Also, we wont be affected in the cases// where bluedart site is down or slowExecutors.newSingleThreadExecutor().invokeAll(Collections.singletonList(new Callable<Boolean>() {public Boolean call() throws Exception {if (order.getLogistics_provider_id() == 1)shipmentUpdates = blueDartTrackingService.getUpdates(order.getAirwaybill_no());else if (order.getLogistics_provider_id() == 2) {shipmentUpdates = aramexTrackingService.getUpdates(order.getAirwaybill_no());}else if (order.getLogistics_provider_id() == 3) {shipmentUpdates = delhiveryTrackingService.getUpdates(order.getAirwaybill_no());}else if (order.getLogistics_provider_id() == 6) {shipmentUpdates = redexpressTrackingService.getUpdates(order.getAirwaybill_no());}else {shipmentUpdates = new ArrayList<ShipmentUpdate>();log.error("Error : providerId = " + order.getLogistics_provider_id() + "for orderId : " + order.getId());}return true;}}), 60, TimeUnit.SECONDS);if (order.isCod() && OrderStatus.COD_VERIFICATION_PENDING.equals(order.getStatus())) {populateCODTicketId(order.getCustomer_id());}if (canEditOrderAddress()) {userContextServiceClient = new UserClient().getClient();addresses = userContextServiceClient.getAllAddressesForUser(order.getCustomer_id());}} catch (TTransportException e) {log.error("Unable to create thrift Client", e);} catch (TransactionServiceException e) {addActionError("Invalid order id or no order selected.");} catch (TException e) {log.error("Unable to get thrift Client", e);} catch (PaymentException e) {log.error("Unable to get payments for transctionId : " + order.getTransactionId(), e);} catch (InterruptedException e) {log.error("Thread was interrupted", e);} catch (UserContextException e) {log.error("Unable to get addresses for user : " + order.getCustomer_id(), e);} catch(CatalogServiceException csex) {log.error("Unable to get item details for itemId: " + order.getFreebieItemId(), csex);}return INDEX;}private boolean canEditOrderAddress() {return false;}private void populateCODTicketId(long customerId) {try {SearchFilter searchFilter = new SearchFilter();searchFilter.setTicketCategory(TicketCategory.COD_VERIFICATION);searchFilter.setTicketStatuses(new ArrayList<TicketStatus>());searchFilter.getTicketStatuses().add(TicketStatus.OPEN);searchFilter.getTicketStatuses().add(TicketStatus.REOPEN);searchFilter.setCustomerId(customerId);crmServiceClient = new CRMClient().getClient();List<Ticket> tickets = crmServiceClient.getTickets(searchFilter);if (tickets != null && !tickets.isEmpty()) {codTicketId = tickets.get(0).getId();}} catch (TException e) {log.error("Error fetching tickets for customerId: " + customerId, e);}}public String markOrderForCancellation() {try{TransactionClient transactionServiceClient = new TransactionClient();log.info("URL = " + request.getRequestURI());log.info("Initiator = " + request.getParameter("cancellationInitiator"));log.info("orderId = " + request.getParameter("orderId"));order = transactionServiceClient.getClient().getOrder(orderId);/*** If the order is from store then refund the order directly.*/if (order.getSource() == 2) {String plainTextbody = "";if(body!=null && !body.isEmpty()){plainTextbody = new Source(body).getTextExtractor().toString();}if (cancellationInitiator.equals("CUSTOMER")) {transactionServiceClient.getClient().markOrderCancellationRequestReceived(orderId);transactionServiceClient.getClient().markOrderCancellationRequestConfirmed(orderId);}transactionServiceClient.getClient().saveRefundAmountsForStoreOrder(orderId, order.getStoreId(), cashAmount, cardAmount);transactionServiceClient.getClient().refundOrder(orderId, currentAgentEmailId, cancelReason + " : " + plainTextbody);} else {if (cancellationInitiator.equals("CUSTOMER")) {transactionServiceClient.getClient().markOrderCancellationRequestReceived(orderId);long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();Ticket ticket = new Ticket();String plainTextbody = "";if(body!=null && !body.isEmpty()){plainTextbody = new Source(body).getTextExtractor().toString();}ticket.setDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);ticket.setCreatorId(creatorId);ticket.setStatus(TicketStatus.OPEN);ticket.setPriority(TicketPriority.HIGH);ticket.setCategory(TicketCategory.ORDER_CANCELLATION);ticket.setOrderId(orderId);Activity activity = new Activity();activity.setDescription("Creating Ticket");activity.setType(ActivityType.OTHER);activity.setTicketPriority(TicketPriority.HIGH);activity.setTicketStatus(TicketStatus.OPEN);activity.setCreatorId(creatorId);activity.setTicketDescription("Creating ticket for Cancellation Request Received, Reason : " + cancelReason + " : " + plainTextbody);activity.setTicketCategory(TicketCategory.ORDER_CANCELLATION);ticket.setCustomerId(order.getCustomer_id());activity.setCustomerId(order.getCustomer_id());ticket.setCustomerName(order.getCustomer_name());activity.setCustomerName(order.getCustomer_name());ticket.setCustomerEmailId(order.getCustomer_email());activity.setCustomerEmailId(order.getCustomer_email());ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());crmServiceClient = new CRMClient().getClient();crmServiceClient.insertTicket(ticket, activity);}else if (cancellationInitiator.equals("INTERNAL")) {String plainTextbody = "";if(body!=null && !body.isEmpty()){plainTextbody = new Source(body).getTextExtractor().toString();}boolean status_returned = transactionServiceClient.getClient().refundOrder(orderId, currentAgentEmailId, cancelReason + " : " + plainTextbody);if (status_returned) {order = transactionServiceClient.getClient().getOrder(orderId);long creatorId = CRMAuthorizingRealm.getAgent(currentAgentEmailId).getId();Ticket ticket = new Ticket();ticket.setDescription("Creating ticket for Order Cancellation due to Low inventory");ticket.setCreatorId(creatorId);ticket.setAssigneeId(36);ticket.setStatus(TicketStatus.OPEN);ticket.setPriority(TicketPriority.MEDIUM);ticket.setCategory(TicketCategory.LOW_INVENTORY_CANCELLED_ORDERS);ticket.setOrderId(orderId);ticket.setCustomerId(order.getCustomer_id());ticket.setCustomerName(order.getCustomer_name());ticket.setCustomerEmailId(order.getCustomer_email());ticket.setCustomerMobileNumber(order.getCustomer_mobilenumber());Activity activity = new Activity();activity.setDescription("Creating Ticket");activity.setType(ActivityType.OTHER);activity.setTicketPriority(TicketPriority.MEDIUM);activity.setTicketStatus(TicketStatus.OPEN);activity.setCreatorId(creatorId);activity.setTicketAssigneeId(36);activity.setTicketCategory(TicketCategory.LOW_INVENTORY_CANCELLED_ORDERS);activity.setTicketDescription("Creating ticket for Order Cancellation due to Low inventory");activity.setCustomerId(order.getCustomer_id());activity.setCustomerName(order.getCustomer_name());activity.setCustomerEmailId(order.getCustomer_email());activity.setCustomerMobileNumber(order.getCustomer_mobilenumber());crmServiceClient = new CRMClient().getClient();crmServiceClient.insertTicket(ticket, activity);}}}} catch(Exception e) {log.error("Could not mark order for Cancellation, OrderId : " + orderId, e);}return index();}public void getOrderConfirmationMail() throws IOException, TException, ConfigException, TransactionServiceException {TransactionClient transactionServiceClient = new TransactionClient();order = transactionServiceClient.getClient().getOrder(orderId);long source = order.getTransactionId();HelperClient helperClient = new HelperClient("helper_service_server","helper_service_server_port");String mail = helperClient.getClient().getOrderConfirmationMail(source);File file = new File("/tmp/temp");FileWriter writer = new FileWriter(file);writer.append(mail);writer.close();byte[] buffer = new byte[(int)file.length()];InputStream input = null;try {int totalBytesRead = 0;input = new BufferedInputStream(new FileInputStream(file));while(totalBytesRead < buffer.length){int bytesRemaining = buffer.length - totalBytesRead;int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining);if (bytesRead > 0){totalBytesRead = totalBytesRead + bytesRead;}}}finally {input.close();file.delete();}response.setHeader("Content-disposition", "inline; filename=" + "OrderDetail_"+orderId );ServletOutputStream sos;try {sos = response.getOutputStream();sos.write(buffer);sos.flush();} catch (IOException e) {System.out.println("Unable to stream the manifest file");}}public void getOrderDeliveryMail() throws IOException, TException, ConfigException, TransactionServiceException {HelperClient helperClient = new HelperClient("helper_service_server","helper_service_server_port");String mail = helperClient.getClient().getOrderDeliveryMail(orderId);File file = new File("/tmp/temp");FileWriter writer = new FileWriter(file);writer.append(mail);writer.close();byte[] buffer = new byte[(int)file.length()];InputStream input = null;try {int totalBytesRead = 0;input = new BufferedInputStream(new FileInputStream(file));while(totalBytesRead < buffer.length){int bytesRemaining = buffer.length - totalBytesRead;int bytesRead = input.read(buffer, totalBytesRead, bytesRemaining);if (bytesRead > 0){totalBytesRead = totalBytesRead + bytesRead;}}}finally {input.close();file.delete();}response.setHeader("Content-disposition", "inline; filename=" + "OrderDetail_"+orderId );ServletOutputStream sos;try {sos = response.getOutputStream();sos.write(buffer);sos.flush();} catch (IOException e) {System.out.println("Unable to stream the manifest file");}}public boolean canOrderBeCancelled() {if (setOfcancellableStates.contains(order.getStatus())) {return true;}return false;}public String getPaymentGateway(Payment payment) {String gatewayName = "";try {Client paymentServiceClient = new PaymentClient().getClient();gatewayName = paymentServiceClient.getPaymentGateway(payment.getGatewayId()).getName();} catch (TTransportException e) {} catch (PaymentException e) {} catch (TException e) {}return gatewayName;}public String getProductName(LineItem lineItem) {String name = ModelUtils.extractProductNameFromLineItem(lineItem);if (lineItem.getColor() != null && !lineItem.getColor().isEmpty()) {name += "(" + lineItem.getColor() + ")";}return name;}public int convertDouble(double value) {return (int)value;}public String getInsuranceExpiryDate(long DeliveryDate) {if (DeliveryDate == 0) {return "N/A";}Calendar cal = Calendar.getInstance();cal.setTimeInMillis(DeliveryDate);cal.add(Calendar.YEAR, 1);SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy");return sdf.format(cal.getTime());}public String getShippingAddressOfStore(long storeId) {try {in.shop2020.logistics.LogisticsService.Client client = new LogisticsClient().getClient();PickupStore store = client.getPickupStore(storeId);return StringUtils.join(new String[] {store.getName(),store.getLine1(),store.getLine2(),store.getPin(),store.getCity(),store.getState(),store.getPhone()}, ",");} catch (Exception e) {return "";}}public String getAddress(Order order) {return ModelUtils.extractAddressFromOrder(order);}public String changeShippingAddress() {try {TransactionClient transactionServiceClient = new TransactionClient();transactionServiceClient.getClient().changeShippingAddress(orderId, line1, line2, city, state, pin);} catch(Exception e) {log.error("Unable to update address for orderId : " + orderId + "and address : " +line1 + ", " + line2+ ", " + city + ", " + state + ", " + pin, e);}return null;}public String getStoreDetails(long storeId) {try {TransactionClient tcl = new TransactionClient();HotspotStore store = tcl.getClient().getHotspotStore(storeId, "");return store.getHotspotId() + " - " + store.getCity();} catch (Exception e) {log.error("Unable to get hostspotStore for id : " + storeId, e);}return "N/A";}public Address getShippingAddress(Order order) {Address address = new Address();address.setLine1(order.getCustomer_address1());address.setLine2(order.getCustomer_address2());address.setCity(order.getCustomer_city());address.setState(order.getCustomer_state());address.setPin(order.getCustomer_pincode());return address;}public String getPaymentMethod(List<Attribute> paymentAttributes) {String paymentMethod = null;if (paymentAttributes == null || paymentAttributes.isEmpty()) {return "N/A";}for (Attribute a : paymentAttributes) {if ("payMethod".equals(a.getName())) {paymentMethod = Constants.PAYMENT_METHOD.get(a.getValue());break;}}return paymentMethod != null ? paymentMethod : "N/A";}public void setOrderId(String orderId) {try {this.orderId = Long.parseLong(orderId);} catch (NumberFormatException e) {log.error(e);}}public List<Payment> getPayments() {return payments;}public List<ShipmentUpdate> getShipmentUpdates() {return shipmentUpdates;}public void setShipmentUpdates(List<ShipmentUpdate> shipmentUpdates) {this.shipmentUpdates = shipmentUpdates;}public Order getOrder() {return order;}public void setOrder(Order order) {this.order = order;}public Long getCodTicketId() {return codTicketId;}public void setCodTicketId(Long codTicketId) {this.codTicketId = codTicketId;}public List<Address> getAddresses() {return addresses;}public void setAddresses(List<Address> addresses) {this.addresses = addresses;}public String getOrderStatusDescription(Order order) {String status = order.getStatus().getDescription();if (order.getStatus() == OrderStatus.DELIVERY_SUCCESS) {status = "Completed";}return status;}public String getCancellationInitiator() {return cancellationInitiator;}public void setCancellationInitiator(String cancellationInitiator) {this.cancellationInitiator = cancellationInitiator;}public String getCancelReason() {return cancelReason;}public void setCancelReason(String cancelReason) {this.cancelReason = cancelReason;}public String getBody() {return body;}public void setBody(String body) {this.body = body;}public String getLine1() {return line1;}public void setLine1(String line1) {this.line1 = line1;}public String getLine2() {return line2;}public void setLine2(String line2) {this.line2 = line2;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public String getState() {return state;}public void setState(String state) {this.state = state;}public String getPin() {return pin;}public void setPin(String pin) {this.pin = pin;}public String getFreebieItem() {return freebieItem;}public void setFreebieItem(String freebieItem) {this.freebieItem = freebieItem;}public String getDealText() {return dealText;}public void setDealText(String dealText) {this.dealText = dealText;}public String getParentOrderIdForFreebieOrder() {return parentOrderIdForFreebieOrder;}public void setParentOrderIdForFreebieOrder(String parentOrderIdForFreebieOrder) {this.parentOrderIdForFreebieOrder = parentOrderIdForFreebieOrder;}public String getFreebieOrderId() {return freebieOrderId;}public void setFreebieOrderId(String freebieOrderId) {this.freebieOrderId = freebieOrderId;}public void setCashAmount(double cashAmount) {this.cashAmount = cashAmount;}public double getCashAmount() {return cashAmount;}public void setCardAmount(double cardAmount) {this.cardAmount = cardAmount;}public double getCardAmount() {return cardAmount;}public long getOrderId() {return orderId;}public void setOrderId(long orderId) {this.orderId = orderId;}public StoreOrderDetail getStoreOrderDetail() {return storeOrderDetail;}public void setStoreOrderDetail(StoreOrderDetail storeOrderDetail) {this.storeOrderDetail = storeOrderDetail;}}