Example #1
0
        /// <summary>
        /// Get the number of blocks for this type of equipment
        /// </summary>
        /// <param name="item"></param>
        /// <param name="context"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        private static int GetNumberOfBlocks(HetRentalRequest item, DbAppContext context, IConfiguration configuration)
        {
            int numberOfBlocks = -1;

            try
            {
                SeniorityScoringRules scoringRules = new SeniorityScoringRules(configuration);

                // get record
                HetDistrictEquipmentType equipment = context.HetDistrictEquipmentType.AsNoTracking()
                                                     .Include(x => x.EquipmentType)
                                                     .FirstOrDefault(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentTypeId);

                if (equipment == null)
                {
                    return(0);
                }

                numberOfBlocks = equipment.EquipmentType.IsDumpTruck ?
                                 scoringRules.GetTotalBlocks("DumpTruck") : scoringRules.GetTotalBlocks();
            }
            catch
            {
                // do nothing
            }

            return(numberOfBlocks);
        }
Example #2
0
        /// <summary>
        /// Recalculates seniority for a specific local area and equipment type
        /// </summary>
        public static void RecalculateSeniority(int?localAreaId, int?districtEquipmentTypeId,
                                                DbAppContext context, string seniorityScoringRules)
        {
            // check if the local area exists
            bool exists = context.HetLocalArea.Any(a => a.LocalAreaId == localAreaId);

            if (!exists)
            {
                throw new ArgumentException("Local Area is invalid");
            }

            // check if the equipment type exists
            exists = context.HetDistrictEquipmentType
                     .Any(a => a.DistrictEquipmentTypeId == districtEquipmentTypeId);

            if (!exists)
            {
                throw new ArgumentException("District Equipment Type is invalid");
            }

            // get the local area
            HetLocalArea localArea = context.HetLocalArea.AsNoTracking()
                                     .First(a => a.LocalAreaId == localAreaId);

            // get the equipment type
            HetDistrictEquipmentType districtEquipmentType = context.HetDistrictEquipmentType.AsNoTracking()
                                                             .Include(x => x.EquipmentType)
                                                             .First(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId);

            // recalculate the seniority list
            SeniorityListHelper.CalculateSeniorityList(localArea.LocalAreaId,
                                                       districtEquipmentType.DistrictEquipmentTypeId,
                                                       context,
                                                       seniorityScoringRules);
        }
        public virtual IActionResult DistrictEquipmentTypesIdGet([FromRoute] int id)
        {
            HetDistrictEquipmentType equipmentType = _context.HetDistrictEquipmentType.AsNoTracking()
                                                     .Include(x => x.District)
                                                     .ThenInclude(y => y.Region)
                                                     .Include(x => x.EquipmentType)
                                                     .FirstOrDefault(a => a.DistrictEquipmentTypeId == id);

            return(new ObjectResult(new HetsResponse(equipmentType)));
        }
        public virtual IActionResult DistrictEquipmentTypesIdPost([FromRoute] int id, [FromBody] HetDistrictEquipmentType item)
        {
            if (id != item.DistrictEquipmentTypeId)
            {
                // not found
                return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            // add or update equipment type
            if (item.DistrictEquipmentTypeId > 0)
            {
                bool exists = _context.HetDistrictEquipmentType.Any(a => a.DistrictEquipmentTypeId == id);

                // not found
                if (!exists)
                {
                    return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                }

                // get record
                HetDistrictEquipmentType equipment = _context.HetDistrictEquipmentType.First(x => x.DistrictEquipmentTypeId == id);

                equipment.DistrictEquipmentName    = item.DistrictEquipmentName;
                equipment.ConcurrencyControlNumber = item.ConcurrencyControlNumber;
                equipment.DistrictId      = item.District.DistrictId;
                equipment.EquipmentTypeId = item.EquipmentType.EquipmentTypeId;
            }
            else
            {
                HetDistrictEquipmentType equipment = new HetDistrictEquipmentType
                {
                    DistrictEquipmentName = item.DistrictEquipmentName,
                    DistrictId            = item.District.DistrictId,
                    EquipmentTypeId       = item.EquipmentType.EquipmentTypeId
                };

                _context.HetDistrictEquipmentType.Add(equipment);
            }

            // save the changes
            _context.SaveChanges();

            // get the id (in the case of new records)
            id = item.DistrictEquipmentTypeId;

            // return the updated equipment type record
            HetDistrictEquipmentType equipmentType = _context.HetDistrictEquipmentType.AsNoTracking()
                                                     .Include(x => x.District)
                                                     .ThenInclude(y => y.Region)
                                                     .Include(x => x.EquipmentType)
                                                     .FirstOrDefault(a => a.DistrictEquipmentTypeId == id);

            return(new ObjectResult(new HetsResponse(equipmentType)));
        }
        public virtual IActionResult DistrictEquipmentTypesIdDeletePost([FromRoute] int id)
        {
            bool exists = _context.HetDistrictEquipmentType.Any(a => a.DistrictEquipmentTypeId == id);

            // not found
            if (!exists)
            {
                return(new ObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            HetDistrictEquipmentType item = _context.HetDistrictEquipmentType.First(a => a.DistrictEquipmentTypeId == id);

            _context.HetDistrictEquipmentType.Remove(item);

            // save changes
            _context.SaveChanges();

            return(new ObjectResult(new HetsResponse(item)));
        }
Example #6
0
        /// <summary>
        /// Copy Block item of LocalAreaRotationList item
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="rotationList"></param>
        /// <param name="systemId"></param>
        /// <param name="maxBlockIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Block oldObject,
                                           ref HetLocalAreaRotationList rotationList, string systemId, ref int maxBlockIndex)
        {
            try
            {
                bool isNew = false;

                if (oldObject.Area_Id <= 0)
                {
                    return; // ignore these records
                }

                if (oldObject.Equip_Type_Id <= 0)
                {
                    return; // ignore these records
                }

                if (oldObject.Last_Hired_Equip_Id <= 0)
                {
                    return; // ignore these records
                }

                string tempRecordDate = oldObject.Created_Dt;

                if (string.IsNullOrEmpty(tempRecordDate))
                {
                    return; // ignore if we don't have a created date
                }

                // ***********************************************
                // get the area record
                // ***********************************************
                string tempOldAreaId = oldObject.Area_Id.ToString();

                HetImportMap mapArea = dbContext.HetImportMap.AsNoTracking()
                                       .FirstOrDefault(x => x.OldKey == tempOldAreaId &&
                                                       x.OldTable == ImportLocalArea.OldTable &&
                                                       x.NewTable == ImportLocalArea.NewTable);

                if (mapArea == null)
                {
                    throw new DataException(string.Format("Area Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                HetLocalArea area = dbContext.HetLocalArea.AsNoTracking()
                                    .FirstOrDefault(x => x.LocalAreaId == mapArea.NewKey);

                if (area == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate Local Area record (Local Area Id: {0})", tempOldAreaId));
                }

                // ***********************************************
                // get the equipment type record
                // ***********************************************
                string tempOldEquipTypeId = oldObject.Equip_Type_Id.ToString();

                HetImportMap mapEquipType = dbContext.HetImportMap.AsNoTracking()
                                            .FirstOrDefault(x => x.OldKey == tempOldEquipTypeId &&
                                                            x.OldTable == ImportDistrictEquipmentType.OldTable &&
                                                            x.NewTable == ImportDistrictEquipmentType.NewTable);

                if (mapEquipType == null)
                {
                    return; // ignore and move to the next record
                }

                HetDistrictEquipmentType equipmentType = dbContext.HetDistrictEquipmentType.AsNoTracking()
                                                         .FirstOrDefault(x => x.DistrictEquipmentTypeId == mapEquipType.NewKey);

                if (equipmentType == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate District Equipment Type record (Equipment Type Id: {0})", tempOldEquipTypeId));
                }

                // ***********************************************
                // see if a record already exists
                // ***********************************************
                rotationList = dbContext.HetLocalAreaRotationList
                               .FirstOrDefault(x => x.LocalAreaId == area.LocalAreaId &&
                                               x.DistrictEquipmentTypeId == equipmentType.DistrictEquipmentTypeId);

                if (rotationList == null)
                {
                    isNew = true;

                    // create new list
                    rotationList = new HetLocalAreaRotationList
                    {
                        LocalAreaRotationListId = ++maxBlockIndex,
                        LocalAreaId             = area.LocalAreaId,
                        DistrictEquipmentTypeId = equipmentType.DistrictEquipmentTypeId,
                        AppCreateUserid         = systemId,
                        AppCreateTimestamp      = DateTime.UtcNow
                    };
                }

                // ***********************************************
                // get the equipment record
                // ***********************************************
                string tempOldEquipId = oldObject.Last_Hired_Equip_Id.ToString();

                HetImportMap mapEquip = dbContext.HetImportMap.AsNoTracking()
                                        .FirstOrDefault(x => x.OldKey == tempOldEquipId &&
                                                        x.OldTable == ImportEquip.OldTable &&
                                                        x.NewTable == ImportEquip.NewTable);

                if (mapEquip == null)
                {
                    throw new DataException(string.Format("Equipment Id cannot be null (BlockIndex: {0})", maxBlockIndex));
                }

                HetEquipment equipment = dbContext.HetEquipment.AsNoTracking()
                                         .FirstOrDefault(x => x.EquipmentId == mapEquip.NewKey);

                if (equipment == null)
                {
                    throw new ArgumentException(string.Format("Cannot locate Equipment record (Equipment Id: {0})", tempOldEquipId));
                }

                // ***********************************************
                // update the "Ask Next" values
                // ***********************************************
                float?blockNum = ImportUtility.GetFloatValue(oldObject.Block_Num);

                if (blockNum == null)
                {
                    throw new DataException(string.Format("Block Number cannot be null (BlockIndex: {0}", maxBlockIndex));
                }

                // extract AskNextBlock*Id which is the secondary key of Equip.Id
                int   equipId   = equipment.EquipmentId;
                float?seniority = equipment.Seniority;

                switch (blockNum)
                {
                case 1:
                    rotationList.AskNextBlock1Id        = equipId;
                    rotationList.AskNextBlock1Seniority = seniority;
                    break;

                case 2:
                    rotationList.AskNextBlock2Id        = equipId;
                    rotationList.AskNextBlock2Seniority = seniority;
                    break;

                case 3:
                    rotationList.AskNextBlockOpenId = equipId;
                    break;
                }

                // ***********************************************
                // update or create rotation list
                // ***********************************************
                rotationList.AppLastUpdateUserid    = systemId;
                rotationList.AppLastUpdateTimestamp = DateTime.UtcNow;

                if (isNew)
                {
                    dbContext.HetLocalAreaRotationList.Add(rotationList);
                }
                else
                {
                    dbContext.HetLocalAreaRotationList.Update(rotationList);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Master Block Index: " + maxBlockIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Example #7
0
        public static void MergeDistrictEquipmentTypes(PerformContext context, string seniorityScoringRules,
                                                       string connectionString)
        {
            // open a connection to the database
            DbAppContext dbContext = new DbAppContext(connectionString);

            // get equipment status
            int?equipmentStatusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", dbContext);

            if (equipmentStatusId == null)
            {
                throw new ArgumentException("Status Code not found");
            }

            // **************************************************
            // Phase 1: Identify Master District Equipment Types
            // **************************************************
            context.WriteLine("Phase 1: Identify Master District Equipment Types");
            IProgressBar progress = context.WriteProgressBar();

            progress.SetValue(0);

            // get records
            List <MergeRecord> masterList = dbContext.HetDistrictEquipmentType.AsNoTracking()
                                            .Where(x => x.ServiceAreaId != null &&
                                                   x.Deleted == false)
                                            .Select(x => new MergeRecord
            {
                DistrictEquipmentTypeId = x.DistrictEquipmentTypeId,
                DistrictEquipmentName   = x.DistrictEquipmentName,
                EquipmentPrefix         = GetPrefix(x.DistrictEquipmentName),
                DistrictId      = x.DistrictId,
                EquipmentTypeId = x.EquipmentTypeId
            })
                                            .Distinct()
                                            .ToList();

            // sort the list accordingly
            masterList = masterList
                         .OrderBy(x => x.DistrictId)
                         .ThenBy(x => x.EquipmentTypeId)
                         .ThenBy(x => x.EquipmentPrefix).ToList();

            int    increment       = 0;
            int?   currentDistrict = -1;
            int?   masterDistrictEquipmentTypeId = -1;
            int?   currentEquipmentType          = -1;
            string currentPrefix = "";

            foreach (MergeRecord detRecord in masterList)
            {
                bool newMerge;

                if (detRecord.DistrictId != currentDistrict ||
                    detRecord.EquipmentTypeId != currentEquipmentType ||
                    detRecord.EquipmentPrefix != currentPrefix)
                {
                    newMerge             = true;
                    currentDistrict      = detRecord.DistrictId;
                    currentEquipmentType = detRecord.EquipmentTypeId;
                    currentPrefix        = detRecord.EquipmentPrefix;

                    masterDistrictEquipmentTypeId = detRecord.DistrictEquipmentTypeId;
                    detRecord.Master = true;
                    detRecord.MasterDistrictEquipmentTypeId = masterDistrictEquipmentTypeId;
                }
                else
                {
                    newMerge         = false;
                    detRecord.Master = false;
                    detRecord.MasterDistrictEquipmentTypeId = masterDistrictEquipmentTypeId;
                }

                // kickoff the merge for this district, equipment type and prefix
                if (newMerge)
                {
                    int    district   = currentDistrict ?? -1;
                    int    type       = currentEquipmentType ?? -1;
                    string prefix     = currentPrefix;
                    string masterName = "";

                    List <MergeRecord> types = masterList
                                               .Where(x => x.DistrictId == district &&
                                                      x.EquipmentTypeId == type &&
                                                      x.EquipmentPrefix == prefix).ToList();

                    // create master name and update master record
                    foreach (MergeRecord equipmentType in types)
                    {
                        string temp  = equipmentType.DistrictEquipmentName.Replace(currentPrefix, "").Trim();
                        int    start = temp.IndexOf("-", StringComparison.Ordinal);
                        if (start > -1)
                        {
                            start++;
                        }
                        int length = temp.Length - start < 0 ? 0 : temp.Length - start;
                        temp = temp.Substring(start, length).Trim();

                        masterName = masterName.Length > 0 ?
                                     $"{masterName} | {temp}" :
                                     temp;
                    }

                    masterName = $"{currentPrefix} - {masterName}";
                    types.ElementAt(0).DistrictEquipmentName = masterName;
                }

                // update status bar
                increment++;
                progress.SetValue(Convert.ToInt32((decimal)(masterList.Count - (masterList.Count - increment)) / masterList.Count * 100));
            }

            // done!
            progress.SetValue(100);

            // **************************************************
            // Phase 2: Update Master District Equipment Types
            // **************************************************
            context.WriteLine("Phase 2: Update Master District Equipment Types");
            progress = context.WriteProgressBar();
            progress.SetValue(0);

            List <MergeRecord> masterRecords = masterList.Where(x => x.Master).ToList();

            increment = 0;

            foreach (MergeRecord detRecord in masterRecords)
            {
                // get det record & update name
                HetDistrictEquipmentType det = dbContext.HetDistrictEquipmentType
                                               .First(x => x.DistrictEquipmentTypeId == detRecord.DistrictEquipmentTypeId);

                det.DistrictEquipmentName = detRecord.DistrictEquipmentName;
                det.ServiceAreaId         = null;

                // save changes to district equipment types and associated equipment records
                dbContext.SaveChangesForImport();

                // update status bar
                increment++;
                progress.SetValue(Convert.ToInt32((decimal)(masterRecords.Count - (masterRecords.Count - increment)) / masterRecords.Count * 100));
            }

            // done!
            progress.SetValue(100);

            // **************************************************
            // Phase 3: Update Non-Master District Equipment Types
            // **************************************************
            context.WriteLine("Phase 3: Update Non-Master District Equipment Types");
            progress = context.WriteProgressBar();
            progress.SetValue(0);

            List <MergeRecord> mergeRecords = masterList.Where(x => !x.Master).ToList();

            increment = 0;

            foreach (MergeRecord detRecord in mergeRecords)
            {
                int originalDistrictEquipmentTypeId = detRecord.DistrictEquipmentTypeId;
                int?newDistrictEquipmentTypeId      = detRecord.MasterDistrictEquipmentTypeId;

                // get equipment & update
                IEnumerable <HetEquipment> equipmentRecords = dbContext.HetEquipment
                                                              .Where(x => x.DistrictEquipmentTypeId == originalDistrictEquipmentTypeId);

                foreach (HetEquipment equipment in equipmentRecords)
                {
                    equipment.DistrictEquipmentTypeId = newDistrictEquipmentTypeId;
                }

                // save changes to associated equipment records
                dbContext.SaveChangesForImport();

                // get det record
                HetDistrictEquipmentType det = dbContext.HetDistrictEquipmentType
                                               .First(x => x.DistrictEquipmentTypeId == originalDistrictEquipmentTypeId);

                // delete old det record
                HetRentalRequest request = dbContext.HetRentalRequest.AsNoTracking()
                                           .FirstOrDefault(x => x.DistrictEquipmentTypeId == originalDistrictEquipmentTypeId);

                HetLocalAreaRotationList rotationList = dbContext.HetLocalAreaRotationList.AsNoTracking()
                                                        .FirstOrDefault(x => x.DistrictEquipmentTypeId == originalDistrictEquipmentTypeId);

                if (request != null || rotationList != null)
                {
                    det.Deleted = true;
                }
                else
                {
                    dbContext.HetDistrictEquipmentType.Remove(det);
                }

                // save changes to district equipment types and associated equipment records
                dbContext.SaveChangesForImport();

                // update status bar
                increment++;
                progress.SetValue(Convert.ToInt32((decimal)(mergeRecords.Count - (mergeRecords.Count - increment)) / mergeRecords.Count * 100));
            }

            // done!
            progress.SetValue(100);

            // **************************************************
            // Phase 4: Update seniority and block assignments
            // **************************************************
            context.WriteLine("Phase 4: Update seniority and block assignments");
            progress = context.WriteProgressBar();
            progress.SetValue(0);

            increment = 0;

            foreach (MergeRecord detRecord in masterRecords)
            {
                // update the seniority and block assignments for the master record
                List <HetLocalArea> localAreas = dbContext.HetEquipment.AsNoTracking()
                                                 .Include(x => x.LocalArea)
                                                 .Where(x => x.EquipmentStatusTypeId == equipmentStatusId &&
                                                        x.DistrictEquipmentTypeId == detRecord.DistrictEquipmentTypeId)
                                                 .Select(x => x.LocalArea)
                                                 .Distinct()
                                                 .ToList();

                foreach (HetLocalArea localArea in localAreas)
                {
                    EquipmentHelper.RecalculateSeniority(localArea.LocalAreaId,
                                                         detRecord.DistrictEquipmentTypeId, dbContext, seniorityScoringRules);
                }

                // save changes to equipment records
                dbContext.SaveChangesForImport();

                // update status bar
                increment++;
                progress.SetValue(Convert.ToInt32((decimal)(masterRecords.Count - (masterRecords.Count - increment)) / masterRecords.Count * 100));
            }

            // done!
            progress.SetValue(100);

            // **************************************************
            // Phase 5: Cleanup "empty" District Equipment Types
            // **************************************************
            context.WriteLine("Phase 5: Cleanup empty District Equipment Types");
            progress = context.WriteProgressBar();
            progress.SetValue(0);

            // get records
            List <HetDistrictEquipmentType> districtEquipmentTypes = dbContext.HetDistrictEquipmentType.AsNoTracking()
                                                                     .Include(x => x.HetEquipment)
                                                                     .Where(x => x.Deleted == false)
                                                                     .Distinct()
                                                                     .ToList();

            increment = 0;

            foreach (HetDistrictEquipmentType districtEquipmentType in districtEquipmentTypes)
            {
                int districtEquipmentTypeId = districtEquipmentType.DistrictEquipmentTypeId;

                // does this det have any equipment records?
                if (districtEquipmentType.HetEquipment.Count < 1)
                {
                    // get det record
                    HetDistrictEquipmentType det = dbContext.HetDistrictEquipmentType
                                                   .First(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId);

                    // delete old det record
                    HetRentalRequest request = dbContext.HetRentalRequest.AsNoTracking()
                                               .FirstOrDefault(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId);

                    HetLocalAreaRotationList rotationList = dbContext.HetLocalAreaRotationList.AsNoTracking()
                                                            .FirstOrDefault(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId);

                    if (request != null || rotationList != null)
                    {
                        det.Deleted = true;
                    }
                    else
                    {
                        dbContext.HetDistrictEquipmentType.Remove(det);
                    }

                    // save changes to district equipment types and associated equipment records
                    dbContext.SaveChangesForImport();
                }

                // update status bar
                increment++;
                progress.SetValue(Convert.ToInt32((decimal)(districtEquipmentTypes.Count - (districtEquipmentTypes.Count - increment)) / districtEquipmentTypes.Count * 100));
            }

            // done!
            progress.SetValue(100);
        }
Example #8
0
        /// <summary>
        /// Calculate the Seniority List
        /// </summary>
        /// <param name="localAreaId"></param>
        /// <param name="districtEquipmentTypeId"></param>
        /// <param name="context"></param>
        /// <param name="seniorityScoringRules"></param>
        public static void CalculateSeniorityList(int localAreaId, int districtEquipmentTypeId,
                                                  DbAppContext context, string seniorityScoringRules)
        {
            try
            {
                // validate data
                if (context != null &&
                    context.HetLocalArea.Any(x => x.LocalAreaId == localAreaId) &&
                    context.HetDistrictEquipmentType.Any(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId))
                {
                    // get processing rules
                    SeniorityScoringRules scoringRules = new SeniorityScoringRules(seniorityScoringRules);

                    // get the associated equipment type
                    HetDistrictEquipmentType districtEquipmentTypeRecord = context.HetDistrictEquipmentType
                                                                           .First(x => x.DistrictEquipmentTypeId == districtEquipmentTypeId);

                    HetEquipmentType equipmentTypeRecord = context.HetEquipmentType
                                                           .FirstOrDefault(x => x.EquipmentTypeId == districtEquipmentTypeRecord.EquipmentTypeId);

                    if (equipmentTypeRecord != null)
                    {
                        // get rules
                        int seniorityScoring = equipmentTypeRecord.IsDumpTruck
                            ? scoringRules.GetEquipmentScore("DumpTruck")
                            : scoringRules.GetEquipmentScore();
                        int blockSize = equipmentTypeRecord.IsDumpTruck
                            ? scoringRules.GetBlockSize("DumpTruck")
                            : scoringRules.GetBlockSize();
                        int totalBlocks = equipmentTypeRecord.IsDumpTruck
                            ? scoringRules.GetTotalBlocks("DumpTruck")
                            : scoringRules.GetTotalBlocks();

                        // get all equipment records
                        IQueryable <HetEquipment> data = context.HetEquipment
                                                         .Include(x => x.EquipmentStatusType)
                                                         .Where(x => x.LocalAreaId == localAreaId &&
                                                                x.DistrictEquipmentTypeId == districtEquipmentTypeId);

                        // get status id
                        int?eqStatusId =
                            StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", context);
                        if (eqStatusId == null)
                        {
                            throw new ArgumentException("Status Code not found");
                        }

                        // update the seniority score
                        foreach (HetEquipment equipment in data)
                        {
                            if (equipment.EquipmentStatusTypeId != eqStatusId)
                            {
                                equipment.SeniorityEffectiveDate = DateTime.UtcNow;
                                equipment.BlockNumber            = null;
                                equipment.Seniority     = null;
                                equipment.NumberInBlock = null;
                            }
                            else
                            {
                                equipment.CalculateSeniority(seniorityScoring);
                                equipment.SeniorityEffectiveDate = DateTime.UtcNow;
                            }

                            context.HetEquipment.Update(equipment);
                        }

                        context.SaveChanges();

                        // put equipment into the correct blocks
                        AssignBlocks(localAreaId, districtEquipmentTypeId, blockSize, totalBlocks, context);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("ERROR: CalculateSeniorityList");
                Console.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// Import District Equipment Types
        /// </summary>
        /// <param name="performContext"></param>
        /// <param name="dbContext"></param>
        /// <param name="fileLocation"></param>
        /// <param name="systemId"></param>
        public static void Import(PerformContext performContext, DbAppContext dbContext, string fileLocation, string systemId)
        {
            // check the start point. If startPoint ==  sigId then it is already completed
            int startPoint = ImportUtility.CheckInterMapForStartPoint(dbContext, OldTableProgress, BcBidImport.SigId, NewTable);

            if (startPoint == BcBidImport.SigId)    // this means the import job it has done today is complete for all the records in the xml file.
            {
                performContext.WriteLine("*** Importing " + XmlFileName + " is complete from the former process ***");
                return;
            }

            int maxEquipTypeIndex = 0;

            if (dbContext.HetDistrictEquipmentType.Any())
            {
                maxEquipTypeIndex = dbContext.HetDistrictEquipmentType.Max(x => x.DistrictEquipmentTypeId);
            }

            try
            {
                string rootAttr = "ArrayOf" + OldTable;

                // create progress indicator
                performContext.WriteLine("Processing " + OldTable);
                IProgressBar progress = performContext.WriteProgressBar();
                progress.SetValue(0);

                // create serializer and serialize xml file
                XmlSerializer            ser          = new XmlSerializer(typeof(ImportModels.EquipType[]), new XmlRootAttribute(rootAttr));
                MemoryStream             memoryStream = ImportUtility.MemoryStreamGenerator(XmlFileName, OldTable, fileLocation, rootAttr);
                ImportModels.EquipType[] legacyItems  = (ImportModels.EquipType[])ser.Deserialize(memoryStream);

                int ii = startPoint;

                // skip the portion already processed
                if (startPoint > 0)
                {
                    legacyItems = legacyItems.Skip(ii).ToArray();
                }

                Debug.WriteLine("Importing DistrictEquipmentType Data. Total Records: " + legacyItems.Length);

                foreach (ImportModels.EquipType item in legacyItems.WithProgress(progress))
                {
                    // see if we have this one already
                    HetImportMap importMap = dbContext.HetImportMap.AsNoTracking()
                                             .FirstOrDefault(x => x.OldTable == OldTable &&
                                                             x.OldKey == item.Equip_Type_Id.ToString() &&
                                                             x.NewTable == NewTable);

                    // new entry
                    if (importMap == null && item.Equip_Type_Id > 0)
                    {
                        HetDistrictEquipmentType equipType = null;
                        CopyToInstance(dbContext, item, ref equipType, systemId, ref maxEquipTypeIndex);
                        ImportUtility.AddImportMap(dbContext, OldTable, item.Equip_Type_Id.ToString(), NewTable, equipType.DistrictEquipmentTypeId);

                        // save has to be done immediately because we need access to the records
                        dbContext.SaveChangesForImport();
                    }

                    // periodically save change to the status
                    if (ii++ % 1000 == 0)
                    {
                        try
                        {
                            ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, ii.ToString(), BcBidImport.SigId, NewTable);
                            dbContext.SaveChangesForImport();
                        }
                        catch (Exception e)
                        {
                            performContext.WriteLine("Error saving data " + e.Message);
                        }
                    }
                }

                try
                {
                    performContext.WriteLine("*** Importing " + XmlFileName + " is Done ***");
                    ImportUtility.AddImportMapForProgress(dbContext, OldTableProgress, BcBidImport.SigId.ToString(), BcBidImport.SigId, NewTable);
                    dbContext.SaveChangesForImport();
                }
                catch (Exception e)
                {
                    string temp = string.Format("Error saving data (DistrictEquipmentTypeIndex: {0}): {1}", maxEquipTypeIndex, e.Message);
                    performContext.WriteLine(temp);
                    throw new DataException(temp);
                }
            }
            catch (Exception e)
            {
                performContext.WriteLine("*** ERROR ***");
                performContext.WriteLine(e.ToString());
                throw;
            }
        }
        /// <summary>
        /// Copy xml item to instance (table entries)
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipType"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipTypeIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.EquipType oldObject,
                                           ref HetDistrictEquipmentType equipType, string systemId, ref int maxEquipTypeIndex)
        {
            try
            {
                if (equipType != null)
                {
                    return;
                }

                // ***********************************************
                // get the equipment type
                // ***********************************************
                float?tempBlueBookRate = ImportUtility.GetFloatValue(oldObject.Equip_Rental_Rate_No);

                if (tempBlueBookRate == null)
                {
                    return;
                }

                // ***********************************************
                // get the parent equipment type
                // ***********************************************
                HetEquipmentType type = dbContext.HetEquipmentType.FirstOrDefault(x => x.BlueBookSection == tempBlueBookRate);

                // if it's not found - try to round up to the "parent" blue book section
                if (type == null)
                {
                    int tempIntBlueBookRate = Convert.ToInt32(tempBlueBookRate);
                    type = dbContext.HetEquipmentType.FirstOrDefault(x => x.BlueBookSection == tempIntBlueBookRate);
                }

                // finally - if that's not found - map to 0 (MISCELLANEOUS)
                if (type == null)
                {
                    int tempIntBlueBookRate = 0;
                    type = dbContext.HetEquipmentType.FirstOrDefault(x => x.BlueBookSection == tempIntBlueBookRate);
                }

                if (type == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Equipment Type (Blue Book Rate Number: {0} | Equipment Type Id: {1})",
                                            tempBlueBookRate.ToString(), oldObject.Equip_Type_Id));
                }

                // ***********************************************
                // get the description
                // ***********************************************
                string tempDistrictDescriptionOnly = ImportUtility.CleanString(oldObject.Equip_Type_Desc);
                tempDistrictDescriptionOnly = ImportUtility.GetCapitalCase(tempDistrictDescriptionOnly);

                // cleaning up a few data errors from BC Bid
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("  ", " ");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" Lrg", "Lgr");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" LoadLgr", " Load Lgr");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("23000 - 37999", "23000-37999");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator- Class 1", "Excavator-Class 1");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" 3-4(19.05-23.13)Tonnes", " 3-4 (19.05-23.13)Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" 3 - 4 (19.05-23.13)Tonnes", " 3-4 (19.05-23.13)Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" 5(23.13-26.76)Tonnes", " 5 (23.13-26.76)Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" 6(26.76-30.84)Tonnes", " 6 (26.76-30.84)Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" 7(30.84-39.92)Tonnes", " 7 (30.84-39.92)Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator-Class 8 - 12", "Excavator-Class 8-12");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(")Tonnes", ") Tonnes");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("(Trailer/Skidmou", "(Trailer/Skidmou)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(" Lgr", "Large");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Compressors", "Compressor");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Bulldozers-Mini", "Bulldozer Mini");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Curbing Machines", "Curbing Machine");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Drilling, Specialized Equipment", "Specialized Drilling Equipment");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Geotch. Drilling Companie", "Geotch. Drilling Company");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavators", "Excavator");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavatr", "Excavator");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excvtr", "Excavator");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Attachements", "Attachments");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 2 To 41,000 Lbs", "Class 2 To 41,999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Heavy Excavator Class 5 To 58,999", "Heavy Excavator Class 5 To 58,999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Heavy Excavator Class 6 To 67,999", "Heavy Excavator Class 6 To 67,999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Heavy Excavator Class 7 To 87.999", "Heavy Excavator Class 7 To 87.999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Heavy Excavator Class 9 To 152,999 Lbs", "Heavy Excavator Class Class 9-12 To 152,999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 1 (Under 32000 Lbs)", "Excav Class 1 (Under 32000 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 2 (32000 - 41999 Lbs)", "Excav Class 2 (32000-41999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 3 (42000 - 44999 Lbs)", "Excav Class 3 (42000-44999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 4 (45000 - 50999 Lbs)", "Excav Class 4 (45000-50999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 5 (51000 - 58999 Lbs)", "Excav Class 5 (51000-58999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 6 (59000 - 67999 Lbs)", "Excav Class 6 (59000-67999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 8 (88000 - 95999 Lbs)", "Excav Class 8 (88000-95999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 9 (96000 - 102999 Lbs)", "Excav Class 9 (96000-102999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 10 (103000 - 118999 Lbs)", "Excav Class 10 (103000-118999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excav Class 11 (119000 - 151999 Lbs)", "Excav Class 11 (119000-151999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator-Class 8-12(39.92-68.95+)", "Excavator-Class 8-12 (39.92-68.95+)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace(") Lbs", " Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Lbs Lbs", "Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Lbs.", "Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Lb", "Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Lbss", "Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("999Lbs", "999 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("000Lbs+", "000 Lbs+");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("000 Lbs +", "000 Lbs+");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("000+ - 152,000Lbs", "000-152,000 Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tract.1", "Tract. 1");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tract.2", "Tract. 2");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class Class", "Class");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Graders 130 - 144 Fwhp", "Graders 130-144 Fwhp");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Graders Under 100 - 129 Fwhp", "Graders Under 100-129 Fwhp");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Craw.64-90,999Lbs", "Craw 64-90,999Lbs");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator Mini-", "Excavator Mini -");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator Mini -2", "Excavator Mini - 2");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator Mini 2", "Excavator Mini - 2");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Flat Decks", "Flat Deck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Misc. Equipment", "Misc Equipment");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Misc. Equip", "Miscellaneous");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Pipe Crews", "Pipe Crew");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Pipecrew", "Pipe Crew");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roll.TandemLarge.", "Roll. Tandem Large");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roll. TandemLarge", "Roll. Tandem Large");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roll.Tandem Med.", "Roll. Tandem Med");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Scraper - Two Engine -", "Scraper - Two Engines -");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("14.2 Scrapers", "14.2 Scraper");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Skidders", "Skidder");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Selfprop Scrapr", "Self Prop Scrapr");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Bellydump", "Belly Dump");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Dump Combo Pup", "Dump Combo (Pup)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tandem Dump Trk", "Tandem Dump Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tandem Dump Trks", "Tandem Dump Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tandem Dump Truc", "Tandem Dump Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tandem Dump Truckk", "Tandem Dump Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tractor/Trailers", "Tractor Trailers");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Truck - Tractor Trucks", "Truck - Tractor Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Loaders-Rubber Tired", "Loaders - Rubber Tired");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tractor-Crawler-Class ", "Tractor - Crawler - Class ");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Heavy Hydraulic Excav Class 11 (119000 - 151999 Lbs)", "Heavy Hydraulic Excav Class 11 (119000-151999 Lbs)");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 1-3 Under", "Class 1-3 - Under");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 4-5 2", "Class 4-5 - 2");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 6-7 3", "Class 6-7 - 3");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 8-9 4", "Class 8-9 - 4");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 10-11 5", "Class 10-11 - 5");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 12-16 6", "Class 12-16 - 6");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Tractors-Rubber Tired", "Tractors - Rubber Tired");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("(Rubber Tired)6.", "(Rubber Tired) 6");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Rubber Tired-Class ", "Rubber Tired - Class ");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("20 - 59.9 Fhwp", "20-59.9 Fhwp");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("20 - 150+ Fhwp", "20-150+ Fhwp");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 6-11 60-119.9 Fwhp", "Class 6-11 - 60-119.9 Fwhp");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Water Trucks", "Water Truck");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Welding Outfit/Truck Mounted", "Welding Outfit-Truck Mounted");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator-Wheeled-Class", "Excavator-Wheeled - Class");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 1-2(", "Class 1-2 - (");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Class 3(", "Class 3 - (");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Backhoe Sm.-40", "Backhoe Sm. -40");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Water Truck -Tandem", "Water Truck - Tandem");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer-Class ", "Roller/Packer - Class ");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer - Class 7 - 11", "Roller/Packer - Class 7-11");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer - Class 5 8", "Roller/Packer - Class 5 - 8");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer - Class 2-4", "Roller/Packer - Class 2 - 4");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer - Class 7-11", "Roller/Packer - Class 7 - 11");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Sp,Vib,Rubber", "Sp, Vib, Rubber");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Roller/Packer 10-15.9T, ", "Roller/Packer 10-15.9T ");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator-Class", "Excavator - Class");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator - Class 3 6", "Excavator - Class 3 - 6");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator - Class 2 3", "Excavator - Class 2 - 3");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Excavator - Class 5 13", "Excavator - Class 5 - 13");
                tempDistrictDescriptionOnly = tempDistrictDescriptionOnly.Replace("Graders-Class", "Graders - Class");

                // get the abbreviation portion
                string tempAbbrev = ImportUtility.CleanString(oldObject.Equip_Type_Cd).ToUpper();

                // cleaning up a few data errors from BC Bid
                tempAbbrev = tempAbbrev.Replace("BUCTRK", "BUCKET");
                tempAbbrev = tempAbbrev.Replace("DUMP 1", "DUMP1");
                tempAbbrev = tempAbbrev.Replace("DUMP 2", "DUMP2");
                tempAbbrev = tempAbbrev.Replace("MIS", "MISC");
                tempAbbrev = tempAbbrev.Replace("MISCC", "MISC");
                tempAbbrev = tempAbbrev.Replace("HEL", "HELICOP");
                tempAbbrev = tempAbbrev.Replace("SCRNGEQ", "SCRPLA");
                tempAbbrev = tempAbbrev.Replace("SECT. ", "SECT.");
                tempAbbrev = tempAbbrev.Replace("SKI", "SKID");
                tempAbbrev = tempAbbrev.Replace("SKIDD", "SKID");
                tempAbbrev = tempAbbrev.Replace("SSM", "SSS");
                tempAbbrev = tempAbbrev.Replace("SSP", "SSS");
                tempAbbrev = tempAbbrev.Replace("TFC", "TFD");
                tempAbbrev = tempAbbrev.Replace("TRUCKS/", "TRUCKS");
                tempAbbrev = tempAbbrev.Replace("TDB", "TBD");

                string tempDistrictDescriptionFull = string.Format("{0} - {1}", tempAbbrev, tempDistrictDescriptionOnly);

                // add new district equipment type
                int tempId = type.EquipmentTypeId;

                equipType = new HetDistrictEquipmentType
                {
                    DistrictEquipmentTypeId = ++maxEquipTypeIndex,
                    EquipmentTypeId         = tempId,
                    DistrictEquipmentName   = tempDistrictDescriptionFull
                };

                // ***********************************************
                // set the district
                // ***********************************************
                HetServiceArea serviceArea = dbContext.HetServiceArea.AsNoTracking()
                                             .Include(x => x.District)
                                             .FirstOrDefault(x => x.MinistryServiceAreaId == oldObject.Service_Area_Id);

                if (serviceArea == null)
                {
                    throw new ArgumentException(
                              string.Format("Cannot find Service Area (Service Area Id: {0} | Equipment Type Id: {1})",
                                            oldObject.Service_Area_Id, oldObject.Equip_Type_Id));
                }

                int districtId = serviceArea.District.DistrictId;
                equipType.DistrictId = districtId;

                // ***********************************************
                // check that we don't have this equipment type
                // already (from another service area - but same district)
                // ***********************************************
                HetDistrictEquipmentType existingEquipmentType = dbContext.HetDistrictEquipmentType.AsNoTracking()
                                                                 .Include(x => x.District)
                                                                 .FirstOrDefault(x => x.DistrictEquipmentName == tempDistrictDescriptionFull &&
                                                                                 x.District.DistrictId == districtId);

                if (existingEquipmentType != null)
                {
                    equipType.DistrictEquipmentTypeId = existingEquipmentType.DistrictEquipmentTypeId;
                    return; // not adding a duplicate
                }

                // ***********************************************
                // save district equipment type record
                // ***********************************************
                equipType.AppCreateUserid        = systemId;
                equipType.AppCreateTimestamp     = DateTime.UtcNow;
                equipType.AppLastUpdateUserid    = systemId;
                equipType.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.HetDistrictEquipmentType.Add(equipType);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - (Old) Equipment Code: " + oldObject.Equip_Type_Cd);
                Debug.WriteLine("***Error*** - Master District Equipment Index: " + maxEquipTypeIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
Example #11
0
        /// <summary>
        /// Map data
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="oldObject"></param>
        /// <param name="equipment"></param>
        /// <param name="systemId"></param>
        /// <param name="maxEquipmentIndex"></param>
        private static void CopyToInstance(DbAppContext dbContext, ImportModels.Equip oldObject,
                                           ref HetEquipment equipment, string systemId, ref int maxEquipmentIndex)
        {
            try
            {
                int?statusIdApproved   = StatusHelper.GetStatusId("Approved", "equipmentStatus", dbContext);
                int?statusIdUnapproved = StatusHelper.GetStatusId("Unapproved", "equipmentStatus", dbContext);
                int?statusIdArchived   = StatusHelper.GetStatusId("Archived", "equipmentStatus", dbContext);

                if (oldObject.Equip_Id <= 0)
                {
                    return;
                }

                equipment = new HetEquipment {
                    EquipmentId = ++maxEquipmentIndex
                };

                // there is a problem with 1 equipment record
                // Per BC Bid - the correct Owner Id should be: 8786195
                if (oldObject.Equip_Id == 19165)
                {
                    oldObject.Owner_Popt_Id = 8786195;
                }

                // ***********************************************
                // equipment code
                // ***********************************************
                string tempEquipmentCode = ImportUtility.CleanString(oldObject.Equip_Cd).ToUpper();

                if (!string.IsNullOrEmpty(tempEquipmentCode))
                {
                    equipment.EquipmentCode = tempEquipmentCode;
                }
                else
                {
                    // must have an equipment code: HETS-817
                    return;
                }

                // ***********************************************
                // set the equipment status
                // ***********************************************
                string tempArchive = oldObject.Archive_Cd;
                string tempStatus  = oldObject.Status_Cd.Trim();

                if (tempArchive == "Y")
                {
                    if (statusIdArchived == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (EquipmentIndex: {0})", maxEquipmentIndex));
                    }

                    // archived!
                    equipment.ArchiveCode           = "Y";
                    equipment.ArchiveDate           = DateTime.UtcNow;
                    equipment.ArchiveReason         = "Imported from BC Bid";
                    equipment.EquipmentStatusTypeId = (int)statusIdArchived;

                    string tempArchiveReason = ImportUtility.CleanString(oldObject.Archive_Reason);

                    if (!string.IsNullOrEmpty(tempArchiveReason))
                    {
                        equipment.ArchiveReason = ImportUtility.GetUppercaseFirst(tempArchiveReason);
                    }
                }
                else
                {
                    if (statusIdApproved == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (EquipmentIndex: {0})", maxEquipmentIndex));
                    }

                    if (statusIdUnapproved == null)
                    {
                        throw new DataException(string.Format("Status Id cannot be null (EquipmentIndex: {0})", maxEquipmentIndex));
                    }

                    equipment.ArchiveCode           = "N";
                    equipment.ArchiveDate           = null;
                    equipment.ArchiveReason         = null;
                    equipment.EquipmentStatusTypeId = tempStatus == "A" ? (int)statusIdApproved : (int)statusIdUnapproved;
                    equipment.StatusComment         = string.Format("Imported from BC Bid ({0})", tempStatus);
                }

                // ***********************************************
                // set equipment attributes
                // ***********************************************
                string tempLicense = ImportUtility.CleanString(oldObject.Licence).ToUpper();

                if (!string.IsNullOrEmpty(tempLicense))
                {
                    equipment.LicencePlate = tempLicense;
                }

                equipment.ApprovedDate = ImportUtility.CleanDate(oldObject.Approved_Dt);

                DateTime?tempReceivedDate = ImportUtility.CleanDate(oldObject.Received_Dt);

                if (tempReceivedDate != null)
                {
                    equipment.ReceivedDate = (DateTime)tempReceivedDate;
                }
                else
                {
                    if (equipment.ArchiveCode == "N" &&
                        equipment.EquipmentStatusTypeId == statusIdApproved)
                    {
                        throw new DataException(string.Format("Received Date cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                    }
                }

                // get the created date and use the timestamp to fix the
                DateTime?tempCreatedDate = ImportUtility.CleanDateTime(oldObject.Created_Dt);

                if (tempCreatedDate != null)
                {
                    int hours   = Convert.ToInt32(tempCreatedDate?.ToString("HH"));
                    int minutes = Convert.ToInt32(tempCreatedDate?.ToString("mm"));
                    int secs    = Convert.ToInt32(tempCreatedDate?.ToString("ss"));

                    equipment.ReceivedDate = equipment.ReceivedDate.AddHours(hours);
                    equipment.ReceivedDate = equipment.ReceivedDate.AddMinutes(minutes);
                    equipment.ReceivedDate = equipment.ReceivedDate.AddSeconds(secs);
                }

                // pay rate
                float?tempPayRate = ImportUtility.GetFloatValue(oldObject.Pay_Rate);

                if (tempPayRate != null)
                {
                    equipment.PayRate = tempPayRate;
                }

                // ***********************************************
                // make, model, year, etc.
                // ***********************************************
                string tempType = ImportUtility.CleanString(oldObject.Type);

                if (!string.IsNullOrEmpty(tempType))
                {
                    tempType       = ImportUtility.GetCapitalCase(tempType);
                    equipment.Type = tempType;
                }

                string tempMake = ImportUtility.CleanString(oldObject.Make);

                if (!string.IsNullOrEmpty(tempMake))
                {
                    tempMake       = ImportUtility.GetCapitalCase(tempMake);
                    equipment.Make = tempMake;
                }

                // model
                string tempModel = ImportUtility.CleanString(oldObject.Model).ToUpper();

                if (!string.IsNullOrEmpty(tempModel))
                {
                    equipment.Model = tempModel;
                }

                // year
                string tempYear = ImportUtility.CleanString(oldObject.Year);

                if (!string.IsNullOrEmpty(tempYear))
                {
                    equipment.Year = tempYear;
                }

                // size
                string tempSize = ImportUtility.CleanString(oldObject.Size);

                if (!string.IsNullOrEmpty(tempSize))
                {
                    tempSize = ImportUtility.GetCapitalCase(tempSize);

                    equipment.Size = tempSize;
                }

                // serial number
                string tempSerialNumber = ImportUtility.CleanString(oldObject.Serial_Num).ToUpper();

                if (!string.IsNullOrEmpty(tempSerialNumber))
                {
                    equipment.SerialNumber = tempSerialNumber;
                }

                // operator
                string tempOperator = ImportUtility.CleanString(oldObject.Operator);

                if (!string.IsNullOrEmpty(tempOperator))
                {
                    equipment.Operator = tempOperator ?? null;
                }

                // ***********************************************
                // add comment into the notes field
                // ***********************************************
                string tempComment = ImportUtility.CleanString(oldObject.Comment);

                if (!string.IsNullOrEmpty(tempComment))
                {
                    tempComment = ImportUtility.GetUppercaseFirst(tempComment);

                    HetNote note = new HetNote
                    {
                        Text = tempComment,
                        IsNoLongerRelevant = false
                    };

                    if (equipment.HetNote == null)
                    {
                        equipment.HetNote = new List <HetNote>();
                    }

                    equipment.HetNote.Add(note);
                }

                // ***********************************************
                // add equipment to the correct area
                // ***********************************************
                if (oldObject.Area_Id != null)
                {
                    HetLocalArea area = dbContext.HetLocalArea.AsNoTracking()
                                        .FirstOrDefault(x => x.LocalAreaNumber == oldObject.Area_Id);

                    if (area != null)
                    {
                        int tempAreaId = area.LocalAreaId;
                        equipment.LocalAreaId = tempAreaId;
                    }
                }

                if (equipment.LocalAreaId == null && equipment.ArchiveCode == "N" &&
                    equipment.EquipmentStatusTypeId == statusIdApproved)
                {
                    throw new DataException(string.Format("Local Area cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set the equipment type
                // ***********************************************
                if (oldObject.Equip_Type_Id != null)
                {
                    // get the new id for the "District" Equipment Type
                    string tempEquipmentTypeId = oldObject.Equip_Type_Id.ToString();

                    HetImportMap equipMap = dbContext.HetImportMap.AsNoTracking()
                                            .FirstOrDefault(x => x.OldTable == ImportDistrictEquipmentType.OldTable &&
                                                            x.OldKey == tempEquipmentTypeId &&
                                                            x.NewTable == ImportDistrictEquipmentType.NewTable);

                    if (equipMap != null)
                    {
                        HetDistrictEquipmentType distEquipType = dbContext.HetDistrictEquipmentType
                                                                 .FirstOrDefault(x => x.DistrictEquipmentTypeId == equipMap.NewKey);

                        if (distEquipType != null)
                        {
                            int tempEquipmentId = distEquipType.DistrictEquipmentTypeId;
                            equipment.DistrictEquipmentTypeId = tempEquipmentId;
                        }
                    }
                }

                if (equipment.DistrictEquipmentTypeId == null && equipment.ArchiveCode == "N" &&
                    equipment.EquipmentStatusTypeId == statusIdApproved)
                {
                    throw new DataException(string.Format("Equipment Type cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set the equipment owner
                // ***********************************************
                HetImportMap ownerMap = dbContext.HetImportMap.AsNoTracking()
                                        .FirstOrDefault(x => x.OldTable == ImportOwner.OldTable &&
                                                        x.OldKey == oldObject.Owner_Popt_Id.ToString());

                if (ownerMap != null)
                {
                    HetOwner owner = dbContext.HetOwner.FirstOrDefault(x => x.OwnerId == ownerMap.NewKey);

                    if (owner != null)
                    {
                        int tempOwnerId = owner.OwnerId;
                        equipment.OwnerId = tempOwnerId;

                        // set address fields on the owner record
                        if (string.IsNullOrEmpty(owner.Address1))
                        {
                            string tempAddress1 = ImportUtility.CleanString(oldObject.Addr1);
                            tempAddress1 = ImportUtility.GetCapitalCase(tempAddress1);

                            string tempAddress2 = ImportUtility.CleanString(oldObject.Addr2);
                            tempAddress2 = ImportUtility.GetCapitalCase(tempAddress2);

                            string tempCity = ImportUtility.CleanString(oldObject.City);
                            tempCity = ImportUtility.GetCapitalCase(tempCity);

                            owner.Address1   = tempAddress1;
                            owner.Address2   = tempAddress2;
                            owner.City       = tempCity;
                            owner.PostalCode = ImportUtility.CleanString(oldObject.Postal).ToUpper();
                            owner.Province   = "BC";

                            dbContext.HetOwner.Update(owner);
                        }
                    }
                }

                if (equipment.OwnerId == null && equipment.ArchiveCode != "Y")
                {
                    throw new DataException(string.Format("Owner cannot be null (EquipmentIndex: {0}", maxEquipmentIndex));
                }

                // ***********************************************
                // set seniority and hours
                // ***********************************************
                float?tempSeniority = ImportUtility.GetFloatValue(oldObject.Seniority);
                equipment.Seniority = tempSeniority ?? 0.0F;

                float?tempYearsOfService = ImportUtility.GetFloatValue(oldObject.Num_Years);
                equipment.YearsOfService = tempYearsOfService ?? 0.0F;

                int?tempBlockNumber = ImportUtility.GetIntValue(oldObject.Block_Num);
                equipment.BlockNumber = tempBlockNumber ?? null;

                float?tempServiceHoursLastYear = ImportUtility.GetFloatValue(oldObject.YTD1);
                equipment.ServiceHoursLastYear = tempServiceHoursLastYear ?? 0.0F;

                float?tempServiceHoursTwoYearsAgo = ImportUtility.GetFloatValue(oldObject.YTD2);
                equipment.ServiceHoursTwoYearsAgo = tempServiceHoursTwoYearsAgo ?? 0.0F;

                float?tempServiceHoursThreeYearsAgo = ImportUtility.GetFloatValue(oldObject.YTD3);
                equipment.ServiceHoursThreeYearsAgo = tempServiceHoursThreeYearsAgo ?? 0.0F;

                // ***********************************************
                // using the "to date" field to store the
                // equipment "Last_Dt" (hopefully the last time
                // this equipment was hired)
                // ***********************************************
                DateTime?tempLastDate = ImportUtility.CleanDate(oldObject.Last_Dt);

                if (tempLastDate != null)
                {
                    equipment.ToDate = (DateTime)tempLastDate;
                }

                // ***********************************************
                // set last verified date (default to March 31, 2018)
                // ***********************************************
                equipment.LastVerifiedDate = DateTime.Parse("2018-03-31 0:00:01");

                // ***********************************************
                // create equipment
                // ***********************************************
                equipment.AppCreateUserid        = systemId;
                equipment.AppCreateTimestamp     = DateTime.UtcNow;
                equipment.AppLastUpdateUserid    = systemId;
                equipment.AppLastUpdateTimestamp = DateTime.UtcNow;

                dbContext.HetEquipment.Add(equipment);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("***Error*** - Equipment Code: " + equipment.EquipmentCode);
                Debug.WriteLine("***Error*** - Master Equipment Index: " + maxEquipmentIndex);
                Debug.WriteLine(ex.Message);
                throw;
            }
        }
        public virtual IActionResult DistrictEquipmentTypesIdPost([FromRoute] int id, [FromBody] HetDistrictEquipmentType item)
        {
            if (id != item.DistrictEquipmentTypeId)
            {
                // not found
                return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            // add or update equipment type
            if (item.DistrictEquipmentTypeId > 0)
            {
                bool exists = _context.HetDistrictEquipmentType.Any(a => a.DistrictEquipmentTypeId == id);

                // not found
                if (!exists)
                {
                    return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                }

                // get equipment status
                int?equipmentStatusId = StatusHelper.GetStatusId(HetEquipment.StatusApproved, "equipmentStatus", _context);

                if (equipmentStatusId == null)
                {
                    return(new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))));
                }

                // get record
                HetDistrictEquipmentType equipment = _context.HetDistrictEquipmentType
                                                     .Include(x => x.EquipmentType)
                                                     .First(x => x.DistrictEquipmentTypeId == id);

                // HETS-1163 - Recalculate seniority and Blk assignment
                // for change in Blue book section number to and from
                bool currentIsDumpTruck = equipment.EquipmentType.IsDumpTruck;

                HetEquipmentType newEquipmentType = _context.HetEquipmentType.AsNoTracking()
                                                    .FirstOrDefault(x => x.EquipmentTypeId == item.EquipmentType.EquipmentTypeId);

                if (newEquipmentType == null)
                {
                    return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
                }

                bool updateSeniority = currentIsDumpTruck != newEquipmentType.IsDumpTruck;

                // modify record
                equipment.DistrictEquipmentName    = item.DistrictEquipmentName;
                equipment.ConcurrencyControlNumber = item.ConcurrencyControlNumber;
                equipment.DistrictId      = item.District.DistrictId;
                equipment.EquipmentTypeId = item.EquipmentType.EquipmentTypeId;

                // update seniority and assignments for this District Equipment Type (HETS-1163)
                if (updateSeniority)
                {
                    IConfigurationSection scoringRules = _configuration.GetSection("SeniorityScoringRules");
                    string seniorityScoringRules       = GetConfigJson(scoringRules);

                    // update the seniority and block assignments for the master record
                    List <HetLocalArea> localAreas = _context.HetEquipment.AsNoTracking()
                                                     .Include(x => x.LocalArea)
                                                     .Where(x => x.EquipmentStatusTypeId == equipmentStatusId &&
                                                            x.DistrictEquipmentTypeId == equipment.DistrictEquipmentTypeId)
                                                     .Select(x => x.LocalArea)
                                                     .Distinct()
                                                     .ToList();

                    foreach (HetLocalArea localArea in localAreas)
                    {
                        EquipmentHelper.RecalculateSeniority(localArea.LocalAreaId, equipment.DistrictEquipmentTypeId, _context, seniorityScoringRules);
                    }
                }
            }
            else
            {
                HetDistrictEquipmentType equipment = new HetDistrictEquipmentType
                {
                    DistrictEquipmentName = item.DistrictEquipmentName,
                    DistrictId            = item.District.DistrictId,
                    EquipmentTypeId       = item.EquipmentType.EquipmentTypeId
                };

                _context.HetDistrictEquipmentType.Add(equipment);
            }

            // save the changes
            _context.SaveChanges();

            // get the id (in the case of new records)
            id = item.DistrictEquipmentTypeId;

            // return the updated equipment type record
            HetDistrictEquipmentType equipmentType = _context.HetDistrictEquipmentType.AsNoTracking()
                                                     .Include(x => x.District)
                                                     .ThenInclude(y => y.Region)
                                                     .Include(x => x.EquipmentType)
                                                     .FirstOrDefault(a => a.DistrictEquipmentTypeId == id);

            return(new ObjectResult(new HetsResponse(equipmentType)));
        }
        public virtual IActionResult DistrictEquipmentTypesIdDeletePost([FromRoute] int id)
        {
            bool exists = _context.HetDistrictEquipmentType.Any(a => a.DistrictEquipmentTypeId == id);

            // not found
            if (!exists)
            {
                return(new NotFoundObjectResult(new HetsResponse("HETS-01", ErrorViewModel.GetDescription("HETS-01", _configuration))));
            }

            HetDistrictEquipmentType item = _context.HetDistrictEquipmentType.First(a => a.DistrictEquipmentTypeId == id);

            // HETS-978 - Give a clear error message when deleting equipment type fails
            int?archiveStatus = StatusHelper.GetStatusId(HetEquipment.StatusArchived, "equipmentStatus", _context);

            if (archiveStatus == null)
            {
                return(new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))));
            }

            int?pendingStatus = StatusHelper.GetStatusId(HetEquipment.StatusPending, "equipmentStatus", _context);

            if (pendingStatus == null)
            {
                return(new NotFoundObjectResult(new HetsResponse("HETS-23", ErrorViewModel.GetDescription("HETS-23", _configuration))));
            }

            HetEquipment equipment = _context.HetEquipment.AsNoTracking()
                                     .FirstOrDefault(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentTypeId &&
                                                     x.EquipmentStatusTypeId != archiveStatus);

            if (equipment != null)
            {
                return(new BadRequestObjectResult(new HetsResponse("HETS-37", ErrorViewModel.GetDescription("HETS-37", _configuration))));
            }

            bool softDelete = false;

            // check for foreign key relationships - equipment
            equipment = _context.HetEquipment.AsNoTracking()
                        .FirstOrDefault(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentTypeId);

            if (equipment != null)
            {
                softDelete = true;
            }

            // check for foreign key relationships - local area rotation lists
            HetLocalAreaRotationList rotationList = _context.HetLocalAreaRotationList.AsNoTracking()
                                                    .FirstOrDefault(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentTypeId);

            if (rotationList != null)
            {
                softDelete = true;
            }

            // check for foreign key relationships - rental requests
            HetRentalRequest request = _context.HetRentalRequest.AsNoTracking()
                                       .FirstOrDefault(x => x.DistrictEquipmentTypeId == item.DistrictEquipmentTypeId);

            if (request != null)
            {
                softDelete = true;
            }

            // delete the record
            if (!softDelete)
            {
                _context.HetDistrictEquipmentType.Remove(item);
            }
            else
            {
                // else "SOFT" delete record
                item.Deleted = true;
            }

            _context.SaveChanges();

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