public Supermarket Provide(IReadOnlyCollection <ProductSpecification> productSpecifications, int cashboxesCount)
        {
            if (productSpecifications == null)
            {
                throw new ArgumentNullException(nameof(productSpecifications));
            }

            var result = new Supermarket();

            var index = 0;

            foreach (var spec in productSpecifications)
            {
                result.AddToAssortment(spec);
                var shelf = result.CreateShelf(spec, $"Полка_{index + 1}");
                shelf.ProductTaked += EventPrinter.PrintProductTaked;

                for (int i = 0; i < 5000; i++)
                {
                    result.AddToShelf(shelf.Id, new Product(spec));
                }

                index++;
            }

            for (int i = 0; i < cashboxesCount; i++)
            {
                var cashbox = result.CreateCashbox($"Касса_{i + 1}");
                cashbox.Scanned += EventPrinter.PrintProductScanned;
            }

            return(result);
        }
Example #2
0
        public ShopList GetShoppingList(Dictionary <Product, int> quantityByProduct, Supermarket market, Customer customer)
        {
            ShopList list = new ShopList();

            foreach (var pair in quantityByProduct)
            {
                var          product  = pair.Key;
                var          quantity = pair.Value;
                ShoplistItem item     = new ShoplistItem();
                item.Product   = product;
                item.ProductId = product.Id;
                item.Quantity  = quantity;
                item.ShopList  = list;
                list.ShoplistItems.Add(item);
            }


            if (market == null)
            {
                var markets = this.GetAllSuperMarkets();
                market = markets[0];
            }
            list.Supermarket   = market;
            list.SuperMarketId = market.Id;


            return(this.GetSortedList(list, customer));
        }
Example #3
0
 public static bool EditSeller(int id, string name, int age, string phone, string password, string emailAddress)
 {
     try
     {
         using (var db = new Supermarket())
         {
             var seller = db.Sellers.Find(id);
             if (seller == null)
             {
                 return(false);
             }
             seller.Name         = name;
             seller.Age          = age;
             seller.Phone        = phone;
             seller.Password     = password;
             seller.EmailAddress = emailAddress;
             db.SaveChanges();
         }
     }
     catch (Exception)
     {
         return(false);
     }
     return(true);
 }
Example #4
0
        public async void Create_ExistedID_ReturnViewResultSupermarket(int id)
        {
            var product = new Supermarket {
                Name = "Rozetka2", Address = "Petrovka district2", Id = id
            };
            var option = new DbContextOptionsBuilder <ShoppingContext>().
                         UseInMemoryDatabase(databaseName: "testsCreate3").Options;
            var context = new ShoppingContext(option);

            SampleData.Initialize(context);
            var mock       = new Mock <SupermarketsService>(context);
            var controller = new SupermarketsController(mock.Object);
            var resultView = await controller.Create(product);

            var viewResult = Assert.IsType <RedirectToActionResult>(resultView);
            var actionName = Assert.IsAssignableFrom <string>(viewResult.ActionName);

            var resultViewDetails = await controller.Details(id);

            var viewResultDetails = Assert.IsType <ViewResult>(resultViewDetails);
            var model             = Assert.IsAssignableFrom <Supermarket>(viewResultDetails.Model);

            Assert.Equal("Index", actionName);
            Assert.Equal(model, product);
        }
        public static void SetDataFromXls(List <List <SaleInfo> > reports)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion <SqlServerEntities, Configuration>());
            using (var db = new SqlServerEntities())
            {
                foreach (var file in reports)
                {
                    foreach (var rep in file)
                    {
                        var supermarket = db.Supermarkets.FirstOrDefault(x => x.SupermarketName == rep.Location);

                        if (supermarket == null)
                        {
                            supermarket = new Supermarket {
                                SupermarketName = rep.Location
                            };
                            db.Supermarkets.Add(supermarket);
                        }

                        var sale = new Sale
                        {
                            ProductId   = rep.ProductId,
                            Supermarket = supermarket,
                            Date        = rep.SaleDate,
                            Quantity    = rep.Quantity,
                            UnitPrice   = rep.UnitPrice,
                            Sum         = rep.Sum
                        };

                        db.Sales.Add(sale);
                        db.SaveChanges();
                    }
                }
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            Supermarket supermarket = new Supermarket();

            supermarket.Start();
            Console.ReadLine();
        }
Example #7
0
        public async Task <IActionResult> Edit(string id, [Bind("SupermarketId,Title,Longitude,Latitude")] Supermarket supermarket)
        {
            if (id != supermarket.SupermarketId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(supermarket);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SupermarketExists(supermarket.SupermarketId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(supermarket));
        }
Example #8
0
 public static List <Seller> GetSellers()
 {
     using (var db = new Supermarket())
     {
         return(db.Sellers.ToList());
     }
 }
Example #9
0
        /// <summary>
        /// Gets a shopping based on data in GUI.
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        private ShopList GetShoppingListFromGui()
        {
            Logger.Log("Getting shopping list from gui");
            ShopList list = new ShopList();


            foreach (DataGridViewRow currRow in this.gvProducts.Rows)
            {
                bool             toBuy    = Convert.ToBoolean(currRow.Cells[this.clmToBuy.Index].Value);
                DataGridViewCell cllQuant = currRow.Cells[this.clmQuantity.Index];
                int quantity;
                if (toBuy && cllQuant.Value != null && int.TryParse(cllQuant.Value.ToString(), out quantity))
                {
                    ShoplistItem item = new ShoplistItem();
                    item.Product  = (Product)currRow.DataBoundItem;
                    item.Quantity = quantity;
                    item.ShopList = list;
                    list.ShoplistItems.Add(item);
                }
            }


            Supermarket market = this.cmbSuperMarkets.SelectedItem as Supermarket;

            list.Supermarket   = market;
            list.SuperMarketId = market.Id;
            Logger.Log(String.Format("got shopping list from gui: {0}", list.ToString()));
            return(list);
        }
Example #10
0
        public void GetAllSuperMarketsFromDbTest()
        {
            DataBase dataBase = Substitute.For <DataBase>();

            //Assign
            Random rnd      = new Random(1);
            int    expected = rnd.Next(1000);

            List <Supermarket> superMarkets = new List <Supermarket>();

            for (int i = 0; i < expected; i++)
            {
                Supermarket sm = new Supermarket()
                {
                    Id = i, Name = "Supermarket " + i
                };
                superMarkets.Add(sm);
            }


            dataBase.GetAllSuperMarkets().Returns(superMarkets);
            SmartShopLogics bs = new SmartShopLogics(dataBase);

            expected = superMarkets.Count;

            //act
            int actual = bs.GetAllSuperMarkets().Count;

            //assert
            Assert.IsTrue(expected == actual, String.Format("Got unexpected number of superMarkets ({0} instead of {1}", actual, expected));
        }
Example #11
0
        public IReadOnlyShelf PickUp(Supermarket supermarket, IReadOnlyShoppingList shoppingList)
        {
            if (supermarket.Shelves.Count == 0)
            {
                throw new InvalidOperationException();
            }

            var result = FindOptimal(supermarket, shoppingList);

            if (shoppingList.Positions.Any(p => p.ProductSpecification.Name == result.ProductSpecification.Name))
            {
                return(result);
            }

            var excluded = new List <IReadOnlyShelf>()
            {
                result
            };

            while (excluded.Count < shoppingList.Positions.Count)
            {
                result = FindOptimal(supermarket, shoppingList, excluded);
                if (shoppingList.Positions.Any(p => p.ProductSpecification.Name == result.ProductSpecification.Name))
                {
                    return(result);
                }

                excluded.Add(result);
            }

            return(null);
        }
Example #12
0
        /// <summary>
        /// Gets a sorted shop list from JSON string in expected format
        /// </summary>
        /// <param name="json">the json string</param>
        /// <returns>the shoplist</returns>
        public static ShopList GetShopList(string json, List <Product> allProducts, Customer customer, IList <Supermarket> markets)
        {
            JObject jObject   = JObject.Parse(json);
            JToken  jlistData = jObject["listData"];

            JToken      jmarketName = jObject["supermarket"];
            string      superName   = jmarketName["superName"].ToString().Trim();
            Supermarket market      = markets.FirstOrDefault(m => m.Name == superName) ?? markets[0];

            JToken jlistItems = jlistData["listItems"];                              //jlistData.First;
            var    AllItems   = jlistItems.Where(token => token.HasValues).ToList(); //jlistItems.Children()[1];//.FirstOrDefault()["Id"];

            int temp;
            var tuplesStr =
                AllItems.OfType <JObject>()
                .Cast <IDictionary <string, JToken> >()                                                                                  //easier to handle as dictionary
                .Where(i => i.ContainsKey("Id") && i["Id"] != null && !String.IsNullOrWhiteSpace(i["Id"].ToString()))                    //make sure ID is available
                .Select(i => new Tuple <string, string>(i["Id"].ToString(), i.ContainsKey("Quantity") ? i["Quantity"].ToString() : "1")) //get tuple with ID / quantity
                .Where(t => int.TryParse(t.Item1, out temp) && int.TryParse(t.Item2, out temp))                                          //parse to int
                .ToList();                                                                                                               //list is easier to debug


            var quantityByProductDic = new Dictionary <Product, int>();

            //add products to dictionary
            tuplesStr.ToList()
            .ForEach(t => quantityByProductDic.Add(allProducts.FirstOrDefault(p => p.Id == int.Parse(t.Item1)), int.Parse(t.Item2)));


            ShopList sl = Logics.GetShoppingList(quantityByProductDic, market, customer);


            return(sl);
        }
Example #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProdcutForm"/> class.
        /// </summary>
        private ProductForm(Product product, IEnumerable <Category> categories, Supermarket superMarket)
        {
            InitializeComponent();

            this._superMarket = superMarket;
            this.Categories   = categories;
            this.Product      = product;
        }
Example #14
0
 public static Category GetCategoryByName(string categoryName)
 {
     using (var db = new Supermarket())
     {
         var category = db.Categories.Where(c => c.Name == categoryName).First();
         return(category);
     }
 }
Example #15
0
 List <Seller> GetSellers()
 {
     using (var db = new Supermarket())
     {
         var sellers = db.Sellers.ToList();
         return(sellers);
     }
 }
        public ActionResult DeleteConfirmed(int id)
        {
            Supermarket supermarket = db.Supermarkets.Find(id);

            db.Supermarkets.Remove(supermarket);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Example #17
0
        public IActionResult Edit(Supermarket supermarket)
        {
            var supermarketToEdit = _context.Supermarkets.FirstOrDefault(s => s.Id == supermarket.Id);

            supermarketToEdit.Name    = supermarket.Name;
            supermarketToEdit.Address = supermarket.Address;
            _context.SaveChanges();
            return(View("Details", supermarket));
        }
        public void InitializeCustomer()
        {
            customer = new Customer("Tan Ah Kow");

            supermarket = new Supermarket("Sheng Siong");
            supermarket.AddProduct(new Product("Beans", "P10001", 1), 10);

            customer.AddToBasket(supermarket, supermarket.FindProduct("Beans"), 5);
        }
Example #19
0
 public static List <CategoryDisplay> GetCategories()
 {
     using (var db = new Supermarket())
     {
         return(db.Categories.Select(c => new CategoryDisplay {
             Id = c.Id, Name = c.Name, Description = c.Description
         }).ToList());
     }
 }
Example #20
0
        public IReadOnlyCashbox PickUp(Supermarket supermarket)
        {
            if (supermarket.Cashboxes.Count == 0)
            {
                throw new InvalidOperationException();
            }

            return(supermarket.Cashboxes.OrderBy(c => c.QueueLength).First().Object);
        }
Example #21
0
        static void Main(string[] args)
        {
            int       N   = 500000;
            Random    rn  = new Random();
            Stopwatch sw1 = new Stopwatch();
            Stopwatch sw2 = new Stopwatch();
            Stopwatch sw3 = new Stopwatch();
            Stopwatch sw4 = new Stopwatch();

            Trading_Establishment[]      Arr1 = new Trading_Establishment[N];        // массив
            List <Trading_Establishment> Arr2 = new List <Trading_Establishment>(N); // типизированная коллекция
            ArrayList      Arr3 = new ArrayList(N);                                  // не типизированная колллекция
            UserCollection Arr4 = new UserCollection(N);                             // пользовательская коллекция

            for (int a = 0; a < N; a++)
            {
                int house = rn.Next(1, 3);
                switch (house)
                {
                case 1:
                    Arr1[a] = new Supermarket();
                    Arr2.Add(new Supermarket());
                    Arr3.Add(new Supermarket());
                    Arr4.Add(new Supermarket());
                    break;

                case 2:
                    Arr1[a] = new Stall();
                    Arr2.Add(new Stall());
                    Arr3.Add(new Stall());
                    Arr4.Add(new Stall());
                    break;
                }
            }
            sw1.Start();
            Array.Sort(Arr1);
            sw1.Stop();

            sw2.Start();
            Arr2.Sort();
            sw2.Stop();

            sw3.Start();
            Arr3.Sort();
            sw3.Stop();

            sw4.Start();
            Arr4.Sorts();
            sw4.Stop();

            Console.WriteLine($"Время на сортировку обычного массива -> {sw1.Elapsed}");
            Console.WriteLine($"Время на сортировку типизированной коллекции -> {sw2.Elapsed}");
            Console.WriteLine($"Время на сортировку не типизированной коллекции -> {sw3.Elapsed}");
            Console.WriteLine($"Время на сортировку пользовательской коллекции -> {sw4.Elapsed}");
            Console.ReadKey();
        }
 public ActionResult Edit([Bind(Include = "Id,Suburb,Name,Latitude,Longitude")] Supermarket supermarket)
 {
     if (ModelState.IsValid)
     {
         db.Entry(supermarket).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(supermarket));
 }
        public async Task <IActionResult> Create([Bind("Id,Name,Address")] Supermarket supermarket)
        {
            if (ModelState.IsValid)
            {
                await _supermarkets.AddAsync(supermarket);

                return(RedirectToAction(nameof(Index)));
            }
            return(View(supermarket));
        }
 public ActionResult Edit([Bind(Include = "Id,Address,Area,Name,Icode,Idesc,Seating_type,Seats,x_coordinate,Location")] Supermarket supermarket)
 {
     if (ModelState.IsValid)
     {
         db.Entry(supermarket).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(supermarket));
 }
Example #25
0
        public async Task AddAsync(Supermarket model)
        {
            Supermarket supermarket = new Supermarket()
            {
                Address = model.Address, Name = model.Name
            };
            await _dbContext.Supermarkets.AddAsync(supermarket);

            await _dbContext.SaveChangesAsync();
        }
        public ActionResult Create([Bind(Include = "Id,Suburb,Name,Latitude,Longitude")] Supermarket supermarket)
        {
            if (ModelState.IsValid)
            {
                db.Supermarkets.Add(supermarket);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(supermarket));
        }
Example #27
0
        public async Task <IActionResult> Create([Bind("SupermarketId,Title,Longitude,Latitude")] Supermarket supermarket)
        {
            if (ModelState.IsValid)
            {
                _context.Add(supermarket);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(supermarket));
        }
Example #28
0
        public ActionResult Create([Bind(Include = "StoreID,StoreName")] Supermarket supermarket)
        {
            if (ModelState.IsValid)
            {
                db.Supermarkets.Add(supermarket);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(supermarket));
        }
Example #29
0
        public async Task EditAsync(Supermarket model)
        {
            if (!(_dbContext.Supermarkets.Any(s => s.Id == model.Id)))
            {
                throw new Exception("On this Id nothing found");
            }
            _dbContext.Supermarkets.FirstOrDefault(s => s.Id == model.Id).Name    = model.Name;
            _dbContext.Supermarkets.FirstOrDefault(s => s.Id == model.Id).Address = model.Address;

            await _dbContext.SaveChangesAsync();
        }
        public static void InsertSalesReports(StoreReport report)
        {
            String marketName = report.MarketName;
            int    marketId   = -1;

            if (!db.Supermarkets.Where(s => s.SupermarketName == marketName).Any())
            {
                var market = new Supermarket()
                {
                    SupermarketName = marketName
                };
                db.Supermarkets.Add(market);
                db.SaveChanges();
                marketId = market.Id;
            }
            else
            {
                marketId = db.Supermarkets.First(s => s.SupermarketName == marketName).Id;
            }

            if (db.DailyReports.Where(x => x.Day == report.Date &&
                                      x.SuperMarketId == marketId).Any())
            {
                return;
            }

            var daily = new DailyReport()
            {
                Day = report.Date, SuperMarketId = marketId
            };

            db.DailyReports.Add(daily);
            db.SaveChanges();

            var reportId = daily.Id;

            ProductsData.ProductsModel mysqlModel = new ProductsData.ProductsModel();

            foreach (var product in report.Products)
            {
                var prodId = db.Products.First(p => p.OldId == product.ProductId).Id;

                db.SalesReports.Add(new SalesReport()
                {
                    ReportId  = reportId,
                    ProductId = prodId,
                    Quantity  = product.QuantityValue,
                    UnitPrice = product.UnitPrice,
                    Sum       = product.Sum
                });
            }

            db.SaveChanges();
        }
        public static List<Supermarket> Read(string path)
        {
            List<Supermarket> supermarkets = new List<Supermarket>();
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            foreach (var file in dirInfo.EnumerateFiles("*.xls"))
            {
                string connectionstring = string.Format(
                    "Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"",
                    file.FullName);
                OleDbConnection oleDbConnection = new OleDbConnection(connectionstring);
                oleDbConnection.Open();

                OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sales$]", oleDbConnection);
                var reader = cmd.ExecuteReader();

                // skip the empty rows
                reader.Read();
                reader.Read();
                string location = reader[0].ToString();
                var supermarket = SessionState.db.Supermarkets.FirstOrDefault(s => s.Name == location);
                if (supermarket == null)
                {
                    supermarket = new Supermarket();
                    supermarket.Name = location;
                    supermarket.Sales = new Collection<Sale>();
                    SessionState.db.Supermarkets.Add(supermarket);
                }

                while (reader.Read())
                {
                    if (!reader[0].ToString().Contains("Total"))
                    {
                        int productId;
                        int quantity;
                        double unitPrice;

                        bool productIdSuccess = int.TryParse(reader[0].ToString(), out productId);
                        bool quantitySuccess = int.TryParse(reader[1].ToString(), out quantity);
                        bool unitPriceSuccess = double.TryParse(reader[2].ToString(), out unitPrice);

                        if (productIdSuccess && quantitySuccess && unitPriceSuccess)
                        {
                            //sales.Add(new Sale(productId, quantity, unitPrice, location));
                            Sale sale = new Sale(productId, quantity, unitPrice);
                            sale.Date = DateTime.Parse(dirInfo.Name);
                            supermarket.Sales.Add(sale);
                        }
                    }
                }

                supermarkets.Add(supermarket);
                reader.Close();
                reader.Dispose();

                oleDbConnection.Close();
                oleDbConnection.Dispose();
            }

            SessionState.db.SaveChanges();
            return supermarkets;
        }