コード例 #1
0
ファイル: SiteUser.cs プロジェクト: wterpstra/Quicksilver
        /// <summary>
        /// Returns a new instance of an ApplicationUser based on a previously made purchase order.
        /// </summary>
        /// <param name="purchaseOrder"></param>
        public SiteUser(IPurchaseOrder purchaseOrder)
        {
            Addresses = new List <CustomerAddress>();

            var billingAddress = purchaseOrder.GetFirstForm().Payments.First().BillingAddress;

            if (billingAddress != null)
            {
                Email     = billingAddress.Email;
                UserName  = billingAddress.Email;
                FirstName = billingAddress.FirstName;
                LastName  = billingAddress.LastName;

                var addressesToAdd = new HashSet <IOrderAddress>(purchaseOrder.GetFirstForm().Shipments.Select(x => x.ShippingAddress));

                foreach (var shippingAddress in addressesToAdd)
                {
                    if (shippingAddress.Id != billingAddress.Id)
                    {
                        Addresses.Add(CreateCustomerAddress(shippingAddress, CustomerAddressTypeEnum.Shipping));
                    }
                }

                Addresses.Add(CreateCustomerAddress(billingAddress, CustomerAddressTypeEnum.Billing));
            }
        }
コード例 #2
0
        /// <summary>
        /// Returns a new instance of an ApplicationUser based on a previously made purchase order.
        /// </summary>
        /// <param name="purchaseOrder"></param>
        public ApplicationUser(IPurchaseOrder purchaseOrder)
        {
            Addresses = new List<CustomerAddress>();

            var billingAddress = purchaseOrder.GetFirstForm().Payments.First().BillingAddress;

            if (billingAddress != null)
            {
                Email = billingAddress.Email;
                UserName = billingAddress.Email;
                FirstName = billingAddress.FirstName;
                LastName = billingAddress.LastName;
            }

            var addressesToAdd = new HashSet<IOrderAddress>(purchaseOrder.GetFirstForm().Shipments.Select(x => x.ShippingAddress));

            foreach (var shippingAddress in addressesToAdd)
            {
                if (shippingAddress.Id != billingAddress.Id)
                {
                    Addresses.Add(CreateCustomerAddress(shippingAddress, CustomerAddressTypeEnum.Shipping));
                }
            }

            Addresses.Add(CreateCustomerAddress(billingAddress, CustomerAddressTypeEnum.Billing));
        }
コード例 #3
0
        private bool Filter(OrderFilter filter, IPurchaseOrder order)
        {
            var result = true;

            if (result && !string.IsNullOrEmpty(filter.OrderGroupId))
            {
                result = order.OrderLink.OrderGroupId.ToString().Contains(filter.OrderGroupId);
            }

            if (result && !string.IsNullOrEmpty(filter.PurchaseOrderNumber))
            {
                result = order.OrderNumber.Contains(filter.PurchaseOrderNumber);
            }

            if (result && filter.DateFrom.HasValue)
            {
                result = order.Created.Date >= filter.DateFrom.Value.Date;
            }

            if (result && filter.DateTo.HasValue)
            {
                result = order.Created.Date <= filter.DateTo.Value.Date;
            }

            if (result && !(filter.OrderStatusId == 0))
            {
                result = order.OrderStatus.Id == filter.OrderStatusId;
            }

            if (result && filter.PriceFrom > 0)
            {
                result = order.GetTotal() >= filter.PriceFrom;
            }

            if (result && filter.PriceTo > 0)
            {
                result = order.GetTotal() <= filter.PriceTo;
            }

            if (result && !string.IsNullOrEmpty(filter.AddressId))
            {
                result = order.GetFirstForm().Shipments.Where(x => x.ShippingAddress.Id == filter.AddressId).Count() > 0;
            }

            if (result && !string.IsNullOrEmpty(filter.PaymentMethodId))
            {
                result = order.GetFirstForm().Payments.Where(x => x.PaymentMethodId.ToString() == filter.PaymentMethodId).Count() > 0;
            }

            if (result && !string.IsNullOrEmpty(filter.Keyword))
            {
                result = order.GetAllLineItems().Where(x => x.DisplayName.Contains(filter.Keyword) || x.Code.Contains(filter.Keyword)).Count() > 0;
            }

            return(result);
        }
        protected OrderConfirmationViewModel <T> CreateViewModel(T currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <T> {
                    CurrentPage = currentPage
                });
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupTotalsCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <T>
            {
                Currency                = order.Currency,
                CurrentPage             = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = _customerContext.CurrentContactId,
                Payments                = order.GetFirstForm().Payments,
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total
            };

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
コード例 #5
0
        private OrderConfirmationViewModel <OrderConfirmationMailPage> CreateViewModel(OrderConfirmationMailPage currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <OrderConfirmationMailPage>(currentPage));
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <OrderConfirmationMailPage>(currentPage)
            {
                Currency                = order.Currency,
                CurrentContent          = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = _customerService.CurrentContactId,
                Payments                = order.GetFirstForm().Payments.Where(c => c.TransactionType == TransactionType.Authorization.ToString() || c.TransactionType == TransactionType.Sale.ToString()),
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total,
                SubTotal                = order.GetSubTotal()
            };

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
コード例 #6
0
ファイル: ReleaseRemainingEvent.cs プロジェクト: Geta/Klarna
        public void Handle(ReleaseRemainingEvent ev)
        {
            _order     = ev.PurchaseOrder;
            _orderForm = _order.GetFirstForm();
            var market = _marketService.GetMarket(_order.MarketId);

            var previousPayment =
                _orderForm.Payments.FirstOrDefault(x => x.IsKlarnaPayment());

            if (previousPayment == null)
            {
                return;
            }

            var payment = _order.CreatePayment(_orderGroupFactory);

            payment.PaymentType       = previousPayment.PaymentType;
            payment.PaymentMethodId   = previousPayment.PaymentMethodId;
            payment.PaymentMethodName = previousPayment.PaymentMethodName;

            var remainingAmount = _orderForm
                                  .Shipments
                                  .Where(s => s.OrderShipmentStatus != OrderShipmentStatus.Shipped)
                                  .Sum(x => x.GetShippingItemsTotal(_order.Currency).Amount + x.GetShippingCost(market, _order.Currency).Amount);

            payment.Amount          = remainingAmount;
            payment.Status          = PaymentStatus.Pending.ToString();
            payment.TransactionType = KlarnaAdditionalTransactionType.ReleaseRemainingAuthorization.ToString();

            _order.AddPayment(payment);

            _paymentProcessor.ProcessPayment(_order, payment, _order.GetFirstShipment());
        }
コード例 #7
0
        public CompletionResult Complete(IPurchaseOrder purchaseOrder)
        {
            if (purchaseOrder == null)
            {
                throw new ArgumentNullException(nameof(purchaseOrder));
            }
            var orderForm = purchaseOrder.GetFirstForm();
            var payment   = orderForm?.Payments.FirstOrDefault(x => x.PaymentMethodName.Equals(Constants.KlarnaPaymentSystemKeyword));

            if (payment == null)
            {
                return(CompletionResult.Empty);
            }

            SetOrderStatus(purchaseOrder, payment);

            var url = payment.Properties[Constants.KlarnaConfirmationUrlPaymentField]?.ToString();

            if (string.IsNullOrEmpty(url))
            {
                return(CompletionResult.Empty);
            }

            return(CompletionResult.WithRedirectUrl(url));
        }
コード例 #8
0
        public void Handle(OrderCancelledEvent ev)
        {
            _order     = ev.PurchaseOrder;
            _orderForm = _order.GetFirstForm();

            if (AlreadyVoided())
            {
                return;
            }

            var previousPayment = _orderForm.Payments.FirstOrDefault(x => x.IsKlarnaPayment());

            if (previousPayment == null)
            {
                return;
            }

            var voidPayment = _order.CreatePayment(_orderGroupFactory);

            voidPayment.PaymentType       = previousPayment.PaymentType;
            voidPayment.PaymentMethodId   = previousPayment.PaymentMethodId;
            voidPayment.PaymentMethodName = previousPayment.PaymentMethodName;
            voidPayment.Amount            = previousPayment.Amount;
            voidPayment.Status            = PaymentStatus.Pending.ToString();
            voidPayment.TransactionType   = TransactionType.Void.ToString();

            _order.AddPayment(voidPayment);

            _paymentProcessor.ProcessPayment(_order, voidPayment, _order.GetFirstShipment());
        }
コード例 #9
0
        public async Task <ActionResult> Index(OrderConfirmationPage currentPage, string notificationMessage, string orderNumber, string trackingNumber)
        {
            int orderId;

            trackingNumber = string.IsNullOrEmpty(trackingNumber) ? orderNumber : trackingNumber;

            IPurchaseOrder order = null;

            if (PageEditing.PageIsInEditMode)
            {
                order = ConfirmationService.CreateFakePurchaseOrder();
            }
            else if (int.TryParse(orderNumber, out orderId))
            {
                order = ConfirmationService.GetOrder(orderId);

                if (order != null)
                {
                    await _recommendationService.TrackOrderAsync(HttpContext, order);
                }
            }
            else if (!string.IsNullOrEmpty(trackingNumber))
            {
                order = ConfirmationService.GetByTrackingNumber(trackingNumber);

                if (order != null)
                {
                    await _recommendationService.TrackOrderAsync(HttpContext, order);
                }
            }

            if (order != null && order.CustomerId == CustomerContext.CurrentContactId)
            {
                var viewModel = CreateViewModel(currentPage, order);
                viewModel.NotificationMessage = notificationMessage;

                var paymentMethod = PaymentManager
                                    .GetPaymentMethodBySystemName(Constants.KlarnaCheckoutSystemKeyword,
                                                                  ContentLanguage.PreferredCulture.Name)
                                    .PaymentMethod.FirstOrDefault();

                if (paymentMethod != null &&
                    order.GetFirstForm().Payments.Any(x => x.PaymentMethodId == paymentMethod.PaymentMethodId &&
                                                      !string.IsNullOrEmpty(order.Properties[Klarna.Common.Constants.KlarnaOrderIdField]?.ToString())))
                {
                    var market      = _marketService.GetMarket(order.MarketId);
                    var klarnaOrder = await _klarnaCheckoutService.GetOrder(
                        order.Properties[Klarna.Common.Constants.KlarnaOrderIdField].ToString(), market).ConfigureAwait(false);

                    viewModel.KlarnaCheckoutHtmlSnippet = klarnaOrder.HtmlSnippet;
                    viewModel.IsKlarnaCheckout          = true;
                }

                return(View(viewModel));
            }

            return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
        }
コード例 #10
0
        public virtual OmniumOrder MapOrder(IPurchaseOrder purchaseOrder)
        {
            // use default Omnium order mapper
            //var mappedOrder = OrderMappings.ConvertToOmniumOrder((OrderGroup)purchaseOrder);

            var orderForm = purchaseOrder.GetFirstForm();

            return(MapOrder(purchaseOrder, orderForm, orderForm.Shipments.ToArray()));
        }
コード例 #11
0
        private static bool IsReleaseRemaining(IPurchaseOrder orderBeforeSave, IPurchaseOrder orderAfterSave)
        {
            var form = orderAfterSave.GetFirstForm();

            return(orderBeforeSave.OrderStatus == OrderStatus.PartiallyShipped &&
                   orderAfterSave.OrderStatus == OrderStatus.Completed &&
                   form.Shipments.Any(s => s.OrderShipmentStatus == OrderShipmentStatus.Cancelled) &&
                   form.Payments.All(p => p.TransactionType != KlarnaAdditionalTransactionType.ReleaseRemainingAuthorization.ToString()));
        }
コード例 #12
0
        protected OrderConfirmationViewModel <T> CreateViewModel(T currentPage, IPurchaseOrder order)
        {
            if (order == null)
            {
                return(new OrderConfirmationViewModel <T> {
                    CurrentPage = currentPage
                });
            }

            var totals = _orderGroupTotalsCalculator.GetTotals(order);

            return(new OrderConfirmationViewModel <T>
            {
                Currency = order.Currency,
                CurrentPage = currentPage,
                HasOrder = true,
                OrderId = order.OrderNumber,
                Created = order.Created,
                BillingAddress = _addressBookService.ConvertToModel(order.GetFirstForm().Payments.First().BillingAddress),
                ContactId = CustomerContext.CurrentContactId,
                Payments = order.GetFirstForm().Payments.Where(c => c.TransactionType == TransactionType.Authorization.ToString() || c.TransactionType == TransactionType.Sale.ToString()),
                OrderGroupId = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(order.Currency),
                ShippingSubTotal = order.GetShippingSubTotal(),
                ShippingDiscountTotal = order.GetShippingDiscountTotal(),
                ShippingTotal = totals.ShippingTotal,
                HandlingTotal = totals.HandlingTotal,
                TaxTotal = totals.TaxTotal,
                CartTotal = totals.Total,
                Shipments = order.Forms.SelectMany(x => x.Shipments).Select(x => new ShipmentConfirmationViewModel
                {
                    Address = _addressBookService.ConvertToModel(x.ShippingAddress),
                    LineItems = x.LineItems,
                    ShipmentCost = x.GetShippingCost(order.Market, order.Currency),
                    DiscountPrice = x.GetShipmentDiscountPrice(order.Currency),
                    ShippingItemsTotal = x.GetShippingItemsTotal(order.Currency),
                    ShippingMethodName = x.ShippingMethodName,
                })
            });
        }
コード例 #13
0
        private bool ShouldProcessVoid(IPurchaseOrder order)
        {
            var orderForm = order.GetFirstForm();

            if (orderForm == null)
            {
                return(false);
            }
            return((!orderForm.Payments.Any(x =>
                                            x.PaymentMethodName.Equals(NetaxeptConstants.NetaxeptSystemKeyword, StringComparison.InvariantCultureIgnoreCase) &&
                                            x.TransactionType == TransactionType.Void.ToString())) &&
                   order.OrderStatus.Equals(OrderStatus.Cancelled));
        }
コード例 #14
0
        public void Complete(IPurchaseOrder purchaseOrder)
        {
            if (purchaseOrder == null)
            {
                throw new ArgumentNullException(nameof(purchaseOrder));
            }
            var orderForm = purchaseOrder.GetFirstForm();
            var payment   = orderForm?.Payments.FirstOrDefault(x =>
                                                               x.PaymentMethodName.Equals(Constants.SwedbankPayCheckoutSystemKeyword));

            if (payment == null)
            {
                return;
            }
        }
コード例 #15
0
        public ActionResult Index(OrderConfirmationPage currentPage, string notificationMessage, int?orderNumber, string trackingNumber)
        {
            IPurchaseOrder order = null;

            if (PageEditing.PageIsInEditMode)
            {
                order = _confirmationService.CreateFakePurchaseOrder();
            }
            else if (orderNumber.HasValue)
            {
                order = _confirmationService.GetOrder(orderNumber.Value);
            }
            else if (!string.IsNullOrEmpty(trackingNumber))
            {
                order = _confirmationService.GetByTrackingNumber(trackingNumber);
            }

            if (order != null /* && order.CustomerId == _customerContext.CurrentContactId*/)
            {
                var viewModel = CreateViewModel(currentPage, order);
                viewModel.NotificationMessage = notificationMessage;

                var paymentMethod = PaymentManager
                                    .GetPaymentMethodBySystemName(Constants.KlarnaCheckoutSystemKeyword,
                                                                  ContentLanguage.PreferredCulture.Name)
                                    .PaymentMethod.FirstOrDefault();

                if (paymentMethod != null &&
                    order.GetFirstForm().Payments.Any(x => x.PaymentMethodId == paymentMethod.PaymentMethodId &&
                                                      !string.IsNullOrEmpty(order.Properties[Klarna.Common.Constants.KlarnaOrderIdField]?.ToString())))
                {
                    var klarnaOrder =
                        _klarnaCheckoutService.GetOrder(
                            order.Properties[Klarna.Common.Constants.KlarnaOrderIdField].ToString(), order.Market);
                    viewModel.KlarnaCheckoutHtmlSnippet = klarnaOrder.HtmlSnippet;
                    viewModel.IsKlarnaCheckout          = true;
                }

                return(View(viewModel));
            }

            return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
        }
コード例 #16
0
        public void Handle(OrderCancelledEvent ev)
        {
            _order     = ev.PurchaseOrder;
            _orderForm = _order.GetFirstForm();

            if (AlreadyVoided())
            {
                return;
            }

            var previousPayment = _orderForm.Payments.FirstOrDefault(x => x.IsVippsPayment() && x.Status == PaymentStatus.Processed.ToString());

            if (previousPayment == null)
            {
                return;
            }

            PaymentHelper.CancelPayment(_order, previousPayment);
        }
コード例 #17
0
        public void Complete(IPurchaseOrder purchaseOrder)
        {
            if (purchaseOrder == null)
            {
                throw new ArgumentNullException(nameof(purchaseOrder));
            }
            var orderForm = purchaseOrder.GetFirstForm();
            var payment   = orderForm?.Payments.FirstOrDefault(x => x.PaymentMethodName.Equals(Constants.KlarnaCheckoutSystemKeyword));

            if (payment == null)
            {
                return;
            }

            if (payment.HasFraudStatus(FraudStatus.PENDING))
            {
                OrderStatusManager.HoldOrder((PurchaseOrder)purchaseOrder);
                _orderRepository.Save(purchaseOrder);
            }
        }
コード例 #18
0
        protected OrderConfirmationViewModel <T> CreateViewModel(T currentPage, IPurchaseOrder order)
        {
            var hasOrder = order != null;

            if (!hasOrder)
            {
                return(new OrderConfirmationViewModel <T>(currentPage));
            }

            var lineItems = order.GetFirstForm().Shipments.SelectMany(x => x.LineItems);
            var totals    = _orderGroupCalculator.GetOrderGroupTotals(order);

            var viewModel = new OrderConfirmationViewModel <T>(currentPage)
            {
                Currency                = order.Currency,
                CurrentContent          = currentPage,
                HasOrder                = hasOrder,
                OrderId                 = order.OrderNumber,
                Created                 = order.Created,
                Items                   = lineItems,
                BillingAddress          = new AddressModel(),
                ShippingAddresses       = new List <AddressModel>(),
                ContactId               = PrincipalInfo.CurrentPrincipal.GetContactId(),
                Payments                = order.GetFirstForm().Payments.Where(c => c.TransactionType == TransactionType.Authorization.ToString() || c.TransactionType == TransactionType.Sale.ToString()),
                OrderGroupId            = order.OrderLink.OrderGroupId,
                OrderLevelDiscountTotal = order.GetOrderDiscountTotal(),
                ShippingSubTotal        = order.GetShippingSubTotal(),
                ShippingDiscountTotal   = order.GetShippingDiscountTotal(),
                ShippingTotal           = totals.ShippingTotal,
                HandlingTotal           = totals.HandlingTotal,
                TaxTotal                = totals.TaxTotal,
                CartTotal               = totals.Total,
                SubTotal                = order.GetSubTotal(),
                FileUrls                = new List <Dictionary <string, string> >(),
                Keys = new List <Dictionary <string, string> >()
            };

            foreach (var lineItem in lineItems)
            {
                var entry   = lineItem.GetEntryContent <EntryContentBase>();
                var variant = entry as GenericVariant;
                if (entry == null || variant == null || variant.VirtualProductMode == null || variant.VirtualProductMode.Equals("None"))
                {
                    continue;
                }

                if (variant.VirtualProductMode.Equals("File"))
                {
                    var url = "";// _urlResolver.GetUrl(((FileVariant)lineItem.GetEntryContentBase()).File);
                    viewModel.FileUrls.Add(new Dictionary <string, string>()
                    {
                        { lineItem.DisplayName, url }
                    });
                }
                else if (variant.VirtualProductMode.Equals("Key"))
                {
                    var key = Guid.NewGuid().ToString();
                    viewModel.Keys.Add(new Dictionary <string, string>()
                    {
                        { lineItem.DisplayName, key }
                    });
                }
                else if (variant.VirtualProductMode.Equals("ElevatedRole"))
                {
                    viewModel.ElevatedRole = variant.VirtualProductRole;
                    var currentContact = _customerService.GetCurrentContact();
                    if (currentContact != null)
                    {
                        currentContact.ElevatedRole = ElevatedRoles.Reader.ToString();
                        currentContact.SaveChanges();
                    }
                }
            }

            var billingAddress = order.GetFirstForm().Payments.First().BillingAddress;

            // Map the billing address using the billing id of the order form.
            _addressBookService.MapToModel(billingAddress, viewModel.BillingAddress);

            // Map the remaining addresses as shipping addresses.
            foreach (var orderAddress in order.Forms.SelectMany(x => x.Shipments).Select(s => s.ShippingAddress))
            {
                var shippingAddress = new AddressModel();
                _addressBookService.MapToModel(orderAddress, shippingAddress);
                viewModel.ShippingAddresses.Add(shippingAddress);
            }

            return(viewModel);
        }
コード例 #19
0
        public virtual IPurchaseOrder CreatePurchaseOrder(
            SaleViewModel kachingSale)
        {
            IMarket market = _marketService.GetMarket(kachingSale.Source.MarketId);

            if (market == null || !market.IsEnabled)
            {
                throw new InvalidOperationException(
                          $"The MarketId ('{kachingSale.Source.MarketId}') is not recognized in Episerver Commerce.");
            }

            CustomerContact customerContact = null;

            if (kachingSale.Summary.Customer?.Identifier != null)
            {
                customerContact = CustomerContext.Current.GetContactById(
                    Guid.Parse(kachingSale.Summary.Customer.Identifier));
                if (customerContact?.PrimaryKeyId == null)
                {
                    throw new InvalidOperationException(
                              $"The customer ('{kachingSale.Summary.Customer.Identifier}') is not recognized in Episerver Commerce.");
                }
            }

            IPurchaseOrder purchaseOrder = _purchaseOrderProvider.Create(
                customerContact?.PrimaryKeyId.Value ?? Guid.Empty,
                "Default");

            if (purchaseOrder == null)
            {
                throw new InvalidOperationException(
                          "The purchase order could not be initialized.");
            }

            PopulateMetaFields(purchaseOrder, market, kachingSale);
            SetCashier(purchaseOrder, kachingSale);

            IOrderForm orderForm = purchaseOrder.GetFirstForm();

            PopulateMetaFields(purchaseOrder, orderForm, market, kachingSale);
            SetCashier(orderForm, kachingSale);

            orderForm.Shipments.Clear();

            decimal orderTotal = 0;

            foreach (var groupedLineItems in kachingSale.Summary
                     .LineItems
                     .GroupBy(li => li.EcomId))
            {
                var shippingLineItem = groupedLineItems.FirstOrDefault(li => li.Behavior?.Shipping != null);
                var kachingShipping  = shippingLineItem?.Behavior?.Shipping;

                decimal shipmentTotal    = 0;
                decimal shippingFeeTotal = shippingLineItem?.Total ?? 0;

                IShipment shipment = CreateShipment(
                    purchaseOrder,
                    orderForm,
                    customerContact,
                    kachingShipping,
                    kachingSale,
                    shippingLineItem);
                orderForm.Shipments.Add(shipment);

                PopulateMetaFields(shipment, market, kachingShipping, kachingSale);
                SetCashier(shipment, kachingSale);

                foreach (var kachingLineItem in groupedLineItems)
                {
                    // Skip special behavior line items. These are:
                    // shipping - handled above
                    // giftcard or voucher purchase
                    // giftcard or voucher use (can be a line item if they are taxed at point of sale)
                    // expenses
                    // customer account deposit
                    // container deposit
                    //
                    // We could consider including container deposit behavior
                    // but for now we just skip that along with the rest.
                    if (kachingLineItem.Behavior != null)
                    {
                        continue;
                    }

                    ILineItem lineItem = CreateLineItem(purchaseOrder, shipment, kachingSale, kachingLineItem);
                    shipment.LineItems.Add(lineItem);

                    PopulateMetaFields(lineItem, market, kachingSale, kachingLineItem);
                    SetCashier(lineItem, kachingSale);

                    shipmentTotal += kachingLineItem.Total;
                }

                // Populate all shipment amount fields, even those that need casting to reach.
                if (shipment is IShipmentCalculatedAmount calculatedAmount)
                {
                    calculatedAmount.IsShippingCostUpToDate = true;
                    calculatedAmount.IsShippingTaxUpToDate  = true;
                    calculatedAmount.ShippingCost           = shippingLineItem?.Total ?? 0;
                    calculatedAmount.ShippingTax            = shippingLineItem?.TotalTax ?? 0;
                }

                if (shipment is Shipment shipment1)
                {
                    shipment1.ShippingSubTotal = shippingLineItem?.Total ?? 0;
                    shipment1.SubTotal         = shipmentTotal;
                }

                shipmentTotal += shippingFeeTotal;
                orderTotal    += shipmentTotal;
            }

            IPayment payment = CreatePayment(purchaseOrder, customerContact, kachingSale, orderTotal);

            PopulateMetaFields(payment, market, kachingSale);
            SetCashier(payment, kachingSale);

            orderForm.Payments.Add(payment);

            return(purchaseOrder);
        }
コード例 #20
0
        public virtual async Task <bool> SendConfirmation(CheckoutViewModel viewModel, IPurchaseOrder purchaseOrder)
        {
            var startpage = _contentRepository.Get <CommerceHomePage>(ContentReference.StartPage);
            var sendOrderConfirmationMail = startpage.SendOrderConfirmationMail;

            if (sendOrderConfirmationMail)
            {
                var queryCollection = new NameValueCollection
                {
                    { "contactId", _customerContext.CurrentContactId.ToString() },
                    { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
                };

                try
                {
                    await _mailService.SendAsync(startpage.OrderConfirmationMail, queryCollection, purchaseOrder.GetFirstForm().Payments.FirstOrDefault().BillingAddress.Email, startpage.Language.Name);
                }
                catch (Exception e)
                {
                    _log.Warning(string.Format("Unable to send purchase receipt to '{0}'.", purchaseOrder.GetFirstForm().Payments.FirstOrDefault().BillingAddress.Email), e);
                    return(false);
                }
            }

            return(true);
        }
コード例 #21
0
        public virtual async Task <bool> SendConfirmation(CheckoutViewModel viewModel, IPurchaseOrder purchaseOrder)
        {
            var referenceSettings         = _settingsService.GetSiteSettings <ReferencePageSettings>();
            var sendOrderConfirmationMail = referenceSettings?.SendOrderConfirmationMail ?? false;

            if (sendOrderConfirmationMail)
            {
                var queryCollection = new NameValueCollection
                {
                    { "contactId", _customerContext.CurrentContactId.ToString() },
                    { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
                };

                try
                {
                    await _mailService.SendAsync(referenceSettings.OrderConfirmationMail, queryCollection, purchaseOrder.GetFirstForm().Payments.FirstOrDefault().BillingAddress.Email, CultureInfo.CurrentCulture.Name);
                }
                catch (Exception e)
                {
                    _log.Warning(string.Format("Unable to send purchase receipt to '{0}'.", purchaseOrder.GetFirstForm().Payments.FirstOrDefault().BillingAddress.Email), e);
                    return(false);
                }
            }

            return(true);
        }