public virtual ActionResult GetAll([DataSourceRequest] DataSourceRequest request, int reportType, int period)
        {
            IList <SalesReportViewModel> items = new List <SalesReportViewModel>();

            switch ((SalesReportViewModel.SalesReportType)reportType)
            {
            case SalesReportViewModel.SalesReportType.ByStyle:
                items = SalesReportViewModel.GetAllByDate(Db, Time, (SalesReportViewModel.FilterPeriod)period);
                break;

            case SalesReportViewModel.SalesReportType.ByLicense:
                items = SalesReportViewModel.GetAllByFeature(Db, Time, (SalesReportViewModel.FilterPeriod)period, StyleFeatureHelper.SUB_LICENSE1);
                break;

            case SalesReportViewModel.SalesReportType.BySleeve:
                items = SalesReportViewModel.GetAllByFeature(Db, Time, (SalesReportViewModel.FilterPeriod)period, StyleFeatureHelper.SLEEVE);
                break;

            case SalesReportViewModel.SalesReportType.ByGender:
                items = SalesReportViewModel.GetAllByFeature(Db, Time, (SalesReportViewModel.FilterPeriod)period, StyleFeatureHelper.GENDER);
                break;
            }

            var dataSource = items.ToDataSourceResult(request);

            return(new JsonResult {
                Data = dataSource, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public ActionResult Show()
        {
            SalesReportViewModel salesReportViewModel = new SalesReportViewModel();

            salesReportViewModel.Sales = _saleManager.GetAll();
            return(View());
        }
Esempio n. 3
0
        public ActionResult SaleReport(DateTime?startdate, DateTime?enddate)
        {
            SalesReportViewModel salesReportViewModel = new SalesReportViewModel();

            var purchaseDetails = _purchaseManager.GetAll();
            var salesDetails    = _salesManager.GetAllSaleDetails();
            var report          = (from sa in salesDetails
                                   join pu in purchaseDetails on sa.ProductId equals pu.ProductId
                                   where sa.Sale.Date >= startdate && sa.Sale.Date <= enddate
                                   select new SalesReportViewModel
            {
                Date = sa.Sale.Date,
                Code = sa.Product.Code,
                Name = sa.Product.Name,
                Category = sa.Category.Name,
                Soldqty = sa.Quantity,
                CP = sa.Quantity * pu.UnitPrice,
                SalesPrice = sa.Quantity * pu.MRP,
                Profit = sa.Quantity * pu.MRP - sa.Quantity * pu.UnitPrice
            }).ToList();

            salesReportViewModel.SalesReport = report;

            return(View(salesReportViewModel));
        }
Esempio n. 4
0
        public ActionResult Sales()
        {
            ISaleRepository repo        = SaleRepositoryFactory.GetRepository();
            var             salesReport = new SalesReportViewModel();

            salesReport.Salespeople = repo.GetSalespeople();
            return(View(salesReport));
        }
Esempio n. 5
0
        public ActionResult Sales()
        {
            SalesReportViewModel model = new SalesReportViewModel();

            model.Users = new SelectList(_userRepo.GetUsersByRole("Sales"), "UserName", "UserName", "-All-");

            return(View(model));
        }
        public ViewSalesReport(IQueryable <SalesReport> salesReport)
        {
            InitializeComponent();
            var VM = new SalesReportViewModel {
                SalesReports = salesReport.ToList()
            };

            salesReportsForm.DataContext = VM;
        }
Esempio n. 7
0
        public ActionResult Sales()
        {
            SalesReportViewModel model = new SalesReportViewModel();
            var repo = InventoryRepositoryFactory.GetRepository();

            model.SalesPerson = new SelectList(repo.SalesPersonSelectAll(), "SalesPerson", "SalesPerson");

            return(View(model));
        }
        public ActionResult Sales()
        {
            var model = new SalesReportViewModel();
            var repo  = AdminFactory.GetRepo();

            model.UserList  = repo.GetAllUsers();
            model.SalesList = new List <Models.Tables.SalesReport>();

            return(View(model));
        }
        public async Task <IActionResult> CreateSalesReportAsync([FromBody] SalesReportViewModel value)
        {
            var response = new SingleModelResponse <SalesReportViewModel>() as ISingleModelResponse <SalesReportViewModel>;

            try
            {
                var entity = await Task.Run(() =>
                {
                    return(_RESTfulAPI_Repository.AddSalesReport(value.ToEntity()));
                });


                if (response.DidError == false)
                {
                    response.Model = entity.ToViewModel();
                }
            }
            catch (Exception ex)
            {
                string webRoot   = _hostingEnvironment.WebRootPath;
                string errorGuid = String.Format(Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 16));

                HttpContext.Session.SetString("ErrorGuid", errorGuid);
                ViewBag.ErrorGuid = HttpContext.Session.GetString("ErrorGuid");

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    using (StreamWriter w = new StreamWriter(webRoot + "\\log.txt", append: true))
                    {
                        Log.Logging(ex.ToString(), w, ViewBag.ErrorGuid);
                    }
                }

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    using (StreamWriter w = new StreamWriter(webRoot + "/log.txt", append: true))
                    {
                        Log.Logging(ex.ToString(), w, ViewBag.ErrorGuid);
                    }
                }


                response.DidError = true;
                //response.ErrorMessage = ex.ToString();


                return(this.Json(new { timestamp = DateTime.Now, errorGuid = ViewBag.ErrorGuid, status = HttpStatusCode.InternalServerError, info = "Error logged in log file." }));
            }



            response.Info = "Client " + " " + HttpContext.Connection.RemoteIpAddress.ToString();

            return(response.ToHttpResponse());
        }
Esempio n. 10
0
        public async Task <IActionResult> SalesReport(ReportsViewModel model)
        {
            DateTime startDateTime = model.FromDate;
            DateTime endDateTime   = model.ToDate.AddDays(1).AddTicks(-1);

            var sales = await
                        _context.Orders.Where(o =>
                                              o.Status == Status.DELIVERED && o.DateOrdered >= startDateTime && o.DateOrdered <= endDateTime).ToListAsync();

            var vm = new SalesReportViewModel();

            vm.Sales    = new List <SalesDetails>();
            vm.FromDate = model.FromDate;
            vm.ToDate   = endDateTime;

            if (sales != null && sales.Count > 0)
            {
                foreach (var s in sales)
                {
                    var product = await _context.Products.FirstOrDefaultAsync(p => p.ProductID == s.ProductID);

                    var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == s.UserID);

                    if (product != null && user != null)
                    {
                        var details = new SalesDetails
                        {
                            OrderID       = s.OrderID,
                            Quantity      = s.Quantity,
                            PaymentMethod = s.PaymentMethod,
                            Status        = s.Status,
                            TotalPrice    = s.Amount,
                            Price         = product.Price,
                            CustomerName  = user.FirstName + " " + user.LastName,
                            DateOrdered   = s.DateOrdered,
                            ProductName   = product.ProductName
                        };


                        vm.Sales.Add(details);
                    }
                }

                return(new ViewAsPdf("SalesReport", vm)
                {
                    PageOrientation = Orientation.Landscape,
                    FileName = "SalesReport_" + DateTime.Now + ".pdf"
                });

//                return View("SalesReport", vm);
            }

            return(NotFound());
        }
        public ActionResult Sales()
        {
            var vm      = new SalesReportViewModel();
            var context = new ApplicationDbContext();
            var manager = AdminManagerFactory.GetManager();
            var users   = context.Users;

            vm.Users = new SelectList(users, "Id", "UserName");
            vm.Sales = manager.GetSalesReport();

            return(View(vm));
        }
Esempio n. 12
0
        public ActionResult GetSalesReportByDate(string startDate, string endDate)
        {
            SalesReportViewModel salesReportViewModel = new SalesReportViewModel();
            var sales       = _saleManager.GetAll().ToList();
            var saledetails = _salesDetailManager.GetAll().ToList();
            var purchase    = _purchasedProductManager.GetAll().ToList();
            var product     = _productManager.GetAll().ToList();
            var category    = _categoryManager.GetAll().ToList();

            // purchase = purchase.Where(c => c.Date == StartDate).ToList();
            var sale = (from p in sales where p.Date.CompareTo(startDate) >= 0 && p.Date.CompareTo(endDate) <= 0 select p).ToList();

            var count = (from sd in saledetails
                         join s in sale on sd.SaleId equals s.Id
                         join pu in purchase on sd.ProductId equals pu.ProductId
                         join p in product on sd.ProductId equals p.Id
                         join c in category on p.CategoryId equals c.Id
                         orderby sd.Id
                         select new SalesReport
            {
                ProductID = sd.ProductId,
                Code = p.Code,
                ProductName = p.Name,
                CategoryName = c.Name,
                Quantity = sd.Quantity,
                UnitPrice = sd.Quantity * pu.UnitPrice,
                MRP = sd.MRP * sd.Quantity,
                Profit = sd.Quantity * (sd.MRP - pu.UnitPrice)
            }).ToList();


            var Sum = (from c in count
                       group c by c.Code into egroup
                       select new SalesReportShow {
                ProductID = egroup.First().ProductID,
                Code = egroup.First().Code,
                ProductName = egroup.First().ProductName,
                CategoryName = egroup.First().CategoryName,
                Quantity = egroup.Sum(s => s.Quantity),
                UnitPrice = egroup.Sum(s => s.UnitPrice),
                MRP = egroup.Sum(s => s.MRP),
                Profit = egroup.Sum(s => s.Profit)
            }).ToList();

            ViewBag.salesDetails = Sum;

            return(PartialView("Report/_SalesReport"));
        }
Esempio n. 13
0
        public ActionResult SalesReport()
        {
            var repo = SalesInformationRepositoryFactory.GetRepository();

            SalesReportViewModel model = new SalesReportViewModel();

            var userRepo = UsersRepositoryFactory.GetRepository();

            var users = userRepo.GetAll();

            var usernames = (from user in users
                             select user.LastName);

            model.Users = new SelectList(usernames);

            return(View(model));
        }
Esempio n. 14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        public static SalesReport ToEntity(this SalesReportViewModel viewModel)
        {
            return(viewModel == null ? null : new SalesReport
            {
                //Id = viewModel.Id,

                Group_By = viewModel.Group_By,
                Display = viewModel.Display,
                Title = viewModel.Title,
                Filter_Row_Source = viewModel.Filter_Row_Source,
                Default = viewModel.Default


                          //
                          //RowGuid = viewModel.RowGuid,
                          //ModifiedDate = viewModel.ModifiedDate
            });
        }
Esempio n. 15
0
        public List <SalesReportViewModel> GetSalesReport(int?userId, DateTime?fromDate, DateTime?toDate)
        {
            List <SalesReportViewModel> report = new List <Models.SalesReportViewModel>();

            var salesQuery = db.Sales.AsQueryable();

            if (userId.HasValue)
            {
                salesQuery = salesQuery.Where(s => s.Salesperson.UserId == userId.Value);
            }
            if (fromDate.HasValue && toDate.HasValue)
            {
                salesQuery = salesQuery.Where(s => s.Date >= fromDate.Value && s.Date <= toDate.Value);
            }
            else
            {
                if (fromDate.HasValue)
                {
                    salesQuery = salesQuery.Where(s => s.Date >= fromDate.Value);
                }
                if (toDate.HasValue)
                {
                    salesQuery = salesQuery.Where(s => s.Date <= toDate.Value);
                }
            }

            var salesReportGroupedByUser = salesQuery.GroupBy(s => s.Salesperson.UserId);

            foreach (var item in salesReportGroupedByUser)
            {
                SalesReportViewModel model = new SalesReportViewModel();
                var user = db.Users.Where(s => s.Id == item.Key).FirstOrDefault();
                if (user != null)
                {
                    model.UserName = user.FirstName + ", " + user.LastName;
                }
                model.TotalVehicles = item.Count();
                model.TotalSales    = item.Sum(s => s.PurchasePrice);

                report.Add(model);
            }

            return(report);
        }
Esempio n. 16
0
        private void OnNav(string Destination)
        {
            switch (Destination)
            {
            case "generalledgerParam":
                GeneralLedgerViewModel = ContainerHelper.Container.Resolve <GeneralLedgerViewModel>();
                CurrentViewModel       = GeneralLedgerViewModel;
                break;

            case "PurchaseReportParam":
                PurchaseReportViewModel = ContainerHelper.Container.Resolve <PurchaseReportViewModel>();
                CurrentViewModel        = PurchaseReportViewModel;
                break;

            case "SalesReportParam":
                SalesReportViewModel = ContainerHelper.Container.Resolve <SalesReportViewModel>();
                CurrentViewModel     = SalesReportViewModel;
                break;

            case "IncomeReportParam":
                IncomeStatementReportViewModel = ContainerHelper.Container.Resolve <IncomeStatementReportViewModel>();
                CurrentViewModel = IncomeStatementReportViewModel;
                break;

            case "TrialBalanceReportParam":
                TrialBalanceReportViewModel = ContainerHelper.Container.Resolve <TrialBalanceReportViewModel>();
                CurrentViewModel            = TrialBalanceReportViewModel;
                break;

            case "BalanceSheetReportParam":
                BalanceSheetReportViewModel = ContainerHelper.Container.Resolve <BalanceSheetReportViewModel>();
                CurrentViewModel            = BalanceSheetReportViewModel;
                break;
            }

            //if (Isvirgin)
            //{
            //    IsReportMayLoaded = false;
            //    await Task.Delay(5000).ContinueWith(a => IsReportMayLoaded = true);
            //}
            //Isvirgin = false;
        }
Esempio n. 17
0
        public IActionResult Index()
        {
            var rand  = new Random(DateTime.Now.Millisecond);
            var games = this.context.Games.ToList();

            var vms = new List <SalesReportViewModel>();

            foreach (var game in games)
            {
                var vm = new SalesReportViewModel();

                vm.GameName          = game.Title;
                vm.NumberOfDownloads = rand.Next(99, 999);
                vm.SalesPrice        = vm.NumberOfDownloads * 79.99;
                vm.Year = DateTime.Now.Year;

                vms.Add(vm);
            }

            return(View(vms));
        }
Esempio n. 18
0
        public List <SalesReportViewModel> GetSalesReport()
        {
            List <SalesReportViewModel> salesReportViewModels = new List <SalesReportViewModel>();

            using (SqlConnection sqlConnection = new SqlConnection(_connectionString))
            {
                string     queryString = @"SELECT p.Id, p.Code AS Code,p.Name AS Name ,c.Name AS Category,SUM(s.Quantity) AS SoldQty ,SUM(MRP*s.Quantity) AS SalesPrice
                 FROM Sales AS s LEFT JOIN Products AS p ON p.Id=s.ProductId 
                 LEFT JOIN Categories AS c ON p.CategoryId=c.Id  GROUP BY p.Id, p.Code,p.Name,c.Name ORDER BY p.Code";
                SqlCommand sqlCommand  = new SqlCommand(queryString, sqlConnection);
                sqlConnection.Open();

                SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();


                while (sqlDataReader.Read())
                {
                    int      productId = Convert.ToInt32(sqlDataReader["Id"]);
                    Purchase purchase  = new Purchase();
                    purchase = _purchaseManager.GetLastPurchasesProductInfoById(productId);



                    SalesReportViewModel model = new SalesReportViewModel();
                    model.Code     = sqlDataReader["Code"].ToString();
                    model.Name     = sqlDataReader["Name"].ToString();
                    model.Category = sqlDataReader["Category"].ToString();
                    model.SoldQty  = Convert.ToInt32(sqlDataReader["SoldQty"]);
                    // model.CP = Convert.ToDouble(sqlDataReader["CP"]);
                    model.CP         = model.SoldQty * purchase.UnitPrice;
                    model.SalesPrice = Convert.ToDouble(sqlDataReader["SalesPrice"]);
                    // model.Profit = Convert.ToDouble(sqlDataReader["Profit"]);
                    model.Profit = model.SalesPrice - model.CP;
                    salesReportViewModels.Add(model);
                }
            }

            return(salesReportViewModels);
        }
        public ActionResult Sales(SalesReportViewModel vm)
        {
            var manager = AdminManagerFactory.GetManager();
            var context = new ApplicationDbContext();
            var users   = context.Users;

            if (ModelState.IsValid)
            {
                vm.Sales = manager.FilterSalesReport(vm.UserId, vm.FromDate, vm.ToDate);
                vm.Users = new SelectList(users, "Id", "UserName");

                return(View(vm));
            }
            else
            {
                manager  = AdminManagerFactory.GetManager();
                vm       = new SalesReportViewModel();
                vm.Users = new SelectList(users, "Id", "UserName");
                vm.Sales = manager.GetSalesReport();

                return(View(vm));
            }
        }
Esempio n. 20
0
        public SalesReportViewModel <SaleViewModel> GetSalesReportGridData(GridRequestModel request, DateTime startDate, DateTime endDate)
        {
            SalesReportViewModel <SaleViewModel> gridData = new SalesReportViewModel <SaleViewModel>();

            endDate = endDate.AddDays(1);

            var query = _repository.GetAllActive(getCreatedCompanyId())
                        .Where(x => x.Created >= startDate && x.Created <= endDate)
                        .Include(x => x.SalesDetails)
                        .Include(x => x.SalesDetails.Select(y => y.Product))
                        .Include(x => x.SalesDetails.Select(y => y.Product.Group))
                        .Include(x => x.SalesDetails.Select(y => y.Product.Brand))
                        .Include(x => x.Customer);

            var invoiceNo = request.Keyword.Contains("PB1-");

            if (request.Keyword == "")
            {
                gridData.Count = _repository.GetAllActive(getCreatedCompanyId())
                                 .Where(x => x.Created >= startDate && x.Created <= endDate).Count();

                gridData.DueCount = _repository.GetAllActive(getCreatedCompanyId())
                                    .Where(x => x.Created >= startDate && x.Created <= endDate && x.Due > 0).Count();

                gridData.TotalAmount = _repository.GetAllActive(getCreatedCompanyId())
                                       .Where(x => x.Created >= startDate && x.Created <= endDate).Sum(x => (decimal?)x.Amount) ?? 0;

                gridData.TotalDue = _repository.GetAllActive(getCreatedCompanyId())
                                    .Where(x => x.Created >= startDate && x.Created <= endDate && x.Due > 0).Sum(x => (decimal?)x.Due) ?? 0;

                gridData.Profit = _repository.GetAllActive(getCreatedCompanyId())
                                  .Where(x => x.Created >= startDate && x.Created <= endDate && x.Profit > 0).Sum(x => (decimal?)x.Profit) ?? 0;
            }
            else if (invoiceNo)
            {
                gridData.Count = _repository.GetAllActive(getCreatedCompanyId())
                                 .Where(x => x.InvoiceNo.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Count();

                gridData.DueCount = _repository.GetAllActive(getCreatedCompanyId())
                                    .Where(x => x.InvoiceNo.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Count();

                gridData.TotalAmount = _repository.GetAllActive(getCreatedCompanyId())
                                       .Where(x => x.InvoiceNo.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Sum(x => (decimal?)x.Amount) ?? 0;

                gridData.TotalDue = _repository.GetAllActive(getCreatedCompanyId())
                                    .Where(x => x.InvoiceNo.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Sum(x => (decimal?)x.Due) ?? 0;

                gridData.Profit = _repository.GetAllActive(getCreatedCompanyId())
                                  .Where(x => x.InvoiceNo.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Profit > 0).Sum(x => (decimal?)x.Profit) ?? 0;

                query = query.Where(x => x.InvoiceNo.Contains(request.Keyword));
            }
            else
            {
                if (request.Keyword.Contains("01"))
                {
                    gridData.Count = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                     .Where(x => x.Customer.Phone.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Count();

                    gridData.DueCount = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                        .Where(x => x.Customer.Phone.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Count();

                    gridData.TotalAmount = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                           .Where(x => x.Customer.Phone.Contains(request.Keyword) && x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Sum(x => (decimal?)x.Amount) ?? 0;

                    gridData.TotalDue = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                        .Where(x => x.Customer.Phone.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Sum(x => (decimal?)x.Due) ?? 0;

                    gridData.Profit = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                      .Where(x => x.Customer.Phone.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Profit > 0).Sum(x => (decimal?)x.Profit) ?? 0;

                    query = query.Where(x => x.Customer.Phone.Contains(request.Keyword));
                }
                else
                {
                    gridData.Count = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                     .Where(x => x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Count();

                    gridData.DueCount = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                        .Where(x => x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Count();

                    gridData.TotalAmount = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                           .Where(x => x.Customer.Name.Contains(request.Keyword) && x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate).Sum(x => (decimal?)x.Amount) ?? 0;

                    gridData.TotalDue = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                        .Where(x => x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Due > 0).Sum(x => (decimal?)x.Due) ?? 0;

                    gridData.Profit = _repository.GetAllActive(getCreatedCompanyId()).Include(x => x.Customer)
                                      .Where(x => x.Customer.Name.Contains(request.Keyword) && x.Created >= startDate && x.Created <= endDate && x.Profit > 0).Sum(x => (decimal?)x.Profit) ?? 0;

                    query = query.Where(x => x.Customer.Name.Contains(request.Keyword));
                }
            }



            if (request.IsAscending)
            {
                switch (request.OrderBy)
                {
                case "InvoiceNo": query = query.OrderBy(l => l.InvoiceNo); break;

                case "Due": query = query.OrderBy(l => l.Due); break;

                case "Created": query = query.OrderBy(l => l.Created); break;

                default: query = query.OrderBy(l => l.Created); break;
                }
            }
            else
            {
                switch (request.OrderBy)
                {
                case "InvoiceNo": query = query.OrderByDescending(l => l.InvoiceNo); break;

                case "Due": query = query.OrderByDescending(l => l.Due); break;

                case "Created": query = query.OrderByDescending(l => l.Created); break;

                default: query = query.OrderByDescending(l => l.Created); break;
                }
            }


            query = query.Skip(((request.Page - 1) * request.PerPageCount)).Take(request.PerPageCount);

            List <Sale> sales = query.ToList();

            foreach (var sale in sales)
            {
                gridData.Data.Add(new SaleViewModel(sale));
            }

            return(gridData);
        }
        public IActionResult SalesReport(SalesReportViewModel model)
        {
            _ = storeLoggedIn;
            model.StoreName = _repo.GetStore(storeLoggedIn).Name;

            bool submitClicked = Request.Form["submit"].ToString() != "";
            bool backClicked   = Request.Form["back"].ToString() != "";

            if (submitClicked && backClicked)
            {
                Console.WriteLine("Both buttons in Sales Report registered as clicked");
                model.ReasonForError = "There was an error processing your request. Please try again.";
                return(View("SalesReport", model));
            }
            else if (submitClicked)
            {
                List <OrderModel> listOfOrders = _repo.GetOrders();

                Dictionary <DateTime, OrderViewModel> salesReport = new Dictionary <DateTime, OrderViewModel>();
                foreach (OrderModel order in listOfOrders)
                {
                    DateTime dayOfOrder            = order.Created.Date;
                    DateTime startingDayOfInterval = dayOfOrder;
                    if (model.Interval == 7)
                    {
                        startingDayOfInterval = dayOfOrder.AddDays(-((int)dayOfOrder.DayOfWeek));
                    }
                    else if (model.Interval == 30)
                    {
                        startingDayOfInterval = dayOfOrder.AddDays(-(dayOfOrder.Day - 1));
                    }
                    else
                    {
                        model.ReasonForError = "Please select an interval";
                        return(View("SalesReport", model));
                    }

                    StringBuilder toppings = new StringBuilder();
                    foreach (string topping in order.Toppings.Split(','))
                    {
                        int toppingID;
                        if (!int.TryParse(topping, out toppingID))
                        {
                            Console.WriteLine($"Database error: Expected integer for pizza ID, received {topping}");
                            toppings.Append("Error, ");
                            continue;
                        }
                        ToppingModel top = _repo.GetTopping(toppingID);
                        toppings.Append($"{top.Name}, ");
                    }
                    toppings.Remove(toppings.Length - 2, 2);
                    OrderViewClass orderView = new OrderViewClass {
                        UserID    = order.UserID,
                        OrderID   = order.OrderID,
                        Created   = order.Created,
                        Size      = order.Size,
                        Crust     = _repo.GetCrust(order.CrustID).Name,
                        Toppings  = toppings.ToString(),
                        Quantity  = order.Quantity,
                        Cost      = order.TotalCost,
                        StoreName = _repo.GetStore(order.StoreID).Name
                    };
                    if (order.PizzaID == 0)
                    {
                        orderView.Pizza = "Custom";
                    }
                    else
                    {
                        try {
                            orderView.Pizza = _repo.GetPizza(order.PizzaID).Name;
                        } catch (NullReferenceException) {
                            Console.WriteLine($"Database error: Could not find a pizza with ID {order.PizzaID} in the Pizza table");
                            orderView.Pizza = "Error";
                        }
                    }

                    try {
                        salesReport[startingDayOfInterval].OrderHistory.Add(orderView);
                    } catch (KeyNotFoundException) {
                        salesReport.Add(startingDayOfInterval, new OrderViewModel {
                            OrderHistory = new List <OrderViewClass> {
                                orderView
                            }
                        });
                    }
                }

                model.SalesReport = new Dictionary <DateTime, OrderViewModel>();
                foreach (DateTime startDate in salesReport.Keys)
                {
                    OrderViewModel orderView = salesReport[startDate];
                    model.SalesReport.Add(startDate, new OrderViewModel {
                        OrderHistory = new List <OrderViewClass>()
                    });
                    foreach (OrderViewClass order in orderView.OrderHistory)
                    {
                        string pizza = order.Pizza;
                        List <OrderViewClass> srOrderHistory = model.SalesReport[startDate].OrderHistory;
                        int i;
                        for (i = 0; i < srOrderHistory.Count(); i++)
                        {
                            OrderViewClass srOrder = model.SalesReport[startDate].OrderHistory[i];
                            if (srOrder.Pizza == pizza)
                            {
                                break;
                            }
                        }

                        if (i == srOrderHistory.Count())
                        {
                            srOrderHistory.Add(new OrderViewClass {
                                Pizza    = pizza,
                                Quantity = 1,
                                Cost     = order.Cost
                            });
                        }
                        else
                        {
                            srOrderHistory[i].Quantity += 1;
                            srOrderHistory[i].Cost     += order.Cost;
                        }
                        model.SalesReport[startDate].IntervalQuantity += 1;
                        model.SalesReport[startDate].IntervalSales    += order.Cost;
                    }
                }

                return(View("SalesReport", model));
            }
            else // if backClicked
            {
                StoreViewModel storeModel = new StoreViewModel {
                    StoreName = model.StoreName,
                    ID        = storeLoggedIn
                };
                return(View("Store", storeModel));
            }
        }
Esempio n. 22
0
 public ReportSalesTemplate(DateTime date)
 {
     InitializeComponent();
     this.DataContext = (salesReportViewModel = new SalesReportViewModel(date));
 }
        public ActionResult Search()
        {
            SalesReportViewModel salesReportViewModel = new SalesReportViewModel();
            var purchases       = _purchaseManager.GetAll();
            var products        = _productManager.GetAll();
            var categories      = _categoryManager.GetAll();
            var purchaseDetails = _purchaseManager.GetAllDetails();
            var salesDetails    = _salesManager.GetAllSaleDetails();
            var report          = (from sa in salesDetails
                                   join Products in products on new { ProductId = sa.ProductId } equals new { ProductId = Products.Id } into Products_join
                                   from Products in Products_join.DefaultIfEmpty()
                                   join Categories in categories on new { CategoryId = Products.CategoryId } equals new { CategoryId = Categories.Id } into Categories_join
                                   from Categories in Categories_join.DefaultIfEmpty()
                                   group new { sa.SalesMaster, sa, Products, Categories } by new
            {
                sa.SalesMaster.Date,
                sa.ProductId,
                Products.Name,
                Products.Code,
                Column1 = Categories.Name
            } into g
                                   select new SalesReportViewModel
            {
                Date = g.Key.Date,
                Code = g.Key.Code,
                Name = g.Key.Name,
                Category = g.Key.Column1,
                Soldqnty = g.Sum(p => p.sa.Quantity),
                CP = g.Sum(p => p.sa.Quantity) *
                     ((from Pu in purchaseDetails
                       where
                       Pu.ProductId == g.Key.ProductId
                       group Pu by new
                {
                    Pu.ProductId
                } into g1
                       select new
                {
                    Column1 = (g1.Sum(p => p.UnitPrice) / g.Count())
                }).First().Column1),
                SalesPrice = (g.Sum(p => p.sa.Quantity) *
                              ((from Pu in purchaseDetails
                                where
                                Pu.ProductId == g.Key.ProductId
                                group Pu by new
                {
                    Pu.ProductId
                } into g2
                                select new
                {
                    Column1 = (g2.Sum(p => p.MRP) / g.Count())
                }).First().Column1)),
                Profit = (g.Sum(p => p.sa.Quantity) *
                          ((from Pu in purchaseDetails
                            where
                            Pu.ProductId == g.Key.ProductId
                            group Pu by new
                {
                    Pu.ProductId
                } into g3
                            select new
                {
                    Column1 = (g3.Sum(p => p.MRP) / g.Count())
                }).First().Column1) - g.Sum(p => p.sa.Quantity) *
                          ((from Pu in purchaseDetails
                            where
                            Pu.ProductId == g.Key.ProductId
                            group Pu by new
                {
                    Pu.ProductId
                } into g4
                            select new
                {
                    Column1 = (g4.Sum(p => p.UnitPrice) / g.Count())
                }).First().Column1))
            }).ToList();

            salesReportViewModel.SalesReport = report;

            return(View(salesReportViewModel));
        }