예제 #1
0
        /// <summary>
        /// Attempts to save a new or existing Period based n the model provided.
        /// </summary>
        /// <param name="currentUser">The user attempting to save.</param>
        /// <param name="period">The model of data trying to be saved.</param>
        /// <exception cref="NullReferenceException">This will be thrown when a period that doesnt seem to be new doesnt exist in the db.</exception>
        /// <exception cref="UnauthorizedAccessException">This will be thrown when a user attempts to save a period they dont have access to.</exception>"
        /// <exception cref="ArgumentException">This will be thrown when the period overlaps an existing period.</exception>
        /// <returns>A period DTO that represents what was saved.</returns>
        private async Task <PeriodModel> SavePeriodModel(PortalUser currentUser, PeriodModel period)
        {
            var existingPeriod = await repository.GetPeriodById(period.PeriodId);

            if (existingPeriod == null && period.PeriodId > 0)
            {
                throw new NullReferenceException("Could not find period with id specified.");
            }
            else if (existingPeriod == null)
            {
                existingPeriod = new Period()
                {
                    CreatedBy    = currentUser.PortalUsername,
                    CreatedDate  = DateTime.UtcNow,
                    ModifiedBy   = currentUser.PortalUsername,
                    ModifiedDate = DateTime.UtcNow
                };
            }
            else if (existingPeriod.CompanyId != currentUser.CompanyId)
            {
                throw new UnauthorizedAccessException("You cannot acces this period as this user.");
            }

            existingPeriod.Year            = period.Year;
            existingPeriod.EndDate         = period.EndDate;
            existingPeriod.StartDate       = period.StartDate;
            existingPeriod.FrequencyTypeId = period.FrequencyTypeId;
            existingPeriod.CompanyId       = currentUser.CompanyId;
            existingPeriod.IsActive        = true;

            existingPeriod.FrequencyType = await repository.GetFrequencyTypeById(period.FrequencyTypeId);

            if (existingPeriod.PeriodId == 0)
            {
                // Need to check for non overlapping periods.
                if (await repository.IsPeriodOverlapping(existingPeriod.StartDate, existingPeriod.EndDate))
                {
                    throw new ArgumentException("New period overlaps with a previous period.");
                }

                repository.Insert(existingPeriod);
                await repository.SaveChanges();
            }
            else if (repository.IsChanged(existingPeriod))
            {
                existingPeriod.ModifiedBy   = currentUser.PortalUsername;
                existingPeriod.ModifiedDate = DateTime.UtcNow;

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

            return(LoadPeriod(existingPeriod));
        }
예제 #2
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)));
        }
        /// <summary>
        /// This method will take the data from the invoice model and save it to the database.
        /// A 0 id will denote a new insert. id > 0 will denote updating an existing row.
        /// </summary>
        /// <param name="currentUser">The user performing this action.</param>
        /// <param name="invoice">The invoice data used to update/insert the row.</param>
        /// <exception cref="NullReferenceException">Denotes that either the driver or the invoice was not found.</exception>
        /// <exception cref="UnauthorizedAccessException">Denotes that you tried to update a record that does not belong to the user's company.</exception>
        /// <returns>An invoice model of the updated data for returning to the UI.</returns>
        public async Task <InvoiceModel> SaveInvoice(PortalUser currentUser, InvoiceModel invoice)
        {
            var existingInvoice = await repository.GetInvoiceById(invoice.InvoiceId);

            if (existingInvoice == null & invoice.InvoiceId > 0)
            {
                throw new NullReferenceException("Invoice was not found.");
            }
            else if (existingInvoice == null)
            {
                existingInvoice = new Invoice()
                {
                    CreatedBy    = currentUser.PortalUsername,
                    CreatedDate  = DateTime.UtcNow,
                    ModifiedBy   = currentUser.PortalUsername,
                    ModifiedDate = DateTime.UtcNow
                };
            }
            else if (existingInvoice.CompanyId != currentUser.CompanyId)
            {
                throw new UnauthorizedAccessException("You cannot access this invoice as this user.");
            }

            existingInvoice.CenterId                  = invoice.Terminal;
            existingInvoice.DeliveryDate              = invoice.DeliveryDate;
            existingInvoice.DispatchLoadNumber        = invoice.DispatchLoadNumber;
            existingInvoice.DriverFuelSurcharge       = invoice.DriverFuelSurcharge;
            existingInvoice.DriverRate                = invoice.DriverRate;
            existingInvoice.CompanyId                 = currentUser.CompanyId;
            existingInvoice.IsActive                  = true;
            existingInvoice.ManufacturerFuelSurcharge = invoice.ManufacturerFuelSurcharge;
            existingInvoice.ManufacturerId            = invoice.VendorId;
            existingInvoice.ManufacturerRate          = invoice.ManufacturerRate;
            existingInvoice.VIN = invoice.TrackingIdNumber;
            existingInvoice.TransactionStatusTypeId = (int)TransactionStatusType.Enum.Open;

            if (invoice.Driver != null)
            {
                var driver = invoice.Driver != null ? await repository.GetDriverById(invoice.Driver.DriverId) : null;

                if (driver != null)
                {
                    existingInvoice.DriverId = driver.DriverId;
                }
                else
                {
                    throw new NullReferenceException("Driver was not found");
                }
            }

            var truck = await repository.GetTruckByTruckNumber(invoice.TruckNumber);

            if (truck != null)
            {
                existingInvoice.TruckId = truck.TruckId;
            }

            if (invoice.InvoiceId == 0)
            {
                repository.Insert(existingInvoice);
                await repository.SaveChanges();
                await CreateInvoiceRevision(currentUser, existingInvoice.InvoiceId, "Created");
            }
            else if (repository.IsChanged(existingInvoice))
            {
                existingInvoice.ModifiedBy   = currentUser.PortalUsername;
                existingInvoice.ModifiedDate = DateTime.UtcNow;

                repository.Attach(existingInvoice);
                await repository.SaveChanges();
                await CreateInvoiceRevision(currentUser, existingInvoice.InvoiceId, "Updated");
            }

            return(LoadInvoice(existingInvoice));
        }