Rev 18462 | 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.LogisticsServiceException;import in.shop2020.logistics.PickupStore;import in.shop2020.logistics.Provider;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.inventory.Warehouse;import in.shop2020.model.v1.order.AmazonOrder;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.OrderSource;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.payments.PaymentStatus;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.FedExTrackingService;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.InventoryClient;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.util.CRMConstants;import in.shop2020.utils.FedExShipAccountInfo;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.Arrays;import java.util.Calendar;import java.util.Collections;import java.util.Date;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;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.shiro.SecurityUtils;import org.apache.struts2.convention.annotation.Result;import org.apache.struts2.convention.annotation.Results;import org.apache.thrift.TException;import org.apache.thrift.transport.TTransportException;import com.ShipWebServiceClient;import com.fedex.ship.stub.AssociatedShipmentDetail;import com.fedex.ship.stub.CompletedPackageDetail;import com.fedex.ship.stub.CompletedShipmentDetail;import com.fedex.ship.stub.OperationalInstruction;import com.fedex.ship.stub.PackageOperationalDetail;import com.fedex.ship.stub.ProcessShipmentReply;import com.fedex.ship.stub.StringBarcode;import com.fedex.ship.stub.TrackingId;/*** @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 FedExTrackingService fedexTrackingService;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;//Start:- Added by Manish Sharma for Physical Refundsprivate Set<OrderStatus> setOfrefundableStates;private Set<OrderStatus> setOfprepaidrefundableStates;//End:- Added by Manish Sharma for Physical Refundsprivate 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;//Start:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013private AmazonOrder amazonOrder = null;private String providerName = "N/A";//End:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013private long gvAmount;//Start:- Added by Manish Sharma for Physical Refundsprivate String rfdRadio;private String couponDetails;private String refundAmountCoupon;private String chequeDetails;private String refundAmountCheque;private String refundAmountGateway;private String comments;private String errorMsg = "";private String successmsg = "";private List<String> refundDetails;private String billingWarehouseName="";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);//Start:- Added by Manish Sharma for Physical RefundssetOfrefundableStates = new HashSet<OrderStatus>();setOfrefundableStates.add(OrderStatus.DOA_VALID_REFUNDED);setOfrefundableStates.add(OrderStatus.DOA_INVALID_REFUNDED);setOfrefundableStates.add(OrderStatus.DOA_REFUNDED_RCVD_DAMAGED);setOfrefundableStates.add(OrderStatus.DOA_REFUNDED_LOST_IN_TRANSIT);setOfrefundableStates.add(OrderStatus.RTO_DAMAGED_REFUNDED);setOfrefundableStates.add(OrderStatus.RET_PRODUCT_USABLE_REFUNDED);setOfrefundableStates.add(OrderStatus.RET_PRODUCT_UNUSABLE_REFUNDED);setOfrefundableStates.add(OrderStatus.RET_REFUNDED_RCVD_DAMAGED);setOfrefundableStates.add(OrderStatus.RET_REFUNDED_LOST_IN_TRANSIT);//End:- Added by Manish Sharma for Physical RefundssetOfprepaidrefundableStates = new HashSet<OrderStatus>();setOfprepaidrefundableStates.add(OrderStatus.RTO_REFUNDED);setOfprepaidrefundableStates.add(OrderStatus.RTO_LOST_IN_TRANSIT_REFUNDED);setOfprepaidrefundableStates.add(OrderStatus.LOST_IN_TRANSIT_REFUNDED);setOfprepaidrefundableStates.add(OrderStatus.CANCELLED_ON_CUSTOMER_REQUEST);setOfprepaidrefundableStates.add(OrderStatus.CANCELLED_DUE_TO_LOW_INVENTORY);}public static final Map<Long,String> billingWarehouseMap = new HashMap<Long, String>() {{put(7l, "Mahipalpur-MMX");put(12l, "Goregaon");put(13l, "Bhiwandi");put(1765l, "Bangalore");put(1768l, "Bangalore - SR");put(3298l, "TG-SORPL/Hyderabad");put(3931l, "HR-SORPL/Gurgaon-S");}};public String index() {try {PaymentClient paymentServiceClient = new PaymentClient();TransactionClient transactionServiceClient = new TransactionClient();/*List<Provider> providerList = logisticsServiceClient.getClient().getAllProviders();Map<Long, String> providerNameMap = new HashMap<Long, String>();for(Provider provider : providerList){providerNameMap.put(provider.getId(), provider.getName());}*/order = transactionServiceClient.getClient().getOrder(orderId);if (billingWarehouseMap.containsKey(order.getWarehouse_id()) && order.getWarehouse_id()!=0){setBillingWarehouseName(billingWarehouseMap.get(order.getWarehouse_id()));}Warehouse warehouse;if (order.getLogistics_provider_id() == 7){warehouse = getWareHouseForOrder(order.getWarehouse_id());fedexTrackingService = new FedExTrackingService(warehouse.getLogisticsLocation());}//Start:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013if(OrderSource.AMAZON == OrderSource.findByValue((int)order.getSource()) || OrderSource.JUNGLEE == OrderSource.findByValue((int)order.getSource())){try {amazonOrder = transactionServiceClient.getClient().getAmazonOrder(orderId);} catch (Exception e) {log.error("Exception : No Amazon order found with orderId " + orderId);}}if (order.getLogistics_provider_id() > 0) {setProviderName(providerNameMap.get(order.getLogistics_provider_id()));}//End:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013if(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());gvAmount = order.getGvAmount();// 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());}//Start:- Added by Manish Sharma for fedex Integration- Shipment Tracking on 31-Jul-2013else if (order.getLogistics_provider_id() == 7) {shipmentUpdates = fedexTrackingService.getUpdates(order.getAirwaybill_no());}//End:- Added by Manish Sharma for fedex Integration- Shipment Tracking on 31-Jul-2013else {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);} /*catch (LogisticsServiceException lsex) {log.error("Unable to get providers infromation: " , lsex);}*/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(cashAmount + cardAmount > order.getAdvanceAmount()) {log.error("Could not mark order for Cancellation, OrderId : " + orderId);return "index";}transactionServiceClient.getClient().saveRefundAmountsForStoreOrder(orderId, order.getStoreId(), cashAmount, cardAmount);if (cancellationInitiator.equals("CUSTOMER")) {transactionServiceClient.getClient().markOrderCancellationRequestReceived(orderId);transactionServiceClient.getClient().markOrderCancellationRequestConfirmed(orderId);}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.setAssigneeId(51);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);activity.setTicketAssigneeId(51);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(51);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(51);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");//Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013if(mail.isEmpty() || mail==null || mail=="")mail="<html><body><p>Sorry, Required e-mail for mentioned order does not exist in the system !!!</p></body></html>";//End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013FileWriter 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 Warehouse getWareHouseForOrder(long warehouseId){Warehouse warehouse = null;try{InventoryClient isc = new InventoryClient();warehouse = isc.getClient().getWarehouse(warehouseId);} catch(Exception e) {log.error("Unable to get warehouse for id : " + warehouseId,e);//TODO throw e;}return warehouse;}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");//Start:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013if(mail.isEmpty() || mail==null || mail=="")mail="<html><body><p>Sorry, Required e-mail for mentioned order does not exist in the system anymore !!!</p></body></html>";//End:- Added by Manish Sharma for resolving Exception for getting order delivery and confirmation mail on 27-Jun-2013FileWriter 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 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();in.shop2020.model.v1.order.TransactionService.Client transactionClient= transactionServiceClient.getClient();in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);transactionClient.changeShippingAddress(orderId, line1, line2, city, state, pin);/*Warehouse warehouse = getWareHouseForOrder(t_order.getWarehouse_id());if(t_order.getLogistics_provider_id()==7L){FedExShipAccountInfo fedexAccountInfo = FedExShipAccountInfo.getFedExInfo(warehouse.getLogisticsLocation());ProcessShipmentReply processShipmentReply = ShipWebServiceClient.getShipmentCreationReply(t_order,fedexAccountInfo.getClientDetail(),fedexAccountInfo.getWad(),fedexAccountInfo.getEndPointAddress());CompletedShipmentDetail completedShipmentDetails = processShipmentReply.getCompletedShipmentDetail();CompletedPackageDetail completedPackageDetails = completedShipmentDetails.getCompletedPackageDetails(0);TrackingId trackId= completedPackageDetails.getTrackingIds(0);t_order = transactionClient.updateOrderAWB(t_order.getId(), trackId.getTrackingNumber());//Start:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013CompletedPackageDetail[] cpd= completedShipmentDetails.getCompletedPackageDetails();AssociatedShipmentDetail[] asdetails = completedShipmentDetails.getAssociatedShipments();List<in.shop2020.model.v1.order.Attribute> attrList = new ArrayList<in.shop2020.model.v1.order.Attribute>();if(t_order.isCod()){if(asdetails!=null){for(AssociatedShipmentDetail as : asdetails){if(as.getType().getValue().equalsIgnoreCase("COD_RETURN")){PackageOperationalDetail pod = as.getPackageOperationalDetail();StringBarcode[] barcodes = pod.getBarcodes().getStringBarcodes();for(StringBarcode bc : barcodes){in.shop2020.model.v1.order.Attribute attr3 = new in.shop2020.model.v1.order.Attribute();attr3.setName("FedEx_COD_Return_BarCode");attr3.setValue(bc.getValue());attrList.add(attr3);}String codReturnTrackingNo= as.getTrackingId().getTrackingNumber();in.shop2020.model.v1.order.Attribute attr4 = new in.shop2020.model.v1.order.Attribute();attr4.setName("FedEx_COD_Return_Tracking_No");attr4.setValue(codReturnTrackingNo);attrList.add(attr4);}}}}for(CompletedPackageDetail cd : cpd){PackageOperationalDetail pod = cd.getOperationalDetail();StringBarcode[] barcodes = pod.getBarcodes().getStringBarcodes();for(StringBarcode bc : barcodes){in.shop2020.model.v1.order.Attribute attr1 = new in.shop2020.model.v1.order.Attribute();attr1.setName("FedEx_Package_BarCode");attr1.setValue(bc.getValue());attrList.add(attr1);}OperationalInstruction[] ois = pod.getOperationalInstructions();in.shop2020.model.v1.order.Attribute attr2 = new in.shop2020.model.v1.order.Attribute();for(OperationalInstruction oi : ois){if(oi.getNumber().intValue()==5){attr2.setName("FedEx_Location_Code");attr2.setValue(oi.getContent());attrList.add(attr2);}}}transactionClient.setOrderAttributes(t_order.getId(), attrList);//End:-Added By Manish Sharma for FedEx Integration - Shipment Creation on 21-Aug-2013}*/} catch(Exception e) {log.error("Unable to update address for orderId : " + orderId + "and address : " +line1 + ", " + line2+ ", " + city + ", " + state + ", " + pin, e);}return null;}public String convertStoreToNormal() {try{TransactionClient transactionServiceClient = new TransactionClient();transactionServiceClient.getClient().convertStoreToNormal(orderId);} catch(Exception e) {log.error("Unable to convert to normal order", 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 getOrderSource(Order order) {return OrderSource.findByValue((int)(order.getSource())).toString();}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";}//Start:- Added by Manish Sharma for Physical Refundspublic String refundOrderPayment(){try{TransactionClient transactionServiceClient = new TransactionClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient= transactionServiceClient.getClient();in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);List<in.shop2020.model.v1.order.Attribute> attrList = new ArrayList<in.shop2020.model.v1.order.Attribute>();in.shop2020.model.v1.order.Attribute attr1 = new in.shop2020.model.v1.order.Attribute();attr1.setName("Refund_Option");in.shop2020.model.v1.order.Attribute attr2 = new in.shop2020.model.v1.order.Attribute();attr2.setName("Refund_Amount");in.shop2020.model.v1.order.Attribute attr3 = new in.shop2020.model.v1.order.Attribute();attr3.setName("Refund_TimeStamp");SimpleDateFormat timestmapFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");PaymentClient paymentServiceClient = new PaymentClient();List<Payment> orderPayments =null;if(!t_order.isCod()){orderPayments =paymentServiceClient.getClient().getPaymentForTxnId(t_order.getTransactionId());}if(rfdRadio.equalsIgnoreCase("rfdCoupon")){if((couponDetails!=null && !("").equalsIgnoreCase(couponDetails)) || (refundAmountCoupon!=null &&!("").equalsIgnoreCase(refundAmountCoupon))){if(Double.parseDouble(refundAmountCoupon) <= t_order.getTotal_amount()){log.info(Double.parseDouble(refundAmountCoupon));log.info(t_order.getTotal_amount());attr1.setValue("Refund By Coupon: "+couponDetails);attrList.add(attr1);attr2.setValue(refundAmountCoupon);attrList.add(attr2);attr3.setValue(timestmapFormat.format(Calendar.getInstance().getTime()));attrList.add(attr3);transactionClient.setOrderAttributes(t_order.getId(), attrList);successmsg = "Refund Marked Successful: Through Coupon";return "physical-refund-result";}else if(orderPayments !=null && !orderPayments.isEmpty()){Payment payment = orderPayments.get(0);if(Double.parseDouble(refundAmountCoupon) <= payment.getAmount()){log.info(Double.parseDouble(refundAmountCoupon));log.info(payment.getAmount());attr1.setValue("Refund By Coupon: "+couponDetails);attrList.add(attr1);attr2.setValue(refundAmountCoupon);attrList.add(attr2);attr3.setValue(timestmapFormat.format(Calendar.getInstance().getTime()));attrList.add(attr3);transactionClient.setOrderAttributes(t_order.getId(), attrList);successmsg = "Refund Marked Successful: Through Coupon";return "physical-refund-result";}else{errorMsg ="Refund Unsuccessful: Due to coupon amount greater than Payment Gateway Amount ";return "physical-refund-result";}}errorMsg ="Refund Unsuccessful: Due to coupon amount greater than Order Total Amount ";}else{errorMsg ="Refund Unsuccessful: Due to either coupon details or refund amount is blank ";return "physical-refund-result";}errorMsg ="Refund Unsuccessful: Due to coupon amount greater than order total amount ";}if(rfdRadio.equalsIgnoreCase("rfdCheque")){if((chequeDetails!=null && !("").equalsIgnoreCase(chequeDetails)) || (refundAmountCheque!=null &&!("").equalsIgnoreCase(refundAmountCheque))){if(Double.parseDouble(refundAmountCheque) <= t_order.getTotal_amount()){attr1.setValue("Refund By Cheque: "+chequeDetails);attrList.add(attr1);attr2.setValue(refundAmountCheque);attrList.add(attr2);attr3.setValue(timestmapFormat.format(Calendar.getInstance().getTime()));attrList.add(attr3);transactionClient.setOrderAttributes(t_order.getId(), attrList);successmsg = "Refund Marked Successful: Through Cheque";return "physical-refund-result";}}else{errorMsg ="Refund Unsuccessful: Due to either cheque details or refund amount is blank ";return "physical-refund-result";}errorMsg ="Refund Unsuccessful: Due to cheque amount greater than order total amount ";}if(rfdRadio.equalsIgnoreCase("rfdGateway")){if((comments!=null && !("").equalsIgnoreCase(comments))|| (refundAmountGateway!=null &&!("").equalsIgnoreCase(refundAmountGateway))){if(orderPayments !=null && !orderPayments.isEmpty()){Payment payment = orderPayments.get(0);if(Double.parseDouble(refundAmountGateway) <= payment.getAmount()){boolean refundResult = paymentServiceClient.getClient().refundPayment(t_order.getTransactionId(), Double.parseDouble(refundAmountGateway), false);if(refundResult){attr1.setValue("Refund By Payment Gatway: "+comments);attrList.add(attr1);attr2.setValue(refundAmountGateway);attrList.add(attr2);attr3.setValue(timestmapFormat.format(Calendar.getInstance().getTime()));attrList.add(attr3);transactionClient.setOrderAttributes(t_order.getId(), attrList);successmsg = "Refund Marked Successful: Through Gateway";return "physical-refund-result";}else{if(payment.getGatewayId()==13L){attr1.setValue("Refund By Innoviti Gatway: "+comments);attrList.add(attr1);attr2.setValue(refundAmountGateway);attrList.add(attr2);attr3.setValue(timestmapFormat.format(Calendar.getInstance().getTime()));attrList.add(attr3);transactionClient.setOrderAttributes(t_order.getId(), attrList);successmsg = "Refund Marked Successful: Through Innoviti Payment Gateway.";return "physical-refund-result";}errorMsg ="Refund Unsuccessful: at Payment Gateway ";return "physical-refund-result";}}else{errorMsg ="Refund Unsuccessful: Due to refund Amount is greater than Payment Gateway Amount ";return "physical-refund-result";}}errorMsg ="Refund Unsuccessful: There is no Payment to be refunded ";}else{errorMsg ="Refund Unsuccessful: Due to either comments or refund amount is blank ";return "physical-refund-result";}}}catch(Exception e){log.error(e);}return "physical-refund-result";}public int getRefundEnabledStatus(){try{TransactionClient transactionServiceClient = new TransactionClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient= transactionServiceClient.getClient();in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);if(OrderSource.WEBSITE.getValue()!=t_order.getSource()){return 1;}String refundOption=transactionClient.getOrderAttributeValue(orderId, "Refund_Option");String refundAmount=transactionClient.getOrderAttributeValue(orderId, "Refund_Amount");String refundTimeStamp = transactionClient.getOrderAttributeValue(orderId, "Refund_TimeStamp");List<String> details = new ArrayList<String>();if(refundOption!=null && !("").equalsIgnoreCase(refundOption)){details.add("Refund Option:- "+refundOption);}if(refundAmount!=null && !("").equalsIgnoreCase(refundAmount)){details.add("Refund Amount:- "+refundAmount);}if(refundTimeStamp!=null && !("").equalsIgnoreCase(refundTimeStamp)){details.add("Refund TimeStamp:- "+refundTimeStamp);}setPhysicalRefundDetails(details);if((refundOption!=null && refundAmount!=null) && (!("").equalsIgnoreCase(refundOption)) && !("").equalsIgnoreCase(refundAmount)){System.out.println("Into the Refund Condition");return 0;}else if(t_order.isCod()){if(setOfrefundableStates.contains(t_order.getStatus()) && SecurityUtils.getSubject().hasRole("TeamLead")){System.out.println("Into the COD Status Condition");return 2;}}else{if(( setOfprepaidrefundableStates.contains(t_order.getStatus()) || setOfrefundableStates.contains(t_order.getStatus()) ) && SecurityUtils.getSubject().hasRole("TeamLead") && (payments.get(0).getStatus() == PaymentStatus.SUCCESS || t_order.isSetOriginalOrderId())){System.out.println("Into the Prepaid Status Condition");return 2;}}}catch(Exception e){log.error(e);}return 1;}public int checkForOriginalOrders(){try{TransactionClient transactionServiceClient = new TransactionClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient= transactionServiceClient.getClient();in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);if(t_order.getOriginalOrderId()!=0l && t_order.getOriginalOrderId() > 0l){in.shop2020.model.v1.order.Order old_order = transactionClient.getOrder(t_order.getOriginalOrderId());if(old_order.isCod()){return 1;}else{return 2;}}}catch(Exception e){log.error(e);}return 0;}public void setPhysicalRefundDetails(List<String> details){this.refundDetails = details;}public List<String> getPhysicalRefundDetails(){return this.refundDetails;}//End:- Added by Manish Sharma for Physical Refundspublic 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;}//Start:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013public AmazonOrder getAmazonOrder() {return amazonOrder;}public void setAmazonOrder(AmazonOrder amazonOrder) {this.amazonOrder = amazonOrder;}//End:- Added by Manish Sharma for Displaying Logistics Provider Id and Amazon Order Id on 25-Jul-2013public void setProviderName(String providerName) {this.providerName = providerName;}public String getProviderName() {return providerName;}public static void main(String[] args) {}public void setGvAmount(long gvAmount) {this.gvAmount = gvAmount;}public long getGvAmount() {return gvAmount;}//Start:- Added by Manish Sharma for Physical Refundspublic String getRfdRadio() {return rfdRadio;}public void setRfdRadio(String rfdRadio) {this.rfdRadio = rfdRadio;}public String getCouponDetails() {return couponDetails;}public void setCouponDetails(String couponDetails) {this.couponDetails = couponDetails;}public String getRefundAmountCoupon() {return refundAmountCoupon;}public void setRefundAmountCoupon(String refundAmountCoupon) {this.refundAmountCoupon = refundAmountCoupon;}public String getChequeDetails() {return chequeDetails;}public void setChequeDetails(String chequeDetails) {this.chequeDetails = chequeDetails;}public String getRefundAmountCheque() {return refundAmountCheque;}public void setRefundAmountCheque(String refundAmountCheque) {this.refundAmountCheque = refundAmountCheque;}public String getRefundAmountGateway() {return refundAmountGateway;}public void setRefundAmountGateway(String refundAmountGateway) {this.refundAmountGateway = refundAmountGateway;}public String getComments() {return comments;}public void setComments(String comments) {this.comments = comments;}public String getErrorMsg(){return this.errorMsg;}public String getSuccessMessage(){return this.successmsg ;}public void setBillingWarehouseName(String billingWarehouseName) {this.billingWarehouseName = billingWarehouseName;}public String getBillingWarehouseName() {return billingWarehouseName;}public String getGatewayName(Payment payment){return CRMConstants.PAYMENT_GATEWAYS.get(payment.getGatewayId());}}