Beispiel #1
0
 public virtual PaymentOrder CreateOrUpdatePaymentOrder(IOrderGroup orderGroup, string description,
                                                        string consumerProfileRef = null)
 {
     //return string.IsNullOrWhiteSpace(orderId) ? CreateOrder(orderGroup, userAgent, consumerProfileRef) :  UpdateOrder(orderId, orderGroup, userAgent);
     return
         (CreatePaymentOrder(orderGroup, description, consumerProfileRef)); //TODO Change to UpdateOrder when SwedbankPay Api supports updating of orderitems
 }
Beispiel #2
0
        public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message)
        {
            if (payment.TransactionType == TransactionType.Void.ToString())
            {
                try
                {
                    var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString();
                    if (!string.IsNullOrEmpty(orderId))
                    {
                        KlarnaOrderService.CancelOrder(orderId);

                        payment.Status = PaymentStatus.Processed.ToString();

                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Order cancelled at Klarna");

                        return(true);
                    }
                }
                catch (Exception ex) when(ex is ApiException || ex is WebException)
                {
                    var exceptionMessage = GetExceptionMessage(ex);

                    payment.Status = PaymentStatus.Failed.ToString();
                    message        = exceptionMessage;
                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
                    Logger.Error(exceptionMessage, ex);
                    return(false);
                }
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message));
            }
            return(false);
        }
Beispiel #3
0
        public virtual PaymentOrderRequest GetPaymentOrderRequest(
            IOrderGroup orderGroup, IMarket market, PaymentMethodDto paymentMethodDto, string description, string consumerProfileRef = null)
        {
            if (orderGroup == null)
            {
                throw new ArgumentNullException(nameof(orderGroup));
            }
            if (market == null)
            {
                throw new ArgumentNullException(nameof(market));
            }

            var marketCountry = CountryCodeHelper.GetTwoLetterCountryCode(market.Countries.FirstOrDefault());

            if (string.IsNullOrWhiteSpace(marketCountry))
            {
                throw new ConfigurationException($"Please select a country in Commerce Manager for market {orderGroup.MarketId}");
            }


            List <OrderItem> orderItems = new List <OrderItem>();

            foreach (var orderGroupForm in orderGroup.Forms)
            {
                foreach (var shipment in orderGroupForm.Shipments)
                {
                    orderItems.AddRange(GetOrderItems(market, orderGroup.Currency, shipment.ShippingAddress, shipment.LineItems));
                    orderItems.Add(GetShippingOrderItem(shipment, market));
                }
            }

            return(CreatePaymentOrderRequest(orderGroup, market, consumerProfileRef, orderItems, description));
        }
Beispiel #4
0
        private Urls GetMerchantUrls(IOrderGroup orderGroup, IMarket market, string payeeReference)
        {
            var checkoutConfiguration = _checkoutConfigurationLoader.GetConfiguration(market.MarketId);

            Uri ToFullSiteUrl(Func <CheckoutConfiguration, Uri> fieldSelector)
            {
                if (fieldSelector(checkoutConfiguration) == null)
                {
                    return(null);
                }
                var url = fieldSelector(checkoutConfiguration).OriginalString
                          .Replace("{orderGroupId}", orderGroup.OrderLink.OrderGroupId.ToString())
                          .Replace("{payeeReference}", payeeReference);

                var uriBuilder = new UriBuilder(url);

                if (!uriBuilder.Uri.IsAbsoluteUri)
                {
                    return(new Uri(SiteDefinition.Current.SiteUrl, uriBuilder.Uri.PathAndQuery));
                }

                return(uriBuilder.Uri);
            }

            var cancelUrl = checkoutConfiguration.PaymentUrl != null?ToFullSiteUrl(c => c.CancelUrl) : null;

            return(new Urls(checkoutConfiguration.HostUrls, ToFullSiteUrl(c => c.CompleteUrl),
                            checkoutConfiguration.TermsOfServiceUrl, ToFullSiteUrl(c => c.CancelUrl), ToFullSiteUrl(c => c.PaymentUrl),
                            ToFullSiteUrl(c => c.CallbackUrl), checkoutConfiguration.LogoUrl));
        }
Beispiel #5
0
        private IPromotionResult PromotionResult(IOrderGroup orderGroup, BuyXFromCategoryGetProductForFree promotion,
                                                 FulfillmentStatus fulfillment)
        {
            BuyXFromCategoryGetProductForFreeResult result = null;

            switch (fulfillment)
            {
            case FulfillmentStatus.NotFulfilled:
                result = new BuyXFromCategoryGetProductForFreeResult(fulfillment,
                                                                     "The promotion is not fulfilled.");
                break;

            case FulfillmentStatus.PartiallyFulfilled:
                result = new BuyXFromCategoryGetProductForFreeResult(fulfillment,
                                                                     "The promotion is somewhat fulfilled.");
                break;

            case FulfillmentStatus.Fulfilled:
            {
                VariationContent content = _contentLoader.Get <VariationContent>(promotion.FreeProduct);
                result = new BuyXFromCategoryGetProductForFreeResult(fulfillment,
                                                                     string.Format("The promotion is fulfilled and it has been applied to item {0}", content.Name),
                                                                     content, orderGroup as OrderGroup);
                break;
            }
            }
            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// When an order needs to be captured the cartridge needs to make an API Call
        /// POST /ordermanagement/v1/orders/{order_id}/captures for the amount which needs to be captured.
        ///     If it's a partial capture the API call will be the same just for the
        /// amount that should be captured. Many captures can be made up to the whole amount authorized.
        /// The shipment information can be added in this call or amended aftewards using the method
        /// "Add shipping info to a capture".
        ///     The amount captured never can be greater than the authorized.
        /// When an order is Partally Captured the status of the order in Klarna is PART_CAPTURED
        /// </summary>
        public override bool Process(IPayment payment, IOrderForm orderForm, IOrderGroup orderGroup, IShipment shipment, ref string message)
        {
            if (payment.TransactionType == TransactionType.Capture.ToString())
            {
                var amount  = AmountHelper.GetAmount(payment.Amount);
                var orderId = orderGroup.Properties[Common.Constants.KlarnaOrderIdField]?.ToString();
                if (!string.IsNullOrEmpty(orderId))
                {
                    try
                    {
                        var captureData = KlarnaOrderService.CaptureOrder(orderId, amount, "Capture the payment", orderGroup, orderForm, payment, shipment);
                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Captured {payment.Amount}, id {captureData.CaptureId}");
                    }
                    catch (Exception ex) when(ex is ApiException || ex is WebException)
                    {
                        var exceptionMessage = GetExceptionMessage(ex);

                        payment.Status = PaymentStatus.Failed.ToString();
                        message        = exceptionMessage;
                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {exceptionMessage}");
                        Logger.Error(exceptionMessage, ex);
                        return(false);
                    }
                }
                return(true);
            }
            else if (Successor != null)
            {
                return(Successor.Process(payment, orderForm, orderGroup, shipment, ref message));
            }
            return(false);
        }
        private PaymentStepResult ProcessFraudUpdate(IPayment payment, IOrderGroup orderGroup)
        {
            var paymentStepResult = new PaymentStepResult();

            if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_ACCEPTED))
            {
                payment.Status = PaymentStatus.Processed.ToString();
                OrderStatusManager.ReleaseHoldOnOrder((PurchaseOrder)orderGroup);
                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk accepted");
                paymentStepResult.Status = true;
                return(paymentStepResult);
            }

            if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_REJECTED))
            {
                payment.Status = PaymentStatus.Failed.ToString();
                OrderStatusManager.HoldOrder((PurchaseOrder)orderGroup);
                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk rejected");
                paymentStepResult.Status = true;
                return(paymentStepResult);
            }

            if (payment.HasFraudStatus(NotificationFraudStatus.FRAUD_RISK_STOPPED))
            {
                payment.Status = PaymentStatus.Failed.ToString();
                OrderStatusManager.HoldOrder((PurchaseOrder)orderGroup);
                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk stopped");
                paymentStepResult.Status = true;
                return(paymentStepResult);
            }

            paymentStepResult.Message = $"Can't process authorization. Unknown fraud notification: {payment.Properties[Common.Constants.FraudStatusPaymentField]} or no fraud notifications received so far.";

            return(paymentStepResult);
        }
        /// <summary>
        /// Processes the successful transaction, was called when Payoo Gateway redirect back.
        /// </summary>
        /// <param name="orderGroup">The order group that was processed.</param>
        /// <param name="payment">The order payment.</param>
        /// <param name="acceptUrl">The redirect url when finished.</param>
        /// <param name="cancelUrl">The redirect url when error happens.</param>
        /// <returns>The url redirection after process.</returns>
        public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl)
        {
            if (HttpContext.Current == null)
            {
                return(cancelUrl);
            }

            var cart = orderGroup as ICart;

            if (cart == null)
            {
                // return to the shopping cart page immediately and show error messages
                return(ProcessUnsuccessfulTransaction(cancelUrl, "Commit Tran Error Cart Null"));
            }

            // everything is fine
            var errorMessages = new List <string>();
            var cartCompleted = _payooCartService.DoCompletingCart(cart, errorMessages);

            if (!cartCompleted)
            {
                return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray())));
            }

            // Place order
            var purchaseOrder  = _payooCartService.MakePurchaseOrder(cart, payment);
            var redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl);

            _logger.Info($"Payoo transaction succeeds, redirect end user to {redirectionUrl}");

            return(redirectionUrl);
        }
        public override PaymentStepResult ProcessAuthorization(IPayment payment, IOrderGroup orderGroup)
        {
            var paymentStepResult = new PaymentStepResult();

            var orderId = orderGroup.Properties[Constants.SwedbankPayOrderIdField]?.ToString();

            if (!string.IsNullOrEmpty(orderId))
            {
                try
                {
                    var result      = AsyncHelper.RunSync(() => SwedbankPayClient.PaymentOrders.Get(new Uri(orderId, UriKind.Relative), Sdk.PaymentOrders.PaymentOrderExpand.All));
                    var transaction = result.PaymentOrderResponse.CurrentPayment.Payment.Transactions.TransactionList?.FirstOrDefault();
                    if (transaction != null)
                    {
                        payment.ProviderTransactionID = transaction.Number;
                        AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Authorize completed at SwedbankPay, Transaction number: {transaction.Number}");
                        paymentStepResult.Status = true;
                    }
                }
                catch (Exception ex)
                {
                    payment.Status            = PaymentStatus.Failed.ToString();
                    paymentStepResult.Message = ex.Message;
                    AddNoteAndSaveChanges(orderGroup, payment.TransactionType, $"Error occurred {ex.Message}");
                    Logger.Error(ex.Message, ex);
                }

                return(paymentStepResult);
            }

            return(paymentStepResult);
        }
        /// <summary>
        /// Initialize a payment request from an <see cref="OrderGroup"/> instance. Adds order number, amount, timestamp, buyer information etc.
        /// </summary>
        /// <param name="payment">The <see cref="VerifonePaymentRequest"/> instance to initialize</param>
        /// <param name="orderGroup"><see cref="OrderGroup"/></param>
        public virtual void InitializePaymentRequest(VerifonePaymentRequest payment, IOrderGroup orderGroup)
        {
            IOrderAddress billingAddress  = FindBillingAddress(payment, orderGroup);
            IOrderAddress shipmentAddress = FindShippingAddress(payment, orderGroup);

            payment.OrderTimestamp        = orderGroup.Created.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
            payment.MerchantAgreementCode = GetMerchantAgreementCode(payment);
            payment.PaymentLocale         = GetPaymentLocale(ContentLanguage.PreferredCulture);
            payment.OrderNumber           = orderGroup.OrderLink.OrderGroupId.ToString(CultureInfo.InvariantCulture.NumberFormat);

            payment.OrderCurrencyCode = IsProduction(payment)
                ? Iso4217Lookup.LookupByCode(CurrentMarket.DefaultCurrency.CurrencyCode).Number.ToString()
                : "978";

            var totals = OrderGroupCalculator.GetOrderGroupTotals(orderGroup);

            payment.OrderGrossAmount = totals.Total.ToVerifoneAmountString();

            var netAmount = orderGroup.PricesIncludeTax ? totals.Total : totals.Total - totals.TaxTotal;

            payment.OrderNetAmount = netAmount.ToVerifoneAmountString();
            payment.OrderVatAmount = totals.TaxTotal.ToVerifoneAmountString();

            payment.BuyerFirstName       = billingAddress?.FirstName;
            payment.BuyerLastName        = billingAddress?.LastName;
            payment.OrderVatPercentage   = "0";
            payment.PaymentMethodCode    = "";
            payment.SavedPaymentMethodId = "";
            payment.RecurringPayment     = "0";
            payment.DeferredPayment      = "0";
            payment.SavePaymentMethod    = "0";
            payment.SkipConfirmationPage = "0";

            string phoneNumber = billingAddress?.DaytimePhoneNumber ?? billingAddress?.EveningPhoneNumber;

            if (string.IsNullOrWhiteSpace(phoneNumber) == false)
            {
                payment.BuyerPhoneNumber = phoneNumber;
            }

            payment.BuyerEmailAddress = billingAddress?.Email ?? orderGroup.Name ?? string.Empty;

            if (payment.BuyerEmailAddress.IndexOf('@') < 0)
            {
                payment.BuyerEmailAddress = null;
            }

            payment.DeliveryAddressLineOne = shipmentAddress?.Line1;

            if (shipmentAddress != null && string.IsNullOrWhiteSpace(shipmentAddress.Line2) == false)
            {
                payment.DeliveryAddressLineTwo = shipmentAddress.Line2;
            }

            payment.DeliveryAddressPostalCode  = shipmentAddress?.PostalCode;
            payment.DeliveryAddressCity        = shipmentAddress?.City;
            payment.DeliveryAddressCountryCode = "246";

            ApplyPaymentMethodConfiguration(payment);
        }
Beispiel #11
0
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            var message     = "message";
            var redirectUrl = CreateRedirectUrl(orderGroup);

            return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl));
        }
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            if (payment.TransactionType != TransactionType.Authorization.ToString() ||
                payment.Status != PaymentStatus.Pending.ToString())
            {
                return(PaymentProcessingResult.CreateSuccessfulResult(string.Empty));
            }

            var settings = ServiceLocator.Current.GetInstance <IVerifoneSettings>();

            if (settings == null)
            {
                throw new ArgumentException($"Configure a default instance for {nameof(IVerifoneSettings)}", nameof(settings));
            }

            var urlResolver = ServiceLocator.Current.GetInstance <UrlResolver>();
            var redirectUrl = urlResolver.GetUrl(settings.PaymentRedirectPage);

            if (!string.IsNullOrEmpty(settings.PaymentRedirectAction))
            {
                redirectUrl  = VirtualPathUtility.AppendTrailingSlash(redirectUrl);
                redirectUrl += settings.PaymentRedirectAction;
            }

            return(PaymentProcessingResult.CreateSuccessfulResult("Redirection is required", redirectUrl));
        }
        // previously used, get it back in
        protected virtual string CreateCustomRewardDescriptionText(
            IEnumerable <RewardDescription> rewardDescriptions
            , FulfillmentStatus fulfillmentStatus
            , MyPercentagePromotion promotion
            , IOrderGroup orderGroup)
        {
            /*var contentNames = GetContentNames(affectedItems); // local method*/
            string contentNames = String.Empty;
            IEnumerable <ILineItem> lineItems = orderGroup.GetAllLineItems();

            if (fulfillmentStatus == FulfillmentStatus.Fulfilled)
            {
                return(String.Format(CultureInfo.InvariantCulture, "{0}% discount has been given for the items '{1}'!"
                                     , promotion.PercentageDiscount, contentNames));
            }

            if (fulfillmentStatus == FulfillmentStatus.PartiallyFulfilled) // have 3 items in cart --> gets this
            {
                //var remainingQuantity = promotion.MinNumberOfItems - rewardDescriptions.Sum(x => x.or.Quantity);
                var remainingQuantity = promotion.MinNumberOfItems.RequiredQuantity - lineItems.Count();

                return(String.Format(CultureInfo.InvariantCulture, "Buy {0} more items and get a {1}% discount!"
                                     , remainingQuantity, promotion.PercentageDiscount));
            }

            return("The promotion is not applicable for the current order.");
        }
        public IOrderAddress ConvertToAddress(AddressModel addressModel, IOrderGroup orderGroup)
        {
            var address = orderGroup.CreateOrderAddress(_orderGroupFactory, addressModel.Name);

            MapToAddress(addressModel, address);
            return(address);
        }
Beispiel #15
0
        public override IPayment CreatePayment(decimal amount, IOrderGroup orderGroup)
        {
            var payment = orderGroup.CreateCardPayment(OrderGroupFactory);

            payment.CardType          = "Credit card";
            payment.PaymentMethodId   = PaymentMethodId;
            payment.PaymentMethodName = SystemKeyword;
            payment.Amount            = amount;
            if (UseSelectedCreditCard && !string.IsNullOrEmpty(SelectedCreditCardId))
            {
                CreditCard creditCard = _creditCardService.GetCreditCard(SelectedCreditCardId);
                payment.CreditCardNumber       = creditCard.CreditCardNumber;
                payment.CreditCardSecurityCode = creditCard.SecurityCode;
                payment.ExpirationMonth        = creditCard.ExpirationMonth ?? 1;
                payment.ExpirationYear         = creditCard.ExpirationYear ?? DateTime.Now.Year;
            }
            else
            {
                payment.CreditCardNumber       = CreditCardNumber;
                payment.CreditCardSecurityCode = CreditCardSecurityCode;
                payment.ExpirationMonth        = ExpirationMonth;
                payment.ExpirationYear         = ExpirationYear;
            }
            payment.Status          = PaymentStatus.Pending.ToString();
            payment.CustomerName    = CreditCardName;
            payment.TransactionType = TransactionType.Authorization.ToString();
            return(payment);
        }
        private bool ProcessFraudUpdate(IPayment payment, IOrderGroup orderGroup, ref string message)
        {
            if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_ACCEPTED.ToString())
            {
                payment.Status = PaymentStatus.Processed.ToString();

                OrderStatusManager.ReleaseHoldOnOrder((PurchaseOrder)orderGroup);

                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk accepted");

                return(true);
            }
            else if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_REJECTED.ToString())
            {
                payment.Status = PaymentStatus.Failed.ToString();

                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk rejected");

                return(false);
            }
            else if (payment.Properties[Common.Constants.FraudStatusPaymentField]?.ToString() == NotificationFraudStatus.FRAUD_RISK_STOPPED.ToString())
            {
                //TODO Fraud status stopped

                payment.Status = PaymentStatus.Failed.ToString();

                AddNoteAndSaveChanges(orderGroup, payment.TransactionType, "Klarna fraud risk stopped");

                return(false);
            }
            message = $"Can't process authorization. Unknown fraud notitication: {payment.Properties[Common.Constants.FraudStatusPaymentField]} or no fraud notifications received so far.";
            return(false);
        }
Beispiel #17
0
        private PaymentProcessingResult ProcessPaymentCapture(IOrderGroup orderGroup,
                                                              ICreditCardPayment creditCardPayment,
                                                              IOrderAddress billingAddress)
        {
            if (string.IsNullOrEmpty(creditCardPayment.ProviderPaymentId))
            {
                return(Charge(orderGroup, creditCardPayment, billingAddress));
            }
            try
            {
                var capture = _stripeChargeService.Capture(creditCardPayment.ProviderPaymentId, new StripeChargeCaptureOptions());
                if (!string.IsNullOrEmpty(capture.FailureCode))
                {
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(capture.Outcome.Reason)));
                }
                creditCardPayment.ProviderPaymentId     = capture.Id;
                creditCardPayment.ProviderTransactionID = capture.BalanceTransactionId;
                return(PaymentProcessingResult.CreateSuccessfulResult(""));
            }
            catch (StripeException e)
            {
                switch (e.StripeError.ErrorType)
                {
                case "card_error":
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(Translate(e.StripeError.Code)));

                default:
                    return(PaymentProcessingResult.CreateUnsuccessfulResult(e.StripeError.Message));
                }
            }
        }
 public ILineItem CreateLineItem(string code, IOrderGroup orderGroup)
 {
     return(new FakeLineItem()
     {
         Code = code
     });
 }
        private PayooOrder CreatePayooOrder(IOrderGroup orderGroup, IPayment payment)
        {
            var orderNumberID = _orderNumberGenerator.GenerateOrderNumber(orderGroup);

            var order = new PayooOrder();

            order.Session           = orderNumberID;
            order.BusinessUsername  = _paymentMethodConfiguration.BusinessUsername;
            order.OrderCashAmount   = (long)payment.Amount;
            order.OrderNo           = orderNumberID;
            order.ShippingDays      = 1;
            order.ShopBackUrl       = $"{HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)}{_cmsPaymentPropertyService.GetPayooPaymentProcessingPage()}";
            order.ShopDomain        = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
            order.ShopID            = long.Parse(_paymentMethodConfiguration.ShopID);
            order.ShopTitle         = _paymentMethodConfiguration.ShopTitle;
            order.StartShippingDate = DateTime.Now.ToString("dd/MM/yyyy");
            order.NotifyUrl         = string.Empty;
            order.ValidityTime      = DateTime.Now.AddDays(1).ToString("yyyyMMddHHmmss");

            var customer = CustomerContext.Current.GetContactById(orderGroup.CustomerId);

            order.CustomerName    = customer.FullName ?? $"{customer.FirstName} {customer.MiddleName} {customer.LastName}";
            order.CustomerPhone   = string.Empty;
            order.CustomerEmail   = customer.Email;
            order.CustomerAddress = customer.PreferredShippingAddress?.Line1;
            order.CustomerCity    = customer.PreferredShippingAddress?.City;

            order.OrderDescription = HttpUtility.UrlEncode(OrderDescriptionHTMLFactory.CreateOrderDescription(orderGroup));
            order.Xml = PaymentXMLFactory.GetPaymentXML(order);
            return(order);
        }
Beispiel #20
0
        private void AddNoteToOrder(IOrderGroup order, string noteDetails, OrderNoteTypes type, Guid customerId)
        {
            if (order == null)
            {
                throw new ArgumentNullException("purchaseOrder");
            }
            var orderNote = order.CreateOrderNote();

            if (!orderNote.OrderNoteId.HasValue)
            {
                var newOrderNoteId = -1;

                if (order.Notes.Count != 0)
                {
                    newOrderNoteId = Math.Min(order.Notes.ToList().Min(n => n.OrderNoteId.Value), 0) - 1;
                }

                orderNote.OrderNoteId = newOrderNoteId;
            }

            orderNote.CustomerId = customerId;
            orderNote.Type       = type.ToString();
            orderNote.Title      = noteDetails.Substring(0, Math.Min(noteDetails.Length, 24)) + "...";
            orderNote.Detail     = noteDetails;
            orderNote.Created    = DateTime.UtcNow;
        }
Beispiel #21
0
        public void CancelOrder(IOrderGroup orderGroup)
        {
            var market            = _marketService.GetMarket(orderGroup.MarketId);
            var swedbankPayClient = _swedbankPayClientFactory.Create(market);

            var orderId = orderGroup.Properties[Constants.SwedbankPayOrderIdField]?.ToString();

            if (!string.IsNullOrWhiteSpace(orderId))
            {
                try
                {
                    var cancelRequest = _requestFactory.GetCancelRequest();
                    var paymentOrder  = AsyncHelper.RunSync(() => swedbankPayClient.PaymentOrders.Get(new Uri(orderId)));

                    if (paymentOrder.Operations.Cancel != null)
                    {
                        var cancelResponse = AsyncHelper.RunSync(() => paymentOrder.Operations.Cancel(cancelRequest));
                        if (cancelResponse.Cancellation.Transaction.Type == TransactionType.Cancellation &&
                            cancelResponse.Cancellation.Transaction.State.Equals(State.Completed))
                        {
                            orderGroup.Properties[Constants.SwedbankPayOrderIdField] = null;
                            _orderRepository.Save(orderGroup);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message, ex);
                    throw;
                }
            }
        }
        public TransactionResponse Process(
            IOrderGroup orderGroup,
            TransactionRequest transactionRequest,
            TransactionData transactionData,
            decimal amount,
            ITokenizedPayment payment)
        {
            switch (transactionData.type)
            {
            case TransactionType.Authorization:
                return(ProcessAuthorizeRequest(orderGroup, transactionData, payment, amount));

            case TransactionType.Capture:
                return(ProcessPriorCaptureRequest(transactionRequest, transactionData, amount));

            case TransactionType.Sale:
                return(ProcessSaleRequest(orderGroup, transactionData, payment, amount));

            case TransactionType.Credit:
                return(ProcessCreditRequest(transactionRequest, transactionData, payment, amount));

            case TransactionType.Void:
                return(ProcessVoidRequest(transactionData, payment));

            case TransactionType.CaptureOnly:
                return(ProcessCaptureOnlyRequest(transactionRequest, transactionData, payment, amount));

            default:
                throw new NotImplementedException("Not implemented TransactionType: " + transactionData.type);
            }
        }
        private IDictionary <int, decimal> GetPriceExcludingTax(IOrderGroup orderGroup)
        {
            var currency = orderGroup.Currency;
            var market   = _marketService.GetMarket(orderGroup.MarketId);
            var itemPriceExcludingTaxMapping = new Dictionary <int, decimal>();

            foreach (var form in orderGroup.Forms)
            {
                foreach (var shipment in form.Shipments)
                {
                    var shippingAddress = shipment.ShippingAddress;
                    foreach (var lineItem in shipment.LineItems)
                    {
                        var priceExcludingTax = lineItem.GetExtendedPrice(currency).Amount;
                        if (orderGroup.PricesIncludeTax)
                        {
                            priceExcludingTax -= _lineItemCalculator.GetSalesTax(lineItem, market, currency, shippingAddress).Round().Amount;
                        }

                        itemPriceExcludingTaxMapping.Add(lineItem.LineItemId, priceExcludingTax);
                    }
                }
            }

            return(itemPriceExcludingTaxMapping);
        }
        protected override void DoCommand(IOrderGroup order, CommandParameters cp)
        {
            Mediachase.Ibn.Web.UI.CHelper.RequireDataBind();
            PurchaseOrder   purchaseOrder   = order as PurchaseOrder;
            WorkflowResults workflowResults = OrderGroupWorkflowManager.RunWorkflow(purchaseOrder, "SaveChangesWorkflow",
                                                                                    false,
                                                                                    false,
                                                                                    new Dictionary <string, object>
            {
                {
                    "PreventProcessPayment",
                    !string.IsNullOrEmpty(order.Properties["QuoteStatus"] as string) &&
                    (order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotation ||
                     order.Properties["QuoteStatus"].ToString() == Constants.Quote.RequestQuotationFinished)
                }
            });

            if (workflowResults.Status != WorkflowStatus.Completed)
            {
                string msg = "Unknow error";
                if (workflowResults.Exception != null)
                {
                    msg = workflowResults.Exception.Message;
                }
                ErrorManager.GenerateError(msg);
            }
            else
            {
                WritePurchaseOrderChangeNotes(purchaseOrder);
                SavePurchaseOrderChanges(purchaseOrder);
                PurchaseOrderManager.UpdatePromotionUsage(purchaseOrder, purchaseOrder);
                OrderHelper.ExitPurchaseOrderFromEditMode(purchaseOrder.OrderGroupId);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Processes the payment. Can be used for both positive and negative transactions.
        /// </summary>
        /// <param name="orderGroup">The order group.</param>
        /// <param name="payment">The payment.</param>
        /// <returns>The payment processing result.</returns>
        public PaymentProcessingResult ProcessPayment(IOrderGroup orderGroup, IPayment payment)
        {
            var creditCardPayment = (ICreditCardPayment)payment;

            return(creditCardPayment.CreditCardNumber.EndsWith("4")
                ? PaymentProcessingResult.CreateSuccessfulResult(string.Empty)
                : PaymentProcessingResult.CreateUnsuccessfulResult("Invalid credit card number."));
        }
Beispiel #26
0
 public static void SetOrderProcessing(this IOrderGroup orderGroup, bool value)
 {
     if (orderGroup == null)
     {
         return;
     }
     orderGroup.Properties[VippsConstants.VippsIsProcessingOrderField] = value;
 }
        protected override Money CalculateTotal(IOrderGroup orderGroup)
        {
            var result = GetSubTotal(orderGroup) - GetOrderDiscountTotal(orderGroup, orderGroup.Currency);
            result +=
                _shippingCalculator.GetShippingCost(orderGroup, orderGroup.Market, orderGroup.Currency) +
                _taxCalculator.GetTaxTotal(orderGroup, orderGroup.Market, orderGroup.Currency);

            return result;
        }
        private static IEnumerable <string> GetAffectedEntryCodes(IOrderGroup order)
        {
            if (HasOrderPromotionWithSavedAmount(order))
            {
                return(GetAllEntryCodesFromOrder(order));
            }

            return(GetAffectedEntryCodesFromEntryPromotions(order));
        }
Beispiel #29
0
        private PaymentStepResult HandlePaymentFailed(IOrderGroup orderGroup, IPayment payment, string title, string message)
        {
            payment.Status = PaymentStatus.Failed.ToString();

            Logger.Error(message);
            AddNoteAndSaveChanges(orderGroup, title, message);

            return(Fail(message));
        }
 private void UpdatePaymentPropertiesFromPayooResponse(IOrderGroup orderGroup, IPayment payment, CreateOrderResponse response)
 {
     payment.Properties[Constant.PayooOrderIdPropertyName]     = response.order.order_id;
     payment.Properties[Constant.PayooOrderNumberPropertyName] = response.order.order_no;
     payment.Properties[Constant.PayooAmountPropertyName]      = response.order.amount;
     payment.Properties[Constant.PayooExpiryDatePropertyName]  = response.order.expiry_date;
     payment.Properties[Constant.PayooPaymentCodePropertyName] = response.order.payment_code;
     _orderRepository.Save(orderGroup);
 }
        public IOrderAddress ConvertToAddress(IOrderGroup orderGroup, AddressModel model)
        {
            var address = _orderGroupFactory.CreateOrderAddress(orderGroup);

            address.Id = model.Name;
            MapToAddress(model, address);

            return(address);
        }
Beispiel #32
0
 public FakeCart(IOrderGroup orderGroup) : base(orderGroup)
 {
 }
Beispiel #33
0
 private ILineItem GetFirstLineItem(IOrderGroup cart, string code)
 {
     return cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);
 }
        private LineItem CreateLineItem(Entry entry, IOrderGroup g)
        {
            var priceService = ServiceLocator.Current.GetInstance<IPriceService>();

            LineItem item = new LineItem();
            if (entry.ParentEntry != null)
            {
                item.DisplayName = string.Format("{0}: {1}", entry.ParentEntry.Name, entry.Name);
                item.ParentCatalogEntryId = entry.ParentEntry.ID;
            }
            else
            {
                item.DisplayName = entry.Name;
            }
            item[Constants.Metadata.LineItem.ImageUrl] =
                "/globalassets/catalogs/photo/accessories/memory-card/sandisk-extreme-pro/824140.jpg?preset=listsmall";
            MarketId marketId = g.Market.MarketId.Value;
            IPriceValue value2 = priceService.GetDefaultPrice(marketId, FrameworkContext.Current.CurrentDateTime, new CatalogKey(entry), g.Currency);
            item.Code = entry.ID;

            item.Quantity = 1;

            if (value2 != null)
            {
                item.ListPrice = value2.UnitPrice.Amount;
                item.PlacedPrice = value2.UnitPrice.Amount;
                item.ExtendedPrice = value2.UnitPrice.Amount;
            }
            else
            {
                item.ListPrice = item.PlacedPrice;
            }

            return item;
        }