예제 #1
0
        public IActionResult Rent([FromBody] RentingDto renting, [FromServices] IUserRepository userRepo)
        {
            if (renting is null)
            {
                return(BadRequest(new ErrorModel
                {
                    CauseValue = "null",
                    CauseValueName = nameof(renting),
                    Message = "Renting parameter is not valid!"
                }));
            }

            if (!userRepo.Validate(renting.Email, renting.Password))
            {
                return(ValidationProblem("User credentials are incorrect!", "Email or password is incorrect!", 422, "Unprocessable Entity"));
            }

            string userId = userRepo.GetUserId(renting.Email, renting.Password);

            Renting rented = _repo.RentCar(renting.CarId, userId, renting.Start, renting.End);

            _repo.Save();

            return(new JsonResult(new
            {
                Rented = true,
                From = renting.Start,
                To = renting.End,
                Car = rented.Car.Brand + " " + rented.Car.Model
            }));
        }
예제 #2
0
        public ActionResult Rent(int carId, int days)
        {
            var db = new CarsDbContext();

            var car = db.Cars
                      .Where(c => c.Id == carId)
                      .FirstOrDefault();

            var userId = this.User.Identity.GetUserId();

            if (car == null || car.IsRented || car.OwnerId == userId)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            var renting = new Renting
            {
                CarId      = carId,
                Days       = days,
                RentedOn   = DateTime.Now,
                UserId     = userId,
                TotalPrice = days * car.PricePerDay
            };

            car.IsRented = true;

            db.Rentings.Add(renting);
            db.SaveChanges();

            return(RedirectToAction("Details", new { id = car.Id }));
        }
예제 #3
0
        private int bookingToRenting(int bid)
        {
            try
            {
                //GET booking from bid
                Booking booking = _context.Booking.FromSql("SELECT * FROM eHotel.Booking WHERE bid={0}", parameters: bid).ToList()[0];

                //insert new renting created from the booking
                Object[] insertArray = new object[] { booking.Rid, booking.CustomerSsn, getUser().SSN, booking.StartDate, booking.EndDate };
                _context.Database.ExecuteSqlCommand("INSERT INTO eHotel.Renting (rid,customer_ssn,employee_ssn,start_date,end_date) VALUES ({0},{1},{2},{3},{4})", parameters: insertArray);

                //get inserted renting
                Renting rentingResult = _context.Renting.FromSql("SELECT * FROM eHotel.Renting WHERE rid={0} AND customer_ssn={1} AND employee_ssn={2} AND start_date={3} AND end_date={4}", parameters: insertArray).ToList()[0];

                //delete old booking
                var numDelete = _context.Database.ExecuteSqlCommand("DELETE FROM eHotel.Booking WHERE bid={0}", parameters: booking.Bid);

                //insert old booking in the archive table
                insertArray = new object[] { booking.Bid, booking.Rid, booking.CustomerSsn, booking.StartDate, booking.EndDate };
                _context.Database.ExecuteSqlCommand("INSERT INTO eHotel.bookingarc (baid,rid,customer_ssn,start_date,end_date) VALUES ({0},{1},{2},{3},{4})", parameters: insertArray);

                return rentingResult.Rentid;
            }
            catch (PostgresException ex)
            {
                //TODO better error handling
                TempData["ErrorMessage"] = Constants.GENERICPOSTGREERROR;
                return -1;
            }
        }
예제 #4
0
 public RentingEditorViewModel(Renting renting)
 {
     this.RentingId = renting.Id;
     this.EndsAt    = renting.EndsAt;
     this.Note      = renting.Note;
     this.State     = renting.State;
 }
예제 #5
0
        public async Task <Renting> CreateEntity(UserManager <User> userManager)
        {
            if (this.CustomerId == 0)
            {
                // Uživatel není v databázi, vytvořím ho.
                var user = new User {
                    UserName = this.CustomerName, Email = this.CustomerName
                };
                var userResult = await userManager.CreateAsync(user);

                if (userResult.Succeeded)
                {
                    await userManager.AddToRoleAsync(user, RoleType.Customer.ToString());
                }

                this.CustomerId = user.Id;
            }

            var renting = Renting.Create(
                this.CustomerId, this.StartsAt, this.EndsAt,
                this.State, this.Note, this.ItemIds
                );

            return(renting);
        }
예제 #6
0
        public bool UpdateRenting(Renting id)
        {
            try
            {
                XElement rentingElement = (from p in rentingRoot.Elements()
                                           where Convert.ToInt32(p.Element("idNumber").Value) == id.IdNumber
                                           select p).FirstOrDefault();

                rentingElement.Element("rentalStartDate").Value = id.RentalStartDate.ToString();
                rentingElement.Element("rentalEndDate").Value   = id.RentalEndDate.ToString();
                rentingElement.Element("driversAllowed").Element("idClient1").Value = id.DriversAllowed.idClient1.ToString();
                rentingElement.Element("driversAllowed").Element("idClient2").Value = id.DriversAllowed.idClient2.ToString();
                rentingElement.Element("carId").Value                   = id.CarId.ToString();
                rentingElement.Element("driversNumber").Value           = id.DriversNumber.ToString();
                rentingElement.Element("kilometersAtRentalStart").Value = id.KilometersAtRentalStart.ToString();
                rentingElement.Element("kilometersAtRentalEnd").Value   = id.KilometersAtRentalEnd.ToString();
                rentingElement.Element("returnedWithFault").Value       = id.ReturnedWithFault.ToString();
                rentingElement.Element("rentalPriceDaily").Value        = id.RentalPriceDaily.ToString();

                rentingRoot.Save(rentingPath);

                return(true);
            }

            catch
            {
                return(false);
            }
        }
        public EditRentingForm(IBL bl, int rentingId)
        {
            this.bl            = bl;
            this.rentingToEdit = bl.SelectRenting(rentingId);

            InitializeComponent();

            // Setting form variables
            rentingIdLabel.Text = "Renting #" + rentingToEdit.IdNumber;

            comboBox1.DataSource   = bl.SelectAllCars().Select(c => c.Name).ToList();
            comboBox1.SelectedItem = bl.SelectCar(rentingToEdit.CarId).Name;

            comboBox2.DataSource   = bl.SelectAllClients().Select(c => c.Name).ToList();
            comboBox2.SelectedItem = bl.SelectClient(rentingToEdit.DriversId()[0]).Name;

            dateTimePicker1.Value = rentingToEdit.RentalStartDate;

            if (rentingToEdit.DriversNumber == 2)
            {
                checkBox1.Checked      = true;
                comboBox3.DataSource   = bl.SelectAllClients().Select(c => c.Name).ToList();
                comboBox3.SelectedItem = bl.SelectClient(rentingToEdit.DriversId()[1]).Name;
                checkBox1.Text         = "Change the Second driver:";
            }
            else
            {
                comboBox3.Enabled = false;
            }

            SummaryUpdate();
        }
예제 #8
0
 public void addrenting(Renting r)
 {
     try
     {
         if (dal.GetCar(r.licensePlate) != null && dal.GetClient(r.drivers.IDMainDrivers) != null)
         {
             IEnumerable <Renting> x = isFault(r.drivers.IDMainDrivers);
             if (thisClientIsFault(r.drivers.IDMainDrivers))
             {
                 dal.addrenting(r);
             }
             else
             {
                 throw new Exception("cont renting for this client");
             }
         }
         else
         {
             throw new Exception("not find this infromasion");
         }
     }
     catch (Exception e)
     {
         throw e;
     }
 }
예제 #9
0
        }//

        #endregion
        #region other function
        /// <summary>
        /// הפונקציה הזאת עושה החלפה בין הזמנה שלא נסגרה להזמנה שנסגרה
        /// </summary>
        /// <param name="rent"></param>
        public void close_rent(Renting rent)
        {
            bool    t     = false;
            Renting rent1 = new Renting();

            foreach (var item in (List <Renting>)Dal.return_list(retur.renting))
            {
                if (item.running_code == rent.running_code)
                {
                    t     = true;
                    rent1 = item;
                    break;
                }
            }
            if (t)
            {
                try
                {
                    del_rent(rent1);
                    add_rent(rent);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
예제 #10
0
 public HistoryCreatorViewModel(Renting renting)
 {
     this.RentingId    = renting.Id;
     this.CustomerId   = renting.UserId;
     this.ItemsHistory = renting.Items
                         .Select(i => new HistoryCreatorSubViewModel(i))
                         .ToArray();
 }
예제 #11
0
        }//+

        #endregion
        #region rent
        /// <summary>
        ///להוסיף חוזה השכרה
        /// </summary>
        /// <param name="rent"></param>
        public void add_rent(Renting rent)
        {
            if (rent.running_code == 0)
            {
                rent.running_code = create_new_run_code();
            }
            DataSource.Renting_list.Add(rent);
        }//+
예제 #12
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,StartDate,EndDate,ReturnDate,SelectedBookId")] Renting renting)
        {
            var selectedBook = await _context.Books.FirstOrDefaultAsync(b => b.Id == renting.SelectedBookId);

            if (selectedBook is null)
            {
                ModelState.AddModelError("SelectedBookId", "Cannot find the Book");
                return(View(renting));
            }

            if (id != renting.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    renting.Book = selectedBook;
                    _context.Add(renting);
                    _context.Update(renting);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RentingExists(renting.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            try
            {
                renting.Book = selectedBook;
                _context.Add(renting);
                _context.Update(renting);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RentingExists(renting.EndDate))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(RedirectToAction(nameof(Index)));
        }
예제 #13
0
        public Task <bool> SendRentingCreated(Renting renting, string token, string url)
        {
            var content = this.Process(File.ReadAllText($"wwwroot/emailTemplates/{EmailType.RentingNew.ToString()}.txt", Encoding.UTF8), new { Renting = renting, Url = url });

            return(SendMail(
                       Message.CreateMessage(renting, EmailType.RentingNew.ToLocalizedEnum(typeof(EmailType)), content),
                       token, EmailType.RentingNew
                       ));
        }
예제 #14
0
        public Task <bool> SendRentingCanceled(Renting renting, User canceledBy, string token)
        {
            var content = this.Process(File.ReadAllText($"wwwroot/emailTemplates/{EmailType.RentingCalcelation.ToString()}.txt", Encoding.UTF8), new { Renting = renting, User = canceledBy });

            return(SendMail(
                       Message.CreateMessage(renting, EmailType.RentingCalcelation.ToLocalizedEnum(typeof(EmailType)), content),
                       token, EmailType.RentingCalcelation
                       ));
        }
예제 #15
0
        // GET: Rentings/Create
        public async Task <IActionResult> CreateAsync()
        {
            var renting = new Renting();

            renting.StartDate      = DateTime.Today;
            renting.EndDate        = DateTime.Today.AddDays(15);
            renting.AvailableBooks = await _context.Books.ToListAsync();

            return(View(renting));
        }
        public EndRentingForm(IBL bl, int rentId)
        {
            this.bl        = bl;
            this.rentToEnd = bl.SelectRenting(rentId);

            InitializeComponent();

            // initializing the variables fields
            titleLabel.Text      = "Ending the renting #" + rentToEnd.IdNumber;
            comboBox1.DataSource = bl.SelectAllFaults().Select(f => f.Description).ToList();
        }
예제 #17
0
 public bool UpdateRenting(Renting rentingUpdated)
 {
     try
     {
         return(MyDAL.UpdateRenting(rentingUpdated));
     }
     catch (Exception)
     {
         throw;
     }
 }
예제 #18
0
 /// <summary>
 /// בבחירת מספר השכרה העלאת הנתונים הרלוונטיים לעידכון בסיום ההשכרה
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void numberCallComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (numberCallComboBox.Text != null)
     {
         r = bl.GetRenting(int.Parse(numberCallComboBox.SelectedItem.ToString()));
         if (r != null)
         {
             endRentingDatePicker.Text = r.endRenting.ToString();
         }
     }
 }
예제 #19
0
 public void updateRenting(Renting renting)
 {
     try
     {
         dal.updateRenting(renting);
     }
     catch (Exception e)
     {
         throw e;
     }
 }
        // Edit
        public async Task ReturnRenting(Renting renting)
        {
            _context.Rentings.Attach(renting);
            _context.Entry(renting).Property(r => r.IsActive).IsModified    = true;
            _context.Entry(renting).Property(r => r.ReturnNotes).IsModified = true;
            _context.Entry(renting).Property(r => r.ReturnDate).IsModified  = true;

            _context.Copies.Attach(renting.Copy);
            _context.Entry(renting.Copy).Property(c => c.IsAvailable).IsModified = true;

            await _context.SaveChangesAsync();
        }
예제 #21
0
        public void renoveRenting(int renting)
        {
            Renting r = GetRenting(renting);

            if (r == null)
            {
                throw new Exception("not find this renting to remove");
            }
            DataSource.rentingList.Remove(r);

            throw new Exception("ok!!");
        }
예제 #22
0
        }//+

        #endregion
        #region rent
        /// <summary>
        /// פונקציה שמוסיפה לרשימת ההזמנות
        /// בודקת שקיים רכב פנוי
        /// בודקת שהחוזה השכרה הזאת לא קיימת
        /// בודקת שהמספר של הנהג קיים
        /// בודקת שמספר הרכב קיים
        /// בודקת שהמשכיר בגיל שמתאים להשכרה
        /// בודקת שרמת הרישיון מתאימה לרכב
        /// </summary>
        /// <param name="rent"></param>
        public void add_rent(Renting rent)
        {
            if (!can_rent())
            {
                throw new Exception("אין רכב פנוי להשכרה");
            }

            if (is_rent_exist(rent.running_code))
            {
                throw new Exception("החוזה הזה כבר קיים");
            }

            if (!is_client_exist(rent.driver.first_id))
            {
                throw new Exception("המספר של הנהג הראשי אינו קיים");
            }

            if (!is_car_exist(rent.number_of_rishui))
            {
                throw new Exception("מספר הרכב אינו קיים");
            }

            Client tempC = ((List <Client>)(Dal.return_list(retur.client))).Where(a => a.Id1 == rent.driver.first_id).First();
            car    tempc = ((List <car>)(Dal.return_list(retur.car))).Where(a => a.car_number == rent.number_of_rishui).First();

            if ((tempC.rishoi.catgor == catagory_of_vehicles.A))
            {
                if (tempc.rishion.type != catagory_of_vehicles.A)
                {
                    throw new Exception("הרישיון שלך אינו מתאים לרכב הזה");
                }
            }

            if (tempC.rishoi.catgor < tempc.rishion.type)
            {
                throw new Exception("הרישיון שלך אינו מתאים לרכב הזה");
            }

            if (tempC.Age < 18)
            {
                throw new Exception("המשכיר צעיר מדי מכדי להשכיר רכב זה");
            }
            try
            {
                update_car(tempc, update.panuy, false);
            }
            catch (Exception e)
            {
                throw e;
            }
            Dal.add_rent(rent);
        }//+
예제 #23
0
        }//+

        /// <summary>
        /// מוחקת חוזה השכרה
        /// בודקת שהחוזה הסתיים
        /// בודקת שהוא קיים
        /// </summary>
        /// <param name="rent"></param>
        public void del_rent(Renting rent)
        {
            if (!is_rent_exist(rent.running_code))
            {
                throw new Exception("החוזה הזה כבר לא קיים");
            }
            if (!rent.ended)
            {
                throw new Exception("אי אפשר למחוק חוזה שעדיין בפעולה");
            }

            Dal.del_rent(rent);
        }//+
예제 #24
0
        public void addrenting(Renting r)
        {
            Car    c  = GetCar(r.licensePlate);
            Client c1 = GetClient(r.drivers.IDMainDrivers);

            if (c == null || c1 == null)
            {
                throw new Exception("Unable to make a reservation with a car or clients not exist");
            }
            r.numberCall = numberRenting++;
            DataSource.rentingList.Add(r);
            throw new Exception("ok!!\n your number renting is   " + r.numberCall);
        }
예제 #25
0
        public void addrenting(string licensePlate, int IDClient)
        {
            Renting r = new Renting();

            //if (r != null)
            //    throw new Exception("this renting is already at the system");
            r.numberCall            = numberRenting++;
            r.drivers.IDMainDrivers = IDClient;
            r.licensePlate          = licensePlate;

            DataSource.rentingList.Add(r);
            throw new Exception("ok!!\n your number renting is" + r.numberCall);
        }
        // Add
        public async Task AddRenting(Renting renting, User user, Copy copy)
        {
            renting.User = _context.Users.Find(user.Id);
            renting.Copy = _context.Copies.Find(copy.Id);

            _context.Copies.Attach(renting.Copy);
            renting.Copy.IsAvailable = false;
            _context.Entry(renting.Copy).Property(c => c.IsAvailable).IsModified = true;

            _context.Rentings.Add(renting);

            await _context.SaveChangesAsync();
        }
예제 #27
0
        public void renoveRenting(int renting)
        {
            Renting r = GetRenting(renting);

            if (r == null)
            {
                throw new Exception("not find this renting to remove");
            }
            if (r.StartRenting < DateTime.Now)
            {
                throw new Exception("Renting already been started so can not be deleted");
            }
            DataSource.rentingList.Remove(r);
        }
예제 #28
0
        }//+

        /// <summary>
        /// עידכון חוזה
        /// בדיקה שהחוזה קיים
        /// בדיקה שאפשר לעדכן
        /// </summary>
        /// <param name="car_id"></param>
        /// <param name="t"></param>
        /// <param name="obj"></param>
        public void update_rent(Renting rent, update t, object obj)
        {
            if (!is_rent_exist(rent.running_code))
            {
                throw new Exception("החוזה הזה לא קיים");
            }
            try
            {
                Dal.update_rent(rent, t, obj);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
예제 #29
0
        public void updateRenting(Renting renting)
        {
            Renting r = GetRenting(renting.numberCall);

            if (r == null)
            {
                throw new Exception("not find this number renting ");
            }

            r.endRenting = renting.endRenting;
            r.chairBaby  = renting.chairBaby;
            r.chairChild = renting.chairChild;
            r.isGPS      = renting.isGPS;
            r.insurance  = renting.insurance;
        }
예제 #30
0
        /// <summary>
        /// פונקציה הבודקת אם היתה תקלה ברכב לפי מספר הזמנה בתוך רשימת התקלות
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        public bool ifFault(Renting r)
        {
            List <Fault> v = (from f in dal.getAllFaults()
                              where f.numbetCall == r.numberCall
                              select f).ToList <Fault>();

            if (v == null)
            {
                r.isFault = false;
                return(false);
            }

            r.isFault = true;
            return(true);
        }