// Complete a order: e.g.,
        //    1) mark item as paid,
        //    2) mark item as shipped,
        //    3) leave feedback for user
        //  Unique identifier for an eBay order line item (transaction).
        //  The TransactionID can be paired up with the corresponding ItemID and used in the CompleteSale request
        //  to identify a single line item order.
        //  Unless an OrderLineItemID is used to identify a single line item order,
        //  or the OrderID is used to identify a single or multiple line item order,
        //  the ItemID/TransactionID pair must be specified.
        //  For a multiple line item order, OrderID must be used.
        //  If OrderID or OrderLineItemID are specified, the ItemID/TransactionID pair is ignored if present in the same request.
        public static bool CompleteSale(AccountType account, string orderId, string buyerId, string itemId, string ebayTransId,
                                        bool setIsPaid, bool isPaid, bool setIsShipped, bool isShipped)
        {
            Logger.WriteSystemLog(string.Format("buyerId={0} orderId={1} :Mark item as shipped.", buyerId, orderId));

            FeedbackInfoType feedback = new FeedbackInfoType();
            feedback.CommentText = "Great Buyer, fast payment, thanks for purchasing!";
            feedback.CommentType = CommentTypeCodeType.Positive;
            feedback.TargetUser = buyerId;

            CompleteSaleCall completeSaleApiCall = new CompleteSaleCall(account.SellerApiContext);
            completeSaleApiCall.FeedbackInfo = feedback;

            if (setIsPaid)
                completeSaleApiCall.Paid = isPaid;
            if (setIsShipped)
                completeSaleApiCall.Shipped = isShipped;

            //completeSaleApiCall.ItemID = itemId;
            //completeSaleApiCall.TransactionID = ebayTransId;
            completeSaleApiCall.OrderID = orderId;

            completeSaleApiCall.Execute();

            return true;
        }
 public void CompleteSale()
 {
     CompleteSaleCall api = new CompleteSaleCall(this.apiContext);
     TransactionType tran = null;
     if( TestData.SellerTransactions != null && TestData.SellerTransactions.Count > 0 )
     tran = TestData.SellerTransactions[0];
     // Make API call.
     ApiException gotException = null;
     // Negative test.
     try
     {
     if( tran != null )
     {
     api.ItemID = tran.Item.ItemID;
     api.TransactionID = tran.TransactionID;
     PaymentStatusCodeType pStatus = tran.Status.eBayPaymentStatus;
     api.Paid = (pStatus == PaymentStatusCodeType.NoPaymentFailure)
     && (tran.PaidTimeSpecified);
     }
     else
     api.ItemID = "TestID";
     api.Execute();
     }
     catch(ApiException ex)
     {
         gotException = ex;
     }
     if( gotException != null )
     Assert.IsNull(tran);
 }
        public void CompleteSale2()
        {
            CompleteSaleCall call = new CompleteSaleCall(this.apiContext);
            call.OrderID = "436095409011";
            call.Shipment = new ShipmentType();

            ShipmentTrackingDetailsType shipmentTrackingDetails = new ShipmentTrackingDetailsType();
            shipmentTrackingDetails.ShippingCarrierUsed = "DHL";
            shipmentTrackingDetails.ShipmentTrackingNumber = "6KH8F75870W5916";
            call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();
            call.Shipment.ShipmentTrackingDetails.Add(shipmentTrackingDetails);
            call.Shipment.ShippedTime = DateTime.Now;
            call.Shipped = true;

            try
            {
                call.Execute();
            }
            catch (Exception ex)
            {
                bool err = call.ApiException.containsErrorCode("55");
                Assert.IsFalse(err);
            }
        }
        public static void EbayUploadTrackCode(string account, KeWeiOMS.Domain.OrderType orderType)
        {
            ISession NSession = NhbHelper.OpenSession();
            Dictionary <string, int> sendNum  = new Dictionary <string, int>();
            IList <AccountType>      accounts = NSession.CreateQuery("from AccountType where AccountName='" + account + "'").SetMaxResults(1).
                                                List <AccountType>();

            if (accounts.Count > 0)
            {
                IList <KeWeiOMS.Domain.OrderType> orderList = new List <KeWeiOMS.Domain.OrderType>();
                if (orderType.IsMerger == 1 || orderType.OrderExNo.IndexOf("|") != -1)
                {
                    orderList = NSession.CreateQuery("from OrderType where MId='" + orderType.Id + "' Or Id ='" + orderType.Id + "'").List <KeWeiOMS.Domain.OrderType>();
                }
                else
                {
                    orderList.Add(orderType);
                }
                ApiContext context = GetGenericApiContext("US");

                context.ApiCredential.eBayToken = accounts[0].ApiToken;
                eBay.Service.Call.CompleteSaleCall call = null;
                string CarrierUsed = "";
                // IList<logisticsSetupType> setups = NSession.CreateQuery("from  logisticsSetupType where LId in (select ParentID from LogisticsModeType where LogisticsCode='" + orderType.LogisticMode + "')").List<logisticsSetupType>();
                //if (setups != null)
                //{
                //    CarrierUsed = setups[0].SetupName;
                //}
                CarrierUsed = "China Post";
                call        = new eBay.Service.Call.CompleteSaleCall(context);
                foreach (KeWeiOMS.Domain.OrderType order in orderList)
                {
                    string orderid = "";
                    string itemid  = "";

                    if (order.OrderExNo.IndexOf("-") == -1)
                    {
                        orderid = order.OrderExNo;

                        GetOrdersCall       apicall = new GetOrdersCall(context);
                        OrderTypeCollection orders  = null;
                        try
                        {
                            orders = apicall.GetOrders(new StringCollection {
                                order.OrderExNo
                            });
                        }
                        catch (Exception)
                        {
                            orders = new OrderTypeCollection();
                        }

                        if (orders.Count > 0)
                        {
                            foreach (TransactionType trans in orders[0].TransactionArray)
                            {
                                itemid        = trans.Item.ItemID;
                                orderid       = trans.TransactionID;
                                call.Shipment = new ShipmentType();
                                call.Shipment.DeliveryStatus          = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                                call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();

                                if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                                {
                                    //call.Shipment.ShipmentTrackingNumber = "";
                                }
                                else
                                {
                                    call.Shipment.ShippingCarrierUsed    = CarrierUsed;
                                    call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                                }
                                call.Shipment.DeliveryDate          = DateTime.Now;
                                call.Shipment.DeliveryDateSpecified = true;
                                call.Shipment.DeliveryStatus        = ShipmentDeliveryStatusCodeType.Delivered;
                                try
                                {
                                    call.CompleteSale(itemid, orderid, true, true);
                                }
                                catch (Exception ex)
                                {
                                    break;
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        itemid        = order.OrderExNo.Substring(0, order.OrderExNo.IndexOf("-"));
                        orderid       = order.OrderExNo.Substring(order.OrderExNo.IndexOf("-") + 1);
                        call.Shipment = new ShipmentType();
                        call.Shipment.DeliveryStatus          = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                        call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();
                        if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                        {
                            //call.Shipment.ShipmentTrackingNumber = "";
                        }
                        else
                        {
                            call.Shipment.ShippingCarrierUsed    = CarrierUsed;
                            call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                        }

                        call.Shipment.DeliveryDate          = DateTime.Now;
                        call.Shipment.DeliveryDateSpecified = true;
                        call.Shipment.DeliveryStatus        = ShipmentDeliveryStatusCodeType.Delivered;
                        try
                        {
                            call.CompleteSale(itemid, orderid, true, true);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        finally
                        {
                        }
                    }
                }
            }
        }
        // Upload tracking number to ebay.
        //  CompleteSale
        //  https://developer.ebay.com/DevZone/XML/docs/Reference/ebay/CompleteSale.html
        public static bool UploadTrackingNumber(AccountType account, string itemId, string ebayTransId, 
            string shippingCarrier, string shipmentTrackingNumber)
        {
            CompleteSaleCall completeSaleApiCall = new CompleteSaleCall(account.SellerApiContext);
            completeSaleApiCall.Shipment = new eBay.Service.Core.Soap.ShipmentType();

            ShipmentTrackingDetailsType shippingDetailsType = new ShipmentTrackingDetailsType();
            shippingDetailsType.ShippingCarrierUsed = shippingCarrier;
            shippingDetailsType.ShipmentTrackingNumber = shipmentTrackingNumber;
            completeSaleApiCall.Shipment.ShipmentTrackingDetails = new eBay.Service.Core.Soap.ShipmentTrackingDetailsTypeCollection();
            completeSaleApiCall.Shipment.ShipmentTrackingDetails.Add(shippingDetailsType);

            completeSaleApiCall.ItemID = itemId;
            completeSaleApiCall.TransactionID = ebayTransId;

            bool result = false;
            try
            {
                completeSaleApiCall.Execute();
                result = true;
            }
            catch (System.Exception ex)
            {
                Logger.WriteSystemLog(string.Format("ERROR: UploadTrackingNumber failed with error msg={0}", ex.Message));
            }

            return result;
        }
        // Leave feedback for an order.
        public static bool LeaveFeedback(AccountType account, string orderId, string buyerId, string itemId, string ebayTransId)
        {
            CompleteSaleCall completeSaleApiCall = new CompleteSaleCall(account.SellerApiContext);

            FeedbackInfoType feedback = new FeedbackInfoType();
            feedback.CommentText = "Great Buyer, fast payment, thanks for purchasing!";
            feedback.CommentType = CommentTypeCodeType.Positive;
            feedback.TargetUser = buyerId;

            completeSaleApiCall.FeedbackInfo = feedback;

            completeSaleApiCall.ItemID = itemId;
            completeSaleApiCall.TransactionID = ebayTransId;

            completeSaleApiCall.Execute();

            return true;
        }
        public ExternalOrderShippedResult SetOrderShipped(IOrderShipmentRequest shipmentRequests)
        {
            CompleteSaleCall completeSales = new CompleteSaleCall(eBayContext);

            ExternalOrderShippedResult result = new ExternalOrderShippedResult() { Success = false, ShippingResults = new List<ShippingResult>() };
            bool allSuccess = true;

            int successCount = 0;

            int failedCount = 0;

            StringBuilder errorBuilder = new StringBuilder();

            foreach (eBayOrderShipmentIfo request in shipmentRequests.ShipmentList)
            {
                ShippingResult shippingResult = new ShippingResult()
                {
                    StoreProviderOrderId = request.OrderId,
                    ExternalOrderHeaderId = request.ExternalOrderHeaderId,
                    ShippedDate = request.ShipmentDate,
                };

                try
                {
                    completeSales.OrderID = request.OrderId;

                    ShipmentType shipment = new ShipmentType();

                    shipment.ShippedTime = request.ShipmentDate;

                    completeSales.Shipment = shipment;

                    completeSales.Shipped = true;

                    completeSales.Site = SiteCodeType.UK;

                    completeSales.DetailLevelList.Add(DetailLevelCodeType.ReturnAll);

                    completeSales.Execute();

                    if (completeSales.ApiResponse.Ack == AckCodeType.Success)
                    {

                        shippingResult.Success = true;

                        successCount += 1;

                    }
                    else
                    {
                        allSuccess = false;
                        shippingResult.Success = false;

                        StringBuilder sb = new StringBuilder();

                        foreach (ErrorType error in completeSales.ApiResponse.Errors)
                        {
                            sb.Append(error.LongMessage + "; ");
                        }

                        shippingResult.ErrorMessage = string.Format("eBay Code returned : {0}; Error: {1}", completeSales.ApiResponse.Ack.ToString(), sb.ToString().Trim());

                        errorBuilder.Append(sb.ToString() + " | ");
                        failedCount += 1;
                    }

                }
                catch (Exception ex)
                {
                    allSuccess = false;

                    shippingResult.Success = false;

                    shippingResult.ErrorMessage = string.Format("Error occurred while updating shipping info: {0}, Error: {1}", request.OrderId, ex.Message);

                    errorBuilder.Append(shippingResult.ErrorMessage + " | ");

                    failedCount += 1;
                }

            }

            if (allSuccess)
            {
                result.Success = true;

            }
            else
            {
                result.Success = false;
                result.ErrorMessage = "Some orders could not be shipped";
            }

            if (successCount > 0)
            {

                result.SuccessMessage = string.Format("Successfully Shipped {0} Orders ", successCount);
            }

            if (failedCount > 0)
            {

                result.ErrorMessage = string.Format("Failed to Ship {0} Orders, please check and try again.", failedCount);

                result.ErrorMessage += "<br/> " + errorBuilder.ToString();

            }

            return result;
        }
        public static void EbayUploadTrackCode(string account, KeWeiOMS.Domain.OrderType orderType)
        {
            ISession NSession = NhbHelper.OpenSession();
            Dictionary<string, int> sendNum = new Dictionary<string, int>();
            IList<AccountType> accounts = NSession.CreateQuery("from AccountType where AccountName='" + account + "'").SetMaxResults(1).
                    List<AccountType>();
            if (accounts.Count > 0)
            {

                IList<KeWeiOMS.Domain.OrderType> orderList = new List<KeWeiOMS.Domain.OrderType>();
                if (orderType.IsMerger == 1 || orderType.OrderExNo.IndexOf("|") != -1)
                {
                    orderList = NSession.CreateQuery("from OrderType where MId='" + orderType.Id + "' Or Id ='" + orderType.Id + "'").List<KeWeiOMS.Domain.OrderType>();
                }
                else
                {
                    orderList.Add(orderType);
                }
                ApiContext context = GetGenericApiContext("US");

                context.ApiCredential.eBayToken = accounts[0].ApiToken;
                eBay.Service.Call.CompleteSaleCall call = null;
                string CarrierUsed = "";
                // IList<logisticsSetupType> setups = NSession.CreateQuery("from  logisticsSetupType where LId in (select ParentID from LogisticsModeType where LogisticsCode='" + orderType.LogisticMode + "')").List<logisticsSetupType>();
                //if (setups != null)
                //{
                //    CarrierUsed = setups[0].SetupName;
                //}
                CarrierUsed = "China Post";
                call = new eBay.Service.Call.CompleteSaleCall(context);
                foreach (KeWeiOMS.Domain.OrderType order in orderList)
                {
                    string orderid = "";
                    string itemid = "";

                    if (order.OrderExNo.IndexOf("-") == -1)
                    {
                        orderid = order.OrderExNo;

                        GetOrdersCall apicall = new GetOrdersCall(context);
                        OrderTypeCollection orders = null;
                        try
                        {
                            orders = apicall.GetOrders(new StringCollection { order.OrderExNo });
                        }
                        catch (Exception)
                        {
                            orders = new OrderTypeCollection();

                        }

                        if (orders.Count > 0)
                        {
                            foreach (TransactionType trans in orders[0].TransactionArray)
                            {
                                itemid = trans.Item.ItemID;
                                orderid = trans.TransactionID;
                                call.Shipment = new ShipmentType();
                                call.Shipment.DeliveryStatus = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                                call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();

                                if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                                {
                                    //call.Shipment.ShipmentTrackingNumber = "";
                                }
                                else
                                {
                                    call.Shipment.ShippingCarrierUsed = CarrierUsed;
                                    call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                                }
                                call.Shipment.DeliveryDate = DateTime.Now;
                                call.Shipment.DeliveryDateSpecified = true;
                                call.Shipment.DeliveryStatus = ShipmentDeliveryStatusCodeType.Delivered;
                                try
                                {
                                    call.CompleteSale(itemid, orderid, true, true);
                                }
                                catch (Exception ex)
                                {
                                    break;
                                }
                                break;

                            }
                        }
                    }
                    else
                    {
                        itemid = order.OrderExNo.Substring(0, order.OrderExNo.IndexOf("-"));
                        orderid = order.OrderExNo.Substring(order.OrderExNo.IndexOf("-") + 1);
                        call.Shipment = new ShipmentType();
                        call.Shipment.DeliveryStatus = eBay.Service.Core.Soap.ShipmentDeliveryStatusCodeType.Delivered;
                        call.Shipment.ShipmentTrackingDetails = new ShipmentTrackingDetailsTypeCollection();
                        if (orderType.OrderNo == order.TrackCode || order.TrackCode == "" || order.TrackCode == null)
                        {
                            //call.Shipment.ShipmentTrackingNumber = "";
                        }
                        else
                        {
                            call.Shipment.ShippingCarrierUsed = CarrierUsed;
                            call.Shipment.ShipmentTrackingNumber = orderType.TrackCode.ToString();
                        }

                        call.Shipment.DeliveryDate = DateTime.Now;
                        call.Shipment.DeliveryDateSpecified = true;
                        call.Shipment.DeliveryStatus = ShipmentDeliveryStatusCodeType.Delivered;
                        try
                        {
                            call.CompleteSale(itemid, orderid, true, true);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                        finally
                        {


                        }
                    }
                }
            }
        }