Esempio n. 1
0
        public ActionResult Delete(int[] ids)
        {
            if (ids == null || !ids.Any())
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            var model = new ShippingZonesDeleteViewModel();

            model.ShippingZones = new List <ShippingZoneDeleteViewModel>();

            foreach (int id in ids)
            {
                ShippingZone shippingZone = shippingZoneService.Find(id);
                if (shippingZone == null)
                {
                    continue;
                }

                model.ShippingZones.Add(new ShippingZoneDeleteViewModel
                {
                    Id   = shippingZone.Id,
                    Name = shippingZone.Name,
                });
            }
            return(View(model));
        }
        public async Task <IActionResult> Create([Bind("Name,Id,CreateDate,CreatedBy,UpdateDate,UpdatedBy,AppTenantId")] ShippingZone shippingZone, long[] zoneRegionId)
        {
            if (ModelState.IsValid)
            {
                _context.Add(shippingZone);
                await _context.SaveChangesAsync();

                var prd = _context.ShippingZones.Include(i => i.ShippingZoneRegions).ThenInclude(t => t.Region).FirstOrDefault(f => f.Id == shippingZone.Id);
                prd.ShippingZoneRegions.Clear();
                await _context.SaveChangesAsync();

                if (zoneRegionId != null)
                {
                    foreach (var k in zoneRegionId)
                    {
                        prd.ShippingZoneRegions.Add(new ShippingZoneRegion()
                        {
                            ShippingZoneId = prd.Id, RegionId = k, AppTenantId = tenant.AppTenantId
                        });
                    }
                }
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(shippingZone));
        }
        public async Task <IActionResult> Edit(long id, [Bind("Name,Id,CreateDate,CreatedBy,UpdateDate,UpdatedBy,AppTenantId")] ShippingZone shippingZone)
        {
            if (id != shippingZone.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(shippingZone);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ShippingZoneExists(shippingZone.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(shippingZone));
        }
        // GET: CmsCore/ShippingZones/Create
        public IActionResult Create()
        {
            var z = new ShippingZone();

            z.CreateDate        = DateTime.Now;
            z.CreatedBy         = User.Identity.Name ?? "username";
            z.UpdateDate        = DateTime.Now;
            z.UpdatedBy         = User.Identity.Name ?? "username";
            z.AppTenantId       = tenant.AppTenantId;
            ViewBag.ZoneRegions = new MultiSelectList(_context.Regions.ToList(), "Id", "Name");
            return(View(z));
        }
Esempio n. 5
0
        public void Delete(int id)
        {
            ShippingZone shippingZone    = Find(id);
            var          shippingMethods = shippingMethodService.FindAll().Where(m => m.ShippingZoneId == id).ToList();

            foreach (var shippingMethod in shippingMethods)
            {
                shippingMethodService.Delete(shippingMethod.Id);
            }

            db.ShippingZones.Remove(shippingZone);
            db.SaveChanges();
        }
Esempio n. 6
0
        public ShippingZone Find(string countryCode, int?regionId)
        {
            // Find zone for country and region (if supplied)
            ShippingZone zone = db.ShippingZones.FirstOrDefault(z =>
                                                                z.IsActive && z.Countries.Any(c => c.Code == countryCode) &&
                                                                ((regionId == null && !z.Regions.Any()) || (z.Regions.Any(r => r.Id == regionId))));

            // Find zone for country (all regions)
            if (zone == null && regionId.HasValue)
            {
                zone = db.ShippingZones.FirstOrDefault(z => z.IsActive && z.Countries.Any(c => c.Code == countryCode));
            }

            // Fine global zone (catchall)
            if (zone == null)
            {
                zone = db.ShippingZones.FirstOrDefault(z => z.IsActive && !z.Countries.Any() && !z.Regions.Any());
            }

            return(zone);
        }
Esempio n. 7
0
        public StandardJsonResult GetShippingMethods(ShoppingCartCheckoutViewModel model)
        {
            var result = new List <ShoppingCartShippingMethodsViewModel>();
            AddressViewModel address = model.SameShippingAddress ? model.BillingAddress : model.ShippingAddress;

            // Find zone for country and region (if supplied)
            ShippingZone zone = shippingService.FindZone(address.CountryCode, address.RegionId);

            if (zone != null)
            {
                List <ShippingMethod> methods = shippingService.FindMethods(zone.Id).ToList();
                foreach (ShippingMethod method in methods)
                {
                    decimal?cost = shippingService.CalculateShipping(method,
                                                                     model.ShoppingCartItems.Sum(i => i.Quantity),
                                                                     model.ShoppingCartItems.Sum(i => i.Quantity * db.Products.Find(i.ProductId).Weight),
                                                                     model.ShoppingCartItems.Sum(i => i.Quantity * i.ItemPrice), Mapper.Map <Address>(address));

                    if (!cost.HasValue)
                    {
                        continue;
                    }

                    var methodView = new ShoppingCartShippingMethodsViewModel
                    {
                        Id     = method.Id,
                        Name   = method.Name,
                        Amount = cost.Value
                    };

                    result.Add(methodView);
                }
            }

            return(JsonSuccess(result.OrderBy(s => s.Amount)));
        }
Esempio n. 8
0
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            ShippingZone shippingZone = shippingZoneService.Find(id.Value);

            if (shippingZone == null)
            {
                return(HttpNotFound());
            }
            var model = Mapper.Map <ShippingZoneEditViewModel>(shippingZone);

            string[] countryCodes = shippingZone.Countries.Select(c => c.Code).ToArray();
            model.CountryCodesJson = JsonConvert.SerializeObject(countryCodes);

            int[] regionIds = shippingZone.Regions.Select(r => r.Id).ToArray();
            model.RegionIdsJson = JsonConvert.SerializeObject(regionIds);

            ViewBag.Countries = countryService.FindAll().Where(c => c.IsActive || countryCodes.Contains(c.Code)).ToList();
            return(View(model));
        }
 public IQueryable<State> GetStatesInShippingZone(ShippingZone shippingZone)
 {
     return this._cityData.States.Where(s => s.ShippingZone == shippingZone).AsQueryable<State>();
 }
Esempio n. 10
0
 public IQueryable <State> GetStatesInShippingZone(ShippingZone shippingZone)
 {
     return(this._cityData.States.Where(s => s.ShippingZone == shippingZone).AsQueryable <State>());
 }
Esempio n. 11
0
        protected override void Seed(DAL.DataContext context)
        {
            #region Import translations

            if (context.Translations.None())
            {
                DataImportController.ImportTranslationsCsv(context, new CsvReader(File.OpenText(
                                                                                      HostingEnvironment.MapPath("~/Content/DataInitializer/Translations/Translations.csv"))),
                                                           TranslationArea.Frontend);

                DataImportController.ImportTranslationsCsv(context, new CsvReader(File.OpenText(
                                                                                      HostingEnvironment.MapPath("~/Content/DataInitializer/Translations/TranslationsAdmin.csv"))),
                                                           TranslationArea.Backend);
            }

            Thread.CurrentThread.CurrentUICulture = new CultureInfo(
                WebConfigurationManager.AppSettings["DefaultCulture"]);

            #endregion

            #region Create user roles

            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!roleManager.RoleExists(User.ADMIN_ROLE))
            {
                roleManager.Create(new IdentityRole(User.ADMIN_ROLE));
            }

            if (!roleManager.RoleExists(User.CUSTOMER_ROLE))
            {
                roleManager.Create(new IdentityRole(User.CUSTOMER_ROLE));
            }

            if (!roleManager.RoleExists(User.OPERATOR_ROLE))
            {
                roleManager.Create(new IdentityRole(User.OPERATOR_ROLE));
            }

            #endregion

            #region Create users

            if (context.Users.None())
            {
                var userManager = new UserManager <User>(new UserStore <User>(context));

                // Create admin user
                var admin = new User
                {
                    FirstName   = "Admin",
                    LastName    = "Admin",
                    Company     = "Admin",
                    PhoneNumber = "1-800-ADMIN",
                    UserName    = WebConfigurationManager.AppSettings["DefaultUserEmail"],
                    Email       = WebConfigurationManager.AppSettings["DefaultUserEmail"],
                };
                IdentityResult result = userManager.Create(admin, WebConfigurationManager.AppSettings["DefaultUserPassword"]);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
                userManager.AddToRole(admin.Id, User.ADMIN_ROLE);
            }

            #endregion

            #region Create EmailTemplates

            if (context.EmailTemplates.None())
            {
                var templateTypes = new List <EmailTemplate>
                {
                    new EmailTemplate
                    {
                        Subject = "Order Successful".TA(),
                        Body    = "Your order has been received successfully".TA(),
                        Type    = EmailTemplateType.OrderCompleted
                    }
                };

                templateTypes.ForEach(t => context.EmailTemplates.AddOrUpdate(t));
                context.SaveChanges();
            }

            #endregion

            #region Import countries and states

            if (context.Countries.None())
            {
                string countryJson =
                    File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/Countries.json"));
                dynamic json = JsonConvert.DeserializeObject(countryJson);

                foreach (dynamic item in json)
                {
                    var country = new Country {
                        Code = item.code, Name = item.name, IsActive = true
                    };
                    context.Countries.Add(country);

                    if (item.filename != null)
                    {
                        dynamic regionJson =
                            File.ReadAllText(
                                HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/" + item.filename +
                                                           ".json"));
                        dynamic json2 = JsonConvert.DeserializeObject(regionJson);
                        foreach (dynamic item2 in json2)
                        {
                            var region = new Region {
                                Country = country, Code = item2.code, Name = item2.name
                            };
                            context.Regions.Add(region);
                        }
                    }
                }

                context.SaveChanges();
            }

            #endregion

            #region Create default shipping and tax zones

            if (context.TaxZones.None())
            {
                var taxZone = new TaxZone {
                    Name = "Default".TA(), IsActive = true
                };
                context.TaxZones.Add(taxZone);
            }

            if (context.ShippingZones.None())
            {
                var shippingZone = new ShippingZone {
                    Name = "Default".TA(), IsActive = true
                };
                context.ShippingZones.Add(shippingZone);
            }

            #endregion

            #region Create default content pages

            if (context.ContentPages.None())
            {
                var page = new ContentPage
                {
                    Title   = "About Us".TA(),
                    Content =
                        "Edit this page contents from the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 1,
                    FooterPosition = 1
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Contact Us".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 2,
                    FooterPosition = 2
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Terms & Conditions".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 3,
                    FooterPosition = 3
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Privacy Policy".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 4,
                    FooterPosition = 4
                };
                context.ContentPages.Add(page);
                page = new ContentPage
                {
                    Title   = "Orders and Returns".TA(),
                    Content =
                        "Edit this page contents form the \"Edit Content Pages\" section in the admin tool".TA(),
                    HeaderPosition = 5,
                    FooterPosition = 5
                };
                context.ContentPages.Add(page);
                context.SaveChanges();
            }

            #endregion

            #region Create default news blog

            if (context.Blogs.None())
            {
                User admin = context.Users.OrderByDescending(u => u.DateRegistered).FirstOrDefault();

                var blog = new Blog
                {
                    Title = "News".T()
                };
                context.Blogs.Add(blog);

                if (admin != null)
                {
                    var blogPost = new BlogPost
                    {
                        UserId  = admin.Id,
                        Blog    = blog,
                        Title   = "Store created".T(),
                        Content = "You can use the blog functionality to post updates for your users...".T()
                    };
                    context.BlogPosts.Add(blogPost);
                }

                context.SaveChanges();
            }

            #endregion

            #region Payment methods

            if (context.PaymentMethods.None())
            {
                var paymentMethods = new List <PaymentMethod>
                {
                    new PaymentMethod
                    {
                        Name     = "Bank Deposit".TA(),
                        Settings =
                            "Bank Name: ACME Bank\nBank Branch: New York\nAccount Name: John Smith\nAccount Number: XXXXXXXXXXX\n\nType any special instructions in here.",
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Cash on Delivery".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "Check".TA(),
                        Countries =
                            new Collection <Country>(
                                context.Countries.Where(c => c.Code == "US").ToArray()),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Money Order".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name     = "Pay in Store".TA(),
                        Type     = PaymentMethodType.Manual,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "ePay.bg".TA(),
                        ClassName = "EPayBgButton",
                        Countries =
                            new Collection <Country>(
                                context.Countries.Where(c => c.Code == "BG").ToArray()),
                        Type     = PaymentMethodType.Hosted,
                        IsActive = true
                    },
                    new PaymentMethod
                    {
                        Name      = "Paypal Website Payments (Standard)".TA(),
                        ClassName = "PayPalStandard",
                        Type      = PaymentMethodType.Hosted,
                        IsActive  = true
                    },
                };
                paymentMethods.ForEach(c => context.PaymentMethods.AddOrUpdate(c));
                context.SaveChanges();
            }

            #endregion
        }
Esempio n. 12
0
        protected override void Seed(DataContext context)
        {
            #region Delete old photos

            foreach (var file in Directory.GetFiles(HostingEnvironment.MapPath("~/Storage/"), "*.*"))
            {
                if (file.Contains("web.config"))
                {
                    continue;
                }
                File.Delete(file);
            }

            #endregion

            #region Import countries and states

            string countryJson =
                File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/Countries.json"));
            dynamic json = JsonConvert.DeserializeObject(countryJson);

            foreach (dynamic item in json)
            {
                var country = new Country {
                    Code = item.code, Name = item.name
                };
                country.IsActive = country.Code == "US" || country.Code == "BG";
                context.Countries.Add(country);

                if (item.filename != null)
                {
                    dynamic regionJson =
                        File.ReadAllText(
                            HostingEnvironment.MapPath("~/Content/DataInitializer/Regional/" + item.filename + ".json"));
                    dynamic json2 = JsonConvert.DeserializeObject(regionJson);
                    foreach (dynamic item2 in json2)
                    {
                        var region = new Region {
                            Country = country, Code = item2.code, Name = item2.name
                        };
                        context.Regions.Add(region);
                    }
                }
            }

            try
            {
                context.SaveChanges();
            }
            catch (Exception err)
            {
                throw err;
            }

            #endregion

            #region Import taxes

            string vatJson =
                File.ReadAllText(HostingEnvironment.MapPath("~/Content/DataInitializer/TaxRates/vat.json"));
            dynamic vats = JsonConvert.DeserializeObject(vatJson);

            foreach (dynamic vat in vats)
            {
                var     countryCode = (string)vat.countryCode;
                Country country     = context.Countries.First(c => c.Code == countryCode);
                var     taxZone     = new TaxZone
                {
                    Name      = country.Name,
                    IsActive  = true,
                    Countries = new Collection <Country> {
                        country
                    }
                };

                var taxRate = new TaxRate
                {
                    Name     = "VAT",
                    TaxZone  = taxZone,
                    Amount   = vat.percentage,
                    IsActive = true
                };

                context.TaxZones.Add(taxZone);
                context.TaxRates.Add(taxRate);
            }

            var calTaxZone = new TaxZone
            {
                Name      = "California Tax",
                Countries = new Collection <Country> {
                    context.Countries.First(c => c.Code == "US")
                },
                Regions = new Collection <Region> {
                    context.Regions.First(r => r.Name == "California")
                },
                IsActive = true
            };
            var calTaxRate = new TaxRate
            {
                Name     = "Sales Tax",
                TaxZone  = calTaxZone,
                Amount   = 7.5m,
                IsActive = true
            };

            context.TaxZones.Add(calTaxZone);
            context.TaxRates.Add(calTaxRate);

            context.SaveChanges();

            #endregion

            #region Create shipping options

            var defShipZone = new ShippingZone
            {
                Name     = "Default",
                IsActive = true
            };
            context.ShippingZones.Add(defShipZone);

            var worldWideShippingUPS = new ShippingMethod
            {
                ShippingZone   = defShipZone,
                Name           = "UPS Worldwide",
                Type           = ShippingMethodType.Flat,
                FlatRateAmount = 500
            };
            context.ShippingMethods.Add(worldWideShippingUPS);

            var bgShipZone = new ShippingZone
            {
                Name      = "Bulgaria",
                Countries = new Collection <Country> {
                    context.Countries.First(c => c.Code == "BG")
                },
                IsActive = true
            };
            context.ShippingZones.Add(bgShipZone);

            var freeBgShipping = new ShippingMethod
            {
                ShippingZone         = bgShipZone,
                Name                 = "Free shipping",
                Type                 = ShippingMethodType.Free,
                FreeShippingMinTotal = 2000
            };
            var econtShipping = new ShippingMethod
            {
                ShippingZone   = bgShipZone,
                Name           = "Econt",
                Type           = ShippingMethodType.Flat,
                FlatRateAmount = 10
            };
            context.ShippingMethods.Add(econtShipping);
            context.ShippingMethods.Add(freeBgShipping);

            context.SaveChanges();

            #endregion

            #region Payment methods

            var paymentMethods = new List <PaymentMethod>
            {
                new PaymentMethod
                {
                    Name     = "Bank Deposit",
                    Settings =
                        "Bank Name: ACME Bank\nBank Branch: New York\nAccount Name: John Smith\nAccount Number: XXXXXXXXXXX\n\nType any special instructions in here.",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Cash on Delivery",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "Check",
                    Countries =
                        new Collection <Country>(
                            context.Countries.Where(c => c.Code == "US").ToArray()),
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Money Order",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name     = "Pay in Store",
                    Type     = PaymentMethodType.Manual,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "ePay.bg",
                    ClassName = "EPayBgButton",
                    Countries =
                        new Collection <Country>(
                            context.Countries.Where(c => c.Code == "BG").ToArray()),
                    Type     = PaymentMethodType.Hosted,
                    IsActive = true
                },
                new PaymentMethod
                {
                    Name      = "Paypal Website Payments (Standard)",
                    ClassName = "PayPalStandard",
                    Type      = PaymentMethodType.Hosted,
                    IsActive  = true
                },
            };
            paymentMethods.ForEach(c => context.PaymentMethods.AddOrUpdate(c));
            context.SaveChanges();

            #endregion

            #region Create users

            var userManager = new UserManager <User>(new UserStore <User>(context));
            var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            // Create admin role
            roleManager.Create(new IdentityRole(User.ADMIN_ROLE));
            roleManager.Create(new IdentityRole(User.CUSTOMER_ROLE));

            // Create admin user
            var admin = new User
            {
                FirstName   = "Admin",
                LastName    = "Adminov",
                Company     = "Admin Inc",
                PhoneNumber = "1-800-ADMIN",
                UserName    = "******",
                Email       = "*****@*****.**",
            };
            IdentityResult result = userManager.Create(admin, "123pass");
            if (!result.Succeeded)
            {
                throw new Exception(string.Join("\n", result.Errors));
            }
            userManager.AddToRole(admin.Id, User.ADMIN_ROLE);

            // Create regular user
            var user = new User
            {
                FirstName   = "Tester",
                LastName    = "Testerov",
                Company     = "Test Ltd",
                PhoneNumber = "1-800-USER",
                UserName    = "******",
                Email       = "*****@*****.**"
            };
            userManager.Create(user, "123pass");
            userManager.AddToRole(user.Id, User.CUSTOMER_ROLE);

            #endregion

            #region Create EmailTemplates

            var templateTypes = new List <EmailTemplate>
            {
                new EmailTemplate
                {
                    Subject = "Order Successful",
                    Body    = "Your order has been received successfully",
                    Type    = EmailTemplateType.OrderCompleted
                }
            };

            templateTypes.ForEach(t => context.EmailTemplates.AddOrUpdate(t));
            context.SaveChanges();

            #endregion

            context.SaveChanges();

            // Temporary until better solution is added to EF Code First
            context.Database.ExecuteSqlCommand("DBCC CHECKIDENT ('Orders', RESEED, 101)");

            base.Seed(context);
        }
Esempio n. 13
0
 public ShippingZone InsertShippingZone(ShippingZone entity)
 {
     return(_iShippingZoneRepository.InsertShippingZone(entity));
 }
Esempio n. 14
0
 public ShippingZone UpdateShippingZone(ShippingZone entity)
 {
     return(_iShippingZoneRepository.UpdateShippingZone(entity));
 }
Esempio n. 15
0
 /// <summary>
 /// Gets an EntityQuery instance that can be used to load <see cref="State"/> entity instances using the 'GetStatesInShippingZone' query.
 /// </summary>
 /// <param name="shippingZone">The value for the 'shippingZone' parameter of the query.</param>
 /// <returns>An EntityQuery that can be loaded to retrieve <see cref="State"/> entity instances.</returns>
 public EntityQuery<State> GetStatesInShippingZoneQuery(ShippingZone shippingZone)
 {
     Dictionary<string, object> parameters = new Dictionary<string, object>();
     parameters.Add("shippingZone", shippingZone);
     this.ValidateMethod("GetStatesInShippingZoneQuery", parameters);
     return base.CreateQuery<State>("GetStatesInShippingZone", parameters, false, true);
 }
Esempio n. 16
0
 partial void OnShippingZoneChanging(ShippingZone value);