Example #1
0
        public void UpdateDriver(DriverViewModel driver)
        {
            var driverToRemove = _driverRepository.GetById(driver.DriverC);
            var updateDriver   = Mapper.Map <DriverViewModel, Driver_M>(driver);

            _driverRepository.Delete(driverToRemove);
            _driverRepository.Add(updateDriver);
            SaveDriver();
        }
        /// <summary>
        /// Delete an invoice.
        /// </summary>
        /// <param name="currentUser">The user deleting the invoice</param>
        /// <param name="invoiceId">The id of the invoice</param>
        /// <exception cref="NullReferenceException">This gets thrown when the invoiceId is not found in the database.</exception>
        /// <returns></returns>
        public async Task DeleteInvoice(PortalUser currentUser, int invoiceId)
        {
            // Get the invoice weare gonig to delete
            Invoice invoice = await repository.GetInvoiceById(invoiceId);

            if (invoice == null)
            {
                throw new NullReferenceException("Could not find the invoice to delete.");
            }

            invoice.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Void;

            await repository.SaveChanges();

            // Second we create a delete revision
            await CreateInvoiceRevision(currentUser, invoiceId, "Deleted");

            // Get all the revisions
            var revisions = await repository.GetInvoiceRevListByInvoiceId(invoiceId);

            // Move them over and delete them as we go.
            foreach (InvoiceRev invoiceRev in revisions)
            {
                InvoiceHist newHistory = new InvoiceHist()
                {
                    CenterId                  = invoiceRev.CenterId,
                    CompanyId                 = invoiceRev.CompanyId,
                    DeliveryDate              = invoiceRev.DeliveryDate,
                    DispatchLoadNumber        = invoiceRev.DispatchLoadNumber,
                    DriverFuelSurcharge       = invoiceRev.DriverFuelSurcharge,
                    DriverId                  = invoiceRev.DriverId,
                    DriverRate                = invoiceRev.DriverRate,
                    InvoiceHistId             = 0,
                    InvoiceId                 = invoiceRev.InvoiceId,
                    IsActive                  = invoiceRev.IsActive,
                    ManufacturerFuelSurcharge = invoiceRev.ManufacturerFuelSurcharge,
                    ManufacturerId            = invoiceRev.ManufacturerId,
                    ManufacturerRate          = invoiceRev.ManufacturerRate,
                    Note                    = invoiceRev.Note,
                    RevisedBy               = invoiceRev.RevisedBy,
                    RevisionDate            = invoiceRev.RevisionDate,
                    TransactionStatusTypeId = invoiceRev.TransactionStatusTypeId,
                    TruckId                 = invoiceRev.TruckId,
                    Version                 = invoiceRev.Version,
                    VIN = invoiceRev.VIN
                };
                repository.Insert(newHistory);
                repository.Delete(invoiceRev);
            }

            repository.Delete(invoice);

            await repository.SaveChanges();
        }
        public ActionResult DeleteConfirmed(int id)
        {
            Driver driver = driverRepository.GetById(id);

            driverRepository.Delete(driver);
            return(RedirectToAction("Index"));
        }
Example #4
0
 public async Task <IActionResult> DeleteDriver([FromRoute] int id)
 {
     repo.Delete(await repo.GetByIdToDelete(id));
     return(StatusCode(200, new {
         response = ApiMessages.RecordDeleted()
     }));
 }
Example #5
0
        public async Task DeleteAsync(Guid userIDP)
        {
            var driver = await _driverrepositroy.Get(userIDP);

            if (driver != null)
            {
                await _driverrepositroy.Delete(driver);
            }
        }
        public void DeleteDriver(int id)
        {
            Domain.Driver.Driver driver = GetDriverById(id);

            if (driver != null)
            {
                _driverResitory.Delete(driver);
                _driverResitory.Save(driver);
            }
        }
        public async Task Delete(int id)
        {
            //TODO: Business Logic goes here
            if (id == null)
            {
                throw new Exception("Driver is NULL!");
            }

            await _driverRepo.Delete(id);
        }
        public Task <object> Handle(DeleteDriverCommand request, CancellationToken cancellationToken)
        {
            //if (!command.IsValid())
            //{
            //    NotifyValidationErrors(command);
            //    return Task.FromResult(false as object);
            //}
            Console.WriteLine("654321");
            var result = _driverRepository.Delete(request.ID);

            return(Task.FromResult(result as object));
        }
        public async Task <Driver> Handle(DeleteDriverCommand request, CancellationToken cancellationToken)
        {
            var notifications = request.Validate();

            if (notifications.Any())
            {
                await notificationService.Notify(notifications);

                return(null);
            }

            return(await driverRepository.Delete(request.Id, cancellationToken));
        }
        public async Task <IActionResult> Delete(string id)
        {
            var post = await _driverRepository.GetDriver(id);

            if (post == null)
            {
                return(new NotFoundResult());
            }

            await _driverRepository.Delete(id);

            return(new OkResult());
        }
Example #11
0
        public async Task <bool> DeleteDriver(Guid id)
        {
            try
            {
                var driver = await GetDriverById(id);

                _driverRepository.Delete(driver);
                await _driverRepository.SaveAsync();

                return(true);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
        }
        public async Task <IActionResult> Delete(int id)
        {
            try
            {
                var driver = await _repo.Delete(id);

                if (driver == null)
                {
                    return(NotFound());
                }
            }
            catch (Exception ex)
            {
                throw new Exception("There was a problem", ex);
            }
            return(NoContent());
        }
Example #13
0
 public ActionResult <Driver> Delete(Guid id)
 {
     try
     {
         var result = driverRepo.Retrieve()
                      .FirstOrDefault((empl) => empl.DriversID == id);
         if (result == null)
         {
             return(NotFound());
         }
         driverRepo.Delete(id);
         return(NoContent());
     }
     catch (Exception)
     {
         return(BadRequest());
     }
 }
Example #14
0
            public async Task <Unit> Handle(Data request, CancellationToken cancellationToken)
            {
                var driver = _driverRepository.GetSingle(request.Id);

                if (driver == null)
                {
                    throw new Exception("no record found");
                }
                _driverRepository.Delete(driver);

                var result = await _driverRepository.Commit();

                if (result > 0)
                {
                    return(Unit.Value);
                }

                throw new Exception("Records were not saved");
            }
Example #15
0
        public async Task <IActionResult> DeleteDriver([FromRoute] int id)
        {
            Driver record = await repo.GetById(id);

            if (record == null)
            {
                LoggerExtensions.LogException(id, logger, ControllerContext, null, null);
                return(StatusCode(404, new {
                    response = ApiMessages.RecordNotFound()
                }));
            }
            try {
                repo.Delete(record);
                return(StatusCode(200, new {
                    response = ApiMessages.RecordDeleted()
                }));
            } catch (DbUpdateException exception) {
                LoggerExtensions.LogException(0, logger, ControllerContext, record, exception);
                return(StatusCode(491, new {
                    response = ApiMessages.RecordInUse()
                }));
            }
        }
Example #16
0
 public void DeleteDriver(Driver driver)
 {
     driversRepository.Delete(driver);
 }
Example #17
0
 public async Task Delete(Driver driver)
 {
     await _driverRepository.Delete(driver);
 }
        public async Task <IHttpActionResult> Delete(int driverId)
        {
            var status = await _repository.Delete(driverId);

            return(Ok(status));
        }
Example #19
0
        public IActionResult DeleteDriver(string id)
        {
            _driverRepository.Delete(id);

            return(NoContent());
        }
Example #20
0
        public async Task <IActionResult> SaveDriver([FromBody] SaveDriverRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            repository.SetTimeout(120);

            PortalUser user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken);

            if (user == null)
            {
                return(NotFound());
            }

            var existingDriver = await repository.GetDriverById(req.CurrentDriver.DriverId);

            if (existingDriver == null && req.CurrentDriver.DriverId > 0)
            {
                return(NotFound());
            }
            else if (existingDriver == null)
            {
                existingDriver = new Driver();
                //set any defaults for new driver
                existingDriver.Cap2Percent      = 0;
                existingDriver.Company          = "";
                existingDriver.ContractExp      = new DateTime(1900, 1, 1);
                existingDriver.ContractTerm     = 1;
                existingDriver.DashNotes        = "";
                existingDriver.Dcxsupplier      = false;
                existingDriver.DcxsupplierId    = "";
                existingDriver.FirstName2       = "";
                existingDriver.FlatRate         = 0;
                existingDriver.IsCoDriver       = 0;
                existingDriver.IsDirDeposit     = false;
                existingDriver.IsReserveFor1099 = false;
                existingDriver.Label            = false;
                existingDriver.LastName2        = "";
                existingDriver.MailTo           = "";
                existingDriver.Mn  = "";
                existingDriver.Mn2 = "";
                existingDriver.NewPayDisplayNotes = "";
                existingDriver.Ssn             = "";
                existingDriver.PayrollId       = "";
                existingDriver.PercentRetained = 0;
                existingDriver.Terminal        = "";
                existingDriver.TransferredFrom = "";
                existingDriver.TruckValue      = 0;
                existingDriver.WorkingDeposit  = 0;
                existingDriver.EthnicityTypeId = 1;
                existingDriver.ModifiedBy      = req.CurrentUser.UserName;
                existingDriver.ModifiedDate    = DateTime.UtcNow;
                existingDriver.CreatedBy       = req.CurrentUser.UserName;
                existingDriver.CreatedDate     = DateTime.UtcNow;
            }
            else if (existingDriver.CompanyId != user.CompanyId)
            {
                return(NotFound());
            }


            existingDriver.DriverId           = req.CurrentDriver.DriverId;
            existingDriver.AccountingDriverId = req.CurrentDriver.DriverAccountingId;
            existingDriver.City = req.CurrentDriver.DriverCity;
            if (req.CurrentDriver.DateOfBirth > DateTime.MinValue)
            {
                existingDriver.DateOfBirth = req.CurrentDriver.DateOfBirth;
            }

            if (req.CurrentDriver.DriverLicenseExpirationDate != null && req.CurrentDriver.DriverLicenseExpirationDate > DateTime.MinValue)
            {
                existingDriver.DriverLicenseExpiration = req.CurrentDriver.DriverLicenseExpirationDate;
            }
            else
            {
                existingDriver.DriverLicenseExpiration = null;
            }

            existingDriver.DriverLicenseNumber          = req.CurrentDriver.DriverLicenseNumber;
            existingDriver.DriverLicenseStateProvinceId = req.CurrentDriver.DriverStateProvinceId;
            existingDriver.FirstName  = req.CurrentDriver.DriverFirstName;
            existingDriver.GenderType = await repository.GetGenderTypeById(req.CurrentDriver.GenderID);

            existingDriver.GenderTypeId = req.CurrentDriver.GenderID;
            if (req.CurrentDriver.HireDate > DateTime.MinValue)
            {
                existingDriver.HireDate = req.CurrentDriver.HireDate;
            }
            existingDriver.CompanyId     = user.CompanyId;
            existingDriver.Inactive      = !req.CurrentDriver.IsActive;
            existingDriver.IsActive      = req.CurrentDriver.IsActive;
            existingDriver.LastName      = req.CurrentDriver.DriverLastName;
            existingDriver.Minority      = false;
            existingDriver.StateProvince = await repository.GetStateProvinceById(req.CurrentDriver.DriverStateProvinceId);

            existingDriver.StateProvinceAbbrev = existingDriver.StateProvince.StateProvinceAbbreviation;
            existingDriver.StateProvinceId     = req.CurrentDriver.DriverStateProvinceId;
            existingDriver.StreetAddressLine1  = req.CurrentDriver.DriverStreetAddressLine1;
            existingDriver.StreetAddressLine2  = req.CurrentDriver.DriverStreetAddressLine2;
            if (req.CurrentDriver.TermDate != null && req.CurrentDriver.TermDate > DateTime.MinValue)
            {
                existingDriver.TermDate = req.CurrentDriver.TermDate;
            }
            else
            {
                existingDriver.TermDate = null;
            }
            existingDriver.Zip = req.CurrentDriver.DriverZip;
            var tempEthnicityType = await repository.GetEthnicityTypeById(req.CurrentDriver.EthnicityTypeId);

            if (tempEthnicityType != null)
            {
                existingDriver.EthnicityType   = tempEthnicityType;
                existingDriver.EthnicityTypeId = tempEthnicityType.EthnicityTypeId;
            }

            //determine if we insert
            if (req.CurrentDriver.DriverId == 0)
            {
                repository.Insert(existingDriver);
                await repository.SaveChanges();
            }
            else
            {
                existingDriver.ModifiedBy   = req.CurrentUser.UserName;
                existingDriver.ModifiedDate = DateTime.UtcNow;

                repository.Attach(existingDriver);
                await repository.SaveChanges();
            }

            //create a placeholder object to hold all the collections
            Driver tempDriverFromCaller = new Driver();

            foreach (DriverPhoneModel p in req.CurrentDriver.DriverPhones)
            {
                var existingPhone = await repository.GetDriverPhoneById(p.DriverPhoneID);

                if (existingPhone == null && p.DriverPhoneID > 0)
                {
                    continue; //skip this record no longer exists or wrong data
                }
                else if (existingPhone == null)
                {
                    existingPhone = new DriverPhone();
                }

                existingPhone.DriverId          = existingDriver.DriverId;
                existingPhone.DriverPhoneNumber = p.DriverPhoneNumber;
                existingPhone.PhoneNumberTypeId = p.DriverPhoneTypeID;
                existingPhone.PhoneNumberType   = await repository.GetPhoneNumberTypeById(p.DriverPhoneTypeID);

                existingPhone.IsActive  = true;
                existingPhone.IsPrimary = p.IsPrimary;

                if (existingPhone.DriverPhoneId <= 0)
                {
                    existingPhone.CreatedBy    = req.CurrentUser.UserName;
                    existingPhone.CreatedDate  = DateTime.UtcNow;
                    existingPhone.ModifiedBy   = req.CurrentUser.UserName;
                    existingPhone.ModifiedDate = DateTime.UtcNow;

                    repository.Insert(existingPhone);
                }
                else
                {
                    if (repository.GetEntityState(existingPhone) == (int)EntityState.Modified)
                    {
                        existingPhone.ModifiedBy   = req.CurrentUser.UserName;
                        existingPhone.ModifiedDate = DateTime.UtcNow;

                        repository.Attach(existingPhone);
                    }
                }

                await repository.SaveChanges();

                //add to temp for compare on deletes
                tempDriverFromCaller.DriverPhone.Add(existingPhone);
            }

            foreach (DriverEmailModel p in req.CurrentDriver.DriverEmails)
            {
                var existingEmail = await repository.GetDriverEmailById(p.DriverEmailAddressID);

                if (existingEmail == null && p.DriverEmailAddressID > 0)
                {
                    continue; //skip this record no longer exists or wrong data
                }
                else if (existingEmail == null)
                {
                    existingEmail = new DriverEmail();
                }

                existingEmail.DriverId           = existingDriver.DriverId;
                existingEmail.DriverEmailAddress = p.DriverEmailAddress;
                existingEmail.IsActive           = true;
                existingEmail.IsPrimary          = p.IsPrimary;

                if (existingEmail.DriverEmailId <= 0)
                {
                    existingEmail.CreatedBy    = req.CurrentUser.UserName;
                    existingEmail.CreatedDate  = DateTime.UtcNow;
                    existingEmail.ModifiedBy   = req.CurrentUser.UserName;
                    existingEmail.ModifiedDate = DateTime.UtcNow;

                    repository.Insert(existingEmail);
                }
                else
                {
                    if (repository.GetEntityState(existingEmail) == (int)EntityState.Modified)
                    {
                        existingEmail.ModifiedBy   = req.CurrentUser.UserName;
                        existingEmail.ModifiedDate = DateTime.UtcNow;

                        repository.Attach(existingEmail);
                    }
                }

                await repository.SaveChanges();

                //add to temp for compare on deletes
                tempDriverFromCaller.DriverEmail.Add(existingEmail);
            }

            foreach (DriverMedicalEvaluationModel p in req.CurrentDriver.DriverMedicalEvaluations)
            {
                var existingMedicalEvaluation = await repository.GetDriverMedicalHistoryById(p.DriverMedicalEvaluationID);

                if (existingMedicalEvaluation == null && p.DriverMedicalEvaluationID > 0)
                {
                    continue; //skip this record no longer exists or wrong data
                }
                else if (existingMedicalEvaluation == null)
                {
                    existingMedicalEvaluation = new DriverMedicalHistory();
                }

                existingMedicalEvaluation.DriverId                  = existingDriver.DriverId;
                existingMedicalEvaluation.MedicalProviderId         = p.DriverMedicalProviderID;
                existingMedicalEvaluation.MedicalExamEffectiveDate  = p.DriverMedicalEffectiveDate;
                existingMedicalEvaluation.MedicalExamExpirationDate = p.DriverMedicalExpirationDate;
                existingMedicalEvaluation.MedicalExamRate           = p.DriverMedicalProviderRate;
                existingMedicalEvaluation.IsActive                  = true;

                if (existingMedicalEvaluation.DriverMedicalHistoryId <= 0)
                {
                    existingMedicalEvaluation.CreatedBy    = req.CurrentUser.UserName;
                    existingMedicalEvaluation.CreatedDate  = DateTime.UtcNow;
                    existingMedicalEvaluation.ModifiedBy   = req.CurrentUser.UserName;
                    existingMedicalEvaluation.ModifiedDate = DateTime.UtcNow;

                    repository.Insert(existingMedicalEvaluation);
                }
                else
                {
                    if (repository.GetEntityState(existingMedicalEvaluation) == (int)EntityState.Modified)
                    {
                        existingMedicalEvaluation.ModifiedBy   = req.CurrentUser.UserName;
                        existingMedicalEvaluation.ModifiedDate = DateTime.UtcNow;

                        repository.Attach(existingMedicalEvaluation);
                    }
                }

                await repository.SaveChanges();

                //add to temp for compare on deletes
                tempDriverFromCaller.DriverMedicalHistory.Add(existingMedicalEvaluation);
            }

            foreach (DriverInsuranceModel p in req.CurrentDriver.DriverInsurances)
            {
                var existingInsurance = await repository.GetDriverInsuranceById(p.DriverInsuranceID);

                if (existingInsurance == null && p.DriverInsuranceID > 0)
                {
                    continue; //skip this record no longer exists or wrong data
                }
                else if (existingInsurance == null)
                {
                    existingInsurance = new DriverInsurance();
                }

                existingInsurance.DriverId               = existingDriver.DriverId;
                existingInsurance.InsuranceProviderId    = p.DriverInsuranceProviderID;
                existingInsurance.InsuranceRate          = p.DriverInsuranceProviderRate;
                existingInsurance.InsuranceEffectiveDate = p.DriverInsuranceStartDate;
                existingInsurance.InsuranceEndDate       = p.DriverInsuranceEndDate;
                existingInsurance.IsActive               = true;

                if (existingInsurance.DriverInsuranceId <= 0)
                {
                    existingInsurance.CreatedBy    = req.CurrentUser.UserName;
                    existingInsurance.CreatedDate  = DateTime.UtcNow;
                    existingInsurance.ModifiedBy   = req.CurrentUser.UserName;
                    existingInsurance.ModifiedDate = DateTime.UtcNow;

                    repository.Insert(existingInsurance);
                }
                else
                {
                    if (repository.GetEntityState(existingInsurance) == (int)EntityState.Modified)
                    {
                        existingInsurance.ModifiedBy   = req.CurrentUser.UserName;
                        existingInsurance.ModifiedDate = DateTime.UtcNow;

                        repository.Attach(existingInsurance);
                    }
                }

                await repository.SaveChanges();

                //add to temp for compare on deletes
                tempDriverFromCaller.DriverInsurance.Add(existingInsurance);
            }

            var curPhones = await repository.GetDriverPhonesByDriverId(existingDriver.DriverId);

            var curEmails = await repository.GetDriverEmailsByDriverId(existingDriver.DriverId);

            var curInsurance = await repository.GetDriverInsuranceByDriverId(existingDriver.DriverId);

            var curMedicalHistory = await repository.GetDriverMedicalHistoryByDriverId(existingDriver.DriverId);

            //delete any collection records that no longer exist
            foreach (DriverPhone p in curPhones)
            {
                var found = tempDriverFromCaller.DriverPhone.FirstOrDefault(o => o.DriverPhoneId == p.DriverPhoneId);
                //if its not found then delete it from database
                if (found == null)
                {
                    repository.Delete(p);
                    await repository.SaveChanges();
                }
            }

            foreach (DriverEmail p in curEmails)
            {
                var found = tempDriverFromCaller.DriverEmail.FirstOrDefault(o => o.DriverEmailId == p.DriverEmailId);
                //if its not found then delete it from database
                if (found == null)
                {
                    repository.Delete(p);
                    await repository.SaveChanges();
                }
            }

            foreach (DriverInsurance insurance in curInsurance)
            {
                var found = tempDriverFromCaller.DriverInsurance.FirstOrDefault(x => x.DriverInsuranceId == insurance.DriverInsuranceId);

                if (found == null)
                {
                    repository.Delete(insurance);
                    await repository.SaveChanges();
                }
            }

            foreach (DriverMedicalHistory medicalHistory in curMedicalHistory)
            {
                var found = tempDriverFromCaller.DriverMedicalHistory.FirstOrDefault(x => x.DriverMedicalHistoryId == medicalHistory.DriverMedicalHistoryId);

                if (found == null)
                {
                    repository.Delete(medicalHistory);
                    await repository.SaveChanges();
                }
            }

            var currentDriver = await repository.GetDriverById(existingDriver.DriverId);

            return(Ok(LoadDriver(currentDriver)));
        }
 public IActionResult RemoveNow(int Id)
 {
     db.Delete(Id);
     db.Save();
     return(RedirectToAction("ShowDrivers"));
 }
Example #22
0
 public Driver Delete(int id)
 {
     return(_driverRepository.Delete(id));
 }
 public ActionResult Delete(int id)
 {
     repository.Delete(id);
     return(RedirectToAction("Index"));
 }
        public async Task <IActionResult> SaveContract([FromBody] SaveContractRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            repository.SetTimeout(120);

            PortalUser user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken);

            if (user == null)
            {
                return(NotFound());
            }

            var existingContract = await repository.GetContractById(req.CurrentContract.ContractId);


            if (existingContract == null && req.CurrentContract.ContractId > 0)
            {
                return(NotFound());
            }
            else if (existingContract == null)
            {
                existingContract = new Contract()
                {
                    CreatedBy   = req.CurrentUser.UserName,
                    CreatedDate = DateTime.UtcNow,
                };
            }
            else if (existingContract.CompanyId != user.CompanyId)
            {
                return(NotFound());
            }

            existingContract.AccountingContractId = req.CurrentContract.AccountingContractId;
            existingContract.ContractName         = req.CurrentContract.ContractName;
            existingContract.ContractNumber       = req.CurrentContract.ContractNumber;
            if (req.CurrentContract.ContractStartDate > DateTime.MinValue)
            {
                existingContract.ContractStartDate = req.CurrentContract.ContractStartDate;
            }
            if (req.CurrentContract.ContractEndDate > DateTime.MinValue)
            {
                existingContract.ContractEndDate = req.CurrentContract.ContractEndDate;
            }
            existingContract.ResponsibleParty = req.CurrentContract.ResponsibleParty;
            existingContract.TIN             = req.CurrentContract.TIN;
            existingContract.PayrollId       = req.CurrentContract.PayrollId;
            existingContract.IsDirectDeposit = req.CurrentContract.IsDirectDeposit;
            existingContract.Is1099Vendor    = req.CurrentContract.Is1099Vendor;
            existingContract.InitialDeposit  = req.CurrentContract.InitialDeposit;
            existingContract.PercentRetained = req.CurrentContract.PercentRetained;
            existingContract.CompanyId       = user.CompanyId;
            existingContract.IsActive        = req.CurrentContract.IsActive;
            existingContract.ModifiedBy      = req.CurrentUser.UserName;
            existingContract.ModifiedDate    = DateTime.UtcNow;

            // Determine if it is an insert. If not it will be an update.
            if (req.CurrentContract.ContractId == 0)
            {
                repository.Insert(existingContract);
            }

            await repository.SaveChanges();

            Contract temp = new Contract();
            List <DriverContract> driverContracts = await repository.GetDriverContractsByContractId(existingContract.ContractId);

            List <ContractTruck> contractTrucks = await repository.GetContractTrucksByContractId(existingContract.ContractId);

            List <ContractFinanceAgreement> contractFinanceAgreement = await repository.GetContractFinanceAgreementsByContractId(existingContract.ContractId);

            foreach (AssignedDriverModel driver in req.CurrentContract.AssignedDrivers)
            {
                DriverContract existingDriverContract = await repository.GetDriverContractById(driver.DriverContractId);

                if (existingDriverContract == null && driver.DriverContractId > 0)
                {
                    // Skip this record. no longer exists or wrong data.
                    continue;
                }
                else if (existingDriverContract == null)
                {
                    existingDriverContract = new DriverContract();
                    repository.Insert(existingDriverContract);
                }

                existingDriverContract.DriverId   = driver.DriverId;
                existingDriverContract.ContractId = existingContract.ContractId;
                existingDriverContract.StartDate  = driver.StartDate;
                existingDriverContract.EndDate    = driver.EndDate;
                existingDriverContract.IsActive   = true;

                if (driver.DriverContractId == 0)
                {
                    existingDriverContract.CreatedBy   = req.CurrentUser.UserName;
                    existingDriverContract.CreatedDate = DateTime.UtcNow;
                }

                if (repository.IsChanged(existingDriverContract))
                {
                    existingDriverContract.ModifiedBy   = req.CurrentUser.UserName;
                    existingDriverContract.ModifiedDate = DateTime.UtcNow;
                }

                driverContracts.RemoveAll(x => x.DriverContractId == existingDriverContract.DriverContractId);

                temp.DriverContract.Add(existingDriverContract);
            }

            foreach (AssignedTruckModel truck in req.CurrentContract.AssignedTrucks)
            {
                ContractTruck exisingContractTruck = await repository.GetContractTruckById(truck.ContractTruckId);

                if (exisingContractTruck == null && truck.ContractTruckId > 0)
                {
                    // Skip this record. no longer exists or wrong data.
                    continue;
                }
                else if (exisingContractTruck == null)
                {
                    exisingContractTruck = new ContractTruck();
                    repository.Insert(exisingContractTruck);
                }

                exisingContractTruck.TruckId    = truck.TruckId;
                exisingContractTruck.ContractId = existingContract.ContractId;
                exisingContractTruck.StartDate  = truck.StartDate;
                exisingContractTruck.EndDate    = truck.EndDate;
                exisingContractTruck.IsActive   = true;

                if (truck.ContractTruckId == 0)
                {
                    exisingContractTruck.CreatedBy   = req.CurrentUser.UserName;
                    exisingContractTruck.CreatedDate = DateTime.UtcNow;
                }

                if (repository.IsChanged(exisingContractTruck))
                {
                    exisingContractTruck.ModifiedBy   = req.CurrentUser.UserName;
                    exisingContractTruck.ModifiedDate = DateTime.UtcNow;
                }

                contractTrucks.RemoveAll(x => x.ContractTruckId == exisingContractTruck.ContractTruckId);

                temp.ContractTruck.Add(exisingContractTruck);
            }

            foreach (AssignedFinanceAgreementModel financialAgreement in req.CurrentContract.AssignedFinanceAgreements)
            {
                ContractFinanceAgreement existingFinancialAgreement = await repository.GetContractFinanceAgreementById(financialAgreement.ContractFinanceAgreementId);

                if (existingFinancialAgreement == null && financialAgreement.ContractFinanceAgreementId > 0)
                {
                    // Skip this record. no longer exists or wrong data.
                    continue;
                }
                else if (existingFinancialAgreement == null)
                {
                    existingFinancialAgreement           = new ContractFinanceAgreement();
                    existingFinancialAgreement.CompanyId = user.CompanyId;
                    repository.Insert(existingFinancialAgreement);
                }

                existingFinancialAgreement.ContractId = existingContract.ContractId;
                existingFinancialAgreement.IsActive   = true;

                if (financialAgreement.ContractFinanceAgreementId == 0)
                {
                    existingFinancialAgreement.CreatedBy   = req.CurrentUser.UserName;
                    existingFinancialAgreement.CreatedDate = DateTime.UtcNow;
                }

                if (repository.IsChanged(existingFinancialAgreement))
                {
                    existingFinancialAgreement.ModifiedBy   = req.CurrentUser.UserName;
                    existingFinancialAgreement.ModifiedDate = DateTime.UtcNow;
                }

                existingFinancialAgreement.StartDate            = financialAgreement.StartDate;
                existingFinancialAgreement.EndDate              = (financialAgreement.EndDate ?? DateTime.MinValue);
                existingFinancialAgreement.PaymentAmount        = financialAgreement.PaymentAmount;
                existingFinancialAgreement.FinanceAgreementName = financialAgreement.FinanceAgreementName;
                existingFinancialAgreement.LoanAmount           = financialAgreement.LoanAmount;
                existingFinancialAgreement.RemainingBalance     = financialAgreement.RemainingBalance;
                var typeQuery = await repository.GetFinanceTypeByName(financialAgreement.FinanceTypeName);

                if (typeQuery == null)
                {
                    return(NotFound());
                }

                existingFinancialAgreement.FinanceTypeId = typeQuery.FinanceTypeId;

                contractFinanceAgreement.RemoveAll(x => x.ContractFinanceAgreementId == existingFinancialAgreement.ContractFinanceAgreementId);

                temp.ContractFinanceAgreement.Add(existingFinancialAgreement);
            }

            // Delete any unincluded elements in the collection.
            foreach (DriverContract driver in driverContracts)
            {
                repository.Delete(driver);
            }
            foreach (ContractTruck truck in contractTrucks)
            {
                repository.Delete(truck);
            }
            foreach (ContractFinanceAgreement financialAgreement in contractFinanceAgreement)
            {
                repository.Delete(financialAgreement);
            }

            existingContract.DriverContract           = temp.DriverContract;
            existingContract.ContractTruck            = temp.ContractTruck;
            existingContract.ContractFinanceAgreement = temp.ContractFinanceAgreement;

            repository.Ignore(existingContract);
            await repository.SaveChanges();

            return(Ok(LoadContract(existingContract)));
        }
Example #25
0
        public async Task <IActionResult> SavePeriodList([FromBody] SavePeriodListRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await repository.AuthenticateUserToken(req.CurrentUser.UserId, req.CurrentUser.UserToken);

            if (user == null)
            {
                return(NotFound());
            }

            if (req.Periods == null)
            {
                req.Periods = (await repository.GetPeriodsByCompanyId(user.CompanyId)).Select(x => LoadPeriod(x)).ToList();
            }

            try
            {
                if (req.IsBuild)
                {
                    req.Periods.AddRange(BuildPeriodList(req.FrequencyTypeId, req.StartDate, req.EndDate));
                }
            }catch (ArgumentException e)
            {
                return(NotFound(e));
            }

            GetPeriodListResponse resp = new GetPeriodListResponse();

            resp.Periods = new List <PeriodModel>(req.Periods.Count + 10);

            using (var transaction = await repository.StartTransaction())
            {
                try
                {
                    foreach (PeriodModel period in req.Periods)
                    {
                        try
                        {
                            if (!period.IsDeleted)
                            {
                                var result = await SavePeriodModel(user, period);

                                resp.Periods.Add(result);
                            }
                            else
                            {
                                Period existingPeriod = await repository.GetPeriodById(period.PeriodId);

                                if (existingPeriod == null)
                                {
                                    throw new NullReferenceException("Could not find the period with the id specified.");
                                }

                                repository.Delete(existingPeriod);
                                await repository.SaveChanges();
                            }
                        }
                        catch (NullReferenceException e)
                        {
                            throw new NullReferenceException($"Period: {period.PeriodId} error", e);
                        }
                        catch (UnauthorizedAccessException e)
                        {
                            throw new UnauthorizedAccessException($"Period: {period.PeriodId} is not editable by this user.", e);
                        }
                        catch (Exception e)
                        {
                            throw new Exception("Unknown Error Occured.", e);
                        }
                    }

                    transaction.Commit();
                }catch (Exception e)
                {
                    transaction.Rollback();

                    return(NotFound(e.InnerException));
                }

                resp.Periods = resp.Periods.OrderByDescending(x => x.StartDate).ToList();

                return(Ok(resp));
            }
        }