Rev 20112 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
package in.shop2020.serving.controllers;import in.shop2020.model.v1.inventory.Warehouse;import in.shop2020.model.v1.order.Attribute;import in.shop2020.model.v1.order.OrderSource;import in.shop2020.model.v1.order.OrderType;import in.shop2020.model.v1.order.TransactionServiceException;import in.shop2020.model.v1.user.Address;import in.shop2020.model.v1.user.Cart;import in.shop2020.model.v1.user.PrivateDealUser;import in.shop2020.model.v1.user.ShoppingCartException;import in.shop2020.serving.interceptors.TrackingInterceptor;import in.shop2020.serving.services.CodPaymentService;import in.shop2020.serving.services.CommonPaymentService;import in.shop2020.serving.services.CouponPaymentService;import in.shop2020.serving.services.EbsPaymentService;import in.shop2020.serving.services.HdfcEmiPaymentService;import in.shop2020.serving.services.HdfcPaymentService;import in.shop2020.serving.services.IPaymentService;import in.shop2020.serving.services.InnovitiPaymentService;import in.shop2020.serving.services.PayuPaymentService;import in.shop2020.serving.utils.DesEncrypter;import in.shop2020.serving.utils.PaymentUtils;import in.shop2020.serving.utils.Utils;import in.shop2020.thrift.clients.InventoryClient;import in.shop2020.thrift.clients.TransactionClient;import in.shop2020.thrift.clients.UserClient;import in.shop2020.utils.FedExShipAccountInfo;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import nl.captcha.Captcha;import org.apache.log4j.Logger;import org.apache.struts2.convention.annotation.InterceptorRef;import org.apache.struts2.convention.annotation.InterceptorRefs;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;@SuppressWarnings("serial")@InterceptorRefs({@InterceptorRef("myDefault"),@InterceptorRef("login")})@Results({@Result(name="shipping-redirect", type="redirectAction", params = {"actionName" , "shipping"}),@Result(name="proceed-to-pay-redirect", type="redirectAction", params = {"actionName" , "proceed-to-pay", "deliveryLocation", "${deliveryLocation}"}),@Result(name="ebs-pay-redirect", type="redirect", location="/ebs-pay/${paymentId}"),@Result(name="payu-pay-redirect", type="redirect", location="/payu-pay/${paymentId}"),@Result(name="hdfc-pay-redirect", type="redirect", location="/hdfc-pay/${paymentId}"),@Result(name="innoviti-pay-redirect", type="redirect", location="/innoviti-pay/${paymentId}"),@Result(name="cod-redirect", type="redirect", location="/pay-success?paymentId=${paymentId}")})public class OrderController extends BaseController {public long getPaymentId() {return paymentId;}private static Logger log = Logger.getLogger(Class.class);private String id;private long txnId = 0;private long paymentId;private String redirectURL;private String deliveryLocation = "";public OrderController(){super();}// GET /order/ orderidpublic String show() {log.info("id=" + id);htmlSnippets.put("MYACCOUNT_HEADER", pageLoader.getMyaccountHeaderHtml());htmlSnippets.put("ORDER_DETAILS", pageLoader.getOrderDetailsHtml(Long.parseLong(id), userinfo));return "show";}// POST /order/public String create(){String addressIdString = this.request.getParameter("addressid");if(addressIdString == null){addActionError("Please specify shipping address to continue.");return "proceed-to-pay-redirect";}long addressId;try {addressId = Long.parseLong(addressIdString);} catch(NumberFormatException nfe){log.error("Unable to get address id", nfe);addActionError("Invalid address. Please add an address to the cart.");return "shipping-redirect";}OrderType orderType = OrderType.B2C;String tin = null;if(userinfo.isPrivateDealUser()){try {UserClient userServiceClient = new UserClient();in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();PrivateDealUser user = userClient.getPrivateDealUser(userinfo.getUserId());Address billingAddress= userClient.getBillingAddressForUser(user.getUserId());if(billingAddress != null){Address shippingAddress = userClient.getAddressById(addressId);if(billingAddress.getState().equals(shippingAddress.getState())){orderType = OrderType.B2B;tin = user.getTin().trim();}}if(user.getTin() != null && !user.getTin().equals("")) {orderType = OrderType.B2B;tin = user.getTin().trim();}} catch (Exception e) {log.error("Unable to talk to the user context service.", e);addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";}}String paymentOption = request.getParameter("payment_option");String paymentType="";log.info("Payment Option Selected: " + paymentOption);if(paymentOption == null || paymentOption.equals("")){addActionError("Please select a payment method to continue.");return "proceed-to-pay-redirect";}if(paymentOption.contains("~")){paymentType = paymentOption.split("~")[0];paymentOption = paymentOption.split("~")[1];}long currentCartId = userinfo.getCartId();long currentUserId = userinfo.getUserId();if(paymentOption.equals(IPaymentService.COD)){if(!userinfo.isPrivateDealUser() && !verifyCaptcha()){addActionError("Invalid captcha");log.info("Invalid captcha error msg has been added");return "proceed-to-pay-redirect";}//Check that this address is eligible for COD shipping.UserClient userServiceClient = null;try {userServiceClient = new UserClient();in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();Address address = userClient.getAddressById(addressId);if(!userClient.showCODOption(currentCartId, sourceId, address.getPin())){addActionError("Cash on Delivery is currently not available for this pincode. Please choose a different payment option.");return "proceed-to-pay-redirect";}} catch (Exception e) {log.error("Unable to talk to the user context service.", e);addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";}}if(paymentOption.equals(IPaymentService.COUPON)) {if(!userinfo.isPrivateDealUser() && !verifyCaptcha()){addActionError("Invalid captcha");log.info("Invalid captcha error msg has been added");return "proceed-to-pay-redirect";}UserClient userServiceClient = null;try {userServiceClient = new UserClient();in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();Cart cart = userClient.getCart(currentCartId);if(!isCouponValid(cart)){addActionError("Cart amount is not zero.");log.info("Cart amount is not zero.");return "proceed-to-pay-redirect";}} catch (Exception e) {log.error("Unable to talk to the user context service.", e);addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";}}try {if(!createOrders(addressId, currentCartId, currentUserId, Long.parseLong(paymentOption))) {addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";}//If tin is available push it to order attribute tableif(tin != null){TransactionClient transactionServiceClient = null;try {transactionServiceClient = new TransactionClient();Attribute attr1 = new Attribute();attr1.setName("tinNumber");attr1.setValue(tin);transactionServiceClient.getClient().setOrderAttributeForTransaction(txnId, attr1);} catch (Exception e1) {log.warn("Unable to log orders through the datalogger", e1);}}} catch (Exception e) {addActionError("We are experiencing some problems. Please try later.");log.error("Exception in createOrders function. Something went wrong.", e);return "proceed-to-pay-redirect";}int gatewayId = (int)findGatewayId(paymentType+paymentOption);switch (gatewayId) {case 4:IPaymentService codPaymentService = new CodPaymentService();paymentId = codPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 4, paymentType);if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {//Very unlikely. The only possible reason can be that the payment service is down.log.error("Unable to process the COD payment.");addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";} else {CommonPaymentService.processCodTxn(txnId, orderType);return "cod-redirect";}case 5:IPaymentService payuPaymentService = new PayuPaymentService();paymentId = payuPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId, paymentType);if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {//Very unlikely. The only possible reason can be that the payment service is down.log.error("Unable to process the payu payment.");addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";} else {log.info("Successfully created payment for Innoviti to process. Redirecting to /payu-pay/" + paymentId);return "payu-pay-redirect";}case 14:IPaymentService hdfcEmiPaymentService = new HdfcEmiPaymentService();paymentId = hdfcEmiPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId, paymentType);if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){addActionError("We are experiencing some problems. Please try later.");log.error("Unable to process payment through HDFC EMI.");return "proceed-to-pay-redirect";} else {this.redirectURL = ((HdfcEmiPaymentService)hdfcEmiPaymentService).getRedirectUrl();log.info(this.redirectURL);return "success";}case 13:IPaymentService innovitiPaymentService = new InnovitiPaymentService();paymentId = innovitiPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId, paymentType);if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {//Very unlikely. The only possible reason can be that the payment service is down.log.error("Unable to process the innoviti payment.");addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";} else {log.info("Successfully created payment for Innoviti to process. Redirecting to /innoviti-pay/" + paymentId);return "innoviti-pay-redirect";}case 17:IPaymentService couponPaymentService = new CouponPaymentService();paymentId = couponPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 17, paymentType);if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {//Very unlikely. The only possible reason can be that the payment service is down.log.error("Unable to process the Coupon payment.");addActionError("We are experiencing some problems. Please try later.");return "proceed-to-pay-redirect";} else {CommonPaymentService.processCouponTxn(txnId, orderType);return "cod-redirect";}case 18:IPaymentService ebsPaymentService = new EbsPaymentService();paymentId = ebsPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 2, paymentType);if(paymentId == IPaymentService.PAYMENT_NOT_CREATED){addActionError("We are experiencing some problems. Please try later.");log.error("Unable to process payment through EBS.");return "proceed-to-pay-redirect";} else {log.info("Successfully created payment for EBS to process. Redirecting to /ebs-pay/" + paymentId);return "ebs-pay-redirect";}default:break;}/*if(paymentOption.equals(IPaymentService.HDFC_MASTERCARD_CREDIT) || paymentOption.equals(IPaymentService.HDFC_MASTERCARD_DEBIT) ||paymentOption.equals(IPaymentService.HDFC_VISA) || paymentOption.equals(IPaymentService.HDFC_VISA_ELECTRON)) {// User has selected Visa or MasterCardIPaymentService hdfcPaymentService = new HdfcPaymentService();paymentId = hdfcPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, 1);if (paymentId == IPaymentService.PAYMENT_NOT_CREATED) {//TODO:Update order gatewayTxnStatus in case its not processed using txnIdlog.error("Unable to process payment through HDFC. Falling through to EBS.");} else {this.redirectURL = ((HdfcPaymentService)hdfcPaymentService).getRedirectUrl();log.info(this.redirectURL);return "success";}}*//* if (paymentOption.equals("91000")){IPaymentService payuPaymentService = new HdfcPaymentService();paymentId = payuPaymentService.createPayment(userinfo.getUserId(), txnId, paymentOption, gatewayId);return "hdfc-pay-redirect";}*/return "payu-pay-redirect";}private boolean isCouponValid(Cart cart) {String couponCode = cart.getCouponCode();double totalAmountD;if(couponCode == null || "".equals(couponCode))totalAmountD = cart.getTotalPrice();elsetotalAmountD = cart.getDiscountedPrice();if(totalAmountD == 0) {return true;}else{return false;}}private long findGatewayId(String paymentOption){long gatewayId = 0;gatewayId = PaymentUtils.getGatewayId(paymentOption);return gatewayId;}/*** Verifies if the recaptcha response matches the recaptcha challenge.** @return True if the captcha was valid, false otherwise.*/private boolean verifyCaptcha() {String cookieCaptchaAnswer = getCookie(Captcha.NAME, true, "saholic");String captchaReceived = (String) request.getParameter("captcha_response_field");if (captchaReceived.equalsIgnoreCase(cookieCaptchaAnswer)) {try {// DataLogger.logData(EventType.CAPTCHA_SUCCESS, getSessionId(), userinfo.getUserId(), userinfo.getEmail());} catch (Exception e1) {log.warn("Unable to log orders through the datalogger", e1);}return true;}else {try {// DataLogger.logData(EventType.CAPTCHA_FAILED, getSessionId(), userinfo.getUserId(), userinfo.getEmail());} catch (Exception e1) {log.warn("Unable to log orders through the datalogger", e1);}return false;}}public String getId(){return id;}public void setId(String id){this.id = id;}public String getMyaccountHeaderSnippet(){return htmlSnippets.get("MYACCOUNT_HEADER");}public String getOrderDetailsSnippet(){return htmlSnippets.get("ORDER_DETAILS");}public long getTxn(){return this.txnId;}/**** @param addressId* @param currentCartId* @return*/private boolean createOrders(long addressId, long currentCartId, long currentUserId, long emiSchemeId){UserClient userServiceClient = null;try {userServiceClient = new UserClient();} catch (Exception e) {log.error("Unable to talk to the user context service.", e);return false;}in.shop2020.model.v1.user.UserContextService.Client userClient = userServiceClient.getClient();try {userClient.addAddressToCart(currentCartId, addressId);} catch (ShoppingCartException e1) {log.error("Not able to set address in the cart.", e1);return false;} catch (TException e1) {log.error("Thrift exception while setting address in cart.", e1);return false;}try {String errorMsg = userClient.validateCart(currentCartId, sourceId).get(0);if(!errorMsg.isEmpty()){addActionError(errorMsg);return false;}} catch (ShoppingCartException e1) {log.error("Error while validating shopping cart.", e1);return false;} catch (TException e) {log.error("Thrift exception while validating cart.", e);return false;}try {String sessionSrc = getCookie(TrackingInterceptor.SESSION_SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);String firstSrc = getCookie(TrackingInterceptor.SRC_COOKIE, true, TrackingInterceptor.ENCRIPTION_STRING);long sessionTime = 0;try {sessionTime = Long.parseLong(getCookie(TrackingInterceptor.SESSION_SRC_TIME_COOKIE, false, null));} catch (Exception e) {log.warn("Unable to parse session src time cookie.", e);}long firstSrcTime = 0;try {firstSrcTime = Long.parseLong(getCookie(TrackingInterceptor.SRC_TIME_COOKIE, false, null));} catch (Exception e) {log.warn("Unable to parse session src time cookie.", e);}txnId = userClient.createOrders(currentCartId, sessionSrc, sessionTime, firstSrc, firstSrcTime, currentUserId, emiSchemeId, OrderSource.WEBSITE.getValue());} catch (ShoppingCartException e1) {log.error("Error while creating orders from cart.", e1);return false;} catch (TException e) {log.error("Thrift exception while creating orders from cart.", e);return false;}TransactionClient transactionServiceClient = null;/*try {transactionServiceClient = new TransactionClient();List<Order> orders = transactionServiceClient.getClient().getOrdersForTransaction(txnId, userinfo.getUserId());for (Order order : orders) {List<Order> tmpOrders = new ArrayList<Order>();tmpOrders.add(order);String itemIdString = Utils.getItemIdStringFromOrders(tmpOrders);// DataLogger.logData(EventType.ORDER_CREATION, getSessionId(), userinfo.getUserId(), userinfo.getEmail(),// Long.toString(order.getId()), Long.toString(currentCartId), itemIdString);}} catch (Exception e1) {log.warn("Unable to log orders through the datalogger", e1);}*/return true;}/*** This method updates address of a given order.** @return*/public String modifyAddress() {long orderId = Long.parseLong(request.getParameter("orderId"));long addressId = Long.valueOf(request.getParameter("addressId"));try {TransactionClient transactionServiceClient = new TransactionClient();in.shop2020.model.v1.order.TransactionService.Client transactionClient= transactionServiceClient.getClient();transactionClient.updateShipmentAddress(orderId, addressId);in.shop2020.model.v1.order.Order t_order = transactionClient.getOrder(orderId);Warehouse warehouse = null;try{InventoryClient isc = new InventoryClient();warehouse = isc.getClient().getWarehouse(t_order.getWarehouse_id());} catch(Exception e) {log.error("Unable to get warehouse for id : " + t_order.getWarehouse_id(), e);//TODO throw e;}if(t_order.getLogistics_provider_id()==7L || t_order.getLogistics_provider_id()==46L){FedExShipAccountInfo fedexAccountInfo = FedExShipAccountInfo.getFedExInfo();List<in.shop2020.model.v1.order.Order> orders = new ArrayList<in.shop2020.model.v1.order.Order>();orders.add(t_order);ProcessShipmentReply processShipmentReply = ShipWebServiceClient.getShipmentCreationReply(orders,fedexAccountInfo.getClientDetail(),fedexAccountInfo.getWad(),fedexAccountInfo.getEndPointAddress(), t_order.getLogistics_provider_id());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<Attribute> attrList = new ArrayList<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){Attribute attr3 = new Attribute();attr3.setName("FedEx_COD_Return_BarCode");attr3.setValue(bc.getValue());attrList.add(attr3);}String codReturnTrackingNo= as.getTrackingId().getTrackingNumber();Attribute attr4 = new 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){Attribute attr1 = new Attribute();attr1.setName("FedEx_Package_BarCode");attr1.setValue(bc.getValue());attrList.add(attr1);}OperationalInstruction[] ois = pod.getOperationalInstructions();Attribute attr2 = new 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 (TTransportException e) {log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);} catch (NumberFormatException e) {log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);} catch (TransactionServiceException e) {log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);} catch (TException e) {log.error("Could not update address: " + addressId + " for orderId: " + orderId, e);}return "index";}public String getRedirectURL(){return this.redirectURL;}public String getDeliveryLocation() {return deliveryLocation;}public void setDeliveryLocation(String deliveryLocation) {this.deliveryLocation = deliveryLocation;}public static void main(String[] args) {DesEncrypter d = new DesEncrypter("shop2020");System.out.println(d.decrypt("pmkcWEzhf4IFRLyHce89Cg"));long[] HDFC_EMI_GATEWAY_IDS = {5,10,11,12};List<Long> stooges = Arrays.asList(5L,10L,11L,12L);List<Long> lista = new ArrayList<Long>();lista.add(5L);lista.add(10L);lista.add(11L);lista.add(12L);long gatewayId = 10;if(stooges.contains(gatewayId)){System.out.println("true");}else{System.out.println("false");}}}