/// <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));
        }
Exemple #2
0
        /// <summary>
        /// Submits a newly created PurchaseOrder containing a list of Items to the database. Returns the newly created OrderNumber
        /// </summary>
        /// <param name="tmpPurchaseOrder"></param>
        /// <returns></returns>
        public static int SubmitPurchaseOrder(IPurchaseOrder tmpPurchaseOrder)
        {
            string sql = "spSubmitPurchaseOrder";
            List <parmStructure> myparms = new List <parmStructure>();

            myparms.Add(new parmStructure("@OrderNumber", 0, ParameterDirection.Output, SqlDbType.Int));
            myparms.Add(new parmStructure("@OrderDate", tmpPurchaseOrder.OrderDate, ParameterDirection.Input, SqlDbType.DateTime));
            myparms.Add(new parmStructure("@Status", tmpPurchaseOrder.Status, ParameterDirection.Input, SqlDbType.NVarChar, 50));
            myparms.Add(new parmStructure("@Subtotal", tmpPurchaseOrder.Subtotal, ParameterDirection.Input, SqlDbType.Money));
            myparms.Add(new parmStructure("@Taxes", tmpPurchaseOrder.Taxes, ParameterDirection.Input, SqlDbType.Money));
            myparms.Add(new parmStructure("@Total", tmpPurchaseOrder.Total, ParameterDirection.Input, SqlDbType.Money));
            myparms.Add(new parmStructure("@EmployeeId", tmpPurchaseOrder.EmployeeId, ParameterDirection.Input, SqlDbType.Int));

            DataTable  workTable        = new DataTable("items");
            DataColumn Name             = workTable.Columns.Add("Name", Type.GetType("System.String"));
            DataColumn Description      = workTable.Columns.Add("Description", Type.GetType("System.String"));
            DataColumn Price            = workTable.Columns.Add("Price", Type.GetType("System.Double"));
            DataColumn PurchaseLocation = workTable.Columns.Add("PurchaseLocation", Type.GetType("System.String"));
            DataColumn Quantity         = workTable.Columns.Add("Quantity", Type.GetType("System.Int16"));
            DataColumn Justification    = workTable.Columns.Add("Justification", Type.GetType("System.String"));
            DataColumn Status           = workTable.Columns.Add("Status", Type.GetType("System.String"));
            DataColumn Subtotal         = workTable.Columns.Add("Subtotal", Type.GetType("System.Double"));

            for (int i = 0; i < tmpPurchaseOrder.PurchaseOrderItemList.Count; i++)
            {
                workTable.Rows.Add(new Object[] {
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Name,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Description,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Price,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].PurchaseLocation,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Quantity,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Justification,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Status,
                    tmpPurchaseOrder.PurchaseOrderItemList[i].Subtotal
                });
            }

            myparms.Add(new parmStructure("@OrderDetail", workTable, ParameterDirection.Input, SqlDbType.Structured));

            DataAccess.SendData(sql, myparms);
            return(Convert.ToInt32(myparms[0].parmValue));
        }
Exemple #3
0
        public async Task <ActionResult> Index(OrderConfirmationPage currentPage, string notificationMessage, int?orderNumber, string payeeReference)
        {
            IPurchaseOrder order = null;

            if (PageEditing.PageIsInEditMode)
            {
                order = ConfirmationService.CreateFakePurchaseOrder();
            }
            else if (orderNumber.HasValue)
            {
                order = ConfirmationService.GetOrder(orderNumber.Value);
                if (order != null)
                {
                    await _recommendationService.TrackOrderAsync(HttpContext, order);
                }
            }

            if (order == null && orderNumber.HasValue)
            {
                var cart = _orderRepository.Load <ICart>(orderNumber.Value);
                if (cart != null)
                {
                    var swedbankPayOrderId = cart.Properties[Constants.SwedbankPayOrderIdField];
                    order = _checkoutService.GetOrCreatePurchaseOrder(orderNumber.Value, swedbankPayOrderId.ToString());
                }
                else
                {
                    order = _swedbankPayCheckoutService.GetByPayeeReference(payeeReference);
                }
            }

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

                return(View(viewModel));
            }


            return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
        }
Exemple #4
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);
            }
        }
        public MaterialAmountModel GetOrderItemMaterialForSingleUnit(IPurchaseOrder order, IOrderItem item)
        {
            var tags = m_virtualProductRepository.GetVirtualProductsByOrderItem(order, item);

            var materialTags = tags.Where(t => t.Materials.Any()).ToList();

            if (materialTags.Count != 1)
            {
                throw new InvalidOperationException($"Prodejní položka '{item.PlacedName}' je spojena s {materialTags.Count} materiálů, požadovaný počet je 1");
            }

            var material = materialTags.Single().Materials.ToList();

            if (material.Count != 1)
            {
                throw new InvalidOperationException($"Prodejní položka '{item.PlacedName}' je tagem '{materialTags[0].Name}' spojena s {material.Count} materiálů, požadovaný počet je 1");
            }

            return(new MaterialAmountModel(material[0].ComponentId, new Amount(material[0].Amount, material[0].Unit)));
        }
Exemple #6
0
 /// <summary>
 /// Update display name with current language
 /// </summary>
 /// <param name="po">The purchase order</param>
 public static void UpdateDisplayNameWithCurrentLanguage(this IPurchaseOrder po)
 {
     if (po != null)
     {
         if (po.Forms != null && po.Forms.Count > 0)
         {
             foreach (IOrderForm orderForm in po.Forms)
             {
                 var lineItems = orderForm.GetAllLineItems();
                 if (lineItems != null && lineItems.Any())
                 {
                     foreach (var item in lineItems)
                     {
                         item.DisplayName = item.GetDisplayNameOfCurrentLanguage(100);
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// Posts the capture request to Epay API.
        /// http://epay.bambora.com/en/payment-web-service#553
        /// https://ssl.ditonlinebetalingssystem.dk/remote/payment.asmx
        /// Returns true if payment is captured
        /// </summary>
        /// <param name="payment">The payment.</param>
        /// <param name="purchaseOrder">The purchase order.</param>
        public bool PostCaptureRequest(IPayment payment, IPurchaseOrder purchaseOrder)
        {
            // Check for subscription and then use auth and capture with that instead
            if (!(string.IsNullOrEmpty(payment.AuthorizationCode)))
            {
                return(PostSubscriptionAuthorize(payment, purchaseOrder));
            }

            // initital
            var currencyCode = purchaseOrder.Currency;

            // parameters
            int amount = 0;

            int.TryParse(Utilities.GetAmount(new Currency(currencyCode), payment.Amount), out amount);
            int  merchantnNumber = int.Parse(EpayConfiguration.Merchant);
            long transactionId   = long.Parse(payment.TransactionID);

            // response parameters
            int pbsresponse = -1;
            int epayrespone = -1;

            // build body
            epayPaymentService.PaymentSoapClient client = new epayPaymentService.PaymentSoapClient("PaymentSoap");
            bool isCaptured = client.capture(
                merchantnumber: merchantnNumber,
                transactionid: transactionId,
                amount: amount,
                group: "",
                invoice: "",
                pwd: "",
                orderid: "",
                pbsResponse: ref pbsresponse,
                epayresponse: ref epayrespone
                );

            //todo: some bug issue handling


            return(isCaptured);
        }
Exemple #8
0
        public virtual bool SendConfirmation(CheckoutViewModel viewModel, IPurchaseOrder purchaseOrder)
        {
            var queryCollection = new NameValueCollection
            {
                { "contactId", _customerContext.CurrentContactId.ToString() },
                { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
            };

            var confirmationPage = _contentRepository.GetChildren <OrderConfirmationPage>(viewModel.CurrentPage.ContentLink).First();

            try
            {
                _mailService.Send(_contentLoader.GetStartPage().OrderConfirmationMail, queryCollection, viewModel.BillingAddress.Email, confirmationPage.Language.Name);
            }
            catch (Exception e)
            {
                _log.Warning($"Unable to send purchase receipt to '{viewModel.BillingAddress.Email}'.", e);
                return(false);
            }
            return(true);
        }
Exemple #9
0
        /// <returns>Product|Qty|SavedWeight</returns>
        private IEnumerable <Tuple <string, decimal, decimal?> > GetWeights(IPurchaseOrder po)
        {
            foreach (var item in po.Items)
            {
                var hasChildItems = false;

                foreach (var child in item.KitChildren)
                {
                    hasChildItems = true;

                    yield return(new Tuple <string, decimal, decimal?>(child.PlacedName, child.Quantity * item.Quantity, child.Weight));
                }

                if (hasChildItems)
                {
                    continue;
                }

                yield return(new Tuple <string, decimal, decimal?>(item.PlacedName, item.Quantity, item.Weight));
            }
        }
        public virtual string BuildRedirectionUrl(IPurchaseOrder purchaseOrder, string billingEmail, bool confirmationSentSuccessfully)
        {
            var queryCollection = new NameValueCollection
            {
                { "contactId", _customerContext.CurrentContactId.ToString() },
                { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
            };

            if (!confirmationSentSuccessfully)
            {
                queryCollection.Add("notificationMessage", string.Format(_localizationService.GetString("/OrderConfirmationMail/ErrorMessages/SmtpFailure"), billingEmail));
            }

            var startPage        = _contentRepository.Get <StartPage>(ContentReference.StartPage);
            var confirmationPage = _contentRepository.GetChildren <OrderConfirmationPage>(startPage.CheckoutPage).First();

            return(new UrlBuilder(confirmationPage.LinkURL)
            {
                QueryCollection = queryCollection
            }.ToString());
        }
Exemple #11
0
        public void MakeOrderSent(IPurchaseOrder po)
        {
            m_log.Info($"Zacinam nastavovat objednavku {po.OrderNumber} jako odeslanou");

            if (!m_config.EnableWriteOperations)
            {
                m_log.Error($"!!! Flox - MarkOrderPaid({po.OrderNumber}) - neaktivni operace");
                return;
            }

            try
            {
                GenerateInvoice(po.OrderNumber);
                SendInvoiceToCustomer(po.ErpOrderId);
                ChangeOrderStatus(po.ErpOrderId, FloxOrderStatuses.Completed);
            }
            catch (Exception ex)
            {
                throw new Exception($"Selhal pokus o zpracovani objednavky {po.OrderNumber}. Objednavku je treba dokoncit ve Floxu. Chyba: {ex.Message}", ex);
            }
        }
        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,
                })
            });
        }
Exemple #13
0
        protected virtual IShipment CreateShipment(
            IPurchaseOrder purchaseOrder,
            IOrderForm orderForm,
            CustomerContact customerContact,
            SaleShippingViewModel kachingShipping,
            SaleViewModel kachingSale,
            SaleLineItemViewModel shippingLineItem)
        {
            IShipment shipment = _orderGroupFactory.CreateShipment(purchaseOrder);

            shipment.OrderShipmentStatus = kachingShipping != null
                ? OrderShipmentStatus.AwaitingInventory
                : OrderShipmentStatus.Shipped;

            if (kachingShipping != null)
            {
                // If this shipment is awaiting delivery, then the whole order is still in-progress.
                purchaseOrder.OrderStatus = OrderStatus.InProgress;
            }

            return(shipment);
        }
        public IHttpActionResult Post(IDictionary <string, SaleViewModel> sales)
        {
            SaleViewModel sale = sales?.Values.FirstOrDefault();

            if (sale == null)
            {
                Logger.Error("The request is missing one or more sales objects. Exiting.");

                return(BadRequest());
            }

            // Ignore returns and voided sales
            if (sale.Summary.IsReturn || sale.Voided)
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }

            // Ignore sales without any non special line items
            var saleLines = sale.Summary.LineItems.Where(lineItem => lineItem.Behavior == null);

            if (!saleLines.Any())
            {
                return(StatusCode(HttpStatusCode.NoContent));
            }

            try
            {
                IPurchaseOrder purchaseOrder = _saleFactory.CreatePurchaseOrder(sale);
                _purchaseOrderProvider.Save(purchaseOrder);
            }
            catch (Exception ex)
            {
                Logger.Error("Error occurred while registering Ka-ching sale in Episerver.", ex);

                return(BadRequest());
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Exemple #15
0
        /// <summary>
        /// Capture transaction
        /// </summary>
        /// <param name="payment"></param>
        /// <param name="purchaseOrder"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public TransactionResult CaptureTransaction(IPayment payment, IPurchaseOrder purchaseOrder, string accessToken, bool skipItems = false)
        {
            var result = new TransactionResult();

            if (!Configuration.IsValid())
            {
                throw new Exception("Dintero configuration is not valid!");
            }

            var url = DinteroAPIUrlHelper.GetTransactionCaptureUrl(payment.TransactionID);

            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    var request = new DinteroCaptureRequest
                    {
                        Amount = CurrencyHelper.CurrencyToInt(payment.Amount, purchaseOrder.Currency.CurrencyCode),
                        CaptureReference = purchaseOrder.OrderNumber,
                        Items = new List<DinteroOrderLine>()
                    };

                    if (!skipItems)
                    {
                        request.Items = ConvertOrderLineItems(purchaseOrder.Forms, purchaseOrder.Currency);
                    }

                    result = SendTransactionRequest(url, "Bearer", accessToken, request, new List<string> {"CAPTURED"});
                }
                catch (Exception e)
                {
                    Logger.Error("An error occurred during capturing transaction. ", e);
                    throw;
                }

            }

            return result;
        }
        public ActionResult Index(OrderConfirmationPage currentPage, string notificationMessage, int?orderNumber)
        {
            IPurchaseOrder order = null;

            if (PageEditing.PageIsInEditMode)
            {
                order = _confirmationService.CreateFakePurchaseOrder();
            }
            else if (orderNumber.HasValue)
            {
                order = _confirmationService.GetOrder(orderNumber.Value);
            }

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

                return(View(viewModel));
            }

            return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
        }
Exemple #17
0
        public virtual bool SendConfirmation(CheckoutViewModel viewModel, IPurchaseOrder purchaseOrder, string email = "")
        {
            var queryCollection = new NameValueCollection
            {
                { "contactId", _customerContext.CurrentContactId.ToString() },
                { "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString(CultureInfo.CurrentCulture) }
            };

            var startpage        = _contentRepository.Get <StartPage>(ContentReference.StartPage);
            var confirmationPage = _contentRepository.GetFirstChild <OrderConfirmationPage>(viewModel.CurrentPage.ContentLink);

            try
            {
                string confirmationEmail = string.IsNullOrWhiteSpace(email) ? viewModel.BillingAddress.Email : email;
                _mailService.Send(startpage.OrderConfirmationMail, queryCollection, confirmationEmail, confirmationPage.Language.Name);
            }
            catch (Exception e)
            {
                _log.Warning(string.Format("Unable to send purchase receipt to '{0}'.", viewModel.BillingAddress.Email), e);
                return(false);
            }
            return(true);
        }
Exemple #18
0
        public decimal?GetWeight(IPurchaseOrder po)
        {
            if (!m_ordersConfig.UseOrderWeight)
            {
                return(null);
            }

            var     isValid = true;
            decimal sum     = 0;

            foreach (var i in GetWeights(po))
            {
                decimal weight = 0;
                if (i.Item3 == null)
                {
                    var inx = GetWeightIndex();

                    if ((!inx.TryGetValue(i.Item1, out var w)) || (w == null))
                    {
                        m_log.Error($"No weight found for \"{i.Item1}\"");
                        isValid = false;

                        continue;
                    }

                    weight = w ?? 0;
                }
                else
                {
                    weight = i.Item3.Value;
                }

                sum += weight; // * i.Item2;
            }

            return(isValid ? (sum + (m_ordersConfig.OrderWeightAddition ?? 0)) : (decimal?)null);
        }
Exemple #19
0
        public IEnumerable <KitItemsCollection> GetKitForOrderItem(IPurchaseOrder order, IOrderItem item)
        {
            var result = new List <KitItemsCollection>();

            var matchingDefinitions = GetAllKitDefinitions().Where(k => k.IsMatch(order, item)).OrderBy(k => k.Id).ToList();

            if (matchingDefinitions.Count == 0)
            {
                return(result);
            }

            var selectedChildItems = m_orderRepository.GetChildItemsByParentItemId(item.Id).OrderBy(i => i.Id).ToList();

            for (var kitItemIndex = 0; kitItemIndex < (int)item.Quantity; kitItemIndex++)
            {
                foreach (var kitDefinition in matchingDefinitions.OrderBy(md => md.Id))
                {
                    foreach (var selection in kitDefinition.SelectionGroups.OrderBy(sg => sg.Id))
                    {
                        IOrderItem selectedItem = null;
                        foreach (var selectionItem in selection.Items.OrderBy(i => i.Id))
                        {
                            selectedItem = selectedChildItems.FirstOrDefault(i => selectionItem.IsMatch(null, i) && (i.KitItemIndex == kitItemIndex));
                            if (selectedItem != null)
                            {
                                selectedChildItems.Remove(selectedItem);
                                break;
                            }
                        }

                        result.Add(new KitItemsCollection(selection.Items, selectedItem, kitItemIndex, selection.Id, selection.Name));
                    }
                }
            }

            return(result.OrderBy(r => r.GroupId));
        }
        public virtual OmniumOrderForm MapOrderForm(IPurchaseOrder orderGroup, IOrderForm orderForm, IShipment[] shipments)
        {
            var market   = _marketService.GetMarket(orderGroup.MarketId);
            var currency = orderGroup.Currency;
            var shipment = shipments.First();

            var appliedDiscounts  = orderGroup.ApplyDiscounts(_promotionEngine, new PromotionEngineSettings())?.ToList();
            var shippingDiscounts = appliedDiscounts?.Where(x => x.IsOfType(DiscountType.Shipping));
            var discounts         = appliedDiscounts?.Where(x => !x.IsOfType(DiscountType.Shipping));

            var omniumDiscounts = MapDiscounts(discounts, orderGroup.Currency, market, shipment.ShippingAddress);
            var omniumShipments = shipments
                                  .Select(x => MapShipment(x, market, currency, shippingDiscounts))
                                  .ToList();

            var totals = GetOrderFormTotals(orderGroup, market, currency, omniumShipments);

            return(new OmniumOrderForm
            {
                Discounts = omniumDiscounts,
                Shipments = omniumShipments,
                Payments = orderForm.Payments.Select(x => MapPayment(x, totals.Total)).ToList(),
                LineItems = omniumShipments.SelectMany(x => x.LineItems).ToList(),
                Properties = orderForm.ToPropertyList(),
                HandlingTotal = totals.Handling,
                SubTotal = totals.SubTotal,
                SubTotalExclTax = totals.SubTotalExclTax,
                ShippingSubTotal = totals.Shipping,
                DiscountAmount = totals.OrderDiscounts,
                Total = totals.Total,
                TaxTotal = totals.TaxTotal,
                TotalExclTax = totals.TotalExclTax,
                AuthorizedPaymentTotal = Math.Min(orderForm.AuthorizedPaymentTotal, totals.Total),
                CapturedPaymentTotal = Math.Min(orderForm.CapturedPaymentTotal, totals.Total),
                ShippingDiscountTotal = totals.ShippingDiscounts
            });
        }
Exemple #21
0
        public static int CreatePO(IPurchaseOrder po)
        {
            List <parameters> parms = new List <parameters>();

            foreach (var item in po.Items)
            {
                parms.Add(new parameters("@name", item.ItemName, SqlDbType.VarChar, ParameterDirection.Input, 30));
                parms.Add(new parameters("@description", item.Description, SqlDbType.VarChar, ParameterDirection.Input, 255));
                parms.Add(new parameters("@qty", item.Quantity, SqlDbType.Int, ParameterDirection.Input));
                parms.Add(new parameters("@price", item.Price, SqlDbType.Money, ParameterDirection.Input));
                parms.Add(new parameters("@location", item.Location, SqlDbType.VarChar, ParameterDirection.Input, 50));
                parms.Add(new parameters("@justification", item.Justification, SqlDbType.VarChar, ParameterDirection.Input, 255));
                parms.Add(new parameters("@total", item.Price, SqlDbType.Money, ParameterDirection.Input));
                parms.Add(new parameters("@empId", po.EmpId, SqlDbType.Int, ParameterDirection.Input));
                parms.Add(new parameters("@orderNumberIn", po.OrderNumber, SqlDbType.Int, ParameterDirection.Input));
                parms.Add(new parameters("@orderNumberOut", 0, SqlDbType.Int, ParameterDirection.Output));
                DAL.SendData("CreatePO", parms);
            }

            parameters myParms     = parms[9];
            int        orderNumber = Convert.ToInt32(myParms.value);

            return(orderNumber);
        }
Exemple #22
0
        private static IEnumerable <Tuple <string, int> > GetTokensWithWeights(IPurchaseOrder po)
        {
            yield return(new Tuple <string, int>(TryTokenize(po.VarSymbol), 10));

            yield return(new Tuple <string, int>(TryTokenize(po.CustomerName), 9));

            yield return(new Tuple <string, int>(TryTokenize(po.CustomerEmail), 9));

            yield return(new Tuple <string, int>(TryTokenize(po.InvoiceAddress.CompanyName), 3));

            yield return(new Tuple <string, int>(TryTokenize(po.InvoiceAddress.FirstName), 1));

            yield return(new Tuple <string, int>(TryTokenize(po.InvoiceAddress.LastName), 5));

            yield return(new Tuple <string, int>(TryTokenize(po.InvoiceAddress.Phone), 1));

            yield return(new Tuple <string, int>(TryTokenize(po.DeliveryAddress?.CompanyName), 2));

            yield return(new Tuple <string, int>(TryTokenize(po.DeliveryAddress?.FirstName), 1));

            yield return(new Tuple <string, int>(TryTokenize(po.DeliveryAddress?.LastName), 4));

            yield return(new Tuple <string, int>(TryTokenize(po.DeliveryAddress?.Phone), 3));
        }
Exemple #23
0
        public SubmitOrderService(IShoppingCartProvider shoppingCart, ICreditCard3dsi creditCard3dsi, ICreditCard3dsiDemo creditCard3dsiDemo, IPurchaseOrder purchaseOrder)
        {
            if (shoppingCart == null)
            {
                throw new ArgumentNullException(nameof(shoppingCart));
            }
            if (creditCard3dsi == null)
            {
                throw new ArgumentNullException(nameof(creditCard3dsi));
            }
            if (creditCard3dsiDemo == null)
            {
                throw new ArgumentNullException(nameof(creditCard3dsiDemo));
            }
            if (purchaseOrder == null)
            {
                throw new ArgumentNullException(nameof(purchaseOrder));
            }

            this.shoppingCart       = shoppingCart;
            this.creditCard3dsi     = creditCard3dsi;
            this.creditCard3dsiDemo = creditCard3dsiDemo;
            this.purchaseOrder      = purchaseOrder;
        }
        public virtual OmniumOrder MapOrder(
            IPurchaseOrder purchaseOrder, IOrderForm orderForm, IShipment[] shipments)
        {
            var market         = _marketService.GetMarket(purchaseOrder.MarketId);
            var currency       = purchaseOrder.Currency;
            var billingAddress = GetBillingAddress(purchaseOrder);
            var customerName   = GetCustomerName(purchaseOrder, billingAddress);
            var orderType      = purchaseOrder.ToOmniumOrderType().ToString();

            var omniumOrderForm = MapOrderForm(purchaseOrder, orderForm, shipments);

            var firstShipment = shipments.FirstOrDefault();

            return(new OmniumOrder
            {
                OrderNumber = purchaseOrder.OrderNumber,
                OrderType = orderType,
                OrderOrigin = "Webshop",
                CustomerName = customerName,
                MarketId = purchaseOrder.MarketId.Value,
                Created = purchaseOrder.Created,
                Modified = purchaseOrder.Modified ?? DateTime.MinValue,
                Status = GetOrderStatus(purchaseOrder.OrderStatus),
                StoreId = "",
                BillingAddress = billingAddress,
                PublicOrderNotes = MapComments(purchaseOrder),
                BillingCurrency = currency,
                OrderForm = omniumOrderForm,
                Properties = purchaseOrder.ToPropertyList(),
                CustomerId = purchaseOrder.CustomerId.ToString(),
                CustomerComment = "",
                CustomerReference = "",
                CustomerEmail = firstShipment?.ShippingAddress?.Email,
                CustomerPhone = firstShipment?.ShippingAddress?.DaytimePhoneNumber
            });
        }
        public ActionResult Purchase(CheckoutViewModel checkoutViewModel, IPaymentMethodViewModel <PaymentMethodBase> paymentViewModel)
        {
            if (CartIsNullOrEmpty())
            {
                return(Redirect(Url.ContentUrl(ContentReference.StartPage)));
            }

            if (User.Identity.IsAuthenticated)
            {
                // load billing and shipping address from address book
                _addressBookService.LoadAddress(checkoutViewModel.BillingAddress);

                foreach (var shipment in checkoutViewModel.Shipments)
                {
                    _addressBookService.LoadAddress(shipment.Address);
                }

                // Because address is selected from drop down, so remove validation for fields
                foreach (var state in ModelState.Where(x => (x.Key.StartsWith("BillingAddress")) || x.Key.StartsWith("Shipments")).ToArray())
                {
                    ModelState.Remove(state);
                }
            }

            if (checkoutViewModel.UseBillingAddressForShipment)
            {
                // If only the billing address is of interest we need to remove any existing error related to the
                // other shipping addresses.
                if (!User.Identity.IsAuthenticated)
                {
                    foreach (var state in ModelState.Where(x => x.Key.StartsWith("Shipments")).ToArray())
                    {
                        ModelState.Remove(state);
                    }
                }

                checkoutViewModel.Shipments.Single().Address = checkoutViewModel.BillingAddress;
            }

            ValidateBillingAddress(checkoutViewModel);

            HandleValidationIssues(_cartService.ValidateCart(Cart));

            if (!ModelState.IsValid)
            {
                return(View(checkoutViewModel, paymentViewModel));
            }

            // Since the payment property is marked with an exclude binding attribute in the CheckoutViewModel
            // it needs to be manually re-added again.
            checkoutViewModel.Payment = paymentViewModel;

            ValidateShippingAddress(checkoutViewModel);

            HandleValidationIssues(_cartService.RequestInventory(Cart));

            if (!ModelState.IsValid)
            {
                return(View(checkoutViewModel, paymentViewModel));
            }

            UpdateAddressNames(checkoutViewModel);

            SetShipmentAddresses(checkoutViewModel.Shipments);

            CreatePayment(checkoutViewModel.Payment, checkoutViewModel.BillingAddress);

            var            startpage        = _contentRepository.Get <StartPage>(ContentReference.StartPage);
            var            confirmationPage = _contentRepository.GetFirstChild <OrderConfirmationPage>(checkoutViewModel.CurrentPage.ContentLink);
            IPurchaseOrder purchaseOrder    = null;

            try
            {
                purchaseOrder = PlaceOrder(checkoutViewModel);
            }
            catch (PaymentException)
            {
                ModelState.AddModelError("", _localizationService.GetString("/Checkout/Payment/Errors/ProcessingPaymentFailure"));
                return(View(checkoutViewModel, paymentViewModel));
            }

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

            SendConfirmationEmail(checkoutViewModel.BillingAddress.Email, startpage.OrderConfirmationMail, confirmationPage.Language.Name, queryCollection);

            return(Redirect(new UrlBuilder(confirmationPage.LinkURL)
            {
                QueryCollection = queryCollection
            }.ToString()));
        }
Exemple #26
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);
        }
Exemple #27
0
 public void AcknowledgeOrder(IPurchaseOrder purchaseOrder)
 {
     _client.NewOrder(purchaseOrder.Properties[Constants.KlarnaOrderIdField]?.ToString()).Acknowledge();
 }
Exemple #28
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);
        }
Exemple #29
0
 public void MakeOrderSent(IPurchaseOrder po)
 {
     throw new NotImplementedException("Fler zatim nepodporuje odesilani zasilek :(");
 }
Exemple #30
0
 public string GetPackingReferenceNumber(IPurchaseOrder po)
 {
     return(po.VarSymbol);
 }
 public OrderCancelledEvent(IPurchaseOrder purchaseOrder)
 {
     PurchaseOrder = purchaseOrder ?? throw new ArgumentNullException(nameof(purchaseOrder));
 }