Example #1
0
        //Check to not register same order twice in DB
        public bool OrderIsAlreadyRegistered(OrderRow order)
        {
            var orderRepository = new OrderRepository();
            var orders          = orderRepository.GetOrders();

            foreach (OrderRow or in orders)
            {
                if (order.Id == or.Id)
                {
                    continue;
                }

                if (or.OrderNumber.Equals(order.OrderNumber, StringComparison.InvariantCultureIgnoreCase) &&
                    or.OrderLineNumber.Equals(order.OrderLineNumber, StringComparison.InvariantCultureIgnoreCase) &&
                    or.ProductNumber.Equals(order.ProductNumber, StringComparison.InvariantCultureIgnoreCase) &&
                    or.Quantity.CompareTo(order.Quantity) == 0 &&
                    or.Name.Equals(order.Name, StringComparison.InvariantCultureIgnoreCase) &&
                    or.Description.Equals(order.Description, StringComparison.InvariantCultureIgnoreCase) &&
                    or.Price.CompareTo(order.Price) == 0 &&
                    or.ProductGroup.Equals(order.ProductGroup, StringComparison.InvariantCultureIgnoreCase) &&
                    or.OrderDate.Date.CompareTo(order.OrderDate.Date) == 0 &&
                    or.CustomerName.Equals(order.CustomerName, StringComparison.InvariantCultureIgnoreCase) &&
                    or.CustomerNumber.Equals(order.CustomerNumber, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(true);
                }
            }

            return(false);
        }
        private ProductPriceModel.PriceItem GetCampaignPrice(OrderRow orderRow, SalesOrder salesOrder)
        {
            ProductPriceModel.PriceItem campaignPrice = null;
            if (salesOrder.Rows.Any(c => c.OrderRowType == OrderRowType.Discount && c.ArticleNumber == orderRow.ArticleNumber))
            {
                bool    haveCampaignPrice = false;
                decimal priceExcludingVat = orderRow.UnitPriceExcludingVat;
                decimal priceIncludingVat = orderRow.UnitPriceIncludingVat;
                foreach (var discount in salesOrder.DiscountInfo.Where(x => x.SourceOrderRowSystemIds != null && x.SourceOrderRowSystemIds.Contains(orderRow.SystemId)))
                {
                    var discountRow = salesOrder.Rows.Single(x => x.SystemId == discount.ResultOrderRowSystemId);
                    if (discountRow.OrderRowType == OrderRowType.Discount && discountRow.ArticleNumber == orderRow.ArticleNumber)
                    {
                        priceExcludingVat += discountRow.UnitPriceExcludingVat;
                        priceIncludingVat += discountRow.UnitPriceIncludingVat;
                        haveCampaignPrice  = true;
                    }
                }

                if (haveCampaignPrice)
                {
                    campaignPrice = new ProductPriceModel.PriceItem(0, priceExcludingVat, orderRow.VatRate, priceIncludingVat);
                }
            }
            return(campaignPrice);
        }
Example #3
0
        public ActionResult ConfirmTrip(TripConfirmRequest request)
        {
            try
            {
                var  decryptId = EncryptionHelper.Decrypt(request.Token);
                int  id;
                bool success = Int32.TryParse(decryptId, out id);
                if (success)
                {
                    using (var connection = SqlConnections.NewByKey("Northwind"))
                        using (var uow = new UnitOfWork(connection))
                        {
                            var updateOrder = new OrderRow
                            {
                                OrderID     = id,
                                ConfirmRide = true
                            };
                            connection.UpdateById <OrderRow>(updateOrder);
                            uow.Commit();
                        }
                }

                return(View("~/Modules/Northwind/Order/TripConfirm.cshtml", new TripConfirm {
                    Message = "Success"
                }));
            }
            catch
            {
                return(View("~/Modules/Northwind/Order/TripConfirm.cshtml", new TripConfirm {
                    Message = "Error"
                }));
            }
        }
 public OrderRow UpdateOrderRow(OrderRow initialOrderRow, OrderRow replacementOrderRow)
 {
     initialOrderRow.Pizza      = replacementOrderRow.Pizza;
     initialOrderRow.Soda       = replacementOrderRow.Soda;
     initialOrderRow.TotalPrice = replacementOrderRow.TotalPrice;
     return(initialOrderRow);
 }
        private OrderDetailsViewModel.OrderRowItem BuildOrderRow(OrderRow orderRow, bool includeVat, Currency currency, SalesOrder order)
        {
            var productModel = _productModelBuilder.BuildFromVariant(_variantService.Get(orderRow.ArticleNumber));

            var unitOfMeasurement             = _unitOfMeasurementService.Get(orderRow.UnitOfMeasurementSystemId.Value);
            var unitOfMeasurementFormatString = $"0.{new string('0', unitOfMeasurement?.DecimalDigits ?? 0)}";

            var campaignPrice = GetCampaignPrice(orderRow, order);
            var totalPrice    = GetTotalPrice(campaignPrice, includeVat, orderRow);

            var model = new OrderDetailsViewModel.OrderRowItem
            {
                DeliveryId     = orderRow.ShippingInfoSystemId is null ? Guid.Empty : orderRow.ShippingInfoSystemId.Value,
                Brand          = productModel == null ? null : _fieldDefinitionService.Get <ProductArea>("Brand")?.GetTranslation(productModel.GetValue <string>("Brand")),
                Name           = productModel == null ? orderRow.ArticleNumber : productModel.GetValue <string>(SystemFieldDefinitionConstants.Name),
                QuantityString = $"{orderRow.Quantity.ToString(unitOfMeasurementFormatString, CultureInfo.CurrentUICulture.NumberFormat)} {unitOfMeasurement?.Localizations.CurrentUICulture.Name}",
                PriceInfo      = new ProductPriceModel
                {
                    Price         = SetFormattedPrice(new ProductPriceModel.PriceItem(0, orderRow.UnitPriceExcludingVat, orderRow.VatRate, orderRow.UnitPriceExcludingVat * (1 + orderRow.VatRate)), includeVat, currency),
                    CampaignPrice = campaignPrice != null?SetFormattedPrice(campaignPrice, includeVat, currency) : null
                },
                TotalPrice = currency.Format(totalPrice, true, CultureInfo.CurrentUICulture),
                Link       = productModel?.SelectedVariant.MapTo <LinkModel>()
            };

            return(model);
        }
Example #6
0
        //Method takes a cart and a customer and creates an order, as well as appropriate rows out of it.
        public static void CreateOrder(string UserID, ShoppingCart Cart, string FirstName, string LastName, string Address, string Zip, string City)
        {
            ApplicationDbContext db = new ApplicationDbContext();
            Order NewOrder          = new Order
            {
                Recipient       = FirstName + " " + LastName,
                DeliveryAddress = Address,
                DeliveryZip     = Zip,
                DeliveryCity    = City,
                User            = db.Users.Find(UserID),
                OrderDate       = DateTime.Now
            };

            NewOrder.OrderRows = new List <OrderRow>();
            foreach (var item in Cart.Items)
            {
                OrderRow row = new OrderRow
                {
                    MovieID  = item.Movie.ID,
                    Price    = item.CostPerItem * item.Quantity,
                    Quantity = item.Quantity
                };
                NewOrder.OrderRows.Add(row);
            }


            db.Orders.Add(NewOrder);
            db.SaveChanges();
        }
Example #7
0
        public ActionResult ProductToOrderRow(int pId, int oId)
        {
            Order order = db.Orders.Include("OrderRows").Include("OrderRows.Product").SingleOrDefault(o => o.Id == oId);

            bool foundIt = false;

            foreach (var item in order.OrderRows)
            {
                if (item.Product.Id == pId)
                {
                    item.Amount++;
                    foundIt = true;
                    break;
                }
            }

            if (foundIt == false)
            {
                Product product = db.Products.SingleOrDefault(p => p.Id == pId);

                OrderRow orderRow = new OrderRow();

                orderRow.Amount  = 1;
                orderRow.Product = product;
                orderRow.Price   = product.Price;
                order.OrderRows.Add(orderRow);
            }


            db.SaveChanges();

            return(RedirectToAction("Details", new { id = oId }));
        }
        public OrderRow CreateOrderRow(Pizza pizza, Soda soda)
        {
            var pizzaPrice = pizza.Price;
            var extraPrice = 0;

            if (pizza.ExtraIngredients != null)
            {
                foreach (var ing in pizza.ExtraIngredients)
                {
                    extraPrice += ing.PriceAsExtra;
                }
            }

            var sodaPrice  = soda.Price;
            var totalPrice = pizzaPrice + extraPrice + sodaPrice;

            var orderRow = new OrderRow
            {
                RowId      = rowId,
                Pizza      = pizza,
                Soda       = soda,
                TotalPrice = totalPrice
            };

            OrderRows.Rows.Add(orderRow);
            rowId++;
            return(orderRow);
        }
Example #9
0
        public async Task UpdateOrderRow(string orderId, string productId, int count)
        {
            var order = await _orderRepository.GetOrder(orderId);

            var orderRow = order.Rows.FirstOrDefault(row => string.Equals(row.Product.Id, productId, StringComparison.OrdinalIgnoreCase));

            if (orderRow == null)
            {
                var product = await _productService.GetProduct(productId);

                orderRow = new OrderRow {
                    Product = product,
                    Count   = count
                };
                order.Rows.Add(orderRow);
            }
            else
            {
                orderRow.Count = count;
                if (orderRow.Count == 0)
                {
                    order.Rows.Remove(orderRow);
                }
            }

            _ = await SaveOrder(order);
        }
Example #10
0
        private OrderDetailsViewModel.OrderRowItem BuildOrderRow(OrderRow orderRow, Currency currency)
        {
            var productModel           = _productModelBuilder.BuildFromVariant(_variantService.Get(orderRow.ArticleNumber));
            var shoppingCartIncludeVat = _requestModelAccessor.RequestModel.Cart.IncludeVAT;

            var unitOfMeasurement             = _unitOfMeasurementService.Get(orderRow.SKUCode);
            var unitOfMeasurementFormatString = $"0.{new string('0', unitOfMeasurement?.DecimalDigits ?? 0)}";

            var totalPrice = shoppingCartIncludeVat ? orderRow.TotalPriceWithVat : orderRow.TotalPrice;

            var campaign = orderRow.Campaign;
            var model    = new OrderDetailsViewModel.OrderRowItem
            {
                DeliveryId     = orderRow.DeliveryID,
                Brand          = productModel == null ? null : _fieldDefinitionService.Get <ProductArea>("Brand")?.GetTranslation(productModel.GetValue <string>("Brand")),
                Name           = productModel == null ? orderRow.ArticleNumber : productModel.GetValue <string>(SystemFieldDefinitionConstants.Name),
                QuantityString = $"{orderRow.Quantity.ToString(unitOfMeasurementFormatString, CultureInfo.CurrentUICulture.NumberFormat)} {unitOfMeasurement?.Localizations.CurrentUICulture.Name ?? orderRow.SKUCode}",
                PriceInfo      = new ProductPriceModel
                {
                    CampaignPrice = campaign == null ? null : SetFormattedPrice(new ProductPriceModel.CampaignPriceItem(0, orderRow.UnitCampaignPrice, orderRow.VATPercentage, orderRow.UnitCampaignPrice * (1 + orderRow.VATPercentage), campaign.ID), shoppingCartIncludeVat, currency),
                    Price         = SetFormattedPrice(new ProductPriceModel.PriceItem(0, orderRow.UnitListPrice, orderRow.VATPercentage, orderRow.UnitListPrice * (1 + orderRow.VATPercentage)), shoppingCartIncludeVat, currency)
                },
                TotalPrice = currency.Format(totalPrice, true, CultureInfo.CurrentUICulture),
                Link       = productModel?.SelectedVariant.MapTo <LinkModel>()
            };

            return(model);
        }
Example #11
0
        private List <OrderRow> getOrderRowsByOrderId(int orderId)
        {
            List <OrderRow> returnList = new List <OrderRow>();

            try
            {
                using (SqlConnection con = new SqlConnection(Env.ConString))
                {
                    string query =
                        "SELECT * FROM Order_Product where orderId = @id";
                    SqlCommand cmd = new SqlCommand(query, con);
                    cmd.Parameters.AddWithValue("@id", orderId);
                    con.Open();
                    var reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        OrderRow or = new OrderRow(reader.GetInt32(1), reader.GetInt32(2));
                        returnList.Add(or);
                    }
                    con.Close();
                }

                return(returnList);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #12
0
        public void Order_GivenOrderWithExistingProductAndTooSmallStock_ShouldAddItToBoth()
        {
            var productId     = Guid.NewGuid();
            var productAmount = 5;
            var orderRow      = new OrderRow()
            {
                Amount = productAmount, ProductId = productId
            };

            _repository.TryTake(productId, productAmount, out Arg.Any <int>())
            .Returns(x =>
            {
                x[2] = 2;
                return(false);
            });

            var result = _sut.Order(new[] { orderRow });

            Assert.Equal(1, result.Products.Count);
            Assert.Equal(productId, result.Products.First().ProductId);
            Assert.Equal(2, result.Products.First().Amount);

            Assert.Equal(1, result.MissingProducts.Count);
            Assert.Equal(productId, result.MissingProducts.First().ProductId);
            Assert.Equal(3, result.MissingProducts.First().Amount);
        }
Example #13
0
        public ActionResult CheckOut(CheckOutVM chkVM)
        {
            //Create Order
            Order order = new Order
            {
                CustomerId = chkVM.Customer.Id,
                OrderDate  = DateTime.Today
            };

            db.Orders.Add(order);
            db.SaveChanges();

            foreach (var row in chkVM.ShoppingCart)
            {
                OrderRow orows = new OrderRow
                {
                    Order   = order,
                    MovieId = row.Id,
                    Price   = row.Price
                };
                db.OrderRows.Add(orows);
                db.SaveChanges();
            }

            TempData["Message"] = "Order Placed";

            Session["Cart"] = null;

            return(RedirectToAction("Index", "Home"));
        }
Example #14
0
        public IActionResult Post([FromBody] OrderViewModel newOrder)
        {
            using (SurfboardContext context = new SurfboardContext())
            {
                Customer c = new Customer();
                c.Address   = newOrder.Customer.Address;
                c.FirstName = newOrder.Customer.FirstName;
                c.LastName  = newOrder.Customer.LastName;

                context.Customers.Add(c);
                context.SaveChanges();

                Order o = new Order();
                o.OrderDate  = DateTime.Now;
                o.CustomerId = c.Id;
                context.Orders.Add(o);
                context.SaveChanges();

                // Skapa orderrader!!!!
                foreach (var item in newOrder.Cart)
                {
                    OrderRow or = new OrderRow();
                    or.OrderId     = o.Id;
                    or.SurfBoardId = item.Id;
                    or.Price       = item.Price;
                    or.SizeId      = item.SizeId;
                    context.OrderRows.Add(or);
                    context.SaveChanges();
                }

                return(Created("/orders", o));
            }
        }
Example #15
0
        // GET: Orders/Review
        public async Task <ActionResult> Review()
        {
            ShoppingCart cart  = ShoppingCart.GetCart();
            Order        order = new Order();

            order.UserID = User.Identity.Name;
            ApplicationUser user = await UserManager.FindByNameAsync(order.UserID);

            order.DeliveryName    = user.FirstName + " " + user.LastName;
            order.DeliveryAddress = user.Address;
            order.OrderRows       = new List <OrderRow>();
            foreach (var cartqueue in cart.GetCartQueues())
            {
                OrderRow row = new OrderRow
                {
                    Product     = cartqueue.Product,
                    ProductID   = cartqueue.ProductID,
                    ProductName = cartqueue.Product.ProductName,
                    Quantity    = cartqueue.Quantity,
                    UnitPrice   = cartqueue.Product.ProductPrice
                };
                order.OrderRows.Add(row);
            }
            order.TotalPrice = cart.GetTotalCost();
            return(View(order));
        }
Example #16
0
        public void TestFormatFixedDiscountRowsAmountExVatAndVatPercentWithDifferentVatRatesPresent()
        {
            CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig())
                                       .AddOrderRow(Item.OrderRow()
                                                    .SetAmountExVat(100.00M)
                                                    .SetVatPercent(25)
                                                    .SetQuantity(2))
                                       .AddOrderRow(Item.OrderRow()
                                                    .SetAmountExVat(100.00M)
                                                    .SetVatPercent(6)
                                                    .SetQuantity(1))
                                       .AddDiscount(Item.FixedDiscount()
                                                    .SetDiscountId("42")
                                                    .SetName(".SetAmountIncVat(100)")
                                                    .SetDescription("testFormatFixedDiscountRowsWithDifferentVatRatesPresent")
                                                    .SetAmountExVat(111)
                                                    .SetVatPercent(25)
                                                    .SetUnit("st"));

            List <OrderRow> newRows = new WebServiceRowFormatter <CreateOrderBuilder>(order).FormatRows();


            // 100 @25% vat = -80 excl. vat
            OrderRow newRow = newRows[2];

            Assert.That(newRow.ArticleNumber, Is.EqualTo("42"));
            Assert.That(newRow.Description, Is.EqualTo(".SetAmountIncVat(100): testFormatFixedDiscountRowsWithDifferentVatRatesPresent"));
            Assert.That(newRow.PricePerUnit, Is.EqualTo(-111.00M));
            Assert.That(newRow.VatPercent, Is.EqualTo(25));
            Assert.That(newRow.DiscountPercent, Is.EqualTo(0));
            Assert.That(newRow.NumberOfUnits, Is.EqualTo(1));
            Assert.That(newRow.Unit, Is.EqualTo("st"));
        }
Example #17
0
        public void TestFormatFixedDiscountRowsAmountExVatAndVatPercentWithSingleVatRatePresent()
        {
            CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig())
                                       .AddOrderRow(Item.OrderRow()
                                                    .SetAmountExVat(4.0M)
                                                    .SetVatPercent(25)
                                                    .SetQuantity(1))
                                       .AddDiscount(Item.FixedDiscount()
                                                    .SetDiscountId("0")
                                                    .SetName("Tess")
                                                    .SetDescription("Tester")
                                                    .SetAmountExVat(1.0M)
                                                    .SetVatPercent(25)
                                                    .SetUnit("st"));

            List <OrderRow> newRows = new WebServiceRowFormatter <CreateOrderBuilder>(order).FormatRows();

            OrderRow newRow = newRows[1];

            Assert.That(newRow.ArticleNumber, Is.EqualTo("0"));
            Assert.That(newRow.Description, Is.EqualTo("Tess: Tester"));
            Assert.That(newRow.PricePerUnit, Is.EqualTo(-1.0M));
            Assert.That(newRow.VatPercent, Is.EqualTo(25));
            Assert.That(newRow.DiscountPercent, Is.EqualTo(0));
            Assert.That(newRow.NumberOfUnits, Is.EqualTo(1));
            Assert.That(newRow.Unit, Is.EqualTo("st"));
        }
        public IHttpActionResult AddProductToCart(string customerId, int productId, int amount)
        {
            var order = GetOrder(customerId, true);

            var product = db.Products.Find(productId);

            if (product == null)
            {
                return(NotFound());
            }

            // Check if the order already has the product
            var orderRow = db.OrderRows.Where(o => o.Order_ID == order.ID && o.Product_ID == productId).FirstOrDefault();

            if (orderRow != null)
            {
                orderRow.Amount += amount;
                orderRow.Price  += (product.Price * amount);
            }
            else
            {
                orderRow = new OrderRow
                {
                    Order_ID   = order.ID,
                    Product_ID = productId,
                    Amount     = amount,
                    Price      = (product.Price * amount)
                };

                db.OrderRows.Add(orderRow);
            }
            db.SaveChanges();

            return(Ok());
        }
Example #19
0
        public void GetTrimedOrderValues_SenUntrimedOrder_ShouldTrimAllPropertyValues()
        {
            var order = new OrderRow
            {
                OrderNumber     = "  17835  ",
                OrderLineNumber = "     0002    ",
                ProductNumber   = "	4000-AAA",
                Quantity        = 2,
                Name            = "  Test",
                Description     = "   Some des  ",
                Price           = 1.25,
                ProductGroup    = "  Normal ",
                OrderDate       = DateTime.Now,
                CustomerName    = "   Centiro  ",
                CustomerNumber  = "   1234"
            };

            var utils = new Utils();

            order = utils.GetTrimedOrderValues(order);

            Assert.AreEqual(order.OrderNumber, "17835");
            Assert.AreEqual(order.ProductNumber, "4000-AAA");
            Assert.AreEqual(order.ProductGroup, "Normal");
            Assert.AreEqual(order.CustomerName, "Centiro");
        }
Example #20
0
        public void SaveOrderRowTest()
        {
            using (var scope = CreateDatabaseScope())
            {
                using (var session1 = scope.OpenSession())
                {
                    var row = new OrderRow()
                    {
                        Product = "Product1",
                        Price   = 10,
                    };

                    session1.Save(row);
                    session1.Flush();
                }

                using (var session2 = scope.OpenSession())
                {
                    var query = session2.CreateQuery("from OrderRow where Product='Product1'");
                    var row   = query.UniqueResult <OrderRow>();

                    Assert.IsNotNull(row);
                    Assert.AreEqual("Product1", row.Product);
                    Assert.AreEqual(10, row.Price);
                }
            }
        }
Example #21
0
        private static void ProcessOrder(MessageContext context, OrderRow order)
        {
            if (context.AvaiableSlots <= 0)
            {
                return;
            }

            int quantity = order.Quantity;

            if (quantity > context.AvaiableSlots)
            {
                quantity = context.AvaiableSlots;
            }

            if (quantity == 1)
            {
                context.MessageParts.Add($"{order.ItemName} ({order.Plat}p)");
            }
            else
            {
                context.MessageParts.Add($"{quantity}x {order.ItemName} ({order.Plat}p/ea)");
            }

            context.AvaiableSlots -= quantity;
            context.TotalPrice    += quantity * order.Plat;
        }
Example #22
0
 public static string Generate(OrderRow order)
 {
     return(Generate(new List <OrderRow>(1)
     {
         order
     }));
 }
Example #23
0
        public void TestFormatRelativeDiscountRowsWithSingleVatRatePresent()
        {
            CreateOrderBuilder order = WebpayConnection.CreateOrder(SveaConfig.GetDefaultConfig())
                                       .AddOrderRow(Item.OrderRow()
                                                    .SetAmountExVat(100.00M)
                                                    .SetVatPercent(12)
                                                    .SetQuantity(1))
                                       .AddDiscount(Item.RelativeDiscount()
                                                    .SetDiscountId("0")
                                                    .SetName(".SetDiscountPercent(20)")
                                                    .SetDescription("TestFormatRelativeDiscountRowsWithSingleVatRatePresent")
                                                    .SetDiscountPercent(20)
                                                    .SetUnit("st"));

            List <OrderRow> newRows = new WebServiceRowFormatter <CreateOrderBuilder>(order).FormatRows();

            OrderRow newRow = newRows[1];

            Assert.That(newRow.ArticleNumber, Is.EqualTo("0"));
            Assert.That(newRow.Description, Is.EqualTo(".SetDiscountPercent(20): TestFormatRelativeDiscountRowsWithSingleVatRatePresent"));
            Assert.That(newRow.PricePerUnit, Is.EqualTo(-20.00M));
            Assert.That(newRow.VatPercent, Is.EqualTo(12));
            Assert.That(newRow.DiscountPercent, Is.EqualTo(0)); // not the same thing as in our WebPayItem...
            Assert.That(newRow.NumberOfUnits, Is.EqualTo(1));
            Assert.That(newRow.Unit, Is.EqualTo("st"));
        }
Example #24
0
        public static Order ConvertViewModelToOrder(OrderViewModel vm)
        {
            Order order = new Order
            {
                Id             = vm.Id,
                Number         = vm.Number,
                DeliveryAdress = vm.DeliveryAdress,
                Date           = vm.OrderDate,
                Comment        = vm.Comment,
                Total          = vm.Total,
                Customer       = Mapper.Map <Customer>(vm.Customer)
            };

            foreach (var r in vm.PizzaList)
            {
                OrderRow row = new OrderRow {
                    Order = order, Pizza = Mapper.Map <Pizza>(r), Price = r.Price, Amount = 1, Total = r.Total
                };

                foreach (var i in r.Ingredients)
                {
                    if (i.Selected)
                    {
                        OrderRowIngredient rowIngredient = new OrderRowIngredient {
                            OrderRow = row, Ingredient = Mapper.Map <Ingredient>(i), Price = i.Price
                        };
                        row.OrderRowIngredients.Add(rowIngredient);
                    }
                }

                order.OrderRows.Add(row);
            }
            return(order);
        }
        public ActionResult CompleteOrder()
        {
            var currentUserId = User.Identity.GetUserId();

            var customer = (from c in db.Customers
                            where c.User_Id == currentUserId
                            select c).FirstOrDefault();

            if (customer == null)
            {
                return(RedirectToAction("Create", "Customers", new { isProcessingCheckout = true }));
            }
            else
            {
                List <Movie> movyList  = new List <Movie>();
                var          totalCart = 0.0M;

                foreach (string key in Session.Keys)
                {
                    if (key.ToString() != "isCheckout")
                    {
                        Movie movy = (from c in db.Movies
                                      where c.Title == key
                                      select c).FirstOrDefault();

                        movyList.Add(movy);

                        int countMovy = int.Parse(Session[key].ToString());

                        totalCart += (movy.Price * countMovy);
                    }
                }

                Order order = new Order();
                order.CustomerId = customer.Id;
                order.OrderDate  = DateTime.Now;
                order.TotalPrice = totalCart;

                db.Orders.Add(order);
                db.SaveChanges();

                foreach (Movie movy in movyList)
                {
                    //creamos el orderrows con la pelicual y el order insertado
                    OrderRow orderRow = new OrderRow();
                    orderRow.OrderId = order.Id;
                    orderRow.MovieId = movy.Id;
                    orderRow.Price   = movy.Price;

                    db.OrderRows.Add(orderRow);
                }

                var rows = db.SaveChanges();

                Session.Clear();

                return(RedirectToAction("FinishOrder"));
            }
        }
Example #26
0
 public static int AddOrderRow(OrderRow orderRow)
 {
     using (var _context = new EduShopEntities())
     {
         _context.OrderRowSet.AddOrUpdate(orderRow);
         return(_context.SaveChanges());
     }
 }
        public List <OrderRow> get_by_order_id(Int32 id = 0)
        {
            // Create the list to return
            List <OrderRow> posts = OrderRow.GetByOrderId(id);

            // Return the list
            return(posts);
        } // End of the get_by_order_id method
        public OrderRow get_by_id(Int32 id = 0, string productCode = "")
        {
            // Create the post to return
            OrderRow post = OrderRow.GetOneById(id, productCode);

            // Return the post
            return(post);
        } // End of the get_by_id method
Example #29
0
        public bool Remove(OrderRow orderRow)
        {
            var result = _handleWebshopsDbContext.OrderRows.Remove(orderRow);

            _handleWebshopsDbContext.SaveChanges();

            return(true);
        }
Example #30
0
        public OrderRow Create(OrderRow orderRow)
        {
            _handleWebshopsDbContext.OrderRows.Add(orderRow);

            _handleWebshopsDbContext.SaveChanges();

            return(orderRow);
        }
            public bool Warrenty; // Garanti

            #endregion Fields

            #region Methods

            /// <summary>
            /// Konvertera en ArrayList till OrderRow object.
            /// </summary>
            /// <param name="arr"></param>
            /// <returns></returns>
            public static OrderRow[] convertFromArray(ArrayList arr)
            {
                OrderRow[] or = new OrderRow[arr.Count];

                for (int i = 0; i < arr.Count; i++)
                {
                    or[i] = (OrderRow)arr[i];
                }
                return or;
            }
Example #32
0
    } // End of the constructor

    #endregion

    #region Insert methods

    /// <summary>
    /// Add one order row
    /// </summary>
    /// <param name="post">A reference to a order row post</param>
    public static void Add(OrderRow post)
    {

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "INSERT INTO dbo.order_rows (order_id, product_code, manufacturer_code, product_id, gtin, "
            + "product_name, vat_percent, quantity, unit_id, unit_price, account_code, supplier_erp_id, sort_order) "
            + "VALUES (@order_id, @product_code, @manufacturer_code, @product_id, @gtin, @product_name, "
            + "@vat_percent, @quantity, @unit_id, @unit_price, @account_code, @supplier_erp_id, @sort_order);";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@order_id", post.order_id);
                cmd.Parameters.AddWithValue("@product_code", post.product_code);
                cmd.Parameters.AddWithValue("@manufacturer_code", post.manufacturer_code);
                cmd.Parameters.AddWithValue("@product_id", post.product_id);
                cmd.Parameters.AddWithValue("@gtin", post.gtin);
                cmd.Parameters.AddWithValue("@product_name", post.product_name);
                cmd.Parameters.AddWithValue("@vat_percent", post.vat_percent);
                cmd.Parameters.AddWithValue("@quantity", post.quantity);
                cmd.Parameters.AddWithValue("@unit_id", post.unit_id);
                cmd.Parameters.AddWithValue("@unit_price", post.unit_price);
                cmd.Parameters.AddWithValue("@account_code", post.account_code);
                cmd.Parameters.AddWithValue("@supplier_erp_id", post.supplier_erp_id);
                cmd.Parameters.AddWithValue("@sort_order", post.sort_order);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection
                    cn.Open();

                    // Execute the insert
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Add method
            public static ListViewItem[] convertToSmallListView(OrderRow[] or)
            {
                ListViewItem[] lw = new ListViewItem[or.Length];

                for (int i = 0; i < lw.Length; i++)
                {
                    lw[i] = new ListViewItem(or[i].Artikel);
                    lw[i].SubItems.Add(or[i].ProductName);
                    lw[i].SubItems.Add(or[i].Antal);
                    lw[i].SubItems.Add(or[i].Rad).Name = or[i].Rad;
                    lw[i].Tag = or[i].Rad;
                    if (or[i].ViewInList)
                        lw[i].Checked = true;
                }

                return lw;
            }
        public HttpResponseMessage update(OrderRow post)
        {
            // Check for errors
            if (post == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The post is null");
            }
            else if (Order.MasterPostExists(post.order_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The order does not exist");
            }
            else if (Unit.MasterPostExists(post.unit_id) == false)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The unit does not exist");
            }

            // Make sure that the data is valid
            post.product_code = AnnytabDataValidation.TruncateString(post.product_code, 50);
            post.manufacturer_code = AnnytabDataValidation.TruncateString(post.manufacturer_code, 50);
            post.gtin = AnnytabDataValidation.TruncateString(post.gtin, 20);
            post.product_name = AnnytabDataValidation.TruncateString(post.product_name, 100);
            post.vat_percent = AnnytabDataValidation.TruncateDecimal(post.vat_percent, 0, 9.99999M);
            post.quantity = AnnytabDataValidation.TruncateDecimal(post.quantity, 0, 999999.99M);
            post.unit_price = AnnytabDataValidation.TruncateDecimal(post.unit_price, 0, 9999999999.99M);
            post.account_code = AnnytabDataValidation.TruncateString(post.account_code, 10);
            post.supplier_erp_id = AnnytabDataValidation.TruncateString(post.supplier_erp_id, 20);

            // Get the saved post
            OrderRow savedPost = OrderRow.GetOneById(post.order_id, post.product_code);

            // Check if the post exists
            if (savedPost == null)
            {
                return Request.CreateResponse<string>(HttpStatusCode.BadRequest, "The record does not exist");
            }

            // Update the post
            OrderRow.Update(post);

            // Return the success response
            return Request.CreateResponse<string>(HttpStatusCode.OK, "The update was successful");

        } // End of the update method
Example #35
0
    } // End of the Add method

    #endregion

    #region Update methods

    /// <summary>
    /// Update a order row post
    /// </summary>
    /// <param name="post">A reference to a order row post</param>
    public static void Update(OrderRow post)
    {
        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "UPDATE dbo.order_rows SET manufacturer_code = @manufacturer_code, product_id = @product_id, "
            + "gtin = @gtin, product_name = @product_name, vat_percent = @vat_percent, quantity = @quantity, "
            + "unit_id = @unit_id, unit_price = @unit_price, account_code = @account_code, "
            + "supplier_erp_id = @supplier_erp_id, sort_order = @sort_order WHERE order_id = @order_id AND product_code = @product_code;";

        // The using block is used to call dispose automatically even if there are an exception.
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there are an exception.
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {

                // Add parameters
                cmd.Parameters.AddWithValue("@order_id", post.order_id);
                cmd.Parameters.AddWithValue("@product_code", post.product_code);
                cmd.Parameters.AddWithValue("@manufacturer_code", post.manufacturer_code);
                cmd.Parameters.AddWithValue("@product_id", post.product_id);
                cmd.Parameters.AddWithValue("@gtin", post.gtin);
                cmd.Parameters.AddWithValue("@product_name", post.product_name);
                cmd.Parameters.AddWithValue("@vat_percent", post.vat_percent);
                cmd.Parameters.AddWithValue("@quantity", post.quantity);
                cmd.Parameters.AddWithValue("@unit_id", post.unit_id);
                cmd.Parameters.AddWithValue("@unit_price", post.unit_price);
                cmd.Parameters.AddWithValue("@account_code", post.account_code);
                cmd.Parameters.AddWithValue("@supplier_erp_id", post.supplier_erp_id);
                cmd.Parameters.AddWithValue("@sort_order", post.sort_order);

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases.
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Execute the update
                    cmd.ExecuteNonQuery();

                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

    } // End of the Update method
Example #36
0
        public ActionResult index(FormCollection collection)
        {
            // Check if the customer is signed in
            if (Request.Cookies.Get("CustomerCookie") == null)
            {
                return RedirectToAction("login", "customer");
            }

            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();

            // Get the language
            Language currentLanguage = Language.GetOneById(currentDomain.front_end_language);

            // Get the currency 
            Currency currency = Currency.GetOneById(currentDomain.currency);
            currency = currency != null ? currency : new Currency();

            // Get the document type
            byte document_type = 1;
            if(collection["btnRequest"] != null)
            {
                document_type = 0;
            }

            // Get all the form values
            Int32 customerId = Convert.ToInt32(collection["hiddenCustomerId"]);
            byte customerType = Convert.ToByte(collection["hiddenCustomerType"]);
            byte vatCode = Convert.ToByte(collection["hiddenVatCode"]);
            string[] additionalServiceIds = collection.GetValues("cbService");
            Int32 paymentOptionId = Convert.ToInt32(collection["radioPaymentOption"]);
            string email = collection["txtEmail"];
            string orgNumber = collection["txtOrgNumber"];
            string vatNumber = "";
            string contactName = collection["txtContactName"];
            string phoneNumber = collection["txtPhoneNumber"];
            string mobilePhoneNumber = collection["txtMobilePhoneNumber"];
            string invoiceName = collection["txtInvoiceName"];
            string invoiceAddress1 = collection["txtInvoiceAddress1"];
            string invoiceAddress2 = collection["txtInvoiceAddress2"];
            string invoicePostCode = collection["txtInvoicePostCode"];
            string invoiceCity = collection["txtInvoiceCity"];
            Int32 invoiceCountryId = Convert.ToInt32(collection["selectInvoiceCountry"]);
            string deliveryName = collection["txtDeliveryName"];
            string deliveryAddress1 = collection["txtDeliveryAddress1"];
            string deliveryAddress2 = collection["txtDeliveryAddress2"];
            string deliveryPostCode = collection["txtDeliveryPostCode"];
            string deliveryCity = collection["txtDeliveryCity"];
            Int32 deliveryCountryId = Convert.ToInt32(collection["selectDeliveryCountry"]);
            Country deliveryCountry = Country.GetOneById(deliveryCountryId, currentDomain.front_end_language);
            DateTime desired_date_of_delivery = DateTime.MinValue;
            DateTime.TryParse(collection["txtDesiredDateOfDelivery"], out desired_date_of_delivery);
            string discount_code_id = collection["hiddenDiscountCodeId"];

            // Set values depending of the customer type, 0: Company
            if(customerType == 0)
            {
                vatNumber = collection["txtVatNumber"];    
            }

            // Create the customer
            Customer customer = new Customer();
            customer.id = customerId;
            customer.email = email.Length > 100 ? email.Substring(0, 100) : email;
            customer.customer_type = customerType;
            customer.org_number = orgNumber.Length > 20 ? orgNumber.Substring(0, 20) : orgNumber;
            customer.vat_number = vatNumber.Length > 20 ? vatNumber.Substring(0, 20) : vatNumber;
            customer.contact_name = contactName.Length > 100 ? contactName.Substring(0, 100) : contactName;
            customer.phone_number = phoneNumber.Length > 100 ? phoneNumber.Substring(0, 100) : phoneNumber;
            customer.mobile_phone_number = mobilePhoneNumber.Length > 100 ? mobilePhoneNumber.Substring(0, 100) : mobilePhoneNumber;
            customer.invoice_name = invoiceName.Length > 100 ? invoiceName.Substring(0, 100) : invoiceName;
            customer.invoice_address_1 = invoiceAddress1.Length > 100 ? invoiceAddress1.Substring(0, 100) : invoiceAddress1;
            customer.invoice_address_2 = invoiceAddress2.Length > 100 ? invoiceAddress2.Substring(0, 100) : invoiceAddress2;
            customer.invoice_post_code = invoicePostCode.Length > 100 ? invoicePostCode.Substring(0, 100) : invoicePostCode;
            customer.invoice_city = invoiceCity.Length > 100 ? invoiceCity.Substring(0, 100) : invoiceCity;
            customer.invoice_country = invoiceCountryId;
            customer.delivery_name = deliveryName.Length > 100 ? deliveryName.Substring(0, 100) : deliveryName;
            customer.delivery_address_1 = deliveryAddress1.Length > 100 ? deliveryAddress1.Substring(0, 100) : deliveryAddress1;
            customer.delivery_address_2 = deliveryAddress2.Length > 100 ? deliveryAddress2.Substring(0, 100) : deliveryAddress2;
            customer.delivery_post_code = deliveryPostCode.Length > 100 ? deliveryPostCode.Substring(0, 100) : deliveryPostCode;
            customer.delivery_city = deliveryCity.Length > 100 ? deliveryCity.Substring(0, 100) : deliveryCity;
            customer.delivery_country = deliveryCountryId;

            // Create the order
            Order order = new Order();
            order.document_type = document_type;
            order.customer_id = customer.id;
            order.order_date = DateTime.UtcNow;
            order.company_id = currentDomain.company_id;
            order.country_code = currentLanguage.country_code;
            order.language_code = currentLanguage.language_code;
            order.currency_code = currency.currency_code;
            order.conversion_rate = (currency.conversion_rate / currency.currency_base);
            order.customer_type = customer.customer_type;
            order.customer_org_number = customer.org_number;
            order.customer_vat_number = customer.vat_number;
            order.customer_name = customer.contact_name;
            order.customer_email = customer.email;
            order.customer_phone = customer.phone_number;
            order.customer_mobile_phone = customer.mobile_phone_number;
            order.invoice_name = customer.invoice_name;
            order.invoice_address_1 = customer.invoice_address_1;
            order.invoice_address_2 = customer.invoice_address_2;
            order.invoice_post_code = customer.invoice_post_code;
            order.invoice_city = customer.invoice_city;
            order.invoice_country_id = invoiceCountryId;
            order.delivery_name = customer.delivery_name;
            order.delivery_address_1 = customer.delivery_address_1;
            order.delivery_address_2 = customer.delivery_address_2;
            order.delivery_post_code = customer.delivery_post_code;
            order.delivery_city = customer.delivery_city;
            order.delivery_country_id = deliveryCountryId;
            order.vat_code = vatCode;
            order.payment_option = paymentOptionId;
            order.payment_status = "payment_status_pending";
            order.exported_to_erp = false;
            order.order_status = "order_status_pending";
            order.desired_date_of_delivery = AnnytabDataValidation.TruncateDateTime(desired_date_of_delivery);
            order.discount_code = discount_code_id;

            // Calculate the decimal multiplier
            Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals);

            // Get the cart items
            List<CartItem> cartItems = CartItem.GetCartItems(currentDomain.front_end_language);
            Dictionary<string, decimal> cartAmounts = CartItem.GetCartAmounts(cartItems, currentDomain.front_end_language, vatCode, decimalMultiplier);

            // Create order rows
            List<OrderRow> orderRows = CartItem.GetOrderRows(cartItems, order.vat_code, currentDomain.front_end_language, decimalMultiplier);

            // Get additional services
            List<AdditionalService> additionalServices = AdditionalService.GetAllActive(currentDomain.front_end_language, "id", "ASC");
            Int32 additionalServiceIdsCount = additionalServiceIds != null ? additionalServiceIds.Length : 0;

            // Loop additional services
            for(int i = 0; i < additionalServices.Count; i++)
            {
                // Check if the service is selected
                for (int j = 0; j < additionalServiceIdsCount; j++)
                {
                    // Convert the id
                    Int32 serviceId = Convert.ToInt32(additionalServiceIds[j]);

                    // The service is selected
                    if(additionalServices[i].id == serviceId)
                    {
                        // Set the service as selected
                        additionalServices[i].selected = true;

                        // Calculate the fee
                        decimal fee = additionalServices[i].price_based_on_mount_time == true ? additionalServices[i].fee * cartAmounts["total_mount_time"] : additionalServices[i].fee;
                        fee *= (currency.currency_base / currency.conversion_rate);
                        fee = Math.Round(fee * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

                        // Get the value added tax percent
                        ValueAddedTax vat = ValueAddedTax.GetOneById(additionalServices[i].value_added_tax_id);

                        // Create a order row
                        OrderRow orderRow = new OrderRow();
                        orderRow.product_code = additionalServices[i].product_code;
                        orderRow.manufacturer_code = "";
                        orderRow.product_id = 0;
                        orderRow.product_name = additionalServices[i].name;
                        orderRow.vat_percent = order.vat_code != 0 ? 0 : vat.value;
                        orderRow.quantity = 1;
                        orderRow.unit_id = additionalServices[i].unit_id;
                        orderRow.unit_price = fee;
                        orderRow.account_code = additionalServices[i].account_code;
                        orderRow.supplier_erp_id = "";
                        orderRow.sort_order = (Int16)orderRows.Count();

                        // Add the order row
                        orderRows.Add(orderRow);
                    }
                }
            }

            // Get the payment fee
            PaymentOption paymentOption = PaymentOption.GetOneById(order.payment_option, currentDomain.front_end_language);
            paymentOption = paymentOption != null ? paymentOption : new PaymentOption();

            if (paymentOption.fee > 0)
            {
                // Get the value added tax percent
                ValueAddedTax vat = ValueAddedTax.GetOneById(paymentOption.value_added_tax_id);

                // Calculate the fee
                decimal fee = paymentOption.fee * (currency.currency_base / currency.conversion_rate);
                fee = Math.Round(fee * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

                // Create a order row
                OrderRow orderRow = new OrderRow();
                orderRow.product_code = paymentOption.product_code;
                orderRow.manufacturer_code = "";
                orderRow.product_id = 0;
                orderRow.product_name = paymentOption.name;
                orderRow.vat_percent = order.vat_code != 0 ? 0 : vat.value;
                orderRow.quantity = 1;
                orderRow.unit_id = paymentOption.unit_id;
                orderRow.unit_price = fee;
                orderRow.account_code = paymentOption.account_code;
                orderRow.supplier_erp_id = "";
                orderRow.sort_order = (Int16)orderRows.Count();

                // Add the order row
                orderRows.Add(orderRow);
            }

            // Get translated texts
            KeyStringList translatedTexts = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

            // Create a error message
            string errorMessage = string.Empty;

            // Check for errors
            if (AnnytabDataValidation.IsEmailAddressValid(customer.email) == null)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_email_valid") + "<br/>";
            }
            if(cartItems.Count <= 0)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_cart_empty") + "<br/>";
            }
            if (order.payment_option == 0)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_no_payment_option") + "<br/>";
            }
            if(order.invoice_country_id == 0)
            {
                errorMessage += "&#149; " + String.Format(translatedTexts.Get("error_select_value"), translatedTexts.Get("invoice_address") + ":" + translatedTexts.Get("country").ToLower()) + "<br/>";
            }
            if (order.delivery_country_id == 0)
            {
                errorMessage += "&#149; " + String.Format(translatedTexts.Get("error_select_value"), translatedTexts.Get("delivery_address") + ":" + translatedTexts.Get("country").ToLower()) + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == "")
            {
                // Get the order sums and add them to the order
                Dictionary<string, decimal> orderAmounts = Order.GetOrderAmounts(orderRows, order.vat_code, decimalMultiplier);

                // Add the sums to the order
                order.net_sum = orderAmounts["net_amount"];
                order.vat_sum = orderAmounts["vat_amount"];
                order.rounding_sum = orderAmounts["rounding_amount"];
                order.total_sum = orderAmounts["total_amount"];

                // Add the order
                Int64 insertId = Order.Add(order);
                order.id = Convert.ToInt32(insertId);

                // Update the gift cards amount for the order
                if(order.document_type != 0)
                {
                    order.gift_cards_amount = ProcessGiftCards(order.id, order.total_sum);
                    Order.UpdateGiftCardsAmount(order.id, order.gift_cards_amount);
                }
                
                // Add the order rows
                for (int i = 0; i < orderRows.Count; i++)
                {
                    orderRows[i].order_id = order.id;
                    OrderRow.Add(orderRows[i]);
                }

                // Delete the shopping cart
                CartItem.ClearShoppingCart();

                // Get the confirmation message
                string message = RenderOrderConfirmationView(order.id, this.ControllerContext);

                // Create a session to indicate that ecommerce data should be sent to google
                Session["SendToGoogleEcommerce"] = true;

                // Check if the user wants to send a request
                if (order.document_type == 0)
                {
                    // Send the request email
                    Tools.SendOrderConfirmation(customer.email, translatedTexts.Get("request") + " " + order.id.ToString() + " - " + currentDomain.webshop_name, message);
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }

                // Send the order confirmation email
                Tools.SendOrderConfirmation(customer.email, translatedTexts.Get("order_confirmation") + " " + order.id.ToString() + " - " + currentDomain.webshop_name, message);

                // Check if the order has been paid by gift cards
                if (order.total_sum <= order.gift_cards_amount)
                {
                    // Update the order status
                    Order.UpdatePaymentStatus(order.id, "payment_status_paid");

                    // Add customer files
                    CustomerFile.AddCustomerFiles(order);

                    // Return the order confirmation
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }

                // Check the selected payment option
                if(paymentOption.connection == 101)
                {
                    return CreatePaysonPayment(order, orderRows, currentDomain, translatedTexts, "DIRECT");
                }
                if (paymentOption.connection == 102)
                {
                    return CreatePaysonPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 201)
                {
                    return CreatePayPalPayment(order, orderRows, currentDomain, translatedTexts);
                }
                else if (paymentOption.connection == 301)
                {
                    return CreateSveaPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 302)
                {
                    return CreateSveaPayment(order, orderRows, currentDomain, translatedTexts, "CREDITCARD");
                }
                else if (paymentOption.connection == 401)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "CREDITCARD");
                }
                else if (paymentOption.connection == 402)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "DIRECTDEBIT");
                }
                else if (paymentOption.connection == 403)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 404)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "MICROACCOUNT");
                }
                else
                {
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }
            }
            else
            {

                // Create the bread crumb list
                List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2);
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("start_page"), "/"));
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("check_out"), "/order/"));

                // Set form values
                ViewBag.BreadCrumbs = breadCrumbs;
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.CurrentDomain = currentDomain;
                ViewBag.TranslatedTexts = translatedTexts;
                ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
                ViewBag.CurrentCategory = new Category();
                ViewBag.Customer = customer;
                ViewBag.Currency = currency;
                ViewBag.CartItems = cartItems;
                ViewBag.DecimalMultiplier = decimalMultiplier;
                ViewBag.PaymentOptionId = paymentOptionId;
                ViewBag.VatCode = vatCode;
                ViewBag.CartAmounts = cartAmounts;
                ViewBag.PricesIncludesVat = Session["PricesIncludesVat"] != null ? Convert.ToBoolean(Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat;
                ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage);
                ViewBag.DesiredDateOfDelivery = order.desired_date_of_delivery;
                ViewBag.DiscountCodeId = order.discount_code;
                ViewBag.GiftCards = Session["GiftCards"] != null ? (List<GiftCard>)Session["GiftCards"] : new List<GiftCard>(0);

                // Return the index view
                return currentDomain.custom_theme_id == 0 ? View("index") : View("/Views/theme/checkout.cshtml");
            }

        } // End of the index method
Example #37
0
    } // End of the Update method

    #endregion

    #region Get methods

    /// <summary>
    /// Get one order row based on id
    /// </summary>
    /// <param name="orderId">A order row id</param>
    /// <param name="productCode">A product code</param>
    /// <returns>A reference to a order row post</returns>
    public static OrderRow GetOneById(Int32 orderId, string productCode)
    {
        // Create the post to return
        OrderRow post = null;

        // Create the connection and the sql statement
        string connection = Tools.GetConnectionString();
        string sql = "SELECT * FROM dbo.order_rows WHERE order_id = @order_id AND " 
            + "product_code = @product_code;";

        // The using block is used to call dispose automatically even if there is a exception
        using (SqlConnection cn = new SqlConnection(connection))
        {
            // The using block is used to call dispose automatically even if there is a exception
            using (SqlCommand cmd = new SqlCommand(sql, cn))
            {
                // Add parameters
                cmd.Parameters.AddWithValue("@order_id", orderId);
                cmd.Parameters.AddWithValue("@product_code", productCode);

                // Create a reader
                SqlDataReader reader = null;

                // The Try/Catch/Finally statement is used to handle unusual exceptions in the code to
                // avoid having our application crash in such cases
                try
                {
                    // Open the connection.
                    cn.Open();

                    // Fill the reader with one row of data.
                    reader = cmd.ExecuteReader();

                    // Loop through the reader as long as there is something to read and add values
                    while (reader.Read())
                    {
                        post = new OrderRow(reader);
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    // Call Close when done reading to avoid memory leakage.
                    if (reader != null)
                        reader.Close();
                }
            }
        }

        // Return the post
        return post;

    } // End of the GetOneById method
Example #38
0
    } // End of the GetCartAmounts method

    /// <summary>
    /// Get a list of order rows
    /// </summary>
    /// <param name="cartItems">A list of cart items</param>
    /// <param name="vatCode">The current vat code</param>
    /// <param name="languageId">A language id</param>
    /// <param name="decimalMultiplier">A decimal multiplier</param>
    /// <returns>A list with order rows</returns>
    public static List<OrderRow> GetOrderRows(List<CartItem> cartItems, byte vatCode, Int32 languageId, Int32 decimalMultiplier)
    {
        // Create order rows
        List<OrderRow> orderRows = new List<OrderRow>(10);

        // Loop all the cart items
        Int16 rowCounter = 0;
        for(int i = 0; i < cartItems.Count; i++)
        {
            // Get data
            Product product = Product.GetOneById(cartItems[i].product_id, languageId);

            // Calculate the freight price
            decimal price = Math.Round(cartItems[i].unit_price * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;
            decimal freight = Math.Round(cartItems[i].unit_freight * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;
            decimal priceFreight = price + freight;

            // Create a new order row and add values to it
            OrderRow orderRow = new OrderRow();
            orderRow.product_code = AnnytabDataValidation.TruncateString(cartItems[i].product_code, 50);
            orderRow.manufacturer_code = AnnytabDataValidation.TruncateString(cartItems[i].manufacturer_code, 50);
            orderRow.product_id = product.id;
            orderRow.gtin = product.gtin;
            orderRow.product_name = AnnytabDataValidation.TruncateString(cartItems[i].product_name, 100);
            orderRow.vat_percent = vatCode != 0 ? 0 : cartItems[i].vat_percent;
            orderRow.quantity = AnnytabDataValidation.TruncateDecimal(cartItems[i].quantity, 0, 999999.99M);
            orderRow.unit_id = product.unit_id;
            orderRow.unit_price = AnnytabDataValidation.TruncateDecimal(priceFreight, 0, 9999999999.99M);
            orderRow.account_code = product.account_code;
            orderRow.supplier_erp_id = product.supplier_erp_id;
            orderRow.sort_order = rowCounter;

            // Add to the row counter
            rowCounter += 1;

            // Update product buys
            Product.UpdateBuys(product.id, AnnytabDataValidation.TruncateDecimal(cartItems[i].quantity + product.buys, 0, 9999999999.99M));

            // Add the row to the list
            orderRows.Add(orderRow);

            // Get bundle items
            List<ProductBundle> bundleItems = ProductBundle.GetByBundleProductId(product.id);

            // Add all the bundle items
            for(int j = 0; j < bundleItems.Count; j++)
            {
                // Get the product
                product = Product.GetOneById(bundleItems[j].product_id, languageId);

                // Get the value added tax
                ValueAddedTax valueAddedTax = ValueAddedTax.GetOneById(product.value_added_tax_id);

                // Create a new order row and add values to it
                orderRow = new OrderRow();
                orderRow.product_code = product.product_code;
                orderRow.manufacturer_code = product.manufacturer_code;
                orderRow.product_id = product.id;
                orderRow.gtin = product.gtin;
                orderRow.product_name = product.title;
                orderRow.vat_percent = vatCode != 0 ? 0 : valueAddedTax.value;
                orderRow.quantity = bundleItems[j].quantity;
                orderRow.unit_id = product.unit_id;
                orderRow.unit_price = 0;
                orderRow.account_code = product.account_code;
                orderRow.supplier_erp_id = product.supplier_erp_id;
                orderRow.sort_order = rowCounter;

                // Add to the row counter
                rowCounter += 1;

                // Update product buys
                Product.UpdateBuys(product.id, AnnytabDataValidation.TruncateDecimal(bundleItems[j].quantity + product.buys, 0, 9999999999.99M));

                // Add the row to the list
                orderRows.Add(orderRow);
            }
        }

        // Return the list
        return orderRows;

    } // End of the GetOrderRows method