public void ReturnEarly_Confirmed()
        {
            //arrange
            _view.ConfirmReturnEarly().Returns(true); // юзер соглашается "Вернуть фильм"

            var testMovieCopy = new MovieCopy(9999, "TEST COMMENT", 50)
            {
                Available = false
            };                                                                               // копия у кого-то в аренде

            // взяли 20 января, договорились вернуть 25, но вернули 23
            var startDate       = new DateTime(2020, 01, 20);
            var expectedEndDate = new DateTime(2020, 01, 25);
            var returnDate      = new DateTime(2020, 01, 23);
            var testLeasing     = new Leasing(startDate, expectedEndDate, 0, 0, 50)
            {
                MovieCopy = testMovieCopy
            };

            _view.CurrentLeasing = testLeasing;

            testLeasing.ReturnEarly(returnDate);

            //act
            _presenter.ReturnEarly(returnDate);

            //assert
            Assert.AreEqual(testLeasing.TotalPrice, _view.CurrentLeasing.TotalPrice);
            Assert.AreEqual(testLeasing.MovieCopy.Available, _view.CurrentLeasing.MovieCopy.Available);
            Assert.AreEqual(testLeasing.ReturnDate, _view.CurrentLeasing.ReturnDate);

            _view.Received().Close();
        }
        public void ReturnDelayed_NotConfirmed()
        {
            //arrange
            _view.ConfirmReturnDelayed().Returns(false); // юзер отказывается "Вернуть фильм"

            var testMovieCopy = new MovieCopy(9999, "TEST COMMENT", 50)
            {
                Available = false
            };                                                                               // копия у кого-то в аренде

            var startDate       = new DateTime(2020, 01, 20);
            var expectedEndDate = new DateTime(2020, 01, 25);
            var returnDate      = new DateTime(2020, 01, 28);
            var leasing         = new Leasing(startDate, expectedEndDate, 0, 0, 50)
            {
                MovieCopy = testMovieCopy
            };

            _view.CurrentLeasing = leasing;

            const decimal fineMultiplier = 2;

            //act
            _presenter.ReturnDelayed(returnDate, fineMultiplier);

            //assert
            Assert.AreEqual(false, _view.CurrentLeasing.MovieCopy.Available);

            _view.DidNotReceive().Close();
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> Edit(int id, [Bind("LeasingId,LeasingStart,LeasingEnd,LeasingExtend,Id")] Leasing leasing)
        {
            if (id != leasing.LeasingId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(leasing);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LeasingExists(leasing.LeasingId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Id"] = new SelectList(_context.ApplicationUsers, "Id", "Id", leasing.Id);
            return(View(leasing));
        }
Ejemplo n.º 4
0
 public ActionResult HotDealsEdit()
 {
     if (!string.IsNullOrEmpty(Session["username"] as string))
     {
         if (Session["roleid"].ToString() == "1" || Session["roleid"].ToString() == "7")
         {
             try
             {
                 Leasing     leasing = new Leasing();
                 LeasingData ld      = new LeasingData();
                 leasing.hotDeals = ld.GetHotDeals();
                 return(View(leasing.hotDeals));
             }
             catch (Exception ex)
             {
                 return(View("Error", ex));
             }
         }
         else
         {
             return(View("Accessdenied"));
         }
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
Ejemplo n.º 5
0
        CarBusiness GenerateBusiness(int index)
        {
            var cb = new CarBusiness();

            cb.Name  = "Car_" + index.ToString();
            cb.Month = m_month;

            var count = m_rand.Next(1, 10);

            int start = 1;
            int end   = 1;

            var dayCount = m_month.DayCount + 1;

            for (int i = 0; i < count && end < dayCount; i++)
            {
                var b = new Leasing();
                b.Title        = "bussy_" + i.ToString();
                start          = m_rand.Next(end, dayCount);
                b.DateStart    = new DateTime(m_month.Year, m_month.Index, start);
                end            = m_rand.Next(start, dayCount);
                b.DateEnd      = new DateTime(m_month.Year, m_month.Index, end);
                b.CurrentMonth = m_month;
                cb.Add(b);
                end++;
            }

            return(cb);
        }
 public ActionResult Index()
 {
     if (!string.IsNullOrEmpty(Session["username"] as string))
     {
         try
         {
             Leasing            leasing = new Leasing();
             LeasingDataMonthly ld      = new LeasingDataMonthly();
             leasing.NewTenantOpenings = ld.GetNewTenantOpeningData();
             leasing.DeliveredSpaces   = ld.GetDelieverdSpaces();
             leasing.keyDeals          = ld.GetKeyDeals();
             leasing.completedRenewals = ld.GetCompletedRenewals();
             leasing.hotDeals          = ld.GetHotDeals();
             leasing.tenantsAtRisks    = ld.GetTenantAtRisk();
             leasing.tenantClosures    = ld.GetTenantClosure();
             return(View(leasing));
         }
         catch (Exception ex)
         {
             return(View("Error", ex));
         }
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
 public ActionResult TenantsClosureEdit()
 {
     if (!string.IsNullOrEmpty(Session["username"] as string))
     {
         if (Session["roleid"].ToString() == "1" || Session["roleid"].ToString() == "7")
         {
             try
             {
                 Leasing            leasing = new Leasing();
                 LeasingDataMonthly ld      = new LeasingDataMonthly();
                 leasing.tenantClosures = ld.GetTenantClosure();
                 return(View(leasing.tenantClosures));
             }
             catch (Exception ex)
             {
                 return(View("Error", ex));
             }
         }
         else
         {
             return(View("Accessdenied"));
         }
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
Ejemplo n.º 8
0
        public bool ConfirmNewLeasing()
        {
            if (customersComboBox.SelectedIndex > -1)
            {
                if (startDatePicker.Value.Date < endDatePicker.Value.Date)
                {
                    var leasing = new Leasing(startDatePicker.Value.Date, endDatePicker.Value.Date, Convert.ToInt32(customersComboBox.SelectedValue),
                                              CurrentMovieCopy.Id, CurrentMovieCopy.PricePerDay);
                    var result = MessageBox.Show($"Прокат {CurrentMovie.Title}, {CurrentMovieCopy.Commentary} " +
                                                 $"с {startDatePicker.Value.Date} по {endDatePicker.Value.Date} за {leasing.TotalPrice}?", "Прокат", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        return(true);
                    }
                }
                else
                {
                    MessageBox.Show("Дата окончания проката не может быть раньше даты начала");
                }
            }
            else
            {
                MessageBox.Show("Укажите клиента");
            }

            return(false);
        }
Ejemplo n.º 9
0
        void OnBuisenessSetted(Leasing business)
        {
            if (business == null)
            {
                return;
            }

            Text = business.Title;

            OnWidthChanged(ColumnWidth);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Create([Bind("LeasingId,LeasingStart,LeasingEnd,LeasingExtend,Id")] Leasing leasing)
        {
            if (ModelState.IsValid)
            {
                _context.Add(leasing);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["Id"] = new SelectList(_context.ApplicationUsers, "Id", "Id", leasing.Id);
            return(View(leasing));
        }
        public Task <bool> Handle(CreateLeasingCommand request, CancellationToken cancellationToken)
        {
            var leasing = new Leasing
            {
                WorkorderId = request.WorkorderId,
                Amount      = request.Amount,
                Currency    = request.Currency
            };

            _leasingRepository.Add(leasing);
            return(Task.FromResult(true));
        }
        public void AddLeasing(Leasing leasing)
        {
            if (!_leasingView.ConfirmNewLeasing())
            {
                return;
            }
            var movieCopy = _context.MoviesCopies.Single(c => c.Id == leasing.MovieCopyId);

            movieCopy.Available = false;
            _context.LeasedCopies.Add(leasing);
            _context.SaveChanges();
            _leasingView.Close();
        }
        public string Print()
        {
            Leasing            leasing = new Leasing();
            LeasingDataMonthly ld      = new LeasingDataMonthly();

            leasing.NewTenantOpenings = ld.GetNewTenantOpeningData();
            leasing.DeliveredSpaces   = ld.GetDelieverdSpaces();
            leasing.keyDeals          = ld.GetKeyDeals();
            leasing.completedRenewals = ld.GetCompletedRenewals();
            leasing.hotDeals          = ld.GetHotDeals();
            leasing.tenantsAtRisks    = ld.GetTenantAtRisk();
            leasing.tenantClosures    = ld.GetTenantClosure();
            return(new PageOrientations().RenderRazorViewToString(this, "Print", leasing));
        }
Ejemplo n.º 14
0
        public LeasingForm()
        {
            InitializeComponent();

            leaseButton.Click += (sender, args) =>
            {
                var startDate   = startDatePicker.Value.Date;
                var endDate     = endDatePicker.Value.Date;
                var customerId  = Convert.ToInt32(customersComboBox.SelectedValue);
                var movieCopyId = CurrentMovieCopy.Id;
                var pricePerDay = CurrentMovieCopy.PricePerDay;
                var leasing     = new Leasing(startDate, endDate, customerId, movieCopyId, pricePerDay);
                OnLeaseMovieCopy?.Invoke(leasing);
            };
        }
Ejemplo n.º 15
0
        static CarBusiness GenerateBusiness(int index, Month start, Month end)
        {
            var cb = new CarBusiness();

            cb.Name = "Car_" + index.ToString();
            //start = new Month(start.Year, m_rand.Next(start.Index, end.Index + 1));
            //end = new Month(end.Year, m_rand.Next(start.Index, end.Index + 1));
            cb.Monthes = Month.GetMonthes(start, end);

            var count = m_rand.Next(1, 10);

            int startDayI  = 1;
            var dayCount   = Month.GetDaysCount(start, end);
            int endDayI    = end.DayCount;
            int monthIndex = 0;

            var blockedFlag = m_rand.Next(1, 25);
            var addBlocked  = App.SearchSettings.IncludeBlocked;

            for (int mi = start.Index; mi <= end.Index; mi++)
            {
                monthIndex = mi;

                for (int i = 0; i < count && endDayI <= end.DayCount; i++)
                {
                    var b = new Leasing();
                    b.Title     = "bussy_" + i.ToString();
                    startDayI   = m_rand.Next(startDayI, endDayI);
                    b.DateStart = new DateTime(start.Year, monthIndex, startDayI);
                    endDayI     = m_rand.Next(startDayI, dayCount);
                    //b.DateEnd = new DateTime(end.Year, end.Index, end.DayCount <= endI ? endI : end);
                    b.Monthes = cb.Monthes;
                    b.CarName = cb.Name;
                    b.Saler   = "Saler_" + i.ToString();

                    if (addBlocked)
                    {
                        b.Blocked = blockedFlag == 23; //магическое число 23 (просто случайное число в пределах диапазона)
                    }
                    cb.Add(b);
                    endDayI++;
                }
            }

            return(cb);
        }
        public void Run()
        {
            //arrange
            // добавляем и сразу же сохраняем по цепочке чтобы последующие элементы получили актуальное значение необходимого Id
            var testMovie = new MovieOriginal("TEST TITLE", "TEST DESCR", 9999);

            _context.MoviesOriginal.Add(testMovie);
            _context.SaveChanges();
            var testMovieCopy = new MovieCopy(testMovie.Id, "TEST COMMENT", 9999);

            _context.MoviesCopies.Add(testMovieCopy);
            _context.SaveChanges();
            var testCustomer = new Customer("TEST NAME");

            _context.Customers.Add(testCustomer);
            _context.SaveChanges();
            var testLeasing = new Leasing(DateTime.Now, DateTime.Now, testCustomer.Id, testMovieCopy.Id, 9999);

            _context.LeasedCopies.Add(testLeasing);
            _context.SaveChanges();

            //act
            _presenter.Run(testLeasing.Id);

            //assert
            Assert.AreEqual(testLeasing.StartDate, _view.CurrentLeasing.StartDate);
            Assert.AreEqual(testLeasing.ExpectedEndDate, _view.CurrentLeasing.ExpectedEndDate);
            Assert.AreEqual(testLeasing.CustomerId, _view.CurrentLeasing.CustomerId);
            Assert.AreEqual(testLeasing.MovieCopyId, _view.CurrentLeasing.MovieCopyId);
            Assert.AreEqual(testLeasing.TotalPrice, _view.CurrentLeasing.TotalPrice);

            Assert.AreEqual(testMovieCopy.MovieId, _view.CurrentMovieCopy.MovieId);
            Assert.AreEqual(testMovieCopy.Commentary, _view.CurrentMovieCopy.Commentary);
            Assert.AreEqual(testMovieCopy.PricePerDay, _view.CurrentMovieCopy.PricePerDay);

            Assert.AreEqual(testMovie.Title, _view.CurrentMovie.Title);
            Assert.AreEqual(testMovie.Description, _view.CurrentMovie.Description);
            Assert.AreEqual(testMovie.YearReleased, _view.CurrentMovie.YearReleased);

            Assert.AreEqual(testCustomer.Name, _view.CurrentCustomer.Name);

            _view.Received().Show();
        }
Ejemplo n.º 17
0
        public void LeasingAdd_Confirmed()
        {
            //arrange
            _view.ConfirmNewLeasing().Returns(true); // юзер соглашается "Подтвердить нового пользователя" (MessageBox)

            var testMovieCopy = new MovieCopy(9999, "TEST", 9999);

            _context.MoviesCopies.Add(testMovieCopy);
            _context.SaveChanges();

            var testLeasing = new Leasing(DateTime.Now, DateTime.Now, 9999, testMovieCopy.Id, 9999);

            //act
            _presenter.AddLeasing(testLeasing);

            //assert
            Assert.AreEqual(false, testMovieCopy.Available);
            Assert.AreEqual(true, _context.LeasedCopies.Any());
            _view.Received().Close();
        }
Ejemplo n.º 18
0
        public void LeasingAdd_NotConfirmed()
        {
            //arrange
            _view.ConfirmNewLeasing().Returns(false);

            var testMovieCopy = new MovieCopy(9999, "TEST", 9999);

            _context.MoviesCopies.Add(testMovieCopy);
            _context.SaveChanges();

            var testLeasing = new Leasing(DateTime.Now, DateTime.Now, 9999, testMovieCopy.Id, 9999);

            //act
            _presenter.AddLeasing(testLeasing);

            //assert
            Assert.AreEqual(true, testMovieCopy.Available);
            Assert.AreEqual(false, _context.LeasedCopies.Any());
            _view.DidNotReceive().Close();
        }
Ejemplo n.º 19
0
 public ActionResult TenantsAtRiskEdit()
 {
     if (!string.IsNullOrEmpty(Session["username"] as string))
     {
         if (Session["roleid"].ToString() == "1" || Session["roleid"].ToString() == "7")
         {
             Leasing     leasing = new Leasing();
             LeasingData ld      = new LeasingData();
             leasing.tenantsAtRisks = ld.GetTenantAtRisk();
             return(View(leasing.tenantsAtRisks));
         }
         else
         {
             return(View("Accessdenied"));
         }
     }
     else
     {
         return(RedirectToAction("Index", "Login"));
     }
 }
Ejemplo n.º 20
0
        static CarBusiness GenerateBusiness(int index, Month month)
        {
            var cb = new CarBusiness();

            cb.Name  = "Car_" + index.ToString();
            cb.Month = month;

            var count = m_rand.Next(1, 10);

            int start = 1;
            int end   = 1;

            var dayCount = month.DayCount + 1;

            var blockedFlag = m_rand.Next(1, 25);
            var addBlocked  = App.SearchSettings.IncludeBlocked;

            for (int i = 0; i < count && end < dayCount; i++)
            {
                blockedFlag = m_rand.Next(1, 25);
                var b = new Leasing();
                b.Title        = "bussy_" + i.ToString();
                start          = m_rand.Next(end, dayCount);
                b.DateStart    = new DateTime(month.Year, month.Index, start);
                end            = m_rand.Next(start, dayCount);
                b.DateEnd      = new DateTime(month.Year, month.Index, end);
                b.CurrentMonth = month;
                b.CarName      = cb.Name;
                b.Saler        = "Saler_" + i.ToString();

                if (addBlocked)
                {
                    b.Blocked = blockedFlag == 23; //магическое число 23 (просто случайное число в пределах диапазона)
                }
                cb.Add(b);
                end++;
            }

            return(cb);
        }
Ejemplo n.º 21
0
        private void btLeasing_Click(object sender, EventArgs e)
        {
            if (dgvAirplanesToBuy.SelectedRows.Count == 0 || dgvAirplaneData.Rows.Count == 0)
            {
                return;
            }
            double  priceL   = (int)dgvAirplaneData.Rows[3].Cells[1].Value;                                  //цена за лизинг в месяц
            double  priceAll = (int)dgvAirplaneData.Rows[1].Cells[1].Value;
            Leasing leasing  = new Leasing(priceL, priceAll, dt);

            leasing.Activate();
            if (leasing.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            int idx = dgvAirplanesToBuy.SelectedRows[0].Index;                                                  //самолет, которые хотят взять в лизинг

            airport.ListAirplanes.Add(CopyAirplane(airport.ListAirplanesToBuy[idx]));                           //добавляем самолет в аэропорт
            dgvAirplanesOfTheAirport.Rows.Add(airport.ListAirplanes[airport.ListAirplanes.Count - 1].Model);
            airport.ListAirplanes[airport.ListAirplanes.Count - 1].Status  = Airplane.StatusAirplane.INLEASING; //указываем, что самолет в лизинге
            airport.ListAirplanes[airport.ListAirplanes.Count - 1].Tenancy = leasing.tenancy;                   //устанавливаем дату, когда самолет перейдет в собственность
        }
Ejemplo n.º 22
0
        public MonthBusiness GetBusinessByMonth(Month month, SearchSettings settings = null, Region region = null)
        {
            if (settings == null)
            {
                settings = App.SearchSettings;
            }

            var carBusinesses = new List <CarBusiness>();

            #region Old

            /*
             * var sql = $@"SELECT DISTINCT
             *                            l.[Document No_]
             *                          ,h.[Salesperson Code]
             *                          ,h.[Bal_ Account No_]
             *                          ,h.[Sell-to Customer Name] as Buyer
             *                          ,h.[Bill-to Name]
             *                          ,h.[Ship-to Name]
             *                      ,l.[Description] as CarName
             *                      ,l.[Vehicle Reg_ No_] as CarNumber
             *                          ,h.[Venicle Operation Area]
             *                          ,h.[Date Begin] as DateStart
             *                          ,h.[Time Begin]
             *                          ,h.[Date End] as DateEnd
             *                          ,h.[Time End]
             *                          ,h.[Comment Text] as Comment
             *                  FROM [CARLSON_Test_10052018].[dbo].[Carlson$Sales{(invoice ? " Invoice" : "")} Line] l
             *                  INNER JOIN [CARLSON_Test_10052018].[dbo].[Carlson$Sales{(invoice ? " Invoice" : "")} Header] h ON h.[Sell-to Customer No_] = l.[Sell-to Customer No_]
             *                  WHERE l.[Vehicle Reg_ No_] != ''
             *                  AND h.[Date End] > h.[Date Begin]
             *                  ORDER BY l.[Document No_], h.[Date Begin]";
             */
            #endregion

            var sql = string.Empty;

            if (settings.SelectedDBSearchType == DBSearchType.All)
            {
                var sb = new StringBuilder(1000);
                sb.Append("SELECT DISTINCT (");
                //настройки с поиском старых заказов
                var oldSettings = new SearchSettings(settings);
                oldSettings.SelectedDBSearchType = DBSearchType.Old;

                sb.Append(GetBusinessByMonthQuery(month, oldSettings, region));
                sb.Append("\r\n UNION \r\n"); //объединяем два запроса

                //настройки с поиском актуальных заказов
                var curentSettings = new SearchSettings(settings);
                curentSettings.SelectedDBSearchType = DBSearchType.Curent;
                sb.Append(GetBusinessByMonthQuery(month, curentSettings, region));
                sb.Append(")");

                sql = sb.ToString();
            }
            else
            {
                sql = GetBusinessByMonthQuery(month, settings, region);
            }
            //sql = $@"SELECT
            //             i.[No_]
            //            , i.[Description] as CarName
            //            , i.[Vehicle Reg_ No_] as CarNumber
            //            , i.[Blocked]
            //            , l.[Document No_]
            //         ,h.[Salesperson Code]
            //         ,h.[Bal_ Account No_]
            //         ,h.[Sell-to Customer Name] as Buyer
            //         ,h.[Bill-to Name]
            //         ,h.[Ship-to Name]
            //         ,h.[Venicle Operation Area]
            //         ,h.[Date Begin] as DateStart
            //         ,h.[Time Begin]
            //         ,h.[Date End] as DateEnd
            //         ,h.[Time End]
            //         ,h.[Comment Text] as Comment
            //             FROM Carlson$Item i
            //              LEFT JOIN [Carlson$Sales {(settings.SelectedDBSearchType == DBSearchType.Curent ? string.Empty : invoice)}Line] l ON l.No_ = i.No_
            //              LEFT JOIN [Carlson$Sales {(settings.SelectedDBSearchType == DBSearchType.Curent ? string.Empty : invoice)}Header] h ON h.No_ = l.[Document No_]

            //            WHERE 1 = 1
            //                {(settings.IncludeBlocked ? string.Empty : "AND i.Blocked = 0")}
            //              AND i.IsService = 0
            //              AND i.IsFranchise = 0
            //                AND h.[Date Begin] IS NOT NULL
            //                {(region == null || string.IsNullOrWhiteSpace(region.DBKey) ? "" : "AND i.[Responsibility Center] = '" + region.DBKey + "'")}
            //                AND ((h.[Date Begin] BETWEEN '{month.GetSqlDate(1)}' AND '{month.Next().GetSqlDate(1)}') OR (h.[Date End] BETWEEN '{month.GetSqlDate(1)}' AND '{month.Next().GetSqlDate(1)}'))

            //            ORDER BY l.[Document No_]";

            try
            {
                using (var con = new SqlConnection(m_connectionString))
                {
                    var com = new SqlCommand(sql);
                    com.Connection = con;

                    con.Open();

                    using (var reader = com.ExecuteReader())
                    {
                        var         curentCar  = string.Empty;
                        var         previosCar = string.Empty;
                        var         buyer      = string.Empty;
                        CarBusiness cb         = null;
                        while (reader.Read())
                        {
                            curentCar = (string)reader["CarName"];

                            var no_ = (string)reader["No_"];

                            cb = carBusinesses.FirstOrDefault(_cb => _cb.ItemNo.Equals(no_));
                            if (cb == null)
                            {
                                previosCar = curentCar;

                                cb        = new CarBusiness();
                                cb.Month  = month;
                                cb.ItemNo = (string)reader["No_"];
                                carBusinesses.Add(cb);

                                var number        = ((string)reader["CarNumber"]).Trim();
                                var lastCharIndex = number.Last(c => char.IsLetter(c)) + 1;

                                if ((lastCharIndex) < number.Length)
                                {
                                    number = number.Substring(lastCharIndex, number.Length - lastCharIndex);
                                }

                                cb.Name = $"{curentCar} ({number})";
                            }

                            buyer = (string)reader["Buyer"];

                            if (cb.Count > 0 && cb.Business.Last().Title.Equals(buyer))
                            {
                                cb.Business.Last().DateEnd = ((DateTime)reader["DateEnd"]);
                            }
                            else
                            {
                                var b = new Leasing();
                                b.DateStart    = ((DateTime)reader["DateStart"]);
                                b.DateEnd      = ((DateTime)reader["DateEnd"]);
                                b.Title        = buyer;
                                b.Type         = BusinessType.Leasing;
                                b.Comment      = (string)reader["Comment"];
                                b.CurrentMonth = month;

                                cb.Add(b);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_loger.Log("Возникло исключение при запросе выборки из БД", ex);
            }

            var monthBusiness = new MonthBusiness(carBusinesses);
            monthBusiness.Month = month;

            return(monthBusiness);
        }
 public void Add(Leasing leasing)
 {
     _leasingDbContext.Add(leasing);
     _leasingDbContext.SaveChanges();
 }
Ejemplo n.º 24
0
        void OnWidthChanged(double newWidth)
        {
            //где newWidth - ширина колонки дня

            if (newWidth <= 0d)
            {
                return;
            }

            Leasing b = Business;

            if (b == null)
            {
                return;
            }

            #region расчёт отступа слева

            var offsetLeft = 0d;
            var startDay   = b.DateStart.Day;

            //если начало в текущем месяце
            if (b.MonthCount == 1 || b.DateStart.Month == b.CurrentMonth.Index)
            {
                if (startDay > 1)
                {
                    //т.к. дня нумеруются с единицы, то для первого дня отступ будет 0 дней, для второго - 1 и т.д.
                    var dayOffsetCount = startDay - 1;
                    offsetLeft = dayOffsetCount * (newWidth) + (dayOffsetCount * 1); //1 - ширина границ у колонок
                }
            }
            //для продолжения / сквозного месяца смещения нет

            //изменяем отступ элемента от левого края
            if (offsetLeft > 0)
            {
                if (offsetLeft != Margin.Left)
                {
                    Margin = new Thickness(offsetLeft, Margin.Top, Margin.Right, Margin.Bottom);
                }
            }

            #endregion

            #region  асчёт ширины TextBlock'a

            var width = 0d;

            var dayCount = 1; //прибавляем единичку, так как при сложении/вычитании теряем день

            //если машину взяли/вернули в течении 1 месяца
            if (b.MonthCount == 1)
            {
                dayCount += (b.DateEnd - b.DateStart).Days;
            }

            //если машина занята несколько месяцев
            else
            {
                var currentMonth = b.CurrentMonth.Index;

                //для месяца, в котором начали съём
                if (b.DateStart.Month == currentMonth)
                {
                    //отсчитываем от конца начального месяца
                    dayCount += (b.CurrentMonth.DayCount - b.DateStart.Day);
                }

                //для месяца в котором закончили съём
                else if (b.DateEnd.Month == currentMonth)
                {
                    dayCount = b.DateEnd.Day; //индекс дня - количество дней от начала месяца
                }
                //если период начинается и заканчивается за пределами текущего месяца
                else
                {
                    //берём первую дату месяца
                    var curentDate = b.CurrentMonth[1];
                    //если 'начало' < 'текущая дата' < 'конец'
                    dayCount = ((b.DateStart < curentDate) && (curentDate < b.DateEnd))
                        ? b.CurrentMonth.DayCount //берём количество дней в текущем месяце (закрашиваем всё)
                        : 0;                      //0 - хз чего ещё делать. В этом месяце занятости не было, хз как сюда попало
                }
            }

            if (dayCount < 0)
            {
                m_loger.Log("Получен отрицательный период аренды. Значение сброшено в 0", MessageType.Debug
                            , new LogParameter("Съёмщик", b.Title)
                            , new LogParameter("Комментарий", b.Comment)
                            , new LogParameter("Дата начала", b.DateStart.ToShortDateString())
                            , new LogParameter("Дата окончания", b.DateEnd.ToShortDateString()));

                dayCount = 0;
            }

            width = (newWidth * dayCount) + dayCount; //прибавляем количество дней, т.к. ширина границ - 1

            Width   = width;
            b.Width = width.ToString() + " | " + ActualWidth.ToString();

            #endregion
        }
Ejemplo n.º 25
0
        public MonthBusiness GetBusinessByMonthes(Month start, Month end, SearchSettings settings = null, Region region = null)
        {
            if (settings == null)
            {
                settings = App.SearchSettings;
            }

            var carBusinesses = new List <CarBusiness>();

            var sql = string.Empty;

            if (settings.SelectedDBSearchType == DBSearchType.All)
            {
                var sb = new StringBuilder(1000);
                sb.Append("SELECT DISTINCT ").Append("(");
                //настройки с поиском старых заказов
                var oldSettings = new SearchSettings(settings);
                oldSettings.SelectedDBSearchType = DBSearchType.Old;

                sb.Append(GetBusinessByMonthesQuery(start, end, oldSettings, region));
                //sb.Append(")");
                sb.Append("\r\n UNION \r\n");//.Append("("); //объединяем два запроса

                //настройки с поиском актуальных заказов
                var curentSettings = new SearchSettings(settings);
                curentSettings.SelectedDBSearchType = DBSearchType.Curent;
                sb.Append(GetBusinessByMonthesQuery(start, end, curentSettings, region));
                sb.Append(")");//.Append(" ORDER BY [Document No_]");

                sql = sb.ToString();
            }
            else
            {
                sql = GetBusinessByMonthesQuery(start, end, settings, region);
            }

            try
            {
                using (var con = new SqlConnection(m_connectionString))
                {
                    var com = new SqlCommand(sql);
                    com.Connection = con;

                    con.Open();

                    using (var reader = com.ExecuteReader())
                    {
                        var         curentCar  = string.Empty;
                        var         previosCar = string.Empty;
                        var         buyer      = string.Empty;
                        CarBusiness cb         = null;
                        while (reader.Read())
                        {
                            curentCar = (string)reader["CarName"];

                            var no_ = (string)reader["No_"];

                            cb = carBusinesses.FirstOrDefault(_cb => _cb.ItemNo.Equals(no_));
                            if (cb == null)
                            {
                                previosCar = curentCar;

                                cb         = new CarBusiness();
                                cb.Monthes = Month.GetMonthes(new DateTime(start.Year, start.Index, 1), new DateTime(end.Year, end.Index, 1));
                                cb.ItemNo  = (string)reader["No_"];
                                carBusinesses.Add(cb);

                                var number        = ((string)reader["CarNumber"]).Trim();
                                var lastCharIndex = number.Last(c => char.IsLetter(c)) + 1;

                                if ((lastCharIndex) < number.Length)
                                {
                                    number = number.Substring(lastCharIndex, number.Length - lastCharIndex);
                                }

                                cb.Name = $"{curentCar} ({number})";
                            }

                            buyer = (string)reader["Buyer"];

                            if (cb.Count > 0 && cb.Business.Last().Title.Equals(buyer))
                            {
                                cb.Business.Last().DateEnd = ((DateTime)reader["DateEnd"]);
                            }
                            else
                            {
                                var b = new Leasing();
                                b.DateStart = ((DateTime)reader["DateStart"]);
                                b.DateEnd   = ((DateTime)reader["DateEnd"]);
                                b.Title     = buyer;
                                b.Type      = BusinessType.Leasing;
                                b.Comment   = (string)reader["Comment"];
                                b.Monthes   = Month.GetMonthes(b.DateStart, b.DateEnd);
                                b.Saler     = (string)reader["Saler"];
                                b.Blocked   = (bool)reader["Blocked"];

                                cb.Add(b);
                            }
                        }
                    }
                }
            }
            catch (SqlException sqlEx)
            {
                m_loger.Log("Возникло исключение при запросе выборки из БД", sqlEx,
                            new LogParameter("Запрос", sql));
            }
            catch (Exception ex)
            {
                m_loger.Log("Возникло исключение при запросе выборки из БД", ex);
            }

            var monthBusiness = new MonthBusiness(carBusinesses);

            monthBusiness.Monthes = Month.GetMonthes(new DateTime(start.Year, start.Index, 1), new DateTime(end.Year, end.Index, 1));

            return(monthBusiness);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Creates a vehicle of a given state dependent on selected customer type(null,pri,bus). Has inputbox fault logic to stop the creation of bugged inputs
        /// </summary>
        private void create_vehicle_click(object sender, RoutedEventArgs e)
        {
            bool car_null_exception     = false;
            bool truck_null_exception   = false;
            bool car_format_exception   = false;
            bool truck_format_exception = false;
            bool error_found_truck      = false;
            bool error_found_car        = false;

            string car_boxes_empty_string    = "";
            string truck_boxes_empty_string  = "";
            string car_wrong_format_string   = "";
            string truck_wrong_format_string = "";

            //selected private
            #region
            if (select_combobox_customer.SelectedValue is Private || select_combobox_customer.SelectedValue == null)
            {
                //Test if text boxes in the car section are empty.
                if (string.IsNullOrEmpty(textbox_car_model.Text) == true ||
                    string.IsNullOrEmpty(textbox_car_license.Text) == true ||
                    string.IsNullOrEmpty(textbox_car_price.Text) == true ||
                    string.IsNullOrEmpty(textbox_car_colour.Text) == true)
                {
                    car_boxes_empty_string = "You have forgotten to fill in informationboxes in your car informations\n";
                    car_null_exception     = true;
                }

                //Test if text boxes in the car section are in the right format
                if (IsALLnumeric(textbox_car_price.Text, false) == false)
                {
                    car_wrong_format_string = "Your have format errors in your car informations\n";
                    car_format_exception    = true;
                }
                if ((car_null_exception ||
                     car_format_exception) == true)
                {
                    MessageBox.Show(car_boxes_empty_string +
                                    car_wrong_format_string);
                    error_found_car = true;
                }
            }

            //selected business
            if (select_combobox_customer.SelectedValue is Business || select_combobox_customer.SelectedValue == null)
            {
                //Test if text boxes in the truck section are empty
                if (string.IsNullOrEmpty(textbox_truck_model.Text) == true ||
                    string.IsNullOrEmpty(textbox_truck_license.Text) == true ||
                    string.IsNullOrEmpty(textbox_truck_rent.Text) == true ||
                    string.IsNullOrEmpty(textbox_truck_colour.Text) == true)
                {
                    truck_boxes_empty_string = "You have forgotten to fill in informationboxes in your truck informations \n";
                    truck_null_exception     = true;
                }
                //Test if text boxes in the truck section are in the right format
                if (IsALLnumeric(textbox_truck_rent.Text, false) == false)
                {
                    truck_wrong_format_string = "Your have format errors in your truck informations\n";
                    truck_format_exception    = true;
                }
            }
            //If any of the boxes were in the wrong format or empty,
            //then show the messagebox notifying the user and break the finalize action.
            if ((truck_null_exception ||
                 truck_format_exception) == true)
            {
                MessageBox.Show(truck_boxes_empty_string +
                                truck_wrong_format_string);
                error_found_truck = true;
            }

            #endregion
            // if no errors found then complete the finalize action and bring up the finalize window.

            //check if private customer and create contract.
            if (error_found_car == false)
            {
                if (select_combobox_customer.SelectedValue == null)
                {
                    if (combo_veh_size_small_item.IsSelected) //Remember to add size parameter
                    {
                        Small myveh = new Small(textbox_car_colour.Text,
                                                textbox_car_model.Text,
                                                Convert.ToInt32(textbox_car_price.Text),
                                                "in stock",
                                                textbox_car_license.Text);

                        mycardealer.AddVehicle(myveh);
                    }
                    if (combo_veh_size_large_item.IsSelected)
                    {
                        Large myveh = new Large(textbox_car_colour.Text,
                                                textbox_car_model.Text,
                                                Convert.ToInt32(textbox_car_price.Text),
                                                "in stock",
                                                textbox_car_license.Text);

                        mycardealer.AddVehicle(myveh);
                    }


                    MessageBox.Show("Car Added");
                    this.comboBox_Del_Vehicle.ItemsSource = mycardealer.VehicleList;
                }

                if (select_combobox_customer.SelectedValue is Private)
                {
                    if (combo_veh_size_small_item.IsSelected) //Remember to add size parameter
                    {
                        Small myveh = new Small(textbox_car_colour.Text,
                                                textbox_car_model.Text,
                                                Convert.ToInt32(textbox_car_price.Text),
                                                "sold",
                                                textbox_car_license.Text);

                        mycardealer.AddVehicle(myveh);
                        Private b = (Private)select_combobox_customer.SelectedValue;
                        mycardealer.DeleteCustomer(b.Address);
                        Contract gui_contract = new Contract(myveh, "contract");

                        b.AddContract(gui_contract);
                        mycardealer.AddCustomer(b);
                        //MessageBox.Show("ADDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD contract\n");
                    }

                    if (combo_veh_size_large_item.IsSelected)
                    {
                        Large myveh = new Large(textbox_car_colour.Text,
                                                textbox_car_model.Text,
                                                Convert.ToInt32(textbox_car_price.Text),
                                                "sold",
                                                textbox_car_license.Text);

                        mycardealer.AddVehicle(myveh);
                        Private b = (Private)select_combobox_customer.SelectedValue;
                        //Delete the customer without the contract
                        mycardealer.DeleteCustomer(b.Address);
                        Contract gui_contract = new Contract(myveh, "contract");
                        b.AddContract(gui_contract);
                        //Update the new customer with the contract
                        mycardealer.AddCustomer(b);
                    }
                    //       mycardealer.SaveCustomersToFile();

                    this.comboBox_del_customer.ItemsSource = mycardealer.LoadCustomers();
//__________
                    this.select_combobox_customer.ItemsSource = mycardealer.CustomerList;

                    MessageBox.Show(mycardealer.ToString());
                }

                mycardealer.SaveVehiclesToFile();
            }
            //check if business customer and create lease.
            if (error_found_truck == false)
            {
                if (select_combobox_customer.SelectedValue == null)
                {
                    Truck myveh = new Truck(textbox_truck_colour.Text,
                                            textbox_truck_model.Text,
                                            Convert.ToInt32(textbox_truck_rent.Text),
                                            "in stock",
                                            textbox_truck_license.Text);

                    mycardealer.AddVehicle(myveh);
                    MessageBox.Show(mycardealer.ToString());
                    //this.comboBox_Del_Vehicle.ItemsSource = mycardealer.VehicleList;
                }

                if (select_combobox_customer.SelectedValue is Business)
                {
                    Truck myveh = new Truck(textbox_truck_colour.Text,
                                            textbox_truck_model.Text,
                                            Convert.ToInt32(textbox_truck_rent.Text),
                                            "leased",
                                            textbox_truck_license.Text);

                    mycardealer.AddVehicle(myveh);
                    Business b = (Business)select_combobox_customer.SelectedValue;
                    mycardealer.DeleteCustomer(b.Address);
                    Leasing gui_contract = new Leasing(myveh,
                                                       "truckContract",
                                                       Convert.ToInt32(textbox_truck_rent.Text),
                                                       datepicker_truck_start.SelectedDate,
                                                       datepicker_truck_end.SelectedDate);
                    b.AddLease(gui_contract);
                    mycardealer.AddCustomer(b);
                    MessageBox.Show(mycardealer.ToString());
                }

                mycardealer.SaveVehiclesToFile();
                this.comboBox_Del_Vehicle.ItemsSource = mycardealer.VehicleList;
                MessageBox.Show(mycardealer.ToString());
            }
        }
Ejemplo n.º 27
0
        public async Task <IActionResult> Leasing()
        {
            List <ShoppingCart> cart = SessionHelper.GetObjectFromJson <List <ShoppingCart> >(HttpContext.Session, "cart");

            var id = _userManager.GetUserId(User);

            try
            {
                Leasing l = new Leasing
                {
                    LeasingStart = DateTime.Now,
                    Id           = id
                };
                _context.Add(l);

                LeasingDetail ld;

                foreach (var item in cart)
                {
                    ld = new LeasingDetail
                    {
                        LeasingId           = l.LeasingId,
                        LeasingDetailAmount = item.Quantity,
                        LeasingDetailExtend = true,
                        LeasingDetailEnd    = DateTime.Now.AddYears(1),
                        ProductId           = item.Product.ProductId
                    };
                    var product = _context.Products.Where(p => p.ProductId == item.Product.ProductId).ToList();
                    foreach (var prod in product)
                    {
                        prod.ProductAvailability -= item.Quantity;
                    }

                    _context.Add(ld);
                }

                SmtpClient client = new SmtpClient();
                client.Host                  = "smtp.gmail.com";
                client.Port                  = 587;
                client.EnableSsl             = true;
                client.UseDefaultCredentials = false;
                client.Credentials           = new NetworkCredential("*****@*****.**", "dup@1234");

                var user = await _userManager.GetUserAsync(User);

                var email = user.Email;

                MailMessage mailMessage = new MailMessage();
                mailMessage.From = new MailAddress("*****@*****.**");
                mailMessage.To.Add(email);
                mailMessage.Body    = "Order no. " + l.LeasingId;
                mailMessage.Subject = "Your order is completed. Please pay your bill.";
                mailMessage.Attachments.Add(new Attachment(@"C:\PDF\Leasing.pdf"));
                client.Send(mailMessage);

                _context.SaveChanges();
            }
            catch
            {
                ViewBag.ErrorMessage = "Your cart can't be empty";
                return(RedirectToAction("Index", "Leasings", new { id = _context.Leasings.Last().LeasingId }));
            }

            cart = null;
            SessionHelper.SetObjectAsJson(HttpContext.Session, "cart", cart);

            return(RedirectToAction("Index", "Leasings"));
        }