Exemplo n.º 1
0
        /// <summary>
        /// 模拟累积积分
        /// </summary>
        static void SimulateAddingPoints()
        {
            var dataService = new FakeLoyalDataService();//这里使用的数据库服务是伪造的
            var service     = new LoyaltyAccrualService(dataService);
            var agreement   = new RentalAgreement
            {
                Customer = new Customer
                {
                    Id             = Guid.NewGuid(),
                    Name           = "tkb至简",
                    DateOfBirth    = new DateTime(2000, 1, 1),
                    DriversLicense = "123456"
                },
                Vehicle = new Vehicle
                {
                    Id    = Guid.NewGuid(),
                    Make  = "Ford",
                    Model = "金牛座",
                    Size  = Size.Compact,
                    Vin   = "浙-ABC123"
                },
                StartDate = DateTime.Now.AddDays(-3),
                EndDate   = DateTime.Now
            };

            service.Accrue(agreement);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Get rental agreement by id
        /// </summary>
        /// <param name="id">id of Project to fetch</param>
        /// <response code="200">OK</response>
        /// <response code="404">Project not found</response>
        public virtual IActionResult RentalagreementsIdGetAsync(int id)
        {
            bool exists = _context.RentalAgreements.Any(a => a.Id == id);

            if (exists)
            {
                RentalAgreement result = _context.RentalAgreements.AsNoTracking()
                                         .Include(x => x.Equipment)
                                         .ThenInclude(y => y.Owner)
                                         .Include(x => x.Equipment)
                                         .ThenInclude(y => y.DistrictEquipmentType)
                                         .ThenInclude(d => d.EquipmentType)
                                         .Include(x => x.Equipment)
                                         .ThenInclude(y => y.EquipmentAttachments)
                                         .Include(x => x.Equipment)
                                         .ThenInclude(y => y.LocalArea.ServiceArea.District.Region)
                                         .Include(x => x.Project)
                                         .ThenInclude(p => p.District.Region)
                                         .Include(x => x.RentalAgreementConditions)
                                         .Include(x => x.RentalAgreementRates)
                                         .Include(x => x.TimeRecords)
                                         .First(a => a.Id == id);

                return(new ObjectResult(new HetsResponse(result)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Exemplo n.º 3
0
        static void StimulateAddingPoints()
        {
            var dataService     = new FakeLoyaltyDataService();
            var service         = new LoyaltyAccuralService(dataService);
            var rentalAgreement = new RentalAgreement
            {
                Id        = Guid.NewGuid(),
                StartDate = DateTime.Now.AddDays(-3),
                EndDate   = DateTime.Now,
                Customer  = new Customer
                {
                    Id            = Guid.NewGuid(),
                    BirthDate     = DateTime.Now.AddYears(-25),
                    DriverLicense = "DL0012345",
                    Name          = "John Papa"
                },
                Vehicle = new Vehicle
                {
                    Id    = Guid.NewGuid(),
                    Make  = "Honda",
                    Model = "Sedan",
                    Size  = Size.Compact
                }
            };

            service.Accrue(rentalAgreement);
        }
Exemplo n.º 4
0
        private static void SimulateAddingPoints()
        {
            var dataService = new FakeLoyaltyDataService(); // 模拟数据库服务
            var service     = new LoyaltyAccrualService(dataService);
            var agreement   = new RentalAgreement
            {
                Customer = new Customer
                {
                    Id             = Guid.NewGuid(),
                    Name           = "Jackie",
                    DateOfBirth    = new DateTime(1999, 1, 1),
                    DriversLicense = "12345678"
                },
                Vehicle = new Vehicle
                {
                    Id    = Guid.NewGuid(),
                    Make  = "Ford",
                    Model = "小奔",
                    Size  = Size.Compact,
                    Vin   = "粤BABC12"
                },
                StartDate = DateTime.Now.AddDays(-3),
                EndDate   = DateTime.Now,
                Id        = Guid.NewGuid()
            };

            service.Accrue(agreement);
        }
Exemplo n.º 5
0
        static void SimulateAddingPoints(ILoyaltyAccrualService service)
        {
            var rentalAgreement = new RentalAgreement
            {
                Customer = new Customer
                {
                    Id             = Guid.NewGuid(),
                    Name           = "Matthew D. Groves",
                    DateOfBirth    = new DateTime(1980, 2, 10),
                    DriversLicense = "RR123456"
                },
                Vehicle = new Vehicle
                {
                    Id    = Guid.NewGuid(),
                    Make  = "Honda",
                    Model = "Accord",
                    Size  = Size.Compact,
                    Vin   = "1HABC123"
                },
                StartDate = DateTime.Now.AddDays(-3),
                EndDate   = DateTime.Now
            };

            service.Accrue(rentalAgreement);
        }
Exemplo n.º 6
0
        public void Accrue(RentalAgreement agreement)
        {
            // defensive programming
            if (agreement == null)
            {
                throw new ArgumentNullException(nameof(agreement));
            }

            // logging
            Console.WriteLine("Accrue: {0}", DateTime.Now);
            Console.WriteLine("Customer: {0}", agreement.Customer.Id);
            Console.WriteLine("Vehicle: {0}", agreement.Vehicle.Id);

            // exception handling
            _exceptionHandler.Wrapper(() =>
            {
                _transactionManager.Wrapper(() =>
                {
                    var rentalTimeSpan =
                        agreement.EndDate.Subtract(agreement.StartDate);
                    var numberOfDays = (int)Math.Floor(rentalTimeSpan.TotalDays);
                    var pointsPerDay = 1;
                    if (agreement.Vehicle.Size >= Size.Luxury)
                    {
                        pointsPerDay = 2;
                    }
                    var points = numberOfDays * pointsPerDay;
                    _loyaltyDataService.AddPoints(agreement.Customer.Id, points);

                    // logging
                    Console.WriteLine("Accrue complete: {0}", DateTime.Now);
                });
            });
        }
Exemplo n.º 7
0
        /// <summary>
        /// Create rental agreement
        /// </summary>
        /// <param name="item"></param>
        /// <response code="200">Project created</response>
        public virtual IActionResult RentalagreementsPostAsync(RentalAgreement item)
        {
            if (item != null)
            {
                AdjustRecord(item);

                bool exists = _context.RentalAgreements.Any(a => a.Id == item.Id);

                if (exists)
                {
                    _context.RentalAgreements.Update(item);
                }
                else
                {
                    item.Number = GetRentalAgreementNumber(item, _context);

                    // record not found
                    _context.RentalAgreements.Add(item);
                }

                // save the changes
                _context.SaveChanges();

                return(new ObjectResult(new HetsResponse(item)));
            }

            // no record to insert
            return(new ObjectResult(new HetsResponse("HETS-04", ErrorViewModel.GetDescription("HETS-04", _configuration))));
        }
        public override Entity Execute(ActionContext context)
        {
            Asset asset = context.Entity as Asset;

            if (asset != null)
            {
                RentalAgreement rentalAgreement = context.AssetManager.FindRentalAgreement(asset.Id);

                if (rentalAgreement != null)
                {
                    if (MessageBox.Show(context.WindowOwner,
                                        "Asset is rented, are you sure you want to delete the asset entry?",
                                        "Asset is Rented",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Warning) == DialogResult.Yes)
                    {
                        context.AssetManager.DeleteAsset(asset.Id);
                        return(asset);
                    }
                }
                else if (MessageBox.Show(context.WindowOwner,
                                         "Are you sure you want to delete the asset entry?",
                                         "Confirm Deletion",
                                         MessageBoxButtons.OKCancel,
                                         MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    context.AssetManager.DeleteAsset(asset.Id);
                    return(asset);
                }
            }

            return(null);
        }
Exemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="item"></param>
        /// <response code="201">Project created</response>
        public virtual IActionResult RentalagreementsPostAsync(RentalAgreement item)
        {
            if (item != null)
            {
                AdjustRecord(item);

                var exists = _context.RentalAgreements.Any(a => a.Id == item.Id);
                if (exists)
                {
                    _context.RentalAgreements.Update(item);
                }
                else
                {
                    item.Number = GetRentalAgreementNumber(item);

                    // record not found
                    _context.RentalAgreements.Add(item);
                }
                // Save the changes
                _context.SaveChanges();
                return(new ObjectResult(item));
            }
            else
            {
                return(new StatusCodeResult(400));
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Printed rental agreement view model
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static RentalAgreementPdfViewModel ToViewModel(this RentalAgreement model)
        {
            var dto = new RentalAgreementPdfViewModel();

            if (model != null)
            {
                dto.DatedOn           = ConvertDate(model.DatedOn);
                dto.Equipment         = model.Equipment;
                dto.EquipmentRate     = model.EquipmentRate;
                dto.EstimateHours     = model.EstimateHours;
                dto.EstimateStartWork = ConvertDate(model.EstimateStartWork);
                dto.Id          = model.Id;
                dto.Note        = model.Note;
                dto.Number      = model.Number;
                dto.Project     = model.Project;
                dto.RateComment = model.RateComment;
                dto.RatePeriod  = model.RatePeriod;
                dto.RentalAgreementConditions = model.RentalAgreementConditions;
                dto.RentalAgreementRates      = model.RentalAgreementRates;
                dto.Status      = model.Status;
                dto.TimeRecords = model.TimeRecords;
            }

            return(dto);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Release (terminate) a rental agreement
        /// </summary>
        /// /// <param name="id">Id of Rental Agreement to release</param>
        /// <response code="200">Rental Agreement released</response>
        public virtual IActionResult RentalagreementsIdReleasePostAsync(int id)
        {
            bool exists = _context.RentalAgreements.Any(a => a.Id == id);

            if (exists)
            {
                RentalAgreement rentalAgreement = _context.RentalAgreements.FirstOrDefault(a => a.Id == id);

                if (rentalAgreement == null)
                {
                    // record not found
                    return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                }

                // release (terminate) rental agreement
                rentalAgreement.Status = "Complete";

                _context.RentalAgreements.Update(rentalAgreement);

                // save the changes
                _context.SaveChanges();

                return(new ObjectResult(new HetsResponse(rentalAgreement)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Exemplo n.º 12
0
        private string GetRentalAgreementNumber(RentalAgreement item)
        {
            string result = "";

            // validate item.

            if (item.Equipment != null && item.Equipment.LocalArea != null)
            {
                DateTime currentTime = DateTime.UtcNow;

                int fiscalYear = currentTime.Year;

                // fiscal year always ends in March.
                if (currentTime.Month > 3)
                {
                    fiscalYear++;
                }

                int localAreaNumber = item.Equipment.LocalArea.LocalAreaNumber;
                int localAreaId     = item.Equipment.LocalArea.Id;

                DateTime fiscalYearStart = new DateTime(fiscalYear - 1, 1, 1);

                // count the number of rental agreements in the system.
                int currentCount = _context.RentalAgreements
                                   .Include(x => x.Equipment.LocalArea)
                                   .Where(x => x.Equipment.LocalArea.Id == localAreaId && x.CreateTimestamp >= fiscalYearStart)
                                   .Count();
                currentCount++;

                // format of the Rental Agreement number is YYYY-#-####
                result = fiscalYear.ToString() + "-" + localAreaNumber.ToString() + "-" + currentCount.ToString("D4");
            }
            return(result);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Edit(int id, [Bind("RentalID,ReservationEmail,DateOfPickup,LocationToPickup,DateOfReturn,LocationToDropOff,Destination,Drivers")] RentalAgreement rentalAgreement)
        {
            if (id != rentalAgreement.RentalID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(rentalAgreement);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!RentalAgreementExists(rentalAgreement.RentalID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(rentalAgreement));
        }
Exemplo n.º 14
0
        private static void SimulateAddingPoints()
        {
            var dataService = new FakeLoyaltyDataService();
            var service     = new LoyaltyAccrualService(dataService);

            var rentalAgreement = new RentalAgreement {
                Customer = new Customer {
                    Id             = Guid.NewGuid(),
                    Name           = "Test name 1",
                    DateOfBirth    = new DateTime(1980, 2, 10),
                    DriversLicense = "RR123456"
                },
                Vehicule = new Vehicule {
                    Id    = new Guid(),
                    Make  = "Honda",
                    Model = "Accord",
                    Size  = Size.Compact,
                    Vin   = "1HABBC123"
                },
                StartDate = DateTime.Now.AddDays(-3),
                EndDate   = DateTime.Now
            };

            service.Accrue(rentalAgreement);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Update or create an array of rental agreement rate records associated with a rental agreement
        /// </summary>
        /// <remarks>Update a Rental Agreement&#39;s Rate Records</remarks>
        /// <param name="id">id of Rental Agreement to update Rate Records for</param>
        /// <param name="items">Array of Rental Agreement Rate Records</param>
        /// <response code="200">OK</response>
        public virtual IActionResult RentalAgreementsIdRentalAgreementRatesBulkPostAsync(int id, RentalAgreementRate[] items)
        {
            bool exists = _context.RentalAgreements.Any(a => a.Id == id);

            if (exists && items != null)
            {
                RentalAgreement agreement = _context.RentalAgreements
                                            .Include(x => x.RentalAgreementRates)
                                            .First(x => x.Id == id);

                // process each rate records
                foreach (RentalAgreementRate item in items)
                {
                    // ******************************************************************
                    // add or update rate records
                    // ******************************************************************
                    if (item.Id > 0)
                    {
                        int rateIndex = agreement.RentalAgreementRates.FindIndex(a => a.Id == item.Id);

                        if (rateIndex < 0)
                        {
                            // record not found
                            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                        }

                        agreement.RentalAgreementRates[rateIndex].Comment                = item.Comment;
                        agreement.RentalAgreementRates[rateIndex].ComponentName          = item.ComponentName;
                        agreement.RentalAgreementRates[rateIndex].IsAttachment           = item.IsAttachment;
                        agreement.RentalAgreementRates[rateIndex].IsIncludedInTotal      = item.IsIncludedInTotal;
                        agreement.RentalAgreementRates[rateIndex].PercentOfEquipmentRate = item.PercentOfEquipmentRate;
                        agreement.RentalAgreementRates[rateIndex].Rate       = item.Rate;
                        agreement.RentalAgreementRates[rateIndex].RatePeriod = item.RatePeriod;
                    }
                    else // add rate records
                    {
                        agreement.RentalAgreementRates.Add(item);
                    }

                    _context.SaveChanges();
                }

                // *************************************************************
                // return updated rental agreement rate records
                // *************************************************************
                agreement = _context.RentalAgreements
                            .Include(x => x.RentalAgreementRates)
                            .First(x => x.Id == id);

                List <RentalAgreementRate> rateRecords = new List <RentalAgreementRate>();

                rateRecords.AddRange(agreement.RentalAgreementRates);

                return(new ObjectResult(new HetsResponse(rateRecords)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Exemplo n.º 16
0
        public void SetUp()
        {
            carRental = new CarRental();

            Vehicle vehicle = new Vehicle(1000, 4, 1);

            rentalAgreement = new RentalAgreement(vehicle, 5, 5000, 1000, 10, true);
        }
Exemplo n.º 17
0
 public async Task <IActionResult> GenerateDocument([FromBody] RentalAgreement rentalAgreement)
 {
     return(new FileContentResult
            (
                await this.documentService.RenderDocumentAsync(rentalAgreement),
                ContentType
            ));
 }
Exemplo n.º 18
0
        /// <summary>
        /// Update or create an array of time records associated with a rental agreement
        /// </summary>
        /// <remarks>Update a Renta Agreement&#39;s Time Records</remarks>
        /// <param name="id">id of Rental Agreement to update Time Records for</param>
        /// <param name="items">Array of Rental Agreement Time Records</param>
        /// <response code="200">OK</response>
        public virtual IActionResult RentalAgreementsIdTimeRecordsBulkPostAsync(int id, TimeRecord[] items)
        {
            bool exists = _context.RentalAgreements.Any(a => a.Id == id);

            if (exists && items != null)
            {
                RentalAgreement agreement = _context.RentalAgreements
                                            .Include(x => x.TimeRecords)
                                            .First(x => x.Id == id);

                // process each time record
                foreach (TimeRecord item in items)
                {
                    // ******************************************************************
                    // add or update time record
                    // ******************************************************************
                    if (item.Id > 0)
                    {
                        int timeIndex = agreement.TimeRecords.FindIndex(a => a.Id == item.Id);

                        if (timeIndex < 0)
                        {
                            // record not found
                            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                        }

                        agreement.TimeRecords[timeIndex].EnteredDate = DateTime.UtcNow;
                        agreement.TimeRecords[timeIndex].Hours       = item.Hours;
                        agreement.TimeRecords[timeIndex].TimePeriod  = item.TimePeriod;
                        agreement.TimeRecords[timeIndex].WorkedDate  = item.WorkedDate;
                    }
                    else // add time record
                    {
                        item.EnteredDate = DateTime.Now.ToUniversalTime();

                        agreement.TimeRecords.Add(item);
                    }

                    _context.SaveChanges();
                }

                // *************************************************************
                // return updated time records
                // *************************************************************
                agreement = _context.RentalAgreements
                            .Include(x => x.TimeRecords)
                            .First(x => x.Id == id);

                List <TimeRecord> timeRecords = new List <TimeRecord>();

                timeRecords.AddRange(agreement.TimeRecords);

                return(new ObjectResult(new HetsResponse(timeRecords)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Exemplo n.º 19
0
 /// <summary>
 /// 该方法包含了积分系统累积客户积分的逻辑和规则
 /// </summary>
 /// <param name="agreement">租赁协议实体</param>
 public void Accrue(RentalAgreement agreement)
 {
     //防御性编程
     if (agreement == null)
     {
         throw new Exception("agreement为null!");
     }
     //日志
     Console.WriteLine("Accrue:{0}", DateTime.Now);
     Console.WriteLine("Customer:{0}", agreement.Customer.Id);
     Console.WriteLine("Vehicle:{0}", agreement.Vehicle.Id);
     try
     {
         using (var ts = new TransactionScope()) //开始一个新事务
         {
             var retries   = 3;                  //重试事务3次
             var succeeded = false;
             while (!succeeded)                  //一直循环,直到成功
             {
                 try
                 {
                     var rentalTimeSpan = agreement.EndDate.Subtract(agreement.StartDate);
                     var numberOfDays   = (int)rentalTimeSpan.TotalDays;
                     var pointsPerDay   = 1;
                     if (agreement.Vehicle.Size >= Size.Luxury)
                     {
                         pointsPerDay = 2;
                     }
                     var points = numberOfDays * pointsPerDay;
                     //调用数据服务存储客户获得的积分
                     _loyaltyDataService.AddPoints(agreement.Customer.Id, points);
                     ts.Complete();                                          //调用Complete方法表明事务成功提交
                     succeeded = true;                                       //成功后设置为true,确保最后一次循环迭代
                     Console.WriteLine("Accrue Complete:{0}", DateTime.Now); //这句移入try里
                 }
                 catch
                 {
                     if (retries >= 0)
                     {
                         retries--;//直到尝试完次数时才重抛异常
                     }
                     else
                     {
                         throw;//没有调用Complete方法,事务会回滚
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         if (!ExceptionHelper.Handle(ex))//如果没有处理异常,继续重抛
         {
             throw ex;
         }
     }
 }
Exemplo n.º 20
0
        public async Task <IActionResult> Create([Bind("RentalID,ReservationEmail,DateOfPickup,LocationToPickup,DateOfReturn,LocationToDropOff,Destination,Drivers")] RentalAgreement rentalAgreement)
        {
            if (ModelState.IsValid)
            {
                _context.Add(rentalAgreement);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(rentalAgreement));
        }
Exemplo n.º 21
0
        /// <summary>
        /// Update or create an array of rental agreement condition records associated with a rental agreement
        /// </summary>
        /// <remarks>Update a Rental Agreement&#39;s Condition Records</remarks>
        /// <param name="id">id of Rental Agreement to update Condition Records for</param>
        /// <param name="items">Array of Rental Agreement Condition Records</param>
        /// <response code="200">OK</response>
        public virtual IActionResult RentalAgreementsIdRentalAgreementConditionsBulkPostAsync(int id, RentalAgreementCondition[] items)
        {
            bool exists = _context.RentalAgreements.Any(a => a.Id == id);

            if (exists && items != null)
            {
                RentalAgreement agreement = _context.RentalAgreements
                                            .Include(x => x.RentalAgreementConditions)
                                            .First(x => x.Id == id);

                // process each condition records
                foreach (RentalAgreementCondition item in items)
                {
                    // ******************************************************************
                    // add or update rate records
                    // ******************************************************************
                    if (item.Id > 0)
                    {
                        int condIndex = agreement.RentalAgreementConditions.FindIndex(a => a.Id == item.Id);

                        if (condIndex < 0)
                        {
                            // record not found
                            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                        }

                        agreement.RentalAgreementConditions[condIndex].Comment       = item.Comment;
                        agreement.RentalAgreementConditions[condIndex].ConditionName = item.ConditionName;
                    }
                    else // add condition records
                    {
                        agreement.RentalAgreementConditions.Add(item);
                    }

                    _context.SaveChanges();
                }

                // *************************************************************
                // return updated rental agreement condition records
                // *************************************************************
                agreement = _context.RentalAgreements
                            .Include(x => x.RentalAgreementConditions)
                            .First(x => x.Id == id);

                List <RentalAgreementCondition> condRecords = new List <RentalAgreementCondition>();

                condRecords.AddRange(agreement.RentalAgreementConditions);

                return(new ObjectResult(new HetsResponse(condRecords)));
            }

            // record not found
            return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
        }
Exemplo n.º 22
0
        public async Task UpdateRentalAgreementAsync(RentalAgreement theRentalAgreement)
        {
            var aAdditionalDrivers = theRentalAgreement.AdditionalDrivers;
            var aAdditions         = theRentalAgreement.Additions;

            try
            {
                await Connection.OpenAsync().ConfigureAwait(false);

                var aCommand = new NpgsqlCommand(
                    "UPDATE rentalagreement SET customerid = :value1, locationid = :value2, renterid = :value3, additionaldrivers = :value4, outdate = :value5, indate = :value6, automobileid = :value7, additions = :value8, status = :value9, employeeid = :value10 where id=:value11;", Connection);
                aCommand.Parameters.AddWithValue("value1", theRentalAgreement.Customer);
                aCommand.Parameters.AddWithValue("value2", theRentalAgreement.Location);
                aCommand.Parameters.AddWithValue("value3", theRentalAgreement.Renter);

                if (aAdditionalDrivers != null)
                {
                    aCommand.Parameters.AddWithValue("value4", string.Join(";;", theRentalAgreement.AdditionalDrivers));
                }
                else
                {
                    aCommand.Parameters.AddWithValue("value4", DBNull.Value);
                }

                aCommand.Parameters.AddWithValue("value5", theRentalAgreement.OutDate);
                aCommand.Parameters.AddWithValue("value6", theRentalAgreement.InDate);
                aCommand.Parameters.AddWithValue("value7", theRentalAgreement.Automobile);

                if (aAdditions != null)
                {
                    aCommand.Parameters.AddWithValue("value8", string.Join(";;", theRentalAgreement.Additions));
                }
                else
                {
                    aCommand.Parameters.AddWithValue("value8", DBNull.Value);
                }

                aCommand.Parameters.AddWithValue("value9", theRentalAgreement.Status);
                aCommand.Parameters.AddWithValue("value10", theRentalAgreement.EmployeeId);
                aCommand.Parameters.AddWithValue("value11", theRentalAgreement.Id);

                await aCommand.ExecuteNonQueryAsync().ConfigureAwait(false);
            }
            // no catch here, this is a reference project
            // TODO: add catch and actions here
            finally
            {
                if (Connection.State == ConnectionState.Open)
                {
                    Connection.Close();
                }
            }
        }
Exemplo n.º 23
0
        public async Task <RentalAgreement> GetRentalAgreementAsync(int theRentalAgreementId)
        {
            try
            {
                await Connection.OpenAsync().ConfigureAwait(false);

                var aPreparedCommand =
                    new NpgsqlCommand(
                        "SELECT id, customerid, locationid, renterid, additionaldrivers, outdate, indate, automobileid, additions, status, employeeid from rentalagreement where id = :value1", Connection);
                var aParam = new NpgsqlParameter("value1", NpgsqlDbType.Integer)
                {
                    Value = theRentalAgreementId
                };
                aPreparedCommand.Parameters.Add(aParam);

                var aReader = await aPreparedCommand.ExecuteReaderAsync().ConfigureAwait(false);

                if (!aReader.HasRows)
                {
                    return(null);
                }

                var aReturn = new RentalAgreement();
                while (await aReader.ReadAsync().ConfigureAwait(false))
                {
                    aReturn = ReadRentalAgreement(aReader);
                }
                return(aReturn);
            }
            catch (NpgsqlException)
            {
                return(null);
            }
            catch (InvalidOperationException)
            {
                return(null);
            }
            catch (SqlException)
            {
                return(null);
            }
            catch (ConfigurationErrorsException)
            {
                return(null);
            }
            finally
            {
                if (Connection.State == ConnectionState.Open)
                {
                    Connection.Close();
                }
            }
        }
Exemplo n.º 24
0
        private void AdjustRecord(RentalAgreement item)
        {
            if (item != null)
            {
                if (item.Equipment != null)
                {
                    item.Equipment = _context.Equipments
                                     .Include(x => x.LocalArea)
                                     .FirstOrDefault(a => a.Id == item.Equipment.Id);
                }

                if (item.Project != null)
                {
                    item.Project = _context.Projects.FirstOrDefault(a => a.Id == item.Project.Id);
                }


                if (item.RentalAgreementConditions != null)
                {
                    for (int i = 0; i < item.RentalAgreementConditions.Count; i++)
                    {
                        if (item.RentalAgreementConditions[i] != null)
                        {
                            item.RentalAgreementConditions[i] = _context.RentalAgreementConditions.FirstOrDefault(a => a.Id == item.RentalAgreementConditions[i].Id);
                        }
                    }
                }

                if (item.RentalAgreementRates != null)
                {
                    for (int i = 0; i < item.RentalAgreementRates.Count; i++)
                    {
                        if (item.RentalAgreementRates[i] != null)
                        {
                            item.RentalAgreementRates[i] = _context.RentalAgreementRates.FirstOrDefault(a => a.Id == item.RentalAgreementRates[i].Id);
                        }
                    }
                }

                if (item.TimeRecords != null)
                {
                    for (int i = 0; i < item.TimeRecords.Count; i++)
                    {
                        if (item.TimeRecords[i] != null)
                        {
                            item.TimeRecords[i] = _context.TimeRecords.First(a => a.Id == item.TimeRecords[i].Id);
                        }
                    }
                }
            }
        }
Exemplo n.º 25
0
        public void Accrue(RentalAgreement agreement)
        {
            var rentalTime   = agreement.EndDate.Subtract(agreement.StartDate);
            var days         = (int)Math.Floor(rentalTime.TotalDays);
            var pointsPerDay = 1;

            if (agreement.Vehicle.Size >= Size.Luxury)
            {
                pointsPerDay = 2;
            }
            var totalPoints = days * pointsPerDay;

            _loyaltyDataService.AddPoints(agreement.Customer.Id, totalPoints);
        }
Exemplo n.º 26
0
        public void damage_not_insured_trip__price_should_be_more()
        {
            Vehicle vehicle = new Vehicle(1000, 2, 1);

            rentalAgreement = new RentalAgreement(vehicle, 5, 5000, 1000, 10, false);
            carRental.StartTrip(rentalAgreement);
            rentalAgreement.Vehicle.SetOdomoterReading(1500);
            rentalAgreement.Vehicle.SetDamage(2);

            carRental.EndTrip();

            Assert.IsTrue(carRental.IsTripEnded());
            Assert.AreEqual(5500.0, carRental.FinalPrice);
        }
        public async Task <RentalAgreement> UpdateRentalAgreementAsync(RentalAgreement theRentalAgreement)
        {
            var aUser = await _userRepository.GetUserAsync(theRentalAgreement.EmployeeId);

            if (!aUser.IsEmployee)
            {
                throw new InvalidPermissionsException(
                          $"The user {aUser.LastName}, {aUser.FirstName} is not an employee and cannot modify a rental agreement");
            }

            await _rentalAgreementRepository.UpdateRentalAgreementAsync(theRentalAgreement);

            return(await GetRentalAgreementAsync(theRentalAgreement.Id));
        }
        /// <summary>
        /// Updates an existing rental agreement.
        /// </summary>
        /// <param name="theRentalAgreement">The modified rental agreement</param>
        /// <exception cref="InvalidPermissionsException">InvalidPermissionsException will be thrown
        /// if the user attempting to modify the rental agreement is not an employee</exception>
        /// <returns></returns>
        public RentalAgreement UpdateRentalAgreement(RentalAgreement theRentalAgreement)
        {
            var aUser = _userRepository.GetUser(theRentalAgreement.EmployeeId);

            if (!aUser.IsEmployee)
            {
                throw new InvalidPermissionsException(
                          $"The user {aUser.LastName}, {aUser.FirstName} is not an employee and cannot modify a rental agreement");
            }

            _rentalAgreementRepository.UpdateRentalAgreement(theRentalAgreement);

            return(GetRentalAgreement(theRentalAgreement.Id));
        }
Exemplo n.º 29
0
        /// <summary>
        /// 包含积分系统累计客户积分逻辑和规则
        /// </summary>
        /// <param name="agreement"></param>
        public void Accrue(RentalAgreement agreement)
        {
            var rentalTimeSpan = agreement.EndDate.Subtract(agreement.StartDate);
            var numberOfDays   = (int)rentalTimeSpan.TotalDays;
            var pointsPerDay   = 1;

            if (agreement.Vehicle.Size >= Size.Luxury)
            {
                pointsPerDay = 2;
            }
            var points = pointsPerDay * numberOfDays;

            // 调用数据服务存储客户获得的积分
            _loyaltyDataService.AddPoints(agreement.Customer.Id, points);
        }
        public int AddRentalAgreement(RentalAgreement rentalAgreement)
        {
            String query = "INSERT INTO RentalAgreement (Asset,Tenant,StartDate,EndDate) VALUES (@asset,@tenant,@start,@end);" +
                           "SELECT scope_identity();";

            return(ExecuteScalar
                   (
                       query,
                       new Dictionary <string, object>()
            {
                ["@asset"] = rentalAgreement.AssetId,
                ["@tenant"] = rentalAgreement.Tenant,
                ["@start"] = rentalAgreement.Start,
                ["@end"] = rentalAgreement.End
            }
                   ));
        }