Esempio n. 1
0
        public ActionResult Create()
        {
            var model = new CustomerViewModel();

            ViewBag.Countries = db.Countries.Where(c => c.IsActive).OrderBy(c => c.Name).ToList();

            return View(model);
        }
Esempio n. 2
0
        public ActionResult Create(CustomerViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    customerService.AddOrUpdate(model);
                    return RedirectToAction("Index")
                        .WithSuccess(string.Format("Customer \"{0} {1}\" has been added".TA(), model.BillingAddress.FirstName,
                            model.BillingAddress.LastName));
                }
                catch (ArgumentException err)
                {
                    ModelState.AddModelError(err.ParamName ?? "", err.Message);
                }
            }

            ViewBag.Countries = db.Countries.Where(c => c.IsActive).OrderBy(c => c.Name).ToList();

            return View(model);
        }
Esempio n. 3
0
        public User AddOrUpdate(CustomerViewModel model)
        {
            User user;
            if (!string.IsNullOrEmpty(model.Id))
            {
                user = Find(model.Id);
                user.Email = model.Email;
                if (!string.IsNullOrEmpty(model.NewPassword))
                {
                    var passwordHash = userManager.PasswordHasher.HashPassword(model.NewPassword);
                    user.PasswordHash = passwordHash;
                }
            }
            else
            {
                user = Mapper.Map<User>(model);
            }

            if (model.BillingAddress != null)
            {
                Address billingAddress;
                if (model.BillingAddress.Id == 0)
                {
                    billingAddress = Mapper.Map<Address>(model.BillingAddress);
                    user.Addresses.Add(billingAddress);
                }
                else
                {
                    billingAddress = db.Addresses.Find(model.BillingAddress.Id);
                    billingAddress = Mapper.Map(model.BillingAddress, billingAddress);
                }
                billingAddress.IsPrimary = true;
                billingAddress.Type = AddressType.Billing;

                // Copy basic details from billing address to the user entity
                if (!string.IsNullOrEmpty(billingAddress.FirstName))
                    user.FirstName = billingAddress.FirstName;
                if (!string.IsNullOrEmpty(billingAddress.LastName))
                    user.LastName = billingAddress.LastName;
                if (!string.IsNullOrEmpty(billingAddress.Company))
                    user.Company = billingAddress.Company;
                if (!string.IsNullOrEmpty(billingAddress.Phone))
                    user.PhoneNumber = billingAddress.Phone;
            }

            if (model.ShippingAddress != null)
            {
                if (model.ShippingAddress == model.BillingAddress)
                    model.ShippingAddress.Id = 0;

                Address shippingAddress;
                if (model.ShippingAddress.Id == 0)
                {
                    shippingAddress = Mapper.Map<Address>(model.ShippingAddress);
                    user.Addresses.Add(shippingAddress);
                }
                else
                {
                    shippingAddress = db.Addresses.Find(model.ShippingAddress.Id);
                    shippingAddress = Mapper.Map(model.ShippingAddress, shippingAddress);
                }
                shippingAddress.IsPrimary = true;
                shippingAddress.Type = AddressType.Shipping;
            }

            if (string.IsNullOrEmpty(model.Id))
            {
                // Generate random password for new user if one is not specified
                if (string.IsNullOrEmpty(model.NewPassword))
                    model.NewPassword = Guid.NewGuid().ToString();

                IdentityResult result = userManager.Create(user, model.NewPassword);
                if (result.Succeeded)
                {
                    userManager.AddToRole(user.Id, User.CUSTOMER_ROLE);
                }

                foreach (string error in result.Errors)
                {
                    throw new ArgumentException(error);
                }
            }

            db.SaveChanges();

            return user;
        }
        public ActionResult Checkout(ShoppingCartCheckoutViewModel model)
        {
            if (!ModelState.IsValid)
                return JsonValidationError();

            // Get cart contents
            ShoppingCart cart = GetOrCreateCart();
            if (!cart.ShoppingCartItems.Any())
            {
                return JsonError("Your shopping cart is empty!");
            }

            // Check quantity
            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product product = db.Products.Find(cartItem.ProductId);
                int? qty = null;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Quantity.HasValue)
                    qty = cartItem.ProductSku.Quantity.Value;
                if (qty == null && product.Quantity.HasValue)
                    qty = product.Quantity.Value;
                if (qty.HasValue && qty < cartItem.Quantity)
                {
                    return JsonError(string.Format("The requested quantity for \"{0}\" is not available", product.Name));
                }
            }

            // Get current user (or create a new one)
            User user = null;
            if (User.Identity.IsAuthenticated)
            {
                user = customerService.Find(currentUser.User.Id);
            }
            if (user == null)
            {
                var userModel = new CustomerViewModel
                                {
                                    FirstName = model.BillingAddress.FirstName,
                                    LastName = model.BillingAddress.LastName,
                                    Company = model.BillingAddress.Company,
                                    PhoneNumber = model.BillingAddress.Phone,
                                    Email = model.Email
                                };
                try
                {
                    user = customerService.AddOrUpdate(userModel);
                }
                catch (ArgumentException err)
                {
                    return JsonError(err.Message);
                }

                customerService.LoginUser(HttpContext, user);
            }
            
            // Get addresses
            var billingAddress = Mapper.Map<Address>(model.BillingAddress);
            billingAddress.Type = AddressType.Billing;

            var shippingAddress = Mapper.Map<Address>(model.SameShippingAddress
                ? model.BillingAddress
                : model.ShippingAddress);
            shippingAddress.Type = AddressType.Shipping;

            var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing);
            if (defaultBillingAddress == null)
            {
                // Add default billing address
                defaultBillingAddress = Mapper.Map<Address>(model.BillingAddress);
                defaultBillingAddress.Type = AddressType.Billing;
                defaultBillingAddress.IsPrimary = true;
                user.Addresses.Add(defaultBillingAddress);
            }

            var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping);
            if (defaultShippingAddress == null)
            {
                // Add default shipping address
                defaultShippingAddress = Mapper.Map<Address>(model.SameShippingAddress
                    ? model.BillingAddress
                    : model.ShippingAddress);
                defaultShippingAddress.Type = AddressType.Shipping;
                defaultShippingAddress.IsPrimary = true;
                user.Addresses.Add(defaultShippingAddress);
            }

            db.SaveChanges();

            // Create order
            var order = new Order
                        {
                            UserId = user.Id,
                            BillingAddress = billingAddress,
                            ShippingAddress = shippingAddress,
                            DatePlaced = DateTime.Now,
                            DateUpdated = DateTime.Now,
                            IPAddress = Request.UserHostAddress,
                            UserComments = model.UserComments,
                            Status = OrderStatus.AwaitingPayment
                        };

            db.Orders.Add(order);

            TaxZone taxZone = taxZoneService.Find(billingAddress.CountryCode, billingAddress.RegionId);

            foreach (ShoppingCartItem cartItem in cart.ShoppingCartItems)
            {
                Product product = db.Products.Find(cartItem.ProductId);
                ProductSku productSku = cartItem.ProductSku;

                if (productSku != null && productSku.Quantity.HasValue)
                {
                    productSkuService.RemoveQuantity(productSku.Id, cartItem.Quantity);
                }
                else if (product.Quantity.HasValue)
                {
                    productService.RemoveQuantity(product.Id, cartItem.Quantity);
                }
                
                decimal price = product.SalePrice ?? product.Price;
                if (cartItem.ProductSkuId.HasValue && cartItem.ProductSku.Price.HasValue)
                    price = cartItem.ProductSku.Price.Value;

                var cartItemOptions = JsonConvert.DeserializeObject<ShoppingCartItemOptionViewModel[]>(cartItem.Options);
                var orderItemOptions = Mapper.Map<OrderItemOption[]>(cartItemOptions);

                var orderItem = new OrderItem
                                {
                                    Order = order,
                                    ProductId = product.Id,
                                    ProductSkuId = cartItem.ProductSkuId,
                                    Quantity = cartItem.Quantity,
                                    Options = JsonConvert.SerializeObject(orderItemOptions),
                                    ItemPrice = price
                                };

                db.OrderItems.Add(orderItem);

                order.Subtotal += cartItem.Quantity * price;

                if (taxZone != null)
                    order.TaxAmount += taxRateService.CalculateTax(taxZone.Id, product.TaxClassId, price * cartItem.Quantity);
            }

            ShippingMethod shippingMethod = db.ShippingMethods.Find(model.ShippingMethodId);
            order.ShippingAmount = shippingService.CalculateShipping(shippingMethod,
                cart.ShoppingCartItems.Sum(i => i.Quantity),
                cart.ShoppingCartItems.Sum(i => i.Quantity*i.Product.Weight),
                order.Subtotal, shippingAddress).GetValueOrDefault();

            order.Total = order.Subtotal + order.ShippingAmount;
            if (!settings.Get<bool>(SettingField.TaxIncludedInPrices))
                order.Total += order.TaxAmount;

            db.SaveChanges();

            return JsonSuccess(new {orderId = order.Id, paymentMethodId = model.PaymentMethodId});
        }
Esempio n. 5
0
        public ActionResult Create(OrderEditViewModel model)
        {
            if (!ModelState.IsValid)
                return JsonValidationError();

            var user = customerService.FindAll().FirstOrDefault(u => u.Email == model.UserEmail);
            if (user == null)
            {
                var userModel = new CustomerViewModel
                                {
                                    FirstName = model.BillingAddress.FirstName,
                                    LastName = model.BillingAddress.LastName,
                                    Company = model.BillingAddress.Company,
                                    PhoneNumber = model.BillingAddress.Phone,
                                    Email = model.UserEmail
                                };
                try
                {
                    user = customerService.AddOrUpdate(userModel);
                }
                catch (ArgumentException err)
                {
                    return JsonError(err.Message);
                }
            }

            // Get addresses
            var billingAddress = Mapper.Map<Address>(model.BillingAddress);
            billingAddress.Type = AddressType.Billing;

            var shippingAddress = Mapper.Map<Address>(model.SameShippingAddress
                ? model.BillingAddress
                : model.ShippingAddress);
            shippingAddress.Type = AddressType.Shipping;

            var defaultBillingAddress = customerService.GetAddress(user.Id, AddressType.Billing);
            if (defaultBillingAddress == null || defaultBillingAddress.FirstName == null)
            {
                // Add default billing address
                defaultBillingAddress = Mapper.Map<Address>(model.BillingAddress);
                defaultBillingAddress.Type = AddressType.Billing;
                defaultBillingAddress.IsPrimary = true;
                if (defaultBillingAddress.Id == 0)
                    user.Addresses.Add(defaultBillingAddress);
            }

            var defaultShippingAddress = customerService.GetAddress(user.Id, AddressType.Shipping);
            if (defaultShippingAddress == null || defaultBillingAddress.FirstName == null)
            {
                // Add default shipping address
                defaultShippingAddress = Mapper.Map<Address>(model.SameShippingAddress
                    ? model.BillingAddress
                    : model.ShippingAddress);
                defaultShippingAddress.Type = AddressType.Shipping;
                defaultShippingAddress.IsPrimary = true;
                if (defaultShippingAddress.Id == 0)
                    user.Addresses.Add(defaultShippingAddress);
            }

            db.SaveChanges();

            // Create order
            var order = new Order
                        {
                            UserId = user.Id,
                            BillingAddress = billingAddress,
                            ShippingAddress = shippingAddress,
                            DatePlaced = DateTime.Now,
                            DateUpdated = DateTime.Now,
                            IPAddress = Request.UserHostAddress,
                            UserComments = model.UserComments,
                            Status = OrderStatus.AwaitingPayment,
                            Discount = model.Discount,
                            ShippingAmount = model.ShippingAmount,
                        };

            db.Orders.Add(order);

            var itemDiscount = 0m;
            if (model.Discount < 0)
            {
                itemDiscount = model.Discount / model.Items.Count;
            }

            foreach (var item in model.Items)
            {
                Product product = productFinder.Find(item.ProductId);

                var orderItem = new OrderItem
                                {
                                    Order = order,
                                    ProductId = item.ProductId,
                                    ProductSkuId = item.ProductSkuId,
                                    Quantity = item.Quantity,
                                    Options = item.Options,
                                    ItemPrice = item.ItemPrice
                                };

                db.OrderItems.Add(orderItem);

                order.Subtotal += orderItem.Quantity * orderItem.ItemPrice;

                order.TaxAmount += taxService.CalculateTax(billingAddress.CountryCode, billingAddress.RegionId,
                    product.TaxClassId, (orderItem.ItemPrice + itemDiscount) * orderItem.Quantity);
            }

            order.Total = order.Subtotal + order.Discount + order.ShippingAmount;
            if (!settingService.Get<bool>(SettingField.TaxIncludedInPrices))
                order.Total += order.TaxAmount;

            db.SaveChanges();

            return JsonSuccess(new { orderId = order.Id })
                .WithSuccess("Order created successfully".TA());
        }