Пример #1
0
        private static LSDecimal CalculateTax(TaxRule taxRule, LSDecimal price)
        {
            // DETERMINE TAX FOR TOTAL PRICE
            LSDecimal tempTax = ((price * taxRule.TaxRate) / 100);

            return(TaxHelper.Round((decimal)tempTax, 2, taxRule.RoundingRule));
        }
Пример #2
0
        /// <summary>
        /// Calculates tax
        /// </summary>
        /// <param name="taxRule">The tax rule to process</param>
        /// <param name="order">The order being processed</param>
        /// <param name="shipmentId">The shipment ID to calculate tax for; pass 0 for unshippable or -1 to ignore shipments</param>
        /// <returns>A basket item for the tax entry, or null if no tax is charged.</returns>
        public static OrderItem Calculate(TaxRule taxRule, Order order, int shipmentId)
        {
            //THIS SHIPMENT QUALIFIES, GET TOTAL OF ALL APPLICABLE BASKET ITEMS
            LSDecimal totalPrice = 0;

            foreach (OrderItem oi in order.Items)
            {
                //CHECK IF THE ITEM IS PART OF THE SHIPMENT
                if (oi.OrderShipmentId == shipmentId || shipmentId < 0)
                {
                    //CHECK WHETHER THE TAX CODE IS AFFECTED BY THIS Tax RULE
                    if (taxRule.AppliesToTaxCode(oi.TaxCodeId))
                    {
                        totalPrice += oi.ExtendedPrice;
                    }
                }
            }
            // GENERATE ITEM AND RETURN IF VALID
            OrderItem taxItem = GenerateOrderItem(order.OrderId, shipmentId, taxRule, totalPrice);

            if (taxItem.ExtendedPrice > 0)
            {
                return(taxItem);
            }
            return(null);
        }
Пример #3
0
        public LSDecimal CalculateValue(LSDecimal itemTotal)
        {
            // WE DO NOT NEED TO CALCULATE COUPONS FOR NON-POSITIVE VALUES
            if (itemTotal <= 0)
            {
                return(0);
            }

            // DETERMINE THE COUPON VALUE
            LSDecimal couponValue;

            if (this.IsPercent)
            {
                couponValue = Math.Round(((decimal)itemTotal * (decimal)this.DiscountAmount) / 100, 2, MidpointRounding.AwayFromZero);
            }
            else
            {
                couponValue = this.DiscountAmount;
            }
            if (couponValue > itemTotal)
            {
                couponValue = itemTotal;
            }
            if (this.MaxValue > 0 && couponValue > this.MaxValue)
            {
                couponValue = this.MaxValue;
            }
            return(-1 * couponValue);
        }
Пример #4
0
        private CreditCardRequest InitializeRefundRequest(Payment payment, Transaction captureTransaction, LSDecimal amount)
        {
            VerifyPaymentInstrument(payment);
            CreditCardRequest request = new CreditCardRequest();

            request.setChargeType(CreditCardRequest.CREDIT);
            request.setReferenceId(captureTransaction.ProviderTransactionId);
            request.setOrderId(payment.Order.OrderId.ToString());

            LSDecimal minAmount = 0.01M;

            if (amount > captureTransaction.Amount || amount < minAmount)
            {
                throw new InvalidOperationException("Refund Amount must be from 0.01 to the previously captured amount");
            }

            request.setChargeTotal((double)amount);

            AccountDataDictionary accountData = new AccountDataDictionary(payment.AccountData);

            SetCreditCardData(request, payment, accountData);

            if (!string.IsNullOrEmpty(payment.CurrencyCode))
            {
                request.setCurrency(payment.CurrencyCode);
            }

            return(request);
        }
 public DiscountedBasketProduct(int productId, LSDecimal averagePrice, int quantity)
 {
     _ProductId     = productId;
     _AveragePrice  = averagePrice;
     _Quantity      = quantity;
     _ExtendedPrice = _AveragePrice * Quantity;
 }
Пример #6
0
        private Dictionary <string, ProviderShipRateQuote> ParseProviderRateReponseIntl(XmlDocument providerResponse, Package[] packageList)
        {
            //CREATE TEMPORARY STORAGE FOR PARSING THE QUOTED SERVICES
            Dictionary <string, ProviderShipRateQuote> availableServices = new Dictionary <string, ProviderShipRateQuote>();
            ProviderShipRateQuote serviceQuote;
            //LOOP EACH PACKAGE IN THE RESPONSE
            XmlNodeList packageNodeList = providerResponse.DocumentElement.SelectNodes("Package");

            foreach (XmlNode packageNode in packageNodeList)
            {
                XmlNodeList serviceNodeList = packageNode.SelectNodes("Service");
                foreach (XmlNode serviceNode in serviceNodeList)
                {
                    string    serviceName = XmlUtility.GetElementValue(serviceNode, "SvcDescription", string.Empty);
                    LSDecimal postage     = AlwaysConvert.ToDecimal(XmlUtility.GetElementValue(serviceNode, "Postage", string.Empty));
                    if (postage > 0)
                    {
                        //GET THE INSTANCE OF SERVICEQUOTE TO BE UPDATED
                        if (availableServices.ContainsKey(serviceName))
                        {
                            serviceQuote = availableServices[serviceName];
                        }
                        else
                        {
                            //CREATE A NEW INSTANCE OF ProviderShipRateQuote
                            serviceQuote             = new ProviderShipRateQuote();
                            serviceQuote.ServiceCode = serviceName;
                            availableServices.Add(serviceName, serviceQuote);
                        }
                        //GET THE PACKAGE ID FROM THE RATE
                        int packageId = AlwaysConvert.ToInt(XmlUtility.GetAttributeValue(packageNode, "ID", string.Empty), -1);
                        if (packageId != -1)
                        {
                            //FIND THE PACKAGE IN THE LIST
                            Package package = packageList[packageId];
                            serviceQuote.Rate         += (postage * package.Multiplier);
                            serviceQuote.PackageCount += 1;
                        }
                    }
                }
            }
            //MOVE THROUGH LIST AND FIND SERVICES THAT ARE NOT AVAILABLE
            //FOR ALL PACKAGES IN THE SHIPMENT
            List <string> removeServices = new List <string>();

            foreach (string serviceName in availableServices.Keys)
            {
                serviceQuote = availableServices[serviceName];
                if (serviceQuote.PackageCount < packageList.Length)
                {
                    removeServices.Add(serviceName);
                }
            }
            //REMOVE ANY SERVICES THAT WERE IDENTIFIED
            foreach (string serviceName in removeServices)
            {
                availableServices.Remove(serviceName);
            }
            return(availableServices);
        }
Пример #7
0
        private Transaction ProcessRecurringResponse(AuthorizeRecurringTransactionRequest authRequest, RecurringResponse response)
        {
            //CREATE THE TRANSACTION OBJECT
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            transaction.TransactionType  = TransactionType.AuthorizeRecurring;
            LSDecimal transAmount = authRequest.RecurringChargeSpecified ? authRequest.RecurringCharge : authRequest.Amount;

            transaction.Amount = transAmount;

            if (response.getResponseCode() != 1)
            {
                transaction.TransactionStatus = TransactionStatus.Failed;
                transaction.ResponseCode      = response.getResponseCode().ToString();
                transaction.ResponseMessage   = response.getResponseCodeText();
            }
            else
            {
                transaction.TransactionStatus = TransactionStatus.Successful;
                //transaction.ProviderTransactionId = response.getReferenceId();
                transaction.TransactionDate = response.getTimeStamp();
                transaction.ResponseCode    = response.getResponseCode().ToString();
                transaction.ResponseMessage = response.getResponseCodeText();

                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    transaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"];
                    transaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"];
                }
            }

            return(transaction);
        }
Пример #8
0
        /// <summary>
        /// Processes a partial capture event
        /// </summary>
        /// <param name="payment">The payment that is captured</param>
        /// <param name="captureAmount">The amount that is captured</param>
        public static void PaymentCapturedPartial(Payment payment, LSDecimal captureAmount)
        {
            Order order = payment.Order;

            order.Notes.Add(new OrderNote(order.OrderId, order.UserId, LocaleHelper.LocalNow, string.Format(Properties.Resources.PaymentCapturedPartial, captureAmount), NoteType.SystemPrivate));
            order.Notes.Save();
            UpdateOrderStatus(StoreEvent.PaymentCapturedPartial, order);
            Hashtable parameters = new Hashtable();

            parameters["order"]    = order;
            parameters["customer"] = order.User;
            parameters["payment"]  = payment;
            ProcessEmails(StoreEvent.PaymentCapturedPartial, parameters);
            //A PAYMENT HAS BEEN COMPLETED, SO DETERMINE WHICH ORDER PAID EVENT TO TRIGGER
            LSDecimal balance = order.GetBalance(false);

            if (balance == 0)
            {
                OrderPaid(order);
            }
            else if (balance > 0)
            {
                OrderPaidPartial(order, balance);
            }
            else
            {
                OrderPaidCreditBalance(order, balance);
            }
        }
Пример #9
0
        private LSDecimal Calculate_PointOfDelivery(Basket basket, Dictionary <string, string> existingTransactions)
        {
            WebTrace.Write("CertiTAX: Begin Calculate POD");
            LSDecimal totalTax = 0;

            foreach (BasketShipment shipment in basket.Shipments)
            {
                CertiTAX.Order taxOrder = new CertiTAX.Order();
                //SET THE TAXORDER ADDRESS
                BuildTaxOrderAddress(taxOrder, shipment.Address);
                //BUILD THE TAXORDER OBJECT
                BuildTaxOrder(taxOrder, basket, shipment.BasketShipmentId, existingTransactions);
                taxOrder.Nexus = "POD";
                //EXECUTE THE TRANSACTION
                CertiTAX.TaxTransaction taxTransaction = null;
                try
                {
                    taxTransaction = (new CertiTAX.CertiCalc()).Calculate(taxOrder);
                }
                catch (Exception ex)
                {
                    WebTrace.Write("CertiTax could not calculate tax.  The error was: " + ex.Message);
                    if (!this.IgnoreFailedConfirm)
                    {
                        throw;
                    }
                }
                //PARSE THE RESULTS
                totalTax += ParseTaxTransaction(taxTransaction, basket, shipment.BasketShipmentId);
            }
            WebTrace.Write("CertiTAX: End Calculate POD");
            //RETURN THE TOTAL TAX
            return(totalTax);
        }
Пример #10
0
        /// <summary>
        /// Gets the total value of refunded transactions in this collection
        /// </summary>
        /// <returns>The total value of refunded transactions in this collection</returns>
        public LSDecimal GetTotalRefunded()
        {
            LSDecimal total = 0;

            foreach (Transaction tx in this)
            {
                if (tx.TransactionStatus == TransactionStatus.Successful)
                {
                    switch (tx.TransactionType)
                    {
                    case TransactionType.Authorize:
                    case TransactionType.AuthorizeCapture:
                    case TransactionType.PartialCapture:
                    case TransactionType.Capture:
                    case TransactionType.Void:
                        //do not include in total
                        break;

                    case TransactionType.PartialRefund:
                    case TransactionType.Refund:
                        //include in total
                        total += tx.Amount;
                        break;

                    default:
                        //THIS SHOULD NEVER HAPPEN IF ALL TRANSACTION TYPES ARE SPECIFIED ABOVE
                        throw new ArgumentOutOfRangeException("Invalid Transaction Type : " + tx.TransactionType.ToString());
                    }
                }
            }
            return(total);
        }
Пример #11
0
        private Transaction ProcessRecurringResponse(AuthorizeRecurringTransactionRequest authRequest, string responseData)
        {
            //CREATE THE TRANSACTION OBJECT
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            transaction.TransactionType  = TransactionType.AuthorizeRecurring;
            LSDecimal transAmount = authRequest.RecurringChargeSpecified ? authRequest.RecurringCharge : authRequest.Amount;

            transaction.Amount = transAmount;

            NameValueCollection response = ParseResponseString(responseData);

            int responseCode = AlwaysConvert.ToInt(response.Get("dc_response_code"), -9999);

            if (responseCode == 0 || responseCode == 85)
            {
                transaction.TransactionStatus     = TransactionStatus.Successful;
                transaction.ProviderTransactionId = response.Get("dc_transaction_id");
                transaction.TransactionDate       = LocaleHelper.LocalNow;
                transaction.ResponseCode          = response.Get("dc_response_code");
                transaction.ResponseMessage       = response.Get("dc_response_message");
            }
            else
            {
                transaction.TransactionStatus = TransactionStatus.Failed;
                transaction.ResponseCode      = response.Get("dc_response_code");
                transaction.ResponseMessage   = response.Get("dc_response_message");
            }

            return(transaction);
        }
Пример #12
0
 /// <summary>
 /// Composes the Packages in this list in a way so that their maximum weight
 /// does not exceed the given maximum value and is not below the given minimum value.
 /// </summary>
 /// <param name="maxWeight">The maximum weight that a Package should have</param>
 /// <param name="minWeight">The minimum weight that a Package should have</param>
 public void Compose(LSDecimal maxWeight, LSDecimal minWeight)
 {
     foreach (Package item in this)
     {
         item.Compose(maxWeight, minWeight);
     }
 }
Пример #13
0
        private LSDecimal Calculate_PointOfSale(Basket basket, Dictionary <string, string> existingTransactions)
        {
            WebTrace.Write("CertiTAX: Begin Calculate POS");
            CertiTAX.Order taxOrder = new CertiTAX.Order();
            //SET THE TAXORDER ADDRESS
            BuildTaxOrderAddress(taxOrder, StoreDataSource.Load().DefaultWarehouse);
            //BUILD THE TAXORDER OBJECT
            BuildTaxOrder(taxOrder, basket, 0, existingTransactions);
            taxOrder.Nexus = "POS";
            //EXECUTE THE TRANSACTION
            CertiTAX.TaxTransaction taxTransaction = null;
            try
            {
                taxTransaction = (new CertiTAX.CertiCalc()).Calculate(taxOrder);
            }
            catch (Exception ex)
            {
                WebTrace.Write("CertiTax could not calculate tax.  The error was: " + ex.Message);
                if (!this.IgnoreFailedConfirm)
                {
                    throw;
                }
            }
            //PARSE THE RESULTS
            LSDecimal totalTax = ParseTaxTransaction(taxTransaction, basket, 0);

            WebTrace.Write("CertiTAX: End Calculate POS");
            return(totalTax);
        }
Пример #14
0
 /// <summary>
 /// Converts dimensions of this package to the given measurement unit
 /// </summary>
 /// <param name="to">The measurement unit to convert to</param>
 public void ConvertDimensions(MeasurementUnit to)
 {
     Height = LocaleHelper.ConvertMeasurement(this.MeasurementUnit, Height, to);
     Width  = LocaleHelper.ConvertMeasurement(this.MeasurementUnit, Width, to);
     Length = LocaleHelper.ConvertMeasurement(this.MeasurementUnit, Length, to);
     this.MeasurementUnit = to;
 }
Пример #15
0
        /// <summary>
        /// Gets the total amount for unprocessed payments
        /// </summary>
        /// <returns>The total amount for unprocessed payments</returns>
        public LSDecimal TotalUnprocessed()
        {
            LSDecimal total = 0;

            foreach (Payment item in this)
            {
                if ((item.PaymentStatus != PaymentStatus.Captured) &&
                    (item.PaymentStatus != PaymentStatus.Completed) &&
                    (item.PaymentStatus != PaymentStatus.Refunded) &&
                    (item.PaymentStatus != PaymentStatus.RefundPending) &&
                    (item.PaymentStatus != PaymentStatus.Void) &&
                    (item.PaymentStatus != PaymentStatus.VoidPending)
                    )
                {
                    if (item.PaymentStatus == PaymentStatus.Authorized)
                    {
                        //THE PAYMENT MAY HAVE PARTIAL CAPTURES ATTACHED
                        total += (item.Amount - item.Transactions.GetTotalCaptured());
                    }
                    else
                    {
                        total += item.Amount;
                    }
                }
            }
            return(total);
        }
Пример #16
0
        /// <summary>
        /// Processes a payment refund event
        /// </summary>
        /// <param name="payment">The payment that is refunded</param>
        /// <param name="refundAmount">The amount refunded</param>
        public static void PaymentRefunded(Payment payment, LSDecimal refundAmount)
        {
            Order order = payment.Order;

            order.Notes.Add(new OrderNote(order.OrderId, order.UserId, LocaleHelper.LocalNow, string.Format(Properties.Resources.PaymentRefunded, refundAmount), NoteType.SystemPrivate));
            order.Notes.Save();
        }
Пример #17
0
 /// <summary>
 /// Converts all dimensions, weight and price of this package to whole numbers
 /// </summary>
 public void ConvertAllToWholeNumbers()
 {
     Weight      = Math.Ceiling((Decimal)Weight);
     RetailValue = Math.Ceiling((Decimal)RetailValue);
     Length      = Math.Ceiling((Decimal)Length);
     Width       = Math.Ceiling((Decimal)Width);
     Height      = Math.Ceiling((Decimal)Height);
 }
Пример #18
0
 /// <summary>
 /// Rounds dimensions, weight and price of this package upto given decimals
 /// </summary>
 /// <param name="decimals">number of decimals in fractional part</param>
 public void RoundAll(int decimals)
 {
     Weight      = Math.Round((Decimal)Weight, decimals);
     RetailValue = Math.Round((Decimal)RetailValue, decimals);
     Length      = Math.Round((Decimal)Length, decimals);
     Width       = Math.Round((Decimal)Width, decimals);
     Height      = Math.Round((Decimal)Height, decimals);
 }
Пример #19
0
        /*public override Transaction DoCancelRecurring(CancelRecurringRequest request)
         * {
         *  Transaction errTrans;
         *  string profileId = request.ProviderReference;
         *  if (string.IsNullOrEmpty(profileId))
         *  {
         *      errTrans = Transaction.CreateErrorTransaction(PaymentGatewayId, request.TransactionType, request.Subscription.EffectiveRecurringAmount, "E", "The original profile id is null.", request.RemoteIP);
         *      return errTrans;
         *  }
         *
         *  Transaction trans = CreateTransaction(null, request.TransactionType);
         *  trans.Amount = request.Subscription.EffectiveRecurringAmount;
         *
         *  return trans;
         * }*/

        /*public override Transaction DoModifyRecurring(ModifyRecurringRequest request)
         * {
         *  Transaction errTrans;
         *  string profileId = request.ProviderReference;
         *  if (string.IsNullOrEmpty(profileId))
         *  {
         *      errTrans = Transaction.CreateErrorTransaction(PaymentGatewayId, request.TransactionType, request.EffectiveRecurringAmount, "E", "The original profile id is null.", request.RemoteIP);
         *      return errTrans;
         *  }
         *
         *  Transaction trans = CreateTransaction(null, request.TransactionType);
         *  trans.Amount = request.EffectiveRecurringAmount;
         *
         *  return trans;
         * }*/

        /*public override FetchUpdateRecurringResponse DoFetchUpdateRecurring(FetchUpdateRecurringRequest request)
         * {
         *  throw new NotImplementedException("Not yet implemented");
         * }*/

        private Transaction CreateTransaction(TransactionType transactionType, LSDecimal transactionAmount)
        {
            //CREATE THE TRANSACTION OBJECT
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            transaction.TransactionType  = transactionType;

            bool accept = true;

            if (ExecutionMode == GatewayExecutionMode.AlwaysAccept)
            {
                accept = true;
            }
            else if (ExecutionMode == GatewayExecutionMode.AlwaysReject)
            {
                accept = false;
            }
            else if (ExecutionMode == GatewayExecutionMode.Random)
            {
                accept = RandomAccept();
            }

            if (accept)
            {
                //successful
                transaction.TransactionStatus     = TransactionStatus.Successful;
                transaction.ProviderTransactionId = Guid.NewGuid().ToString();
                transaction.TransactionDate       = DateTime.UtcNow;
                //if (payment != null)
                //{
                //    transaction.Amount = payment.Amount;
                //}
                transaction.Amount            = transactionAmount;
                transaction.ResponseCode      = "0";
                transaction.ResponseMessage   = "Transaction Successful";
                transaction.AuthorizationCode = "";
                transaction.AVSResultCode     = "S"; // NOT SUPPORTED
                transaction.CVVResultCode     = "X"; // NO RESPONSE

                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    transaction.RemoteIP = context.Request.ServerVariables["REMOTE_ADDR"];
                    transaction.Referrer = context.Request.ServerVariables["HTTP_REFERER"];
                }
            }
            else
            {
                //failed
                transaction.TransactionStatus = TransactionStatus.Failed;
                transaction.ResponseCode      = "999";
                transaction.ResponseMessage   = "Transaction Failed.";
            }

            return(transaction);
        }
Пример #20
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="referrer">The referrer</param>
 /// <param name="startDate">The start date</param>
 /// <param name="endDate">The end date</param>
 /// <param name="orderCount">The order count</param>
 /// <param name="productSubtotal">The total of products sold</param>
 /// <param name="orderTotal">Total of all orders</param>
 public ReferrerSalesSummary(String referrer, DateTime startDate, DateTime endDate, int orderCount, LSDecimal productSubtotal, LSDecimal orderTotal)
 {
     _Referrer        = referrer;
     _StartDate       = startDate;
     _EndDate         = endDate;
     _OrderCount      = orderCount;
     _ProductSubtotal = productSubtotal;
     _SalesTotal      = orderTotal;
 }
Пример #21
0
        /// <summary>
        /// Adds a new transaction to the gift certificate for updating its balance
        /// </summary>
        /// <param name="oldBalance">The old balance</param>
        /// <param name="newBalance">The new balance</param>
        public void AddBalanceUpdatedTransaction(LSDecimal oldBalance, LSDecimal newBalance)
        {
            GiftCertificateTransaction trans = new GiftCertificateTransaction();

            trans.Amount          = newBalance - oldBalance;
            trans.Description     = string.Format("Gift certificate balance updated manually from {0:lc} to {1:lc}.", oldBalance, newBalance);
            trans.TransactionDate = LocaleHelper.LocalNow;
            this.Transactions.Add(trans);
        }
Пример #22
0
 /// <summary>
 /// Captures this payment
 /// </summary>
 /// <param name="amount">The amount to capture</param>
 /// <param name="final">If <b>true</b> this capture is considered to be the final capture</param>
 /// <param name="async">If <b>true</b> payment is captured asynchronously</param>
 public virtual void Capture(LSDecimal amount, bool final, bool async)
 {
     System.Web.HttpContext context = System.Web.HttpContext.Current;
     if (context == null)
     {
         throw new ArgumentException("You must specify remoteIP when HttpContext.Current is null.", "remoteIP");
     }
     this.Capture(amount, final, async, context.Request.UserHostAddress);
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="affiliateId">Affiliate Id</param>
 /// <param name="startDate">Start date for this summary data</param>
 /// <param name="endDate">End date for this summary data</param>
 /// <param name="orderCount">Total number of orders</param>
 /// <param name="productSubtotal">Subtotal of products</param>
 /// <param name="orderTotal">Total value of orders</param>
 public AffiliateSalesSummary(int affiliateId, DateTime startDate, DateTime endDate, int orderCount, LSDecimal productSubtotal, LSDecimal orderTotal)
 {
     _AffiliateId     = affiliateId;
     _StartDate       = startDate;
     _EndDate         = endDate;
     _OrderCount      = orderCount;
     _ProductSubtotal = productSubtotal;
     _OrderTotal      = orderTotal;
 }
Пример #24
0
        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);
            }
        }
Пример #25
0
 public ChargeOrderRequest(string MerchantID, string MerchantKey,
                           string Env, string OrderNo, string Currency, LSDecimal Amount)
 {
     _MerchantID  = MerchantID;
     _MerchantKey = MerchantKey;
     _Environment = StringToEnvironment(Env);
     _OrderNo     = OrderNo;
     _Currency    = Currency;
     _Amount      = Amount;
 }
Пример #26
0
 /// <summary>
 /// Ensures no package in the package list is below the minimum weight.
 /// </summary>
 /// <param name="minWeight">The minimum weight that a package should have</param>
 public void EnsureMinimumWeight(LSDecimal minWeight)
 {
     foreach (Package item in this)
     {
         if (item.Weight < minWeight)
         {
             item.Weight = minWeight;
         }
     }
 }
Пример #27
0
        /// <summary>
        /// Submits an authorization request
        /// </summary>
        /// <param name="authorizeRequest">The authorization request</param>
        /// <returns>Transaction that represents the result of the authorization request</returns>
        public override Transaction DoAuthorize(AuthorizeTransactionRequest authorizeRequest)
        {
            Transaction transaction = new Transaction();

            transaction.PaymentGatewayId = this.PaymentGatewayId;
            //always use authorize capture.
            transaction.TransactionType = TransactionType.AuthorizeCapture;

            string          serialNumber = authorizeRequest.Payment.AccountData;
            GiftCertificate gc           = GiftCertificateDataSource.LoadForSerialNumber(serialNumber);

            string errorMessage = string.Empty;

            if (gc == null)
            {
                errorMessage = "No gift certificate found with given serial number.";
            }
            else if (gc.IsExpired())
            {
                errorMessage = "Gift certificate is expired.";
            }
            else if (gc.Balance < authorizeRequest.Amount)
            {
                errorMessage = "Gift certificate does not have enough balance to complete this transaction.";
            }
            else
            {
                LSDecimal newAmount = gc.Balance - authorizeRequest.Amount;
                gc.Balance = newAmount;
                GiftCertificateTransaction trans = new GiftCertificateTransaction();
                trans.TransactionDate = LocaleHelper.LocalNow;
                trans.Amount          = authorizeRequest.Amount;
                trans.OrderId         = authorizeRequest.Payment.OrderId;
                trans.Description     = string.Format("An amount of {0:lc} used in purchase. Remaining balance is {1:lc}.", authorizeRequest.Amount, newAmount);
                gc.Transactions.Add(trans);
                gc.Save();
            }

            if (string.IsNullOrEmpty(errorMessage))
            {
                transaction.TransactionStatus = TransactionStatus.Successful;
                transaction.ResponseCode      = "0";
                transaction.ResponseMessage   = "SUCCESS";
                transaction.Amount            = authorizeRequest.Amount;
            }
            else
            {
                transaction.TransactionStatus = TransactionStatus.Failed;
                transaction.ResponseCode      = "1";
                transaction.ResponseMessage   = errorMessage;
                transaction.Amount            = authorizeRequest.Amount;
            }

            return(transaction);
        }
Пример #28
0
        /// <summary>
        /// Calculates and applies taxes for the given order
        /// </summary>
        /// <param name="basket">The order to calculate taxes on.</param>
        /// <returns>The total amount of tax applied.</returns>
        /// <remarks>Any pre-existing tax line items must be removed from the order before the calculation.</remarks>
        public override LSDecimal Recalculate(Order order)
        {
            if (order == null)
            {
                throw new ArgumentNullException("order");
            }

            // CREATE THE DOR GATEWAY INSTANCE
            DorGateway gateway = new DorGateway(order, this.TaxName, this.UseDebugMode);

            // BUILD A DICTIONARY OF TAXABLE TOTALS BY SHIPMENT
            Dictionary <int, decimal> shipmentTotals = new Dictionary <int, decimal>();

            // LOOP ITEMS IN BASKET TO CALCULATE TAX
            OrderItemCollection newTaxItems = new OrderItemCollection();

            foreach (OrderItem item in order.Items)
            {
                // SEE IF ITEM HAS A TAX CODE THAT APPLIES
                if (item.TaxCodeId > 0 && this.TaxCodes.Contains(item.TaxCodeId))
                {
                    if (shipmentTotals.ContainsKey(item.OrderShipmentId))
                    {
                        shipmentTotals[item.OrderShipmentId] += (decimal)item.ExtendedPrice;
                    }
                    else
                    {
                        shipmentTotals[item.OrderShipmentId] = (decimal)item.ExtendedPrice;
                    }
                }
            }

            // LOOP TAXABLE SHIPMENT TOTALS
            LSDecimal totalTax = 0;

            foreach (int shipmentId in shipmentTotals.Keys)
            {
                // SEE IF THERE IS A TAXINFO INSTANCE FOR THIS ITEM
                TaxInfo taxInfo = gateway.GetTaxInfo(shipmentId);
                if (taxInfo != null)
                {
                    // A TAXINFO STRUCTURE EXISTS, SO CREATE TAX ITEM AND ADD TO BASKET
                    OrderItem taxItem = TaxUtility.GenerateOrderItem(order.OrderId, shipmentId, shipmentTotals[shipmentId], taxInfo);
                    totalTax += taxItem.ExtendedPrice;
                    order.Items.Add(taxItem);
                }
            }

            // SAVE ORDER
            order.Items.Save();

            // return total tax added to basekt
            return(newTaxItems.TotalPrice());
        }
Пример #29
0
        private LSDecimal ParseTaxTransaction(CertiTAX.TaxTransaction taxTransaction, Basket basket, int shipmentId)
        {
            if (taxTransaction == null)
            {
                return(0);
            }
            LSDecimal totalTaxes = 0;

            if (this.ReportBreakdown)
            {
                if (taxTransaction.CityTax > 0)
                {
                    totalTaxes += taxTransaction.CityTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.CityTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.CityTax);
                }
                if (taxTransaction.CountyTax > 0)
                {
                    totalTaxes += taxTransaction.CountyTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.CountyTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.CountyTax);
                }
                if (taxTransaction.LocalTax > 0)
                {
                    totalTaxes += taxTransaction.LocalTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.LocalTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.LocalTax);
                }
                if (taxTransaction.StateTax > 0)
                {
                    totalTaxes += taxTransaction.StateTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.StateTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.StateTax);
                }
                if (taxTransaction.NationalTax > 0)
                {
                    totalTaxes += taxTransaction.NationalTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.NationalTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.NationalTax);
                }
                if (taxTransaction.OtherTax > 0)
                {
                    totalTaxes += taxTransaction.OtherTax;
                    CreateTaxLineItem(basket, shipmentId, taxTransaction.OtherTaxAuthority, taxTransaction.CertiTAXTransactionId, taxTransaction.OtherTax);
                }
            }
            else
            {
                totalTaxes += taxTransaction.CityTax;
                totalTaxes += taxTransaction.CountyTax;
                totalTaxes += taxTransaction.LocalTax;
                totalTaxes += taxTransaction.StateTax;
                totalTaxes += taxTransaction.NationalTax;
                totalTaxes += taxTransaction.OtherTax;
                CreateTaxLineItem(basket, shipmentId, "Tax", taxTransaction.CertiTAXTransactionId, totalTaxes);
            }
            return(totalTaxes);
        }
Пример #30
0
        /// <summary>
        /// Converts an amount in the currency specified by this instance into the
        /// base currency.
        /// </summary>
        /// <param name="value">The amount in this currency to convert</param>
        /// <returns>The converted amount</returns>
        public LSDecimal ConvertToBase(LSDecimal value)
        {
            Currency baseCurrency = Token.Instance.Store.BaseCurrency;

            if (baseCurrency.CurrencyId == this.CurrencyId)
            {
                return(value);
            }
            LSDecimal convertedValue = Math.Round((decimal)(value / this.ExchangeRate), baseCurrency.DecimalDigits);

            return(convertedValue);
        }