Beispiel #1
0
        public void Process()
        {
            //This state has no proper representation in AC.
            //It is roughly equivalant to RefundPending
            string googleOrderNum = N1.googleordernumber;
            Order  order          = OrderDataSource.LoadForGoogleOrderNumber(googleOrderNum);

            if (order == null)
            {
                Logger.Warn("Unknown Google Order Number Chargeback Initialed. GoogleOrderNumber=" + googleOrderNum +
                            ". Amount=" + N1.latestchargebackamount.Value);
            }
            else
            {
                Payment     payment = AcHelper.GetGCPayment(order, GatewayInstance, true);
                Transaction trans   = new Transaction();
                trans.TransactionStatus = TransactionStatus.Pending;
                //trans.TransactionDate = N1.timestamp;
                trans.Amount                = N1.latestchargebackamount.Value;
                trans.TransactionType       = TransactionType.PartialRefund;
                trans.TransactionDate       = LocaleHelper.LocalNow;
                trans.PaymentGatewayId      = GatewayInstance.PaymentGatewayId;
                trans.ResponseMessage       = "Customer Initiated Chargeback";
                trans.ProviderTransactionId = N1.googleordernumber;

                payment.PaymentStatus = PaymentStatusHelper.GetStatusAfterTransaction(payment, trans);

                payment.Transactions.Add(trans);
                payment.Save();
            }
        }
        public void Process()
        {
            string googleOrderNum = N1.googleordernumber;
            Order  order          = OrderDataSource.LoadForGoogleOrderNumber(googleOrderNum);

            if (order == null)
            {
                Logger.Warn("Unknown Google Order Number Risk Information. GoogleOrderNumber=" + googleOrderNum);
            }
            else
            {
                Payment payment = AcHelper.GetGCPayment(order, GatewayInstance, true);
                //IF THE PAYMENT IS A GIFT CERTIFICATE WE SHOULD ADD THIS TX FOR INFO ONLY
                int  gcPayMethodId = PaymentEngine.GetGiftCertificatePaymentMethod().PaymentMethodId;
                bool isGiftCert    = (payment.PaymentMethodId == gcPayMethodId);

                Transaction trans = GetGCAuthorizationTransaction(payment.Transactions, N1.googleordernumber);

                trans.AVSResultCode = N1.riskinformation.avsresponse;
                trans.RemoteIP      = N1.riskinformation.ipaddress;
                if (!isGiftCert)
                {
                    trans.Amount          = payment.Amount;
                    trans.TransactionType = TransactionType.Authorize;
                }
                else
                {
                    trans.Amount          = 0;
                    trans.TransactionType = TransactionType.AuthorizeCapture;
                }

                trans.TransactionDate       = N1.timestamp;
                trans.PaymentGatewayId      = GatewayInstance.PaymentGatewayId;
                trans.ProviderTransactionId = googleOrderNum;
                bool   protection = N1.riskinformation.eligibleforprotection;
                string cvn        = N1.riskinformation.cvnresponse;
                int    age        = N1.riskinformation.buyeraccountage;
                trans.CVVResultCode = cvn;
                StringBuilder responseMessage = new StringBuilder();
                if (protection)
                {
                    responseMessage.Append("Eligible for protection.");
                }
                else
                {
                    responseMessage.Append("NOT eligible for protection.");
                }
                responseMessage.Append("  Buyer account is " + age + " days old.");
                trans.ResponseMessage   = responseMessage.ToString();
                trans.AuthorizationCode = googleOrderNum;
                //trans.AuthorizationCode = (protection ? 1 : 0).ToString() + "|" + cvn + "|" + age;
                payment.Transactions.Add(trans);
                //do not update payment status.
                //It will be updated when order state change notification is received
                payment.Save();
            }
        }
        public override LSDecimal GetTaxResult(Order ThisOrder, AnonymousAddress Address, LSDecimal ShippingRate)
        {
            CommerceBuilder.Orders.Basket basket = ThisOrder.AcBasket;
            if (basket == null)
            {
                basket = AcHelper.GetAcBasket(ThisOrder.ShoppingCart, true);
                if (basket != null)
                {
                    basket.Package(false);
                }
                ThisOrder.AcBasket = basket;
            }

            if (basket != null)
            {
                Orders.BasketItem basketItem = null;
                if (ShippingRate > 0)
                {
                    //only temporarily add basket item for tax calculations
                    basketItem = new Orders.BasketItem();
                    basketItem.OrderItemType = Orders.OrderItemType.Shipping;
                    basketItem.Price         = ShippingRate;
                    basketItem.Quantity      = 1;
                    basketItem.Name          = "Temp_GoogleCheckout";
                    //this basket item should be linked to the shipment
                    if (basket.Shipments.Count > 0)
                    {
                        basketItem.BasketShipmentId = basket.Shipments[0].BasketShipmentId;
                    }
                    basket.Items.Add(basketItem);
                    basketItem.BasketId = basket.BasketId;
                    basketItem.Save();
                }

                CommerceBuilder.Users.Address acAddress = AcHelper.GetAnonAcAddress(basket.User, Address);
                UpdateBillingAddress(basket.User, acAddress);
                foreach (Orders.BasketShipment shipment in basket.Shipments)
                {
                    UpdateShipmentAddress(shipment, acAddress);
                }

                LSDecimal RetVal = Taxes.TaxCalculator.Calculate(basket);

                //now that the tax rate is calculated, we can remove the additional basket item
                if (basketItem != null)
                {
                    basket.Items.Remove(basketItem);
                    basketItem.Delete();
                }
                return(RetVal);
            }
            else
            {
                return(0);
            }
        }
Beispiel #4
0
        public void Process()
        {
            string googleOrderNum = N1.googleordernumber;
            Order  order          = OrderDataSource.LoadForGoogleOrderNumber(googleOrderNum);

            if (order == null)
            {
                Logger.Warn("Unknown Google Order Number Charged. GoogleOrderNumber=" + googleOrderNum +
                            ". Amount=" + N1.latestchargeamount.Value);
            }
            else
            {
                Payment     payment = AcHelper.GetGCPayment(order, GatewayInstance, true);
                Transaction trans   = payment.Transactions.LastCapturePending;
                if (trans == null)
                {
                    trans = new Transaction();
                }
                else
                {
                    //remove the transaction from collection for correct calculations
                    payment.Transactions.Remove(trans);
                }
                trans.TransactionStatus = TransactionStatus.Successful;
                //trans.TransactionDate = N1.timestamp;
                trans.Amount                = N1.latestchargeamount.Value;
                trans.PaymentGatewayId      = GatewayInstance.PaymentGatewayId;
                trans.ProviderTransactionId = googleOrderNum;

                LSDecimal totalAuth  = payment.Transactions.GetTotalAuthorized();
                LSDecimal totalCapt  = payment.Transactions.GetTotalCaptured();
                LSDecimal remainCapt = totalAuth - totalCapt;

                trans.TransactionType = TransactionType.PartialCapture;
                if (remainCapt > trans.Amount)
                {
                    trans.TransactionType = TransactionType.PartialCapture;
                }
                else
                {
                    trans.TransactionType = TransactionType.Capture;
                }

                if (payment.PaymentStatus == PaymentStatus.CapturePending)
                {
                    PaymentEngine.ProcessCapturePending(payment, trans);
                }
                else
                {
                    PaymentEngine.ForceTransaction(payment, trans);
                }
            }
        }
        public void Process()
        {
            // Google has successfully refunded the customer's credit card.
            string googleOrderNum = N1.googleordernumber;
            Order  order          = OrderDataSource.LoadForGoogleOrderNumber(googleOrderNum);

            if (order == null)
            {
                Logger.Warn("Unknown Google Order Number Refunded. GoogleOrderNumber=" + googleOrderNum +
                            ". Amount=" + N1.latestrefundamount.Value);
            }
            else
            {
                Payment     payment = AcHelper.GetGCPayment(order, GatewayInstance, true);
                Transaction trans   = payment.Transactions.LastRefundPending;
                if (trans == null)
                {
                    trans = new Transaction();
                }
                else
                {
                    //remove the transaction from collection for correct calculations
                    payment.Transactions.Remove(trans);
                }
                trans.TransactionStatus = TransactionStatus.Successful;
                trans.PaymentGatewayId  = GatewayInstance.PaymentGatewayId;

                //LSDecimal totalRefunded = payment.Transactions.GetTotalRefunded();
                //trans.Amount = N1.totalrefundamount.Value - totalRefunded;
                trans.Amount = N1.latestrefundamount.Value;
                trans.ProviderTransactionId = N1.googleordernumber;

                LSDecimal totalCharged = payment.Transactions.GetTotalCaptured();
                if (totalCharged > trans.Amount)
                {
                    trans.TransactionType = TransactionType.PartialRefund;
                }
                else
                {
                    trans.TransactionType = TransactionType.Refund;
                }

                if (payment.PaymentStatus == PaymentStatus.RefundPending)
                {
                    PaymentEngine.ProcessRefundPending(payment, trans);
                }
                else
                {
                    PaymentEngine.ForceTransaction(payment, trans);
                }
            }
        }
Beispiel #6
0
        public static Payment GetGCPayment(Order order, GoogleCheckout instance, bool createNew)
        {
            int GCPayMethodId = AcHelper.GetGCPaymentMethodId(instance);

            foreach (Payment pmnt in order.Payments)
            {
                if (pmnt.PaymentMethodId == GCPayMethodId)
                {
                    return(pmnt);
                }
            }
            //IF THERE IS ONE PAYMENT
            //AND IT IS A GIFT CERTIFICATE
            //AND IT COVERS THE BALANCE OF THE ORDER
            //THEN THIS IS THE GOOGLE PAYMENT
            if (order.Payments.Count == 1)
            {
                int     gcPayMethodId = PaymentEngine.GetGiftCertificatePaymentMethod().PaymentMethodId;
                Payment payment       = order.Payments[0];
                if (payment.PaymentMethodId == gcPayMethodId)
                {
                    if (payment.Amount == order.TotalCharges)
                    {
                        return(payment);
                    }
                }
            }

            if (createNew)
            {
                Payment payment = new Payment();
                payment.PaymentMethodId   = GCPayMethodId;
                payment.Amount            = order.GetBalance(false);
                payment.OrderId           = order.OrderId;
                payment.PaymentMethodName = "GoogleCheckout";
                payment.PaymentStatus     = PaymentStatus.Unprocessed;
                order.Payments.Add(payment);
                //payment.Save();
                order.Save();
                return(payment);
            }
            else
            {
                return(null);
            }
        }
Beispiel #7
0
        public static ShipMethod FindShipMethod(ShipMethodCollection shipMethods, string sanitizedName)
        {
            if (string.IsNullOrEmpty(sanitizedName))
            {
                return(null);
            }
            string sanName;

            foreach (ShipMethod shipMeth in shipMethods)
            {
                sanName = AcHelper.SanitizeText(shipMeth.Name);
                if (sanitizedName.Equals(sanName, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(shipMeth);
                }
            }
            return(null);
        }
        public void Process()
        {
            string googleOrderNum = N1.googleordernumber;
            Order  order          = OrderDataSource.LoadForGoogleOrderNumber(googleOrderNum);

            if (order == null)
            {
                Logger.Warn("Unknown Google Order Number Order State Changed. GoogleOrderNumber=" + googleOrderNum);
            }
            else
            {
                //update financial order payment status
                Payment payment = AcHelper.GetGCPayment(order, GatewayInstance, true);
                switch (N1.newfinancialorderstate)
                {
                case FinancialOrderState.CHARGEABLE:
                    //authorized
                    payment.PaymentStatusReason = N1.reason;
                    if (payment.PaymentStatus == PaymentStatus.AuthorizationPending)
                    {
                        PaymentEngine.ProcessAuthorizePending(payment, GatewayInstance.PaymentGatewayId, true);
                    }
                    break;

                case FinancialOrderState.CHARGING:
                    //capture pending
                    break;

                case FinancialOrderState.CANCELLED:
                case FinancialOrderState.CANCELLED_BY_GOOGLE:
                    //cancel the order
                    //if the order has been paid order cancellation will be preceeded by a refund notification
                    //so that aspect will be handled in refund handler
                    //TODO: Do we need to force void the remaining payments?
                    //payment.PaymentStatusReason = N1.reason;
                    //PaymentEngine.ForceVoid(payment, GatewayInstance.PaymentGatewayId, true);
                    if (order.OrderStatus.IsValid)
                    {
                        if (!string.IsNullOrEmpty(N1.reason))
                        {
                            OrderNote on = new OrderNote();
                            on.Comment = "Order Cancelled : " + N1.reason;
                            on.OrderId = order.OrderId;
                            order.Notes.Add(on);
                        }
                        order.Cancel();
                    }
                    break;

                case FinancialOrderState.CHARGED:
                    //charge the payment
                    //we will handle this in charge amount notification handler only
                    //otherwise it can result in double charge transactions

                    /*payment.PaymentStatusReason = N1.reason;
                     * if (payment.PaymentStatus == PaymentStatus.CapturePending)
                     * {
                     *  PaymentEngine.ProcessCapturePending(payment, GatewayInstance.PaymentGatewayId, true);
                     * }*/
                    break;

                case FinancialOrderState.PAYMENT_DECLINED:
                    //payment declined
                    payment.PaymentStatusReason = N1.reason;
                    if (payment.PaymentStatus == PaymentStatus.CapturePending)
                    {
                        PaymentEngine.ProcessCapturePending(payment, GatewayInstance.PaymentGatewayId, false);
                    }
                    else if (payment.PaymentStatus == PaymentStatus.AuthorizationPending)
                    {
                        PaymentEngine.ProcessAuthorizePending(payment, GatewayInstance.PaymentGatewayId, false);
                    }
                    else
                    {
                        PaymentEngine.ForceCapture(payment, GatewayInstance.PaymentGatewayId, false);
                    }
                    break;

                case FinancialOrderState.REVIEWING:
                //No AC equivalent
                default:
                    break;
                }

                //TODO : order statuses are custom defined in AC
                //update order shipment status
                switch (N1.newfulfillmentorderstate)
                {
                case FulfillmentOrderState.NEW:
                    //do nothing
                    break;

                case FulfillmentOrderState.DELIVERED:
                    //order has been shipped
                    foreach (OrderShipment os in order.Shipments)
                    {
                        if (!os.IsShipped)
                        {
                            os.Ship(false);
                        }
                    }
                    break;

                case FulfillmentOrderState.PROCESSING:
                    //no equivalent in AC
                    break;

                case FulfillmentOrderState.WILL_NOT_DELIVER:
                    //this may happen if order is cancelled
                    //order cancelled event will take care of this
                    break;

                default:
                    break;
                }
            }
        }
        public void Process()
        {
            TraceContext trace    = WebTrace.GetTraceContext();
            string       traceKey = "GoogleCheckout.AC.NewOrderHandler";

            trace.Write(traceKey, "Begin NewOrderHandler.Process, Google order number " + N1.googleordernumber);

            Order order = OrderDataSource.LoadForGoogleOrderNumber(N1.googleordernumber);

            if (order == null) // ordernumber not already entered
            {
                trace.Write(traceKey, "Google order not present in database, get basket");
                Basket basket = AcHelper.GetAcBasket(N1.shoppingcart, true);
                if (basket == null)
                {
                    trace.Write(traceKey, "Basket could not be obtained (End NewOrderHandler.Process)");
                    return;
                }

                //basket is ready. check if there are any order adjustments to be made
                trace.Write(traceKey, "Check for order adjustments");
                OrderAdjustment orderAdj = N1.orderadjustment;
                if (orderAdj != null)
                {
                    trace.Write(traceKey, "Order adjustments present, add to basket");
                    OrderAdjustmentHelper.DoOrderAdjustments(orderAdj, basket);
                }

                trace.Write(traceKey, "set billing address");
                Users.Address primaryAddress = basket.User.PrimaryAddress;
                AcHelper.PopulateAcAddress(primaryAddress, N1.buyerbillingaddress);
                trace.Write(traceKey, "set shipping address");
                Users.Address shipAddr = AcHelper.GetAcAddress(basket.User, N1.buyershippingaddress);
                basket.User.Addresses.Add(shipAddr);
                basket.User.Save();

                trace.Write(traceKey, "package the basket");
                basket.Package(false);

                if (basket.Shipments.Count > 0)
                {
                    //there are shippable items / shipments
                    //set shipment address and shipment method
                    trace.Write(traceKey, "shippable items present, get shipping method");
                    ShipMethod shipMethod = AcHelper.GetShipMethod(basket);
                    trace.Write(traceKey, "ship method is " + shipMethod.Name + " (ID" + shipMethod.ShipMethodId.ToString() + ")");
                    foreach (BasketShipment shipment in basket.Shipments)
                    {
                        shipment.AddressId    = shipAddr.AddressId;
                        shipment.ShipMethodId = shipMethod.ShipMethodId;
                        shipment.Save();
                    }
                    //have to link the shipping charges with some shipment.
                    //we can't know which shipment. Just link to the first.
                    trace.Write(traceKey, "assign shipping charges to first shipment");
                    BasketShipment basketShipment = basket.Shipments[0];
                    foreach (BasketItem item in basket.Items)
                    {
                        if (item.OrderItemType == OrderItemType.Shipping)
                        {
                            item.BasketShipmentId = basketShipment.BasketShipmentId;
                            //update the sku and shipping method name so that scrubbed name is not used
                            item.Name = shipMethod.Name;
                            item.Sku  = string.Empty;
                        }
                    }
                }

                trace.Write(traceKey, "save basket");
                basket.Save();

                //now checkout the order with null payment.
                //this will alow payment to be processed later
                trace.Write(traceKey, "submit basket checkout");
                CheckoutRequest  acCheckout = new CheckoutRequest(null);
                CheckoutResponse acResp     = basket.Checkout(acCheckout);
                if (acResp.Success)
                {
                    trace.Write(traceKey, "checkout was successful, update the google order number for AC order number " + acResp.OrderNumber.ToString());
                    order = OrderDataSource.Load(acResp.OrderId, false);
                    if (order != null)
                    {
                        //update email address associated with order
                        order.BillToEmail       = N1.buyerbillingaddress.email;
                        order.GoogleOrderNumber = N1.googleordernumber;

                        bool isPaidByGc = false;

                        //IF THERE IS ONE PAYMENT AND IT IS A GIFT CERTIFICATE
                        //AND IT COVERS THE BALANCE OF THE ORDER THEN THIS IS THE GOOGLE PAYMENT
                        if (order.Payments.Count == 1)
                        {
                            int     gcPayMethodId = PaymentEngine.GetGiftCertificatePaymentMethod().PaymentMethodId;
                            Payment payment       = order.Payments[0];
                            if (payment.PaymentMethodId == gcPayMethodId)
                            {
                                if (payment.Amount == order.TotalCharges)
                                {
                                    isPaidByGc = true;
                                }
                            }
                        }
                        if (!isPaidByGc)
                        {
                            //We need to create a new payment with status of authorization pending
                            Payment payment = new Payment();
                            payment.PaymentMethodId   = AcHelper.GetGCPaymentMethodId(this.GatewayInstance);
                            payment.Amount            = order.GetBalance(false);
                            payment.OrderId           = order.OrderId;
                            payment.PaymentMethodName = "GoogleCheckout";
                            Transaction trans = new Transaction();
                            trans.TransactionType       = TransactionType.Authorize;
                            trans.TransactionStatus     = TransactionStatus.Pending;
                            trans.Amount                = payment.Amount;
                            trans.PaymentGatewayId      = this.GatewayInstance.PaymentGatewayId;
                            trans.ProviderTransactionId = N1.googleordernumber;
                            trans.TransactionDate       = N1.timestamp;
                            payment.Transactions.Add(trans);
                            payment.PaymentStatus = PaymentStatus.AuthorizationPending;
                            order.Payments.Add(payment);
                        }
                        order.Save();
                    }
                    else
                    {
                        OrderDataSource.UpdateGoogleOrderNumber(acResp.OrderId, N1.googleordernumber);
                    }
                }
                else
                {
                    trace.Write(traceKey, "checkout failed for google order");
                    CommerceBuilder.Utility.Logger.Warn("GoogleCheckout : New Order Checkout Failed.");
                }

                trace.Write(traceKey, "Send AC order number back to Google");
                AcNotifier.AddMerchantOrderNumber(GatewayInstance, N1.googleordernumber, acResp.OrderNumber.ToString());
            }
            else
            {
                //order number already entered. Just send notification
                trace.Write(traceKey, "Google order in database, send AC order number back to Google");
                AcNotifier.AddMerchantOrderNumber(GatewayInstance, N1.googleordernumber, order.OrderNumber.ToString());
            }
            trace.Write(traceKey, "End NewOrderHandler.Process");
        }
        public override ShippingResult GetShippingResult(string ShipMethodName, Order ThisOrder, AnonymousAddress Address)
        {
            TraceContext   trace  = WebTrace.GetTraceContext();
            ShippingResult RetVal = new ShippingResult();

            RetVal.Shippable = false;

            CommerceBuilder.Orders.Basket basket = ThisOrder.AcBasket;
            if (basket == null)
            {
                basket = AcHelper.GetAcBasket(ThisOrder.ShoppingCart, true);
                if (basket != null)
                {
                    basket.Package(false);
                }
                ThisOrder.AcBasket = basket;
            }

            if (basket == null || basket.Shipments.Count == 0)
            {
                return(RetVal);
            }

            ShipMethodCollection shipMethods = ThisOrder.AcShipMethods;

            if (shipMethods == null)
            {
                shipMethods             = ShipMethodDataSource.LoadForStore();
                ThisOrder.AcShipMethods = shipMethods;
            }

            if (shipMethods == null || shipMethods.Count == 0)
            {
                return(RetVal);
            }

            ShipMethod shipMethod;
            string     methodName   = "";
            int        shipMethodId = AcHelper.ExtractShipMethodId(ShipMethodName, out methodName);

            if (shipMethodId != 0)
            {
                shipMethod = AcHelper.FindShipMethod(shipMethods, shipMethodId);
            }
            else
            {
                shipMethod = AcHelper.FindShipMethod(shipMethods, methodName);
            }
            if (shipMethod == null)
            {
                return(RetVal);
            }

            CommerceBuilder.Users.Address acAddress = AcHelper.GetAnonAcAddress(basket.User, Address);
            if (!shipMethod.IsApplicableTo(acAddress))
            {
                return(RetVal);
            }

            ShipRateQuote rateQuote;

            //TODO : should assign a default ship rate
            RetVal.ShippingRate = 0;
            bool isValid = true;

            foreach (Orders.BasketShipment bshipment in basket.Shipments)
            {
                bshipment.SetAddress(acAddress);
                if (!bshipment.IsShipMethodApplicable(shipMethod))
                {
                    isValid = false;
                    break;
                }
                rateQuote = shipMethod.GetShipRateQuote(bshipment);
                if (rateQuote != null && rateQuote.TotalRate > 0)
                {
                    RetVal.ShippingRate += rateQuote.TotalRate;
                }
                else if (rateQuote == null)
                {
                    //this ship method is not applicable
                    isValid = false;
                    break;
                }
            }

            if (isValid)
            {
                RetVal.Shippable = true;
            }

            return(RetVal);
        }
        public override MerchantCodeResult GetMerchantCodeResult(Order ThisOrder, AnonymousAddress Address, string MerchantCode)
        {
            MerchantCodeResult RetVal = new MerchantCodeResult();

            RetVal.Valid = false;

            CommerceBuilder.Orders.Basket basket = ThisOrder.AcBasket;
            if (basket == null)
            {
                basket = AcHelper.GetAcBasket(ThisOrder.ShoppingCart);
                if (basket != null)
                {
                    basket.Package(false);
                }
                ThisOrder.AcBasket = basket;
            }

            if (basket != null)
            {
                Marketing.Coupon coupon = AcHelper.GetAcCoupon(MerchantCode);
                if (coupon != null)
                {
                    RetVal.Type = MerchantCodeType.Coupon;
                    if (!Marketing.CouponCalculator.IsCouponValid(basket, coupon))
                    {
                        RetVal.Message = "Coupon '" + MerchantCode + "' is not valid.";
                        return(RetVal);
                    }

                    if (coupon.AllowCombine)
                    {
                        if (HasNoCombineCoupon(basket))
                        {
                            //Basket already has a no combine coupon.
                            RetVal.Message = "The existing coupon applied to the basket can not combine other coupons.";
                            return(RetVal);
                        }
                    }
                    else
                    {
                        if (basket.BasketCoupons.Count > 0)
                        {
                            RetVal.Message = "Coupon " + MerchantCode + " can not combine with other coupons.";
                            return(RetVal);
                        }
                    }

                    if (!Marketing.CouponCalculator.IsCouponAlreadyUsed(basket, coupon))
                    {
                        //Coupon can be applied now.
                        CommerceBuilder.Orders.BasketCoupon recentCoupon = new CommerceBuilder.Orders.BasketCoupon(basket.BasketId, coupon.CouponId);
                        basket.BasketCoupons.Add(recentCoupon);
                        basket.Save();
                    }

                    CouponCalculator.ProcessBasket(basket, false);
                    //basket.Recalculate();

                    CommerceBuilder.Orders.BasketItem couponItem = GetAppliedCouponItem(basket, coupon);

                    if (couponItem != null)
                    {
                        RetVal.Valid   = true;
                        RetVal.Message = "Coupon '" + MerchantCode + "' has been applied.";
                        RetVal.Amount  = Math.Abs(couponItem.ExtendedPrice.ToDecimal(null));
                    }
                    else
                    {
                        RetVal.Message = "Coupon '" + MerchantCode + "' could not be applied.";
                    }

                    return(RetVal);
                }
                else
                {
                    //check giftcertificate
                    Payments.GiftCertificate giftCert = AcHelper.GetAcGiftCert(MerchantCode);
                    if (giftCert != null)
                    {
                        RetVal.Type   = MerchantCodeType.GiftCertificate;
                        RetVal.Amount = giftCert.Balance;
                        if (DateTime.Compare(giftCert.ExpirationDate, DateTime.UtcNow) < 0)
                        {
                            RetVal.Valid = true;
                        }
                        else
                        {
                            RetVal.Message = "Giftcertificate '" + MerchantCode + "' is expired.";
                        }
                    }
                    else
                    {
                        RetVal.Message = "Sorry, we didn't the recognize code '" + MerchantCode + "'.";
                    }
                }
            }

            if (!RetVal.Valid)
            {
                RetVal.Message = "Sorry, we didn't the recognize code '" + MerchantCode + "'.";
            }
            return(RetVal);
        }
Beispiel #12
0
        public static Basket GetAcBasket(AutoGen.ShoppingCart shoppingcart, bool clearShipNTax)
        {
            TraceContext trace    = WebTrace.GetTraceContext();
            string       traceKey = "GoogleCheckout.AC.AcHelper";

            trace.Write(traceKey, "Begin AcHelper.GetAcBasket");

            int basketId = AcHelper.GetAcBasketId(shoppingcart);

            trace.Write(traceKey, "Look for basket ID " + basketId.ToString());
            Basket basket = BasketDataSource.Load(basketId, false);

            if (basket == null)
            {
                trace.Write(traceKey, "Basket not found. Creating New Basket.");
                basket = new Basket();
            }
            else
            {
                //basket found. check if content hash matches
                string contentHash = GetReportedBasketHash(shoppingcart);
                if (contentHash.Equals(GetAcBasketHash(basket)))
                {
                    //hash matched. basket has not changed.
                    if (clearShipNTax)
                    {
                        ClearShippingAndTaxes(basket);
                    }
                    return(basket);
                }
            }

            trace.Write(traceKey, "Clear existing Basket contents and populate with Google Input.");
            basket.Clear();

            if (shoppingcart.items != null)
            {
                trace.Write(traceKey, "Looping " + shoppingcart.items.Length.ToString() + " items in Google cart");
            }
            foreach (Item thisItem in shoppingcart.items)
            {
                trace.Write(traceKey, "itemName: " + thisItem.itemname);
                BasketItem basketItem = new BasketItem();
                basketItem.Name     = thisItem.itemname;
                basketItem.Quantity = (short)thisItem.quantity;
                basketItem.Price    = thisItem.unitprice.Value;

                XmlNode[] privateNodes = thisItem.merchantprivateitemdata.Any;
                foreach (XmlNode privateNode in privateNodes)
                {
                    trace.Write(traceKey, "privateNode.Name: " + privateNode.Name);
                    switch (privateNode.Name)
                    {
                    case "productId":
                        basketItem.ProductId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "orderItemType":
                        basketItem.OrderItemType = (OrderItemType)AlwaysConvert.ToEnum(typeof(OrderItemType), privateNode.InnerText, OrderItemType.Product, true);
                        break;

                    case "shippable":
                        basketItem.Shippable = (Shippable)AlwaysConvert.ToEnum(typeof(Shippable), privateNode.InnerText, Shippable.Yes, true);
                        break;

                    case "taxCodeId":
                        basketItem.TaxCodeId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "weight":
                        basketItem.Weight = AlwaysConvert.ToDecimal(privateNode.InnerText);
                        break;

                    case "wrapStyleId":
                        basketItem.WrapStyleId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "optionList":
                        basketItem.OptionList = privateNode.InnerText;
                        break;

                    case "giftMessage":
                        basketItem.GiftMessage = privateNode.InnerText;
                        break;

                    case "lineMessage":
                        basketItem.LineMessage = privateNode.InnerText;
                        break;

                    case "lastModifiedDate":
                        basketItem.LastModifiedDate = AlwaysConvert.ToDateTime(privateNode.InnerText, LocaleHelper.LocalNow);
                        break;

                    case "orderBy":
                        basketItem.OrderBy = AlwaysConvert.ToInt16(privateNode.InnerText);
                        break;

                    case "parentItemId":
                        basketItem.ParentItemId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "sku":
                        basketItem.Sku = privateNode.InnerText;
                        break;

                    case "wishlistItemId":
                        basketItem.WishlistItemId = AlwaysConvert.ToInt(privateNode.InnerText);
                        break;

                    case "basketItemKitProducts":
                        List <string> kitList = new List <string>();
                        foreach (XmlNode subNode in privateNode.ChildNodes)
                        {
                            if (subNode.Name.Equals("kitProductId"))
                            {
                                int        kitProductId = AlwaysConvert.ToInt(subNode.InnerText);
                                KitProduct kitProd      = KitProductDataSource.Load(kitProductId);
                                if (kitProd != null)
                                {
                                    kitList.Add(kitProductId.ToString());
                                }
                            }
                        }
                        if (kitList.Count > 0)
                        {
                            basketItem.KitList = string.Join(",", kitList.ToArray());
                        }
                        break;

                    case "inputs":
                        foreach (XmlNode subNode in privateNode.ChildNodes)
                        {
                            if (subNode.Name.Equals("itemInput"))
                            {
                                int inputFieldId = 0;
                                foreach (XmlAttribute attr in subNode.Attributes)
                                {
                                    if (attr.Name.Equals("inputFieldId"))
                                    {
                                        inputFieldId = AlwaysConvert.ToInt(attr.InnerText);
                                        break;
                                    }
                                }
                                InputField inputField = InputFieldDataSource.Load(inputFieldId);
                                if (inputField != null)
                                {
                                    BasketItemInput bInput = new BasketItemInput();
                                    bInput.InputFieldId = inputFieldId;
                                    bInput.InputValue   = subNode.InnerText;
                                    basketItem.Inputs.Add(bInput);
                                }
                            }
                        }
                        break;

                    case "couponCode":
                        basketItem.Sku = privateNode.InnerText;
                        break;
                    }
                }
                basket.Items.Add(basketItem);
            }
            trace.Write(traceKey, "Saving basket");
            basket.Save();

            string key = "Basket_" + basket.BasketId.ToString();

            ContextCache.SetObject(key, basket);

            trace.Write(traceKey, "Basket created, returning to caller (End GetAcBasket)");
            return(basket);
        }